コード例 #1
0
        public static void AddToRecurringBilling(IPTV2Entities context, Product product, Offering offering, User user, DateTime registDt, CreditCardInfo info)
        {
            //Check if product is subscription product
            if (product is SubscriptionProduct)
            {
                //check if there are any recurring products that have the same productgroup
                SubscriptionProduct subscriptionProduct = (SubscriptionProduct)product;

                //Get user's recurring productGroups
                var recurringProductGroups = user.GetRecurringProductGroups(offering);
                if (!recurringProductGroups.Contains(subscriptionProduct.ProductGroup))
                {
                    var productPackage = context.ProductPackages.FirstOrDefault(p => p.ProductId == product.ProductId);
                    if (productPackage != null)
                    {
                        var entitlement = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == productPackage.PackageId);
                        if (entitlement != null)
                        {
                            var billing = new CreditCardRecurringBilling()
                            {
                                CreatedOn = registDt,
                                Product = product,
                                User = user,
                                UpdatedOn = registDt,
                                EndDate = entitlement.EndDate,
                                NextRun = entitlement.EndDate.AddDays(-3).Date, // Run day before expiry
                                StatusId = GlobalConfig.Visible,
                                Offering = offering,
                                Package = (Package)productPackage.Package,
                                CreditCardHash = MyUtility.GetSHA1(info.Number),
                                NumberOfAttempts = 0
                            };
                            context.RecurringBillings.Add(billing);
                            context.SaveChanges();
                        }
                    }
                }
            }
        }
コード例 #2
0
 private List<RecurringBillingDisplay> GetRecurringBillingsForUser(User user, IPTV2Entities context)
 {
     List<RecurringBillingDisplay> list = null;
     try
     {
         var recurringBillings = context.RecurringBillings.Where(r => r.UserId == user.UserId && r.StatusId == GlobalConfig.Visible);
         if (recurringBillings != null)
         {
             list = new List<RecurringBillingDisplay>();
             foreach (var item in recurringBillings)
             {
                 RecurringBillingDisplay disp = new RecurringBillingDisplay()
                 {
                     EndDate = (DateTime)item.EndDate,
                     EndDateStr = item.EndDate.Value.ToShortDateString(),
                     NextRun = (DateTime)item.NextRun,
                     NextRunStr = item.NextRun.Value.ToShortDateString(),
                     PackageId = item.PackageId,
                     PackageName = item.Package.Description,
                     ProductId = item.ProductId,
                     ProductName = item.Product.Description,
                     RecurringBillingId = item.RecurringBillingId,
                     StatusId = item.StatusId,
                     UserId = item.UserId,
                     isDisabled = false,
                     PaymentType = item is CreditCardRecurringBilling ? "Credit Card" : "Paypal"
                 };
                 list.Add(disp);
             }
         }
     }
     catch (Exception) { }
     return list;
 }
