public ActionResult Link(FormCollection fc)
        {
            SynapseResponse response = new SynapseResponse();

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

            try
            {
                string EmailAddress = fc["EmailAddress"];
                string Password = fc["Password"];
                var context = new IPTV2Entities();
                var user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EmailAddress, true) == 0);
                if (user == null)
                {
                    response.errorCode = (int)ErrorCodes.UserDoesNotExist;
                    response.errorMessage = "User does not exist.";
                }
                else
                {
                    Password = MyUtility.GetSHA1(Password);
                    if (String.Compare(user.EMail, EmailAddress, true) == 0 && String.Compare(user.Password, Password, false) == 0)
                    {
                        /** notifyRegistration **/
                        Dictionary<string, object> regCollection = new Dictionary<string, object>();

                        regCollection.Add("siteUID", user.UserId.ToString());
                        if (!String.IsNullOrEmpty(fc["UID"]))
                        {
                            regCollection.Add("uid", Uri.UnescapeDataString(fc["UID"]));
                            regCollection.Add("cid", String.Format("{0} - New User", fc["provider"]));
                        }
                        GSResponse notifyRegistration = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(regCollection));

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

                                response.data = token;
                            }
                            response.errorCode = (int)ErrorCodes.Success;
                            response.errorMessage = "Linking successful!";
                            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.FailedToLinkAccount;
                            response.errorMessage = "Unable to link your account. Please try again." + notifyRegistration.GetErrorMessage() + " " + notifyRegistration.GetErrorCode();
                        }
                    }
                    else
                    {
                        response.errorCode = (int)ErrorCodes.IsWrongPassword;
                        response.errorMessage = "Invalid email/password combination.";
                    }
                }
            }
            catch (Exception) { throw; }
            return this.Json(response, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Social()
        {
            NameValueCollection qs = Request.Params;
            SynapseResponse response = new SynapseResponse();
            string gigyaUID = Uri.UnescapeDataString(qs["UID"]);
            bool isRequestValid = SigUtils.ValidateUserSignature(gigyaUID, Uri.UnescapeDataString(qs["timestamp"]), GlobalConfig.GSsecretkey, Uri.UnescapeDataString(qs["signature"]));
            if (isRequestValid)
            {
                var isNewUser = !Convert.ToBoolean(qs["isSiteUID"]); // If isSiteUID=='false' , this means the UID was generated by Gigya, hence the user is new. !(false) == true
                if (isNewUser)
                {
                    //TempData["qs"] = qs; //bring the parameters to the next view
                    //return RedirectToAction("Index");

                    response.errorCode = (int)ErrorCodes.IsNewSiteUser;
                    response.errorMessage = "Register the user";
                    response.data = qs;
                }
                else
                {
                    //FormsAuthentication.SetAuthCookie(gigyaUID, true); //Authenticate user to our site.
                    SetAutheticationCookie(gigyaUID);
                    var context = new IPTV2Entities();
                    User user = context.Users.FirstOrDefault(u => u.UserId == new System.Guid(gigyaUID));
                    if (user != null)
                    {
                        SynapseCookie cookie = new SynapseCookie()
                        {
                            cookieName = FormsAuthentication.FormsCookieName,
                            cookiePath = FormsAuthentication.FormsCookiePath,
                            cookieDomain = FormsAuthentication.CookieDomain
                        };
                        HttpCookie authCookie = SetAutheticationCookie(user.UserId.ToString());
                        cookie.cookieValue = authCookie.Value;
                        response.errorCode = (int)ErrorCodes.Success;
                        response.errorMessage = "Login success";
                        response.info = cookie;
                        GSResponse res = GetToken(user);
                        if (res != null)
                        {
                            SynapseToken token = new SynapseToken()
                            {
                                uid = user.UserId.ToString(),
                                token = res.GetString("access_token", String.Empty),
                                expire = res.GetInt("expires_in", 0),
                            };

                            response.data = token;
                        }
                    }
                    else
                    {
                        response.errorCode = (int)ErrorCodes.UserDoesNotExist;
                        response.errorMessage = "User does not exist";
                    }
                }
            }
            else
            {
                response.errorCode = (int)ErrorCodes.IsInvalidRequest;
                response.errorMessage = "User does not exist";
            }
            return this.Json(response, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Register(FormCollection fc)
        {
            SynapseResponse response = new SynapseResponse();
            Dictionary<string, object> collection = new Dictionary<string, object>();

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

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

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

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


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

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

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

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

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

                user.Transactions.Add(transaction);

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

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


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

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

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

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

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

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

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

                        response.data = token;
                    }

                    HttpCookie authCookie = SetAutheticationCookie(user.UserId.ToString());
                    SynapseCookie cookie = new SynapseCookie()
                    {
                        cookieName = authCookie.Name,
                        cookieDomain = authCookie.Domain,
                        cookiePath = authCookie.Path,
                        cookieValue = authCookie.Value
                    };
                    response.info = cookie;
                }
                else
                {
                    response.errorCode = (int)ErrorCodes.EntityUpdateError;
                    response.errorMessage = "Unable to register user";
                }
            }
            catch (Exception e)
            {
                response.errorCode = (int)ErrorCodes.UnknownError;
                response.errorMessage = e.Message;
            }
            return this.Json(response, JsonRequestBehavior.AllowGet);
        }
        public JsonResult vLogin(string email, string pw)
        {
            SynapseResponse response = new SynapseResponse();
            response.callId = MyUtility.GetSHA1((String.Format("{0}{1}", Guid.NewGuid().ToString(), DateTime.Now.ToString()))).ToLower();
            try
            {
                string EmailAddress = email;
                string Password = pw;
                var context = new IPTV2Entities();

                if (String.IsNullOrEmpty(EmailAddress))
                {
                    response.errorCode = (int)ErrorCodes.IsMissingRequiredFields;
                    response.errorMessage = "Email address is required.";
                }

                if (String.IsNullOrEmpty(Password))
                {
                    response.errorCode = (int)ErrorCodes.IsMissingRequiredFields;
                    response.errorMessage = "Password is required.";
                }

                var user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EmailAddress, true) == 0);
                if (user == null)
                {
                    response.errorCode = (int)ErrorCodes.UserDoesNotExist;
                    response.errorMessage = "User does not exist";
                }
                else
                {
                    Password = MyUtility.GetSHA1(Password);
                    if (String.Compare(user.EMail, EmailAddress, true) == 0 && String.Compare(user.Password, Password, false) == 0)
                    {
                        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));
                        GSResponse res = GigyaHelpers.createAndSendRequest("socialize.getToken", GigyaHelpers.buildParameter(collection));
                        SynapseCookie cookie = new SynapseCookie()
                        {
                            cookieName = FormsAuthentication.FormsCookieName,
                            cookiePath = FormsAuthentication.FormsCookiePath,
                            cookieDomain = FormsAuthentication.CookieDomain
                        };
                        if (res.GetErrorCode() == 0)
                        { // Successful login to Gigya
                            HttpCookie authCookie = SetAutheticationCookie(user.UserId.ToString());
                            cookie.cookieValue = authCookie.Value;
                            ContextHelper.SaveSessionInDatabase(context, user, authCookie.Value);
                            SynapseToken token = new SynapseToken()
                            {
                                uid = user.UserId.ToString(),
                                token = res.GetString("access_token", String.Empty),
                                expire = res.GetInt("expires_in", 0),
                            };
                            response.data = token;
                            response.info = cookie;
                        }
                        else
                        {
                            response.errorCode = res.GetErrorCode();
                            response.errorMessage = "Gigya encountered an error logging you in, please try again";
                            response.errorDetails = res.GetErrorMessage();
                        }
                    }
                    else
                    {
                        response.errorCode = (int)ErrorCodes.IsWrongPassword;
                        response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsWrongPassword);
                    }
                }
            }
            catch (Exception e) { response.errorCode = (int)ErrorCodes.UnknownError; response.errorMessage = "System encountered an unspecified error, please try again"; response.errorDetails = e.Message; }
            return this.Json(response, JsonRequestBehavior.AllowGet);
        }