コード例 #3
0
        private void UpdateRecurringBillingViaEditProfile(IPTV2Entities context, User user, string list, bool? enable)
        {
            try
            {
                DateTime registDt = DateTime.Now;
                var rb_list = list.Split(',');

                var gomsService = new GomsTfcTv();

                if (rb_list.Count() > 0)
                {
                    foreach (var item in rb_list)
                    {
                        if (!String.IsNullOrEmpty(item))
                        {
                            var name = item;
                            if (MyUtility.isUserLoggedIn())
                            {
                                bool RecurringStatus = false;
                                if (enable != null)
                                    RecurringStatus = (bool)enable;

                                int RecurringBillingId = 0;
                                try { RecurringBillingId = Convert.ToInt32(name.Substring(2)); }
                                catch (Exception e) { MyUtility.LogException(e); }

                                if (user != null)
                                {
                                    var CurrencyCode = GlobalConfig.DefaultCurrency;
                                    try { CurrencyCode = user.Country.CurrencyCode; }
                                    catch (Exception) { }
                                    string cancellation_remarks = String.Empty;
                                    string reference = String.Empty;
                                    bool serviceUpdateSuccess = false;
                                    var billing = user.RecurringBillings.FirstOrDefault(r => r.RecurringBillingId == RecurringBillingId && r.StatusId != 2);
                                    if (billing != null)
                                    {
                                        //Check first if there is a same package with recurring turned on
                                        if (user.RecurringBillings.Count(r => r.PackageId == billing.PackageId && r.StatusId == GlobalConfig.Visible && r.RecurringBillingId != billing.RecurringBillingId) > 0)
                                        {
                                            //there is same package with recurring enabled.                                            
                                        }
                                        else
                                        {
                                            if (billing is PaypalRecurringBilling)
                                            {
                                                try
                                                {
                                                    var paypalrbilling = (PaypalRecurringBilling)billing;

                                                    billing.StatusId = RecurringStatus ? 1 : 0;
                                                    billing.UpdatedOn = registDt;
                                                    if (registDt.Date > billing.NextRun && RecurringStatus)
                                                        billing.NextRun = registDt.AddDays(1).Date;
                                                    if (!RecurringStatus)
                                                    {
                                                        try
                                                        {
                                                            if (PaymentHelper.CancelPaypalRecurring(paypalrbilling.SubscriberId))
                                                            {
                                                                reference = String.Format("PayPal Payment Renewal {0} cancelled", billing.RecurringBillingId);
                                                                String.Format("{0} - PayPal Recurring Billing Id cancelled", billing.RecurringBillingId);
                                                                serviceUpdateSuccess = true;
                                                            }
                                                        }
                                                        catch (Exception) { }
                                                    }
                                                }
                                                catch (Exception) { }
                                            }
                                            else
                                            {
                                                if (RecurringStatus)
                                                {
                                                    billing.StatusId = RecurringStatus ? 1 : 0;
                                                    billing.UpdatedOn = registDt;
                                                    if (registDt.Date > billing.NextRun && RecurringStatus)
                                                        billing.NextRun = registDt.AddDays(1).Date;
                                                }
                                                else //if (!RecurringStatus)
                                                {
                                                    try
                                                    {
                                                        var result = gomsService.CancelRecurringPayment(user, billing.Product);
                                                        if (result.IsSuccess)
                                                        {
                                                            billing.StatusId = RecurringStatus ? 1 : 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
                                                            throw new Exception(result.StatusMessage);
                                                    }
                                                    catch (Exception e) { MyUtility.LogException(e); }
                                                }
                                            }

                                            if (!RecurringStatus && 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);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e) { MyUtility.LogException(e); }
        }
コード例 #4
0
        private void UpdateRecurringBillingViaEditProfile(IPTV2Entities context, User user, string list)
        {
            try
            {
                DateTime registDt = DateTime.Now;
                var rb_list = list.Split(',');

                if (rb_list.Count() > 0)
                {
                    foreach (var item in rb_list)
                    {
                        if (!String.IsNullOrEmpty(item))
                        {
                            var name = item;
                            if (MyUtility.isUserLoggedIn())
                            {
                                bool RecurringStatus = false;

                                int RecurringBillingId = 0;
                                try { RecurringBillingId = Convert.ToInt32(name.Substring(2)); }
                                catch (Exception e) { MyUtility.LogException(e); }

                                if (user != null)
                                {
                                    var billing = user.RecurringBillings.FirstOrDefault(r => r.RecurringBillingId == RecurringBillingId && r.StatusId != 2);
                                    if (billing != null)
                                    {
                                        //Check first if there is a same package with recurring turned on
                                        if (user.RecurringBillings.Count(r => r.PackageId == billing.PackageId && r.StatusId == GlobalConfig.Visible && r.RecurringBillingId != billing.RecurringBillingId) > 0)
                                        {
                                            //there is same package with recurring enabled.                                            
                                        }
                                        else
                                        {
                                            if (billing is PaypalRecurringBilling)
                                            {
                                                try
                                                {
                                                    var paypalrbilling = (PaypalRecurringBilling)billing;
                                                    if (PaymentHelper.CancelPaypalRecurring(paypalrbilling.SubscriberId))
                                                    {
                                                        billing.StatusId = RecurringStatus ? 1 : 0;
                                                        billing.UpdatedOn = registDt;
                                                        if (registDt.Date > billing.NextRun && RecurringStatus)
                                                            billing.NextRun = registDt.AddDays(1).Date;
                                                    }
                                                }
                                                catch (Exception) { }
                                            }
                                            else
                                            {
                                                billing.StatusId = RecurringStatus ? 1 : 0;
                                                billing.UpdatedOn = registDt;
                                                if (registDt.Date > billing.NextRun && RecurringStatus)
                                                    billing.NextRun = registDt.AddDays(1).Date;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e) { MyUtility.LogException(e); }
        }
コード例 #5
0
 private void SendToGigya(User user)
 {
     Dictionary<string, object> userInfo = new Dictionary<string, object>();
     userInfo.Add("firstName", user.FirstName);
     userInfo.Add("lastName", user.LastName);
     userInfo.Add("email", user.EMail);
     Dictionary<string, object> gigyaCollection = new Dictionary<string, object>();
     gigyaCollection.Add("siteUID", user.UserId);
     gigyaCollection.Add("cid", "TFCTV - Login");
     //gigyaCollection.Add("sessionExpiration", 2592000);
     gigyaCollection.Add("sessionExpiration", 432000);
     gigyaCollection.Add("userInfo", MyUtility.buildJson(userInfo));
     GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", GigyaHelpers.buildParameter(gigyaCollection));
     GigyaHelpers.setCookie(res, this.ControllerContext);
 }
コード例 #6
0
        public ActionResult Register(FormCollection fc)
        {
            SynapseResponse response = new SynapseResponse();
            Dictionary<string, object> collection = new Dictionary<string, object>();

            response.errorCode = (int)ErrorCodes.IsAlreadyAuthenticated;
            response.errorMessage = @"Please go to http://tfc.tv to register.";
            return this.Json(response, JsonRequestBehavior.AllowGet);

            if (MyUtility.isUserLoggedIn()) //User is logged in.
            {
                response.errorCode = (int)ErrorCodes.IsAlreadyAuthenticated;
                response.errorMessage = "User is already authenticated.";
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }

            if (String.IsNullOrEmpty(fc["Email"]))
            {
                response.errorCode = (int)ErrorCodes.IsEmailEmpty;
                response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsEmailEmpty);
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }
            if (String.Compare(fc["Password"], fc["ConfirmPassword"], false) != 0)
            {
                response.errorCode = (int)ErrorCodes.IsMismatchPassword;
                response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsMismatchPassword);
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }
            if (String.IsNullOrEmpty(fc["FirstName"]) || String.IsNullOrEmpty(fc["LastName"]) || String.IsNullOrEmpty(fc["CountryCode"]))
            {
                response.errorCode = (int)ErrorCodes.IsMissingRequiredFields;
                response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsMissingRequiredFields);
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }

            try
            {
                string FirstName = fc["FirstName"];
                string LastName = fc["LastName"];
                string CountryCode = fc["CountryCode"];
                string EMail = fc["Email"];
                string Password = fc["Password"];
                string City = fc["City"];
                string State = String.IsNullOrEmpty(fc["State"]) ? fc["StateDD"] : fc["State"];
                System.Guid userId = System.Guid.NewGuid();


                if (FirstName.Length > 32)
                {
                    response.errorCode = (int)ErrorCodes.LimitReached;
                    response.errorMessage = "First Name cannot exceed 32 characters.";
                    return this.Json(response, JsonRequestBehavior.AllowGet);
                }
                if (LastName.Length > 32)
                {
                    response.errorCode = (int)ErrorCodes.LimitReached;
                    response.errorMessage = "Last Name cannot exceed 32 characters.";
                    return this.Json(response, JsonRequestBehavior.AllowGet);
                }
                if (EMail.Length > 64)
                {
                    response.errorCode = (int)ErrorCodes.LimitReached;
                    response.errorMessage = "Email cannot exceed 64 characters.";
                    return this.Json(response, JsonRequestBehavior.AllowGet);
                }
                if (!String.IsNullOrEmpty(State))
                    if (State.Length > 30)
                    {
                        response.errorCode = (int)ErrorCodes.LimitReached;
                        response.errorMessage = "State cannot exceed 30 characters.";
                        return this.Json(response, JsonRequestBehavior.AllowGet);
                    }
                if (!String.IsNullOrEmpty(City))
                    if (City.Length > 50)
                    {
                        response.errorCode = (int)ErrorCodes.LimitReached;
                        response.errorMessage = "City cannot exceed 50 characters.";
                        return this.Json(response, JsonRequestBehavior.AllowGet);
                    }

                var context = new IPTV2Entities();
                User user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EMail, true) == 0);
                if (user != null)
                {
                    response.errorCode = (int)ErrorCodes.IsExistingEmail;
                    response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsExistingEmail);
                    return this.Json(response, JsonRequestBehavior.AllowGet);
                }

                /***** CHECK FOR COUNTRY CODE ****/
                if (context.Countries.Count(c => String.Compare(c.Code, CountryCode, true) == 0) <= 0)
                {
                    response.errorCode = (int)ErrorCodes.IsMissingRequiredFields;
                    response.errorMessage = "Country Code is invalid.";
                    return this.Json(response, JsonRequestBehavior.AllowGet);
                }
                else if (GlobalConfig.ExcludedCountriesFromRegistrationDropDown.Split(',').Contains(CountryCode))
                {
                    response.errorCode = (int)ErrorCodes.IsMissingRequiredFields;
                    response.errorMessage = "Country Code is invalid.";
                    return this.Json(response, JsonRequestBehavior.AllowGet);
                }

                DateTime registDt = DateTime.Now;
                user = new User()
                {
                    UserId = userId,
                    FirstName = FirstName,
                    LastName = LastName,
                    City = City,
                    State = State,
                    CountryCode = CountryCode,
                    EMail = EMail,
                    Password = MyUtility.GetSHA1(Password),
                    GigyaUID = userId.ToString(),
                    RegistrationDate = registDt,
                    LastUpdated = registDt,
                    RegistrationIp = Request.GetUserHostAddressFromCloudflare(),
                    StatusId = 1,
                    ActivationKey = Guid.NewGuid(),
                    DateVerified = registDt
                };
                string CurrencyCode = GlobalConfig.DefaultCurrency;
                Country country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, CountryCode, true) == 0);
                if (country != null)
                {
                    Currency currency = context.Currencies.FirstOrDefault(c => String.Compare(c.Code, country.CurrencyCode, true) == 0);
                    if (currency != null) CurrencyCode = currency.Code;
                }
                UserWallet wallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, CurrencyCode, true) == 0);
                if (wallet == null) // Wallet does not exist. Create new wallet for User.
                {
                    wallet = ContextHelper.CreateWallet(0, CurrencyCode, registDt);
                    user.UserWallets.Add(wallet);
                }

                var transaction = new RegistrationTransaction()
                {
                    RegisteredState = user.State,
                    RegisteredCity = user.City,
                    RegisteredCountryCode = user.CountryCode,
                    Amount = 0,
                    Currency = CurrencyCode,
                    Reference = "New Registration (Mobile)",
                    Date = registDt,
                    OfferingId = GlobalConfig.offeringId,
                    UserId = user.UserId,
                    StatusId = GlobalConfig.Visible
                };

                user.Transactions.Add(transaction);

                context.Users.Add(user);
                if (context.SaveChanges() > 0)
                {
                    if (!String.IsNullOrEmpty(fc["UID"]))
                    {
                        Dictionary<string, object> GigyaCollection = new Dictionary<string, object>();
                        collection.Add("uid", fc["UID"]);
                        collection.Add("siteUID", userId);
                        collection.Add("cid", String.Format("{0} - New User", fc["provider"]));
                        GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(collection));
                    }
                    else
                    {
                        Dictionary<string, object> userInfo = new Dictionary<string, object>();
                        userInfo.Add("firstName", user.FirstName);
                        userInfo.Add("lastName", user.LastName);
                        userInfo.Add("email", user.EMail);
                        Dictionary<string, object> gigyaCollection = new Dictionary<string, object>();
                        gigyaCollection.Add("siteUID", user.UserId);
                        gigyaCollection.Add("cid", "TFCTV - Registration");
                        gigyaCollection.Add("sessionExpiration", "0");
                        gigyaCollection.Add("newUser", true);
                        gigyaCollection.Add("userInfo", MyUtility.buildJson(userInfo));
                        GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", GigyaHelpers.buildParameter(gigyaCollection));
                        GigyaHelpers.setCookie(res, this.ControllerContext);
                    }

                    //setUserData
                    User usr = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EMail, true) == 0);
                    setUserData(usr.UserId.ToString(), usr);


                    if (usr.IsTVERegistrant == null || usr.IsTVERegistrant == false)
                    {
                        int freeTrialProductId = 0;
                        if (GlobalConfig.IsFreeTrialEnabled)
                        {
                            freeTrialProductId = MyUtility.GetCorrespondingFreeTrialProductId();
                            context = new IPTV2Entities();
                            if (GlobalConfig.TfcTvFree2StartDate < registDt && GlobalConfig.TfcTvFree2EndDate > registDt)
                            {
                                string UserCountryCode = user.CountryCode;
                                if (!GlobalConfig.isUAT)
                                    try { UserCountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy(); }
                                    catch (Exception) { }

                                var countryList = GlobalConfig.TfcTvFree2CountryWhiteList.Split(',');
                                if (countryList.Contains(UserCountryCode) && String.Compare(user.CountryCode, UserCountryCode, true) == 0)
                                    freeTrialProductId = GlobalConfig.TfcTvFree2ProductId;
                            }
                            //if (user.StatusId == GlobalConfig.Visible)
                            PaymentHelper.PayViaWallet(context, userId, freeTrialProductId, SubscriptionProductType.Package, userId, null);
                        }
                    }

                    //Publish to Activity Feed
                    List<ActionLink> actionlinks = new List<ActionLink>();
                    actionlinks.Add(new ActionLink() { text = SNSTemplates.register_actionlink_text, href = SNSTemplates.register_actionlink_href });
                    UserAction action = new UserAction()
                    {
                        actorUID = userId.ToString(),
                        userMessage = SNSTemplates.register_usermessage,
                        title = SNSTemplates.register_title,
                        subtitle = SNSTemplates.register_subtitle,
                        linkBack = SNSTemplates.register_linkback,
                        description = String.Format(SNSTemplates.register_description, FirstName),
                        actionLinks = actionlinks
                    };

                    GigyaMethods.PublishUserAction(action, userId, "external");
                    action.userMessage = String.Empty;
                    action.title = String.Empty;
                    GigyaMethods.PublishUserAction(action, userId, "internal");
                    //string verification_email = String.Format("{0}/User/Verify?email={1}&key={2}", GlobalConfig.baseUrl, EMail, user.ActivationKey.ToString());
                    //string emailBody = String.Format(GlobalConfig.EmailVerificationBodyTextOnly, FirstName, EMail, verification_email);

                    //if (!Request.IsLocal)
                    //    try { MyUtility.SendEmailViaSendGrid(EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody, MailType.TextOnly, emailBody); }
                    //    catch (Exception e) { MyUtility.LogException(e, "Unable to send email via SendGrid"); }

                    response.errorCode = (int)ErrorCodes.Success;
                    response.errorMessage = "Registration successful.";

                    GSResponse gres = GetToken(user);
                    if (gres != null)
                    {
                        SynapseToken token = new SynapseToken()
                        {
                            uid = user.UserId.ToString(),
                            token = gres.GetString("access_token", String.Empty),
                            expire = gres.GetInt("expires_in", 0),
                        };

                        response.data = token;
                    }

                    HttpCookie authCookie = SetAutheticationCookie(user.UserId.ToString());
                    SynapseCookie cookie = new SynapseCookie()
                    {
                        cookieName = authCookie.Name,
                        cookieDomain = authCookie.Domain,
                        cookiePath = authCookie.Path,
                        cookieValue = authCookie.Value
                    };
                    response.info = cookie;
                }
                else
                {
                    response.errorCode = (int)ErrorCodes.EntityUpdateError;
                    response.errorMessage = "Unable to register user";
                }
            }
            catch (Exception e)
            {
                response.errorCode = (int)ErrorCodes.UnknownError;
                response.errorMessage = e.Message;
            }
            return this.Json(response, JsonRequestBehavior.AllowGet);
        }
コード例 #7
0
 private int setUserData(string uid, User user)
 {
     SignUpModel usr = new SignUpModel()
     {
         City = user.City,
         CountryCode = user.CountryCode,
         Email = user.EMail,
         FirstName = user.FirstName,
         LastName = user.LastName,
         State = user.State
     };
     Dictionary<string, object> collection = new Dictionary<string, object>();
     collection.Add("uid", uid);
     collection.Add("data", JsonConvert.SerializeObject(usr, Formatting.None));
     //gcs.setUserData
     //GSResponse res = GigyaHelpers.createAndSendRequest("gcs.setUserData", GigyaHelpers.buildParameter(collection));
     GSResponse res = GigyaHelpers.createAndSendRequest("ids.setAccountInfo", GigyaHelpers.buildParameter(collection));
     return res.GetErrorCode();
 }
コード例 #8
0
        private void SendGiftShareToSocialNetwork(Product product, User recipient)
        {
            //Publish user action
            List<ActionLink> actionlinks = new List<ActionLink>();
            actionlinks.Add(new ActionLink() { text = SNSTemplates.actionlink_text, href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.sgift_actionlink_href) });
            List<MediaItem> mediaItems = new List<MediaItem>();
            mediaItems.Add(new MediaItem() { type = SNSTemplates.sgift_mediaitem_type, src = String.Format("{0}{1}", GlobalConfig.AssetsBaseUrl, SNSTemplates.sgift_mediaitem_src), href = String.Format("{0}{1}", GlobalConfig.baseUrl, String.Format(SNSTemplates.sgift_mediaitem_href, User.Identity.Name)) });
            UserAction action = new UserAction()
            {
                actorUID = User.Identity.Name,
                userMessage = String.Format(SNSTemplates.sgift_usermessage_external, product.Description, String.Format("{0} {1}", recipient.FirstName, recipient.LastName)),
                title = SNSTemplates.sgift_title,
                subtitle = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.sgift_subtitle),
                linkBack = String.Format(SNSTemplates.sgift_linkback, User.Identity.Name),
                description = SNSTemplates.sgift_description,
                actionLinks = actionlinks,
                mediaItems = mediaItems
            };

            var userId = new Guid(User.Identity.Name);
            var userData = MyUtility.GetUserPrivacySetting(userId);
            if (userData.IsExternalSharingEnabled.Contains("true"))
                GigyaMethods.PublishUserAction(action, new System.Guid(User.Identity.Name), "external");
            //Modify action to suit Internal feed needs
            mediaItems.Clear();
            mediaItems.Add(new MediaItem() { type = SNSTemplates.sgift_mediaitem_type, src = String.Format("{0}{1}", GlobalConfig.AssetsBaseUrl, SNSTemplates.sgift_mediaitem_src_internal), href = String.Format("{0}{1}", GlobalConfig.baseUrl, String.Format(SNSTemplates.sgift_mediaitem_href, User.Identity.Name)) });
            action.userMessage = String.Format(SNSTemplates.sgift_usermessage, product.Description, recipient.UserId, String.Format("{0} {1}", recipient.FirstName, recipient.LastName));
            action.description = String.Format(SNSTemplates.sgift_description_internal, product.Description, recipient.UserId, String.Format("{0} {1}", recipient.FirstName, recipient.LastName));
            action.mediaItems = mediaItems;
            if (userData.IsInternalSharingEnabled.Contains("true"))
                GigyaMethods.PublishUserAction(action, new System.Guid(User.Identity.Name), "internal");
        }
コード例 #9
0
        private RecurringBillingReturnValue CheckIfUserIsEnrolledToSameRecurringProductGroup(IPTV2Entities context, Offering offering, User user, Product product)
        {
            RecurringBillingReturnValue returnValue = new RecurringBillingReturnValue()
            {
                container = null,
                value = false
            };
            var profiler = MiniProfiler.Current;
            using (profiler.Step("Check Recurring Enrolment"))
            {
                try
                {

                    if (product is SubscriptionProduct)
                    {
                        // check if user is part of recurring
                        var subscriptionProduct = (SubscriptionProduct)product;
                        //Get user's recurring productGroups
                        var recurringProductGroups = user.GetRecurringProductGroups(offering);
                        if (recurringProductGroups.Contains(subscriptionProduct.ProductGroup))
                        {
                            var productPackage = context.ProductPackages.FirstOrDefault(p => p.ProductId == product.ProductId);
                            if (productPackage != null)
                            {
                                var entitlement = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == productPackage.PackageId);
                                if (entitlement != null)
                                {
                                    var container = new RecurringBillingContainer()
                                    {
                                        user = user,
                                        product = product,
                                        entitlement = entitlement,
                                        package = (Package)productPackage.Package
                                    };
                                    returnValue.value = true;
                                    returnValue.container = container;
                                }
                            }
                        }
                    }
                }
                catch (Exception e) { MyUtility.LogException(e); }
            }
            return returnValue;
        }
コード例 #10
0
        public static void AddToPaypalRecurringBilling(IPTV2Entities context, Product product, Offering offering, User user, DateTime registDt, string subscr_id, bool IsRecurringSignUp = false, int TrialProductId = 0)
        {
            try
            {
                //Check if product is subscription product
                if (product is SubscriptionProduct)
                {
                    //check if there are any recurring products that have the same productgroup
                    SubscriptionProduct subscriptionProduct = (SubscriptionProduct)product;

                    //Get user's recurring productGroups
                    var recurringProductGroups = user.GetRecurringProductGroups(offering);
                    if (!recurringProductGroups.Contains(subscriptionProduct.ProductGroup))
                    {
                        var productPackage = context.ProductPackages.FirstOrDefault(p => p.ProductId == product.ProductId);
                        if (productPackage != null)
                        {
                            var entitlement = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == productPackage.PackageId);
                            if (entitlement != null)
                            {
                                var paypalRecurringBilling = user.RecurringBillings.FirstOrDefault(r => r is PaypalRecurringBilling && r.StatusId == GlobalConfig.Visible && String.Compare(((PaypalRecurringBilling)r).SubscriberId, subscr_id, true) == 0);
                                if (paypalRecurringBilling == null)
                                {
                                    var billing = new PaypalRecurringBilling()
                                    {
                                        CreatedOn = registDt,
                                        Product = product,
                                        User = user,
                                        UpdatedOn = registDt,
                                        EndDate = entitlement.EndDate,
                                        //NextRun = entitlement.EndDate.AddDays(-3).Date, // Run day before expiry
                                        NextRun = entitlement.EndDate.Date,
                                        StatusId = GlobalConfig.Visible,
                                        Offering = offering,
                                        Package = (Package)productPackage.Package,
                                        SubscriberId = subscr_id,
                                        NumberOfAttempts = 0
                                    };
                                    context.RecurringBillings.Add(billing);
                                }
                                else
                                {
                                    if (paypalRecurringBilling.Product != null)
                                    {
                                        var recurringProduct = paypalRecurringBilling.Product;
                                        if (recurringProduct is SubscriptionProduct)
                                        {
                                            var recurringSubscriptionProduct = (SubscriptionProduct)recurringProduct;
                                            paypalRecurringBilling.NextRun = MyUtility.getEntitlementEndDate(recurringSubscriptionProduct.Duration, recurringSubscriptionProduct.DurationType, paypalRecurringBilling.NextRun != null ? (DateTime)paypalRecurringBilling.NextRun : registDt.Date);
                                            paypalRecurringBilling.UpdatedOn = DateTime.Now;
                                        }
                                    }
                                }
                                context.SaveChanges();
                            }
                            else
                            {
                                if (IsRecurringSignUp)
                                {
                                    // get  trial product
                                    var trialProduct = context.Products.FirstOrDefault(p => p.ProductId == TrialProductId);
                                    SubscriptionProduct trialSubscriptionProduct = (SubscriptionProduct)trialProduct;
                                    var billing = new PaypalRecurringBilling()
                                    {
                                        CreatedOn = registDt,
                                        Product = product,
                                        User = user,
                                        UpdatedOn = registDt,
                                        //NextRun = entitlement.EndDate.AddDays(-3).Date, // Run day before expiry                                    
                                        EndDate = MyUtility.getEntitlementEndDate(trialSubscriptionProduct.Duration, trialSubscriptionProduct.DurationType, registDt),
                                        NextRun = MyUtility.getEntitlementEndDate(trialSubscriptionProduct.Duration, trialSubscriptionProduct.DurationType, registDt),
                                        StatusId = GlobalConfig.Visible,
                                        Offering = offering,
                                        Package = (Package)productPackage.Package,
                                        SubscriberId = subscr_id,
                                        NumberOfAttempts = 0
                                    };
                                    context.RecurringBillings.Add(billing);
                                    context.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e) { MyUtility.LogException(e); }
        }
コード例 #11
0
        public ActionResult SummaryOfOrder(int id, User user, Product product, ProductPrice productPrice)
        {
            try
            {
                var registDt = DateTime.Now;
                var ExpirationDate = registDt;
                //Get entitlement end date for user
                SubscriptionProductType subscriptionType = ContextHelper.GetProductType(product);
                switch (subscriptionType)
                {
                    case SubscriptionProductType.Package:
                        PackageSubscriptionProduct PackageSubscription = (PackageSubscriptionProduct)product;
                        var package = PackageSubscription.Packages.FirstOrDefault();
                        if (package != null)
                        {
                            ViewBag.ListOfDescription = ContextHelper.GetPackageFeatures(user.CountryCode, package);

                            PackageEntitlement UserPackageEntitlement = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId);
                            if (UserPackageEntitlement != null)
                                ExpirationDate = MyUtility.getEntitlementEndDate(PackageSubscription.Duration, PackageSubscription.DurationType, ((UserPackageEntitlement.EndDate > registDt) ? UserPackageEntitlement.EndDate : registDt));
                            else
                                ExpirationDate = MyUtility.getEntitlementEndDate(PackageSubscription.Duration, PackageSubscription.DurationType, registDt);
                        }
                        break;
                    case SubscriptionProductType.Show:
                        ShowSubscriptionProduct ShowSubscription = (ShowSubscriptionProduct)product;
                        var show = ShowSubscription.Categories.FirstOrDefault();
                        if (show != null)
                        {
                            ViewBag.ShowDescription = show.Show.Blurb;
                            ShowEntitlement UserShowEntitlement = user.ShowEntitlements.FirstOrDefault(s => s.CategoryId == show.CategoryId);
                            if (UserShowEntitlement != null)
                                ExpirationDate = MyUtility.getEntitlementEndDate(ShowSubscription.Duration, ShowSubscription.DurationType, ((UserShowEntitlement.EndDate > registDt) ? UserShowEntitlement.EndDate : registDt));
                            else
                                ExpirationDate = MyUtility.getEntitlementEndDate(ShowSubscription.Duration, ShowSubscription.DurationType, registDt);
                        }
                        break;
                    case SubscriptionProductType.Episode:
                        EpisodeSubscriptionProduct EpisodeSubscription = (EpisodeSubscriptionProduct)product;
                        var episode = EpisodeSubscription.Episodes.FirstOrDefault();
                        if (episode != null)
                        {
                            EpisodeEntitlement UserEpisodeEntitlement = user.EpisodeEntitlements.FirstOrDefault(e => e.EpisodeId == episode.EpisodeId);
                            if (UserEpisodeEntitlement != null)
                                ExpirationDate = MyUtility.getEntitlementEndDate(EpisodeSubscription.Duration, EpisodeSubscription.DurationType, ((UserEpisodeEntitlement.EndDate > registDt) ? UserEpisodeEntitlement.EndDate : registDt));
                            else
                                ExpirationDate = MyUtility.getEntitlementEndDate(EpisodeSubscription.Duration, EpisodeSubscription.DurationType, registDt);
                        }
                        break;
                }
                ViewBag.ExpirationDate = ExpirationDate;
                ViewBag.ProductPrice = productPrice;
                return PartialView(product);
            }
            catch (Exception e) { MyUtility.LogException(e); }
            return null;
        }
コード例 #12
0
 public static void UpdateRecurringBillingIfExist(IPTV2Entities context, User user, DateTime registDt, Package package, bool isPayPal = false)
 {
     if (GlobalConfig.IsRecurringBillingEnabled)
     {
         try
         {
             var recurringBillings = user.RecurringBillings.Where(r => r.StatusId == GlobalConfig.Visible && r.PackageId == package.PackageId);
             if (recurringBillings != null)
             {
                 var dtRecur = isPayPal ? registDt.Date : registDt.AddDays(-3).Date;
                 foreach (var item in recurringBillings)
                 {
                     item.EndDate = registDt;
                     item.UpdatedOn = registDt;
                     item.NumberOfAttempts = 0;
                     if (item.NextRun < dtRecur)
                         item.NextRun = dtRecur;
                 }
             }
         }
         catch (Exception e) { MyUtility.LogException(e); }
     }
 }
コード例 #13
0
 public static bool HasEnrolledCreditCard(Offering offering, User user)
 {
     return user.CreditCards.Count(c => c.StatusId == GlobalConfig.Visible && c.OfferingId == offering.OfferingId) > 0;
 }
コード例 #14
0
 public static bool EnrollCreditCard(IPTV2Entities context, Offering offering, User user, DateTime registDt, CreditCardInfo info)
 {
     var retVal = false;
     if (GlobalConfig.IsRecurringBillingEnabled)
     {
         var CreditCardHash = MyUtility.GetSHA1(info.Number);
         if (user.CreditCards.Count(c => c.CreditCardHash == CreditCardHash && c.StatusId == GlobalConfig.Visible && c.OfferingId == offering.OfferingId) > 0)
         {
             // there is an active credit card attached to user
         }
         else
         {
             var paymentMethod = context.GomsPaymentMethods.FirstOrDefault(p => (p.GomsSubsidiaryId == user.GomsSubsidiaryId) && (p.Name == info.CardTypeString));
             if (paymentMethod != null)
             {
                 var creditCard = new IPTV2_Model.CreditCard()
                 {
                     CreditCardHash = CreditCardHash,
                     StatusId = GlobalConfig.Visible,
                     User = user,
                     Offering = offering,
                     LastDigits = info.Number.Right(4),
                     CreatedOn = registDt,
                     UpdatedOn = registDt,
                     GomsPaymentMethod = paymentMethod,
                     CardType = info.CardType.ToString().Replace("_", " ").ToUpper()
                 };
                 context.CreditCards.Add(creditCard);
                 if (context.SaveChanges() > 0)
                     retVal = true;
             }
         }
     }
     return retVal;
 }
コード例 #15
0
ファイル: GomsTfctv.cs プロジェクト: agentvnod/tfctvoldcode
 /// <summary>
 /// Get a user's GOMS wallet
 /// </summary>
 /// <param name="user">User with wallet to be retrieved from GOMS.  Will use the active User's wallet</param>
 /// <returns></returns>
 public RespGetWallet GetWallet(User user)
 {
     RespGetWallet result = null;
     try
     {
         if (user != null)
         {
             if (user.IsGomsRegistered)
             {
                 // get user's wallet
                 var wallet = user.UserWallets.FirstOrDefault(w => w.IsActive);
                 if (wallet != null)
                 {
                     result = GetWallet((int)user.GomsCustomerId, user.EMail, (int)wallet.GomsWalletId);
                 }
                 else
                 {
                     throw new GomsInvalidWalletException();
                 }
             }
             else
             {
                 throw new GomsUserNotRegisteredException();
             }
         }
         else
         {
             throw new GomsInvalidUserException();
         }
     }
     catch (GomsException e)
     {
         result = new RespGetWallet { IsSuccess = false, StatusCode = e.StatusCode, StatusMessage = e.StatusMessage };
     }
     return (result);
 }
コード例 #16
0
 private void ProcessWishlist(string wid, Product product, User recipient, User user)
 {
     if (!String.IsNullOrEmpty(wid))
     {
         GigyaMethods.DeleteWishlist(wid); // Delete from Wishlist
         SendGiftShareToSocialNetwork(product, recipient);
         ReceiveGiftShareToSocialNetwork(product, recipient, user);
     }
 }
コード例 #17
0
ファイル: GomsTfctv.cs プロジェクト: agentvnod/tfctvoldcode
        private GomsException WalletValidation(IPTV2Entities context, User user, int walletId)
        {
            // validate the wallet
            UserWallet thisWallet = user.UserWallets.FirstOrDefault(w => w.WalletId == walletId);
            if (thisWallet == null)
            {
                return new GomsInvalidWalletException();
            }

            if (thisWallet.GomsWalletId == null || thisWallet.GomsWalletId == 0)
            {
                // Update Subscriber Info
                var updateResult = UpdateSubscriber(context, user.UserId);
                if (!updateResult.IsSuccess)
                {
                    return new GomsException { StatusCode = updateResult.StatusCode, StatusMessage = updateResult.StatusMessage };
                }
            }
            return new GomsSuccess();
        }
コード例 #18
0
        public static string GetDealerNearUser(IPTV2Entities context, User user, int offeringId)
        {
            string dealers = String.Empty;
            try
            {
                string userIp = user.RegistrationIp;
                if (!String.IsNullOrEmpty(userIp))
                {
                    var ipLocation = MyUtility.getLocation(userIp);
                    GeoLocation location = new GeoLocation() { Latitude = ipLocation.latitude, Longitude = ipLocation.longitude };
                    SortedSet<StoreFrontDistance> result;
                    if (Convert.ToInt32(Settings.GetSettings("maximumDistance")) != 0)
                        result = StoreFront.GetNearestStores(context, offeringId, location, true, 1000);
                    else
                        result = StoreFront.GetNearestStores(context, offeringId, location, true);
                    StringBuilder sb = new StringBuilder();
                    var ctr = 0;
                    foreach (var item in result)
                    {
                        var email = item.Store.EMailAddress;
                        var fullAddress = String.Format("{0}, {1}, {2} {3}", item.Store.Address1, item.Store.City, item.Store.State, item.Store.ZipCode);
                        string li = String.Format("<li>{0}<br />Address: {1}<br />Phone: {2}</li>", item.Store.BusinessName, fullAddress, item.Store.BusinessPhone);
                        sb.AppendLine(li);
                        ctr++;
                        if (ctr + 1 > 3)
                            break;
                    }

                    dealers = sb.ToString();
                }
            }
            catch (Exception e) { Trace.WriteLine(e.Message); }
            return dealers;
        }
コード例 #19
0
 private GSResponse GetToken(User user)
 {
     SynapseUserInfo uInfo = new SynapseUserInfo() { firstName = user.FirstName, lastName = user.LastName, email = user.EMail };
     Dictionary<string, object> collection = new Dictionary<string, object>();
     collection.Add("client_id", GlobalConfig.GSapikey);
     collection.Add("client_secret", GlobalConfig.GSsecretkey);
     collection.Add("grant_type", "none");
     collection.Add("x_siteUID", user.UserId);
     collection.Add("x_sessionExpiration", 0);
     collection.Add("x_userInfo", JsonConvert.SerializeObject(uInfo));
     return GigyaHelpers.createAndSendRequest("socialize.getToken", GigyaHelpers.buildParameter(collection));
 }
コード例 #20
0
        private void ReceiveGiftShareToSocialNetwork(Product product, User recipient, User user)
        {
            //Publish user action
            List<ActionLink> actionlinks = new List<ActionLink>();
            actionlinks.Add(new ActionLink() { text = SNSTemplates.actionlink_text, href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.rgift_actionlink_href) });
            List<MediaItem> mediaItems = new List<MediaItem>();
            mediaItems.Add(new MediaItem() { type = SNSTemplates.rgift_mediaitem_type, src = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.rgift_mediaitem_src), href = String.Format("{0}{1}", GlobalConfig.baseUrl, String.Format(SNSTemplates.rgift_mediaitem_href, recipient.UserId.ToString())) });
            UserAction action = new UserAction()
            {
                actorUID = recipient.UserId.ToString(),
                userMessage = String.Format(SNSTemplates.rgift_usermessage_external, product.Description, String.Format("{0} {1}", user.FirstName, user.LastName)),
                title = SNSTemplates.rgift_title,
                subtitle = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.rgift_subtitle),
                linkBack = String.Format("{0}{1}", GlobalConfig.baseUrl, String.Format(SNSTemplates.rgift_linkback, recipient.UserId.ToString())),
                description = SNSTemplates.rgift_description,
                actionLinks = actionlinks,
                mediaItems = mediaItems
            };

            GigyaMethods.PublishUserAction(action, recipient.UserId, "external");
            //Modify action to suit Internal feed needs
            mediaItems.Clear();
            mediaItems.Add(new MediaItem() { type = SNSTemplates.rgift_mediaitem_type, src = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.rgift_mediaitem_src_internal), href = String.Format("{0}{1}", GlobalConfig.baseUrl, String.Format(SNSTemplates.rgift_mediaitem_href, recipient.UserId.ToString())) });
            action.userMessage = String.Format(SNSTemplates.rgift_usermessage, product.Description, user.UserId, String.Format("{0} {1}", user.FirstName, user.LastName));
            action.description = String.Format(SNSTemplates.rgift_description_internal, product.Description, user.UserId, String.Format("{0} {1}", user.FirstName, user.LastName));
            action.mediaItems = mediaItems;
            GigyaMethods.PublishUserAction(action, recipient.UserId, "internal");
        }
コード例 #21
0
        private static void AddTfcEverywhereEntitlement(IPTV2Entities context, int GomsProductId, string expiryDate, int serviceId, User user, int GomsTransactionId = 0)
        {
            DateTime registDt = DateTime.Now;
            var product = context.Products.FirstOrDefault(p => p.GomsProductId == GomsProductId && p.GomsProductQuantity == 1);
            if (product != null)
            {
                ProductPrice productPrice;
                try
                {
                    productPrice = product.ProductPrices.FirstOrDefault(i => i.CurrencyCode == user.Country.CurrencyCode);
                }
                catch (Exception)
                {
                    productPrice = product.ProductPrices.FirstOrDefault(i => i.CurrencyCode == GlobalConfig.DefaultCurrency);
                }

                //Create Purchase
                Purchase purchase = ContextHelper.CreatePurchase(registDt, "TFC Everywhere");
                //Create Purchase Item
                PurchaseItem purchaseItem = ContextHelper.CreatePurchaseItem(user.UserId, product, productPrice);

                var productPackage = context.ProductPackages.FirstOrDefault(p => p.ProductId == product.ProductId);
                //Create Entitlement & EntitlementRequest
                Entitlement entitlement = user.PackageEntitlements.FirstOrDefault(i => i.PackageId == productPackage.PackageId);

                user.Purchases.Add(purchase);
                user.PurchaseItems.Add(purchaseItem);


                if (entitlement != null)
                {
                    entitlement.EndDate = Convert.ToDateTime(expiryDate);
                    EntitlementRequest request = new EntitlementRequest()
                    {
                        DateRequested = registDt,
                        StartDate = registDt,
                        EndDate = entitlement.EndDate,
                        Product = productPackage.Product,
                        Source = "TFC Everywhere",
                        ReferenceId = GomsTransactionId.ToString()
                    };
                    user.EntitlementRequests.Add(request);
                    entitlement.LatestEntitlementRequest = request;
                    purchaseItem.EntitlementRequest = request;
                }
                else
                {
                    EntitlementRequest request = new EntitlementRequest()
                    {
                        DateRequested = registDt,
                        StartDate = registDt,
                        EndDate = Convert.ToDateTime(expiryDate),
                        Product = productPackage.Product,
                        Source = "TFC Everywhere",
                        ReferenceId = GomsTransactionId.ToString()
                    };

                    PackageEntitlement pkg_entitlement = new PackageEntitlement()
                    {
                        EndDate = Convert.ToDateTime(expiryDate),
                        Package = (IPTV2_Model.Package)productPackage.Package,
                        OfferingId = GlobalConfig.offeringId,
                        LatestEntitlementRequest = request
                    };

                    user.PackageEntitlements.Add(pkg_entitlement);
                    user.EntitlementRequests.Add(request);
                    purchaseItem.EntitlementRequest = request;
                }
            }
        }
コード例 #22
0
        private static void SendConfirmationEmails(User user, User recipient, Transaction transaction, string ProductNameBought, Product product, DateTime endDt, DateTime registDt, string mode, DateTime? autoRenewReminderDate = null, string GomsError = null)
        {
            if (isSendEmailEnabled)
            {
                string emailBody = String.Empty;
                string mailSubject = String.Empty;
                string toEmail = String.Empty;

                emailBody = String.Format(ExtendSubscriptionBodyWithAutoRenewTextOnly, user.FirstName, ProductNameBought, endDt.ToString("MM/dd/yyyy hh:mm:ss tt"), transaction.TransactionId, product.Name, registDt.ToString("MM/dd/yyyy hh:mm:ss tt"), transaction.Amount.ToString("F2"), transaction.Currency, mode, transaction.Reference, ((DateTime)autoRenewReminderDate).ToString("MMMM dd, yyyy"));
                mailSubject = String.Format("Your {0} has been extended", ProductNameBought);
                toEmail = user.EMail;
                if (!String.IsNullOrEmpty(GomsError))
                {
                    emailBody = String.Format(AutoRenewFailureBodyTextOnly, user.FirstName, ProductNameBought, GomsError);
                    mailSubject = "Unable to Auto-Renew your TFC.tv Subscription";
                }

                try
                {
                    if (!String.IsNullOrEmpty(toEmail))
                        SendEmailViaSendGrid(toEmail, NoReplyEmail, mailSubject, emailBody, MailType.TextOnly, emailBody);
                }
                catch (Exception e)
                {
                    throw new Exception(String.Format("SendGrid: {0}", e.Message));
                }
            }
        }
コード例 #23
0
        public ActionResult _Registration(FormCollection fc)
        {
            //fc["Email"] = "*****@*****.**";
            //fc["Password"] = "******";
            //fc["ConfirmPassword"] = "******";
            //fc["FirstName"] = "Albin";
            //fc["LastName"] = "Lim";
            //fc["CountryCode"] = "US";
            //fc["City"] = "CA";
            //fc["State"] = "CA";
            Dictionary<string, object> collection = new Dictionary<string, object>();
            ErrorCodes errorCode = ErrorCodes.UnknownError;
            string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError);
            collection = MyUtility.setError(errorCode, errorMessage);
            if (!Request.IsAjaxRequest())
            {
                collection = MyUtility.setError(ErrorCodes.UnknownError, "Your request is invalid.");
                return Content(MyUtility.buildJson(collection), "application/json");
            }


            bool isConnectedToSocialNetworks = false;
            string href = "/User/RegisterVerify";

            if (MyUtility.isUserLoggedIn()) //User is logged in.
                return RedirectToAction("Index", "Home");
            if (String.IsNullOrEmpty(fc["Email"]))
            {
                collection = MyUtility.setError(ErrorCodes.IsEmailEmpty);
                return Content(MyUtility.buildJson(collection), "application/json");
            }
            if (String.Compare(fc["Password"], fc["ConfirmPassword"], false) != 0)
            {
                collection = MyUtility.setError(ErrorCodes.IsMismatchPassword);
                return Content(MyUtility.buildJson(collection), "application/json");
            }
            if (String.IsNullOrEmpty(fc["FirstName"]) || String.IsNullOrEmpty(fc["LastName"]) || String.IsNullOrEmpty(fc["CountryCode"]))
            {
                collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields);
                return Content(MyUtility.buildJson(collection), "application/json");
            }

            RegexUtilities util = new RegexUtilities();
            //if (!MyUtility.isEmail(fc["Email"]))
            if (!util.IsValidEmail(fc["Email"]))
            {
                collection = MyUtility.setError(ErrorCodes.IsNotValidEmail);
                return Content(MyUtility.buildJson(collection), "application/json");
            }

            try
            {
                string FirstName = fc["FirstName"];
                string LastName = fc["LastName"];
                string CountryCode = fc["CountryCode"];
                string EMail = fc["Email"];
                string Password = fc["Password"];
                string City = fc["City"];
                string State = String.IsNullOrEmpty(fc["State"]) ? fc["StateDD"] : fc["State"];
                System.Guid userId = System.Guid.NewGuid();
                string provider = "tfctv";

                if (FirstName.Length > 32)
                {
                    collection = MyUtility.setError(ErrorCodes.LimitReached, "First Name cannot exceed 32 characters.");
                    return Content(MyUtility.buildJson(collection), "application/json");
                }
                if (LastName.Length > 32)
                {
                    collection = MyUtility.setError(ErrorCodes.LimitReached, "Last Name cannot exceed 32 characters.");
                    return Content(MyUtility.buildJson(collection), "application/json");
                }
                if (EMail.Length > 64)
                {
                    collection = MyUtility.setError(ErrorCodes.LimitReached, "Email cannot exceed 64 characters.");
                    return Content(MyUtility.buildJson(collection), "application/json");
                }
                if (!String.IsNullOrEmpty(State))
                    if (State.Length > 30)
                    {
                        collection = MyUtility.setError(ErrorCodes.LimitReached, "State cannot exceed 30 characters.");
                        return Content(MyUtility.buildJson(collection), "application/json");
                    }
                if (!String.IsNullOrEmpty(City))
                    if (City.Length > 50)
                    {
                        collection = MyUtility.setError(ErrorCodes.LimitReached, "City cannot exceed 50 characters.");
                        return Content(MyUtility.buildJson(collection), "application/json");
                    }

                var context = new IPTV2Entities();
                User user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EMail, true) == 0);
                if (user != null)
                {
                    collection = MyUtility.setError(ErrorCodes.IsExistingEmail);
                    return Content(MyUtility.buildJson(collection), "application/json");
                }

                /***** CHECK FOR COUNTRY CODE ****/
                if (context.Countries.Count(c => String.Compare(c.Code, CountryCode, true) == 0) <= 0)
                {
                    collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "Country Code is invalid.");
                    return Content(MyUtility.buildJson(collection), "application/json");
                }
                else if (GlobalConfig.ExcludedCountriesFromRegistrationDropDown.Split(',').Contains(CountryCode))
                {
                    collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "Country Code is invalid.");
                    return Content(MyUtility.buildJson(collection), "application/json");
                }

                if (String.IsNullOrEmpty(State))
                {
                    collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "State is required.");
                    return Content(MyUtility.buildJson(collection), "application/json");
                }
                else
                {
                    if (context.States.Count(c => c.CountryCode == CountryCode.ToUpper()) > 0)
                    {
                        if (context.States.Count(s => s.CountryCode == CountryCode.ToUpper() && (s.StateCode == State || s.Name == State)) == 0)
                        {
                            collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "State is invalid.");
                            return Content(MyUtility.buildJson(collection), "application/json");
                        }
                    }
                }


                DateTime registDt = DateTime.Now;
                user = new User()
                {
                    UserId = userId,
                    FirstName = FirstName,
                    LastName = LastName,
                    City = City,
                    State = State,
                    CountryCode = CountryCode,
                    EMail = EMail,
                    Password = MyUtility.GetSHA1(Password),
                    GigyaUID = userId.ToString(),
                    RegistrationDate = registDt,
                    LastUpdated = registDt,
                    RegistrationIp = Request.GetUserHostAddressFromCloudflare(),
                    StatusId = 0,
                    ActivationKey = Guid.NewGuid()
                };


                //UPDATE: FEB 18, 2013
                if (MyUtility.isTVECookieValid())
                    user.IsTVERegistrant = true;

                string CurrencyCode = GlobalConfig.DefaultCurrency;
                Country country = context.Countries.FirstOrDefault(c => c.Code == CountryCode);
                if (country != null)
                {
                    Currency currency = context.Currencies.FirstOrDefault(c => c.Code == country.CurrencyCode);
                    if (currency != null) CurrencyCode = currency.Code;
                }
                UserWallet wallet = user.UserWallets.FirstOrDefault(w => w.Currency == CurrencyCode);
                if (wallet == null) // Wallet does not exist. Create new wallet for User.
                {
                    wallet = ContextHelper.CreateWallet(0, CurrencyCode, registDt);
                    user.UserWallets.Add(wallet);
                }

                var transaction = new RegistrationTransaction()
                {
                    RegisteredState = user.State,
                    RegisteredCity = user.City,
                    RegisteredCountryCode = user.CountryCode,
                    Amount = 0,
                    Currency = CurrencyCode,
                    Reference = "New Registration",
                    Date = registDt,
                    OfferingId = GlobalConfig.offeringId,
                    UserId = user.UserId,
                    StatusId = GlobalConfig.Visible
                };

                user.Transactions.Add(transaction);

                context.Users.Add(user);
                if (context.SaveChanges() > 0)
                {
                    if (TempData["qs"] != null)
                    {
                        NameValueCollection qs = (NameValueCollection)TempData["qs"];
                        Dictionary<string, object> GigyaCollection = new Dictionary<string, object>();
                        collection.Add("uid", qs["UID"]);
                        collection.Add("siteUID", userId);
                        collection.Add("cid", String.Format("{0} - New User", qs["provider"]));
                        GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(collection));
                        provider = qs["provider"];
                        isConnectedToSocialNetworks = true;
                    }
                    else
                    {
                        Dictionary<string, object> userInfo = new Dictionary<string, object>();
                        userInfo.Add("firstName", user.FirstName);
                        userInfo.Add("lastName", user.LastName);
                        userInfo.Add("email", user.EMail);
                        Dictionary<string, object> gigyaCollection = new Dictionary<string, object>();
                        gigyaCollection.Add("siteUID", user.UserId);
                        gigyaCollection.Add("cid", "TFCTV - Registration");
                        gigyaCollection.Add("sessionExpiration", "0");
                        gigyaCollection.Add("newUser", true);
                        gigyaCollection.Add("userInfo", MyUtility.buildJson(userInfo));
                        GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", GigyaHelpers.buildParameter(gigyaCollection));
                        GigyaHelpers.setCookie(res, this.ControllerContext);
                    }

                    //setUserData
                    User usr = context.Users.FirstOrDefault(u => u.EMail == EMail);
                    setUserData(usr.UserId.ToString(), usr);
                    var ActivationKey = usr.ActivationKey;

                    bool isTFCnowCustomer = false;

                    if (TempData["TFCnowCustomer"] != null)
                    {
                        Customer customer = (Customer)TempData["TFCnowCustomer"];
                        usr.StatusId = 1;
                        usr.DateVerified = registDt;
                        TempData["TFCnowCustomer"] = customer;
                        href = "/Migration/Migrate";
                        if (context.SaveChanges() > 0)
                        {
                            //SetAutheticationCookie(userId.ToString());
                            isTFCnowCustomer = true;
                        }
                    }

                    if (isConnectedToSocialNetworks)
                    {
                        usr.StatusId = 1;
                        usr.DateVerified = registDt;
                        context.SaveChanges();
                    }

                    //If FreeTrial is enabled, insert free trial.
                    //if (GlobalConfig.IsFreeTrialEnabled)
                    //{
                    //    context = new IPTV2Entities();
                    //    if (isConnectedToSocialNetworks)
                    //        PaymentHelper.PayViaWallet(context, userId, GlobalConfig.FreeTrial14ProductId, SubscriptionProductType.Package, userId, null);
                    //    else
                    //        PaymentHelper.PayViaWallet(context, userId, GlobalConfig.FreeTrial7ProductId, SubscriptionProductType.Package, userId, null);
                    //    context.SaveChanges();
                    //}

                    /***** DEC 31 2012 ****/
                    //UPDATED: FEB 18, 2013 - To include checking for TVE
                    if (usr.IsTVERegistrant == null || usr.IsTVERegistrant == false)
                    {
                        int freeTrialProductId = 0;
                        if (GlobalConfig.IsFreeTrialEnabled)
                        {
                            freeTrialProductId = MyUtility.GetCorrespondingFreeTrialProductId();
                            context = new IPTV2Entities();
                            if (GlobalConfig.TfcTvFree2StartDate < registDt && GlobalConfig.TfcTvFree2EndDate > registDt)
                            {
                                string UserCountryCode = user.CountryCode;
                                if (!GlobalConfig.isUAT)
                                    try { UserCountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy(); }
                                    catch (Exception) { }

                                var countryList = GlobalConfig.TfcTvFree2CountryWhiteList.Split(',');
                                if (countryList.Contains(UserCountryCode) && String.Compare(user.CountryCode, UserCountryCode, true) == 0)
                                    freeTrialProductId = GlobalConfig.TfcTvFree2ProductId;
                            }
                            if (Request.Cookies.AllKeys.Contains("vntycok"))
                            { freeTrialProductId = GlobalConfig.FreeTrial14ProductId; }
                            if (isConnectedToSocialNetworks)
                                PaymentHelper.PayViaWallet(context, userId, freeTrialProductId, SubscriptionProductType.Package, userId, null);
                        }
                    }


                    //Publish to Activity Feed
                    List<ActionLink> actionlinks = new List<ActionLink>();
                    actionlinks.Add(new ActionLink() { text = SNSTemplates.register_actionlink_text, href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_actionlink_href) });
                    //mediaItem
                    List<MediaItem> mediaItems = new List<MediaItem>();
                    mediaItems.Add(new MediaItem() { type = SNSTemplates.register_mediaitem_type, src = String.Format("{0}{1}", GlobalConfig.AssetsBaseUrl, SNSTemplates.register_mediaitem_src), href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_mediaitem_href) });
                    UserAction action = new UserAction()
                    {
                        actorUID = userId.ToString(),
                        userMessage = SNSTemplates.register_usermessage,
                        title = SNSTemplates.register_title,
                        subtitle = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_subtitle),
                        linkBack = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_linkback),
                        description = String.Format(SNSTemplates.register_description, FirstName),
                        actionLinks = actionlinks,
                        mediaItems = mediaItems
                    };

                    GigyaMethods.PublishUserAction(action, userId, "external");
                    action.userMessage = String.Empty;
                    action.title = String.Empty;
                    action.mediaItems = null;
                    GigyaMethods.PublishUserAction(action, userId, "internal");
                    var email_err = String.Empty;
                    //FormsAuthentication.SetAuthCookie(userId.ToString(), true);
                    if (isConnectedToSocialNetworks)
                    {
                        //SetAutheticationCookie(userId.ToString());
                        if (!Request.IsLocal)
                        {
                            try { MyUtility.SendConfirmationEmail(context, usr); }
                            catch (Exception) { }
                        }

                        href = GlobalConfig.RegistrationConfirmPage;
                        //UPDATED: FEB 18, 2013
                        if (usr.IsTVERegistrant != null)
                            if ((bool)usr.IsTVERegistrant)
                            {
                                href = GlobalConfig.TVERegistrationPage;
                                MyUtility.RemoveTVECookie();
                            }
                    }
                    else
                    {
                        if (!isTFCnowCustomer)
                        {
                            //string emailBody = String.Format("Copy and paste this url to activate your TFC.tv Account {0}/User/Verify?email={1}&key={2}", GlobalConfig.baseUrl, usr.EMail, ActivationKey.ToString());
                            string verification_email = String.Format("{0}/User/Verify?key={1}", GlobalConfig.baseUrl, usr.ActivationKey.ToString());
                            string emailBody = String.Format(GlobalConfig.EmailVerificationBodyTextOnly, usr.FirstName, usr.EMail, verification_email);
                            //MyUtility.SendEmailViaSendGrid(usr.EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody);
                            if (!Request.IsLocal)
                                try
                                {
                                    //MyUtility.SendEmailViaSendGrid(usr.EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody);
                                    MyUtility.SendEmailViaSendGrid(usr.EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody, MailType.TextOnly, emailBody);
                                }
                                catch (Exception)
                                {
                                    email_err = " But we are not able to send the verification email.";
                                }
                        }
                    }

                    ////UPDATED: FEB 12, 2012
                    //if (!String.IsNullOrEmpty(fc["TVEverywhere"]))
                    //{
                    //    if (String.Compare(fc["TVEverywhere"], "0", true) == 0)
                    //    {
                    //        TempData["tempUserId"] = userId;
                    //        href = GlobalConfig.TVERegistrationPage;
                    //        TempData["isConnectedToSocialNetworks"] = isConnectedToSocialNetworks;
                    //    }
                    //}

                    if (usr.StatusId == GlobalConfig.Visible) //UPDATED: MARCH 1, 2013. Only set Authentication Cookie when user is verified.
                        SetAutheticationCookie(userId.ToString());
                    errorMessage = "Thank you! You are now registered to TFC.tv!" + email_err;
                    collection = MyUtility.setError(ErrorCodes.Success, errorMessage);
                    collection.Add("info", String.Format("{0}|{1}|{2}", user.EMail, Request.GetUserHostAddressFromCloudflare(), provider));
                    collection.Add("href", href);

                    FlagBetaKey(fc["iid"]);
                }
                else
                {
                    errorMessage = "The system encountered an unidentified error. Please try again.";
                    collection = MyUtility.setError(ErrorCodes.EntityUpdateError, errorMessage);
                }
            }
            catch (Exception e)
            {
                collection = MyUtility.setError(ErrorCodes.EntityUpdateError, e.InnerException.InnerException.Message + "<br/>" + e.InnerException.InnerException.StackTrace);
            }
            return Content(MyUtility.buildJson(collection), "application/json");
        }
コード例 #24
0
ファイル: GomsTfctv.cs プロジェクト: agentvnod/tfctvoldcode
        public void ProcessAllPendingTransactionsInGoms(IPTV2Entities context, Offering offering, User user)
        {
            string transactiontype = String.Empty;
            bool errorOccured = false; //added var errorOccured to force termination of loop if error occurs.
            var transactions = context.Transactions.Where(t => (t.GomsTransactionId == null || t.GomsTransactionId == 0) && t.OfferingId == offering.OfferingId && t.UserId == user.UserId).OrderBy(t => t.TransactionId).ToList();
            foreach (var t in transactions)
            {
                Console.WriteLine("Processing transaction:" + t.TransactionId.ToString() + " for " + t.User.EMail);
                try
                {
                    if (t is ReloadTransaction)
                    {
                        transactiontype = "Reload";
                        ProcessReloadTransactionInGoms(context, (ReloadTransaction)t);
                    }
                    else if (t is PaymentTransaction)
                    {
                        transactiontype = "Payment";
                        ProcessPaymentTransactionInGoms(context, (PaymentTransaction)t);
                    }
                    else if (t is UpgradeTransaction)
                    {
                        transactiontype = "Upgrade";
                        ProcessUpgradeTransactionInGoms(context, (UpgradeTransaction)t);
                    }
                    else if (t is MigrationTransaction)
                    {
                        transactiontype = "Migration";
                        ProcessMigrationTransactionInGoms(context, (MigrationTransaction)t);
                    }
                    else if (t is ChangeCountryTransaction)
                    {
                        transactiontype = "ChangeCountry";
                        ProcessChangeCountryTransactionInGoms(context, (ChangeCountryTransaction)t);
                    }
                    else if (t is RegistrationTransaction)
                    {
                        transactiontype = "Registration";
                        ProcessRegistrationTransactionInGoms(context, (RegistrationTransaction)t);
                    }
                    else
                    {
                        throw new Exception("Invalid transaction.");
                    }
                }
                catch (EntityCommandExecutionException) { throw; }
                catch (Exception e)
                {
                    var message = e.Message;
                    if (e is GomsException)
                        message = ((GomsException)e).StatusMessage;

                    // TODO: exception processing, put in error digest
                    Console.WriteLine(String.Format("{0}: {1}", transactiontype, message));
                    // update GomsRemarks in transaction
                    try
                    {
                        t.GomsRemarks = message;
                        context.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error in saving GomsRemarks:" + ex.Message);
                    }
                    errorOccured = true;
                }
                if (errorOccured) break;
            }
        }
コード例 #25
0
        //[HttpPost]
        //public string Register(SignUpModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        var context = new IPTV2Entities();
        //        int userExist = context.Users.Where(u => u.EMail == model.Email).Count();
        //        if (userExist == 0) // new user
        //        {
        //            var userId = System.Guid.NewGuid();
        //            User user = new IPTV2_Model.User();
        //            user.UserId = userId;
        //            user.EMail = model.Email;
        //            user.FirstName = model.FirstName;
        //            user.LastName = model.LastName;
        //            user.Password = model.Password;
        //            user.GigyaUID = userId.ToString();
        //            //user.Country = model.Country;
        //            try
        //            {
        //                context.Users.Add(user);
        //                string CurrencyCode = GlobalConfig.DefaultCurrency;
        //                UserWallet wallet = user.UserWallets.FirstOrDefault(w => w.Currency == CurrencyCode);
        //                if (wallet == null) // Wallet does not exist. Create new wallet for User.
        //                {
        //                    wallet = ContextHelper.CreateWallet(0, CurrencyCode);
        //                    user.UserWallets.Add(wallet);
        //                }

        //                int result = context.SaveChanges();
        //                int notifyRegistration = 0;
        //                if (result == 1)
        //                {
        //                    //check if user comes from Gigya
        //                    if (TempData["qs"] != null)
        //                    {
        //                        NameValueCollection qs = (NameValueCollection)TempData["qs"];
        //                        TempData["qs"] = null;
        //                        //notifyRegistration
        //                        Dictionary<string, string> collection = new Dictionary<string, string>();
        //                        collection.Add("uid", qs["UID"]);
        //                        collection.Add("siteUID", userId.ToString());
        //                        collection.Add("cid", String.Format("{0} - New User", qs["provider"]));
        //                        GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(collection));
        //                        notifyRegistration = res.GetErrorCode();
        //                    }
        //                    //return RedirectToAction("Index", "Home", new { register = notifyRegistration });
        //                    return notifyRegistration.ToString();
        //                }
        //            }
        //            catch (Exception e) { Debug.WriteLine(e.InnerException); throw; }
        //        }
        //        else
        //            return "2";
        //        //ModelState.AddModelError("TFCTV_ERROR", "Email is already taken.");
        //    }
        //    //return View(model);
        //    return "1";
        //}

        //[HttpPost]
        //public ActionResult _Register(FormCollection fc)
        //{
        //    Dictionary<string, object> collection = new Dictionary<string, object>();
        //    ErrorCodes errorCode = ErrorCodes.UnknownError;
        //    string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError);
        //    collection = MyUtility.setError(errorCode, errorMessage);
        //    bool isConnectedToSocialNetworks = false;

        //    if (MyUtility.isUserLoggedIn()) //User is logged in.
        //        return RedirectToAction("Index", "Home");
        //    if (String.IsNullOrEmpty(fc["Email"]))
        //    {
        //        collection = MyUtility.setError(ErrorCodes.IsEmailEmpty, MyUtility.getErrorMessage(ErrorCodes.IsEmailEmpty));
        //        return Content(MyUtility.buildJson(collection), "application/json");
        //    }
        //    if (String.Compare(fc["Password"], fc["ConfirmPassword"], false) != 0)
        //    {
        //        collection = MyUtility.setError(ErrorCodes.IsMismatchPassword, MyUtility.getErrorMessage(ErrorCodes.IsMismatchPassword));
        //        return Content(MyUtility.buildJson(collection), "application/json");
        //    }
        //    if (String.IsNullOrEmpty(fc["FirstName"]) || String.IsNullOrEmpty(fc["LastName"]) || String.IsNullOrEmpty(fc["CountryCode"]))
        //    {
        //        collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, MyUtility.getErrorMessage(ErrorCodes.IsExistingEmail));
        //        return Content(MyUtility.buildJson(collection), "application/json");
        //    }

        //    if (!MyUtility.isEmail(fc["Email"]))
        //    {
        //        collection = MyUtility.setError(ErrorCodes.IsNotValidEmail, MyUtility.getErrorMessage(ErrorCodes.IsNotValidEmail));
        //        return Content(MyUtility.buildJson(collection), "application/json");
        //    }

        //    try
        //    {
        //        string FirstName = fc["FirstName"];
        //        string LastName = fc["LastName"];
        //        string CountryCode = fc["CountryCode"];
        //        string EMail = fc["Email"];
        //        string Password = fc["Password"];
        //        string City = fc["City"];
        //        string State = String.IsNullOrEmpty(fc["State"]) ? fc["StateDD"] : fc["State"];
        //        System.Guid userId = System.Guid.NewGuid();
        //        string provider = "tfctv";

        //        var context = new IPTV2Entities();
        //        User user = context.Users.FirstOrDefault(u => u.EMail == EMail);
        //        if (user != null)
        //        {
        //            collection = MyUtility.setError(ErrorCodes.IsExistingEmail, MyUtility.getErrorMessage(ErrorCodes.IsExistingEmail));
        //            return Content(MyUtility.buildJson(collection), "application/json");
        //        }
        //        DateTime registDt = DateTime.Now;
        //        user = new User()
        //        {
        //            UserId = userId,
        //            FirstName = FirstName,
        //            LastName = LastName,
        //            City = City,
        //            State = State,
        //            CountryCode = CountryCode,
        //            EMail = EMail,
        //            Password = MyUtility.GetSHA1(Password),
        //            GigyaUID = userId.ToString(),
        //            RegistrationDate = registDt,
        //            LastUpdated = registDt,
        //            RegistrationIp = Request.GetUserHostAddressFromCloudflare(),
        //            StatusId = 0,
        //            ActivationKey = Guid.NewGuid()
        //        };
        //        string CurrencyCode = GlobalConfig.DefaultCurrency;
        //        Country country = context.Countries.FirstOrDefault(c => c.Code == CountryCode);
        //        if (country != null)
        //        {
        //            Currency currency = context.Currencies.FirstOrDefault(c => c.Code == country.CurrencyCode);
        //            if (currency != null) CurrencyCode = currency.Code;
        //        }
        //        UserWallet wallet = user.UserWallets.FirstOrDefault(w => w.Currency == CurrencyCode);
        //        if (wallet == null) // Wallet does not exist. Create new wallet for User.
        //        {
        //            wallet = ContextHelper.CreateWallet(0, CurrencyCode, registDt);
        //            user.UserWallets.Add(wallet);
        //        }
        //        context.Users.Add(user);
        //        if (context.SaveChanges() > 0)
        //        {
        //            if (TempData["qs"] != null)
        //            {
        //                NameValueCollection qs = (NameValueCollection)TempData["qs"];
        //                Dictionary<string, object> GigyaCollection = new Dictionary<string, object>();
        //                collection.Add("uid", qs["UID"]);
        //                collection.Add("siteUID", userId);
        //                collection.Add("cid", String.Format("{0} - New User", qs["provider"]));
        //                GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(collection));
        //                provider = qs["provider"];
        //                isConnectedToSocialNetworks = true;
        //            }
        //            else
        //            {
        //                Dictionary<string, object> userInfo = new Dictionary<string, object>();
        //                userInfo.Add("firstName", user.FirstName);
        //                userInfo.Add("lastName", user.LastName);
        //                userInfo.Add("email", user.EMail);
        //                Dictionary<string, object> gigyaCollection = new Dictionary<string, object>();
        //                gigyaCollection.Add("siteUID", user.UserId);
        //                gigyaCollection.Add("cid", "TFCTV - Registration");
        //                gigyaCollection.Add("sessionExpiration", "0");
        //                gigyaCollection.Add("newUser", true);
        //                gigyaCollection.Add("userInfo", MyUtility.buildJson(userInfo));
        //                GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", GigyaHelpers.buildParameter(gigyaCollection));
        //                GigyaHelpers.setCookie(res, this.ControllerContext);
        //            }

        //            //setUserData
        //            User usr = context.Users.FirstOrDefault(u => u.EMail == EMail);
        //            setUserData(usr.UserId.ToString(), usr);

        //            if (isConnectedToSocialNetworks)
        //            {
        //                usr.StatusId = 1;
        //                usr.DateVerified = registDt;
        //            }

        //            //If FreeTrial is enabled, insert free trial.
        //            if (GlobalConfig.IsFreeTrialEnabled)
        //            {
        //                context = new IPTV2Entities();
        //                PaymentHelper.PayViaWallet(context, userId, GlobalConfig.FreeTrial14ProductId, SubscriptionProductType.Package, userId, null);
        //                context.SaveChanges();
        //            }

        //            //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.baseUrl, 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");

        //            //FormsAuthentication.SetAuthCookie(userId.ToString(), true);
        //            SetAutheticationCookie(userId.ToString());
        //            errorMessage = "Thank you! You are now registered to TFC.tv!";
        //            collection = MyUtility.setError(ErrorCodes.Success, errorMessage);
        //            collection.Add("info", String.Format("{0}|{1}|{2}", user.EMail, Request.GetUserHostAddressFromCloudflare(), provider));

        //        }
        //        else
        //        {
        //            errorMessage = "The system encountered an unidentified error. Please try again.";
        //            collection = MyUtility.setError(ErrorCodes.EntityUpdateError, errorMessage);
        //        }
        //    }
        //    catch (Exception e) { Debug.WriteLine(e.InnerException); throw; }
        //    return Content(MyUtility.buildJson(collection), "application/json");
        //}

        private int setUserData(string uid, User user)
        {
            try
            {
                //SignUpModel usr = new SignUpModel()
                //{
                //    City = user.City,
                //    CountryCode = user.CountryCode,
                //    Email = user.EMail,
                //    FirstName = user.FirstName,
                //    LastName = user.LastName,
                //    State = user.State
                //};

                GigyaUserData2 userData = new GigyaUserData2()
                {
                    city = user.City,
                    country = user.CountryCode,
                    email = user.EMail,
                    firstName = user.FirstName,
                    lastName = user.LastName,
                    state = user.State
                };

                Dictionary<string, object> collection = new Dictionary<string, object>();
                collection.Add("uid", uid);
                //collection.Add("data", JsonConvert.SerializeObject(usr, Formatting.None));
                collection.Add("profile", JsonConvert.SerializeObject(userData, Formatting.None));
                //gcs.setUserData
                //GSResponse res = GigyaHelpers.createAndSendRequest("gcs.setUserData", GigyaHelpers.buildParameter(collection));
                GSResponse res = GigyaHelpers.createAndSendRequest("ids.setAccountInfo", GigyaHelpers.buildParameter(collection));
                return res.GetErrorCode();
            }
            catch (Exception) { }
            return 0;
        }
コード例 #26
0
ファイル: GomsTfctv.cs プロジェクト: agentvnod/tfctvoldcode
 public RespCancelRecurringPayment CancelRecurringPayment(User user, Product product)
 {
     RespCancelRecurringPayment result = null;
     InitializeServiceClient();
     try
     {
         TestConnect();
         ReqCancelRecurringPayment req = new ReqCancelRecurringPayment()
         {
             CustomerId = (int)user.GomsCustomerId,
             Email = user.EMail,
             UID = ServiceUserId,
             PWD = ServicePassword,
             ServiceId = (int)user.GomsServiceId,
             ItemId = (int)product.GomsProductId,
         };
         result = _serviceClient.CancelRecurringPayment(req);
         return result;
     }
     catch (GomsException e)
     {
         result = new RespCancelRecurringPayment { IsSuccess = false, StatusCode = e.StatusCode, StatusMessage = e.StatusMessage };
     }
     return (result);
 }
コード例 #27
0
        private void UpdateRecurringBillingViaEditProfile2(IPTV2Entities context, User user, string list, bool? enable)
        {
            try
            {
                if (User.Identity.IsAuthenticated)
                {
                    var rb_list = list.Replace("rs", "");
                    var billingIds = MyUtility.StringToIntList(rb_list);
                    DateTime registDt = DateTime.Now;
                    if (billingIds.Count() > 0)
                    {
                        var gomsService = new GomsTfcTv();
                        var recurring_billings = user.RecurringBillings.Where(r => billingIds.Contains(r.RecurringBillingId) && r.StatusId != 2);
                        if (recurring_billings != null)
                        {
                            if (recurring_billings.Count() > 0)
                            {
                                bool RecurringStatus = false;
                                if (enable != null)
                                    RecurringStatus = (bool)enable;

                                var CurrencyCode = GlobalConfig.DefaultCurrency;
                                try { CurrencyCode = user.Country.CurrencyCode; }
                                catch (Exception) { }

                                foreach (var billing in recurring_billings)
                                {
                                    string cancellation_remarks = String.Empty;
                                    string reference = String.Empty;
                                    bool serviceUpdateSuccess = false;

                                    if (user.RecurringBillings.Count(r => r.PackageId == billing.PackageId && r.StatusId == GlobalConfig.Visible && r.RecurringBillingId != billing.RecurringBillingId) > 0)
                                    {
                                        //there is same package with recurring enabled.                                            
                                    }
                                    else
                                    {
                                        if (billing is PaypalRecurringBilling)
                                        {
                                            try
                                            {
                                                var paypalrbilling = (PaypalRecurringBilling)billing;

                                                billing.StatusId = RecurringStatus ? 1 : 0;
                                                billing.UpdatedOn = registDt;
                                                if (registDt.Date > billing.NextRun && RecurringStatus)
                                                    billing.NextRun = registDt.AddDays(1).Date;
                                                if (!RecurringStatus)
                                                {
                                                    try
                                                    {
                                                        if (PaymentHelper.CancelPaypalRecurring(paypalrbilling.SubscriberId))
                                                        {
                                                            reference = String.Format("PayPal billing id {0} cancelled", billing.RecurringBillingId);
                                                            cancellation_remarks = String.Format("{0} - PayPal Recurring Billing Id cancelled", billing.RecurringBillingId);
                                                            serviceUpdateSuccess = true;
                                                        }
                                                    }
                                                    catch (Exception) { }
                                                }
                                            }
                                            catch (Exception) { }
                                        }
                                        else
                                        {
                                            billing.StatusId = RecurringStatus ? 1 : 0;
                                            billing.UpdatedOn = registDt;
                                            if (registDt.Date > billing.NextRun && RecurringStatus)
                                                billing.NextRun = registDt.AddDays(1).Date;

                                            if (!RecurringStatus)
                                            {
                                                try
                                                {
                                                    var result = gomsService.CancelRecurringPayment(user, billing.Product);
                                                    if (result.IsSuccess)
                                                    {
                                                        reference = String.Format("Credit Card billing id {0} cancelled", billing.RecurringBillingId);
                                                        cancellation_remarks = String.Format("{0} - Credit Card Recurring Billing Id cancelled", billing.RecurringBillingId);
                                                        serviceUpdateSuccess = true;
                                                    }
                                                    else
                                                        throw new Exception(result.StatusMessage);
                                                }
                                                catch (Exception e) { MyUtility.LogException(e); }
                                            }
                                        }

                                        if (!RecurringStatus && 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);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e) { MyUtility.LogException(e); }
        }
コード例 #28
0
ファイル: GomsTfctv.cs プロジェクト: agentvnod/tfctvoldcode
 /// <summary>
 /// Retrieve user's info from GOMS
 /// </summary>
 /// <param name="user">User to get info from GOMS</param>
 /// <returns></returns>
 public RespGetSubscriberInfo GetUser(User user)
 {
     RespGetSubscriberInfo result = null;
     try
     {
         if (user != null)
         {
             if (user.IsGomsRegistered)
             {
                 result = GetUser((int)user.GomsCustomerId, user.EMail);
             }
             else
             {
                 throw new GomsUserNotRegisteredException();
             }
         }
         else
         {
             throw new GomsInvalidUserException();
         }
     }
     catch (GomsException e)
     {
         result = new RespGetSubscriberInfo { IsSuccess = false, StatusCode = e.StatusCode, StatusMessage = e.StatusMessage };
     }
     return (result);
 }
コード例 #29
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);
        }
コード例 #30
0
 private static int GetConvertedDaysFromFreeTrial(User user)
 {
     DateTime registDt = DateTime.Now;
     var freeTrialPackageIds = MyUtility.StringToIntList(GlobalConfig.FreeTrialPackageIds);
     var freeTrialPackage = user.PackageEntitlements.FirstOrDefault(p => freeTrialPackageIds.Contains(p.PackageId) && p.EndDate > registDt);
     if (freeTrialPackage != null)
     {
         DateTime tempDt = DateTime.Parse(registDt.ToShortDateString());
         int convertedDays = freeTrialPackage.EndDate.Subtract(tempDt).Days;
         if (convertedDays <= 1)
             return 0;
         return convertedDays;
     }
     return 0;
 }