public Task <GSResponse> RemoveConnectionAsync(GSObject @params) { var tcs = new TaskCompletionSource <GSResponse>(); RemoveConnection(@params, new GSRespnseActionListener(tcs), null); return(tcs.Task); }
public Task <GSResponse> AddConnectionAsync(Activity activity, GSObject @params) { var tcs = new TaskCompletionSource <GSResponse>(); AddConnection(activity, @params, new GSRespnseActionListener(tcs), null); return(tcs.Task); }
public Task <GSResponse> SendRequestAsync(string method, GSObject @params, bool useHTTPS) { var tcs = new TaskCompletionSource <GSResponse>(); SendRequest(method, @params, useHTTPS, new GSRespnseActionListener(tcs), null); return(tcs.Task); }
private static GSObject GenerateIdentity(GSObject identity) { identity.Put("providerUID", GenerateString(20)); identity.Put("nickname", GenerateString(20)); identity.Put("firstName", GenerateString(8)); identity.Put("lastName", GenerateString(10)); identity.Put("email", "user_"+GenerateString(16)+ "@" + GenerateString(6) + ".com"); identity.Put("address", GenerateString(30)); GSObject phone = new GSObject(); GSArray phones = new GSArray(); phone.Put("type", "mobile"); phone.Put("number", GenerateString(9)); phones.Add(phone); phone = new GSObject(); phone.Put("type", "home"); phone.Put("number", GenerateString(9)); phones.Add(phone); phone = new GSObject(); phone.Put("type", "work"); phone.Put("number", GenerateString(9)); phones.Add(phone); identity.Put("phones", phones); return identity; }
public Task <GSResponse> LoginAsync(Activity activity, GSObject @params, bool silent) { var tcs = new TaskCompletionSource <GSResponse>(); Login(activity, @params, new GSRespnseActionListener(tcs), silent, null); return(tcs.Task); }
static void CastTester() { MyClass myClass = new MyClass() { IntField = 10, IntProperty = 11, StringField = "ShacharField", StringProperty = "ShacharProperty", }; myClass.MyInnerClassProperty = new MyInnerClass(); myClass.MyInnerClassProperty.IntField = 12; myClass.MyInnerClassProperty.MyClassListProperty = new List <MyClass>(); myClass.MyInnerClassProperty.MyClassListProperty.Add(new MyClass { IntField = 13 }); GSObject gsObj = new GSObject(myClass); MyClass clone = gsObj.Cast <MyClass>(); bool equals = AreEquals(myClass, clone); Debug.Assert(equals, "objects comparison failed"); gsObj.Put("StringProperty", new GSObject(new GetUserInfoRequestParams())); clone = gsObj.Cast <MyClass>(); bool serializeToString = clone.StringProperty.Equals(new GSObject(new GetUserInfoRequestParams()).ToString()); Debug.Assert(serializeToString, "object to string serialize is not working"); }
public Task <GSResponse> SendRequestAsync(string method, GSObject @params, int timeoutMS) { var tcs = new TaskCompletionSource <GSResponse>(); SendRequest(method, @params, new GSRespnseActionListener(tcs), null, timeoutMS); return(tcs.Task); }
static internal void HandleMessage(GSInstance gsInstance, GSObject messageData) { var message = GSMessage.CreateMessageFromObject(gsInstance, messageData); if (_AllMessages != null) { _AllMessages(message); } message.NotifyListeners(); }
public GSResponse Send(string uid, string apiKey, string secretKey, string apiMethod, string json, bool useHTTPS, string apiDomain, out string format) { GSObject dict = new GSObject(json); dict.Put("uid", uid); format = dict.GetString("format", "json"); GSRequest req = new GSRequest(apiKey, secretKey, apiMethod, dict, useHTTPS); req.APIDomain = ""; return(req.Send()); }
private void verifyResponseSignature(GSResponse res, string format) { if (!format.Equals("xml", StringComparison.InvariantCultureIgnoreCase)) { GSObject data = res.GetData(); if (null != data) { if (cbMethods.Text.IndexOf("getUserInfo", StringComparison.InvariantCultureIgnoreCase) > -1) { string uid = data.GetString("UID", ""); string uidSig = data.GetString("UIDSignature", ""); string sigTimestamp = data.GetString("signatureTimestamp", ""); if (SigUtils.ValidateUserSignature(uid, sigTimestamp, txtSecKey.Text, uidSig)) { lblVerifiedSig.Text = "Signature is verified"; lblVerifiedSig.ForeColor = Color.Green; } else { lblVerifiedSig.Text = "Invalid signature !!!"; lblVerifiedSig.ForeColor = Color.Red; } } if (cbMethods.Text.IndexOf("getFriendsInfo", StringComparison.InvariantCultureIgnoreCase) > -1) { GSArray friends = data.GetArray("friends"); if (null != friends && friends.Length > 0) { GSObject firstFriend = friends.GetObject(0); string friendSig = firstFriend.GetString("friendshipSignature"); string tsSig = firstFriend.GetString("signatureTimestamp"); string friendUID = firstFriend.GetString("UID"); if (SigUtils.ValidateFriendSignature(txtUID.Text, tsSig, friendUID, txtSecKey.Text, friendSig)) { lblVerifiedSig.Text = "1ST friend's signature is verified"; lblVerifiedSig.ForeColor = Color.Green; } else { lblVerifiedSig.Text = "Invalid signature (1ST friend's) !!!"; lblVerifiedSig.ForeColor = Color.Red; } } } } } }
public void LoadComments() { var parameters = new GSObject(); parameters["categoryID"] = "comments_demo"; parameters["streamID"] = "android"; var pluginFragment = GSPluginFragment.NewInstance("comments.commentsUI", parameters); pluginFragment.Load += (sender, e) => Console.WriteLine("Comments UI has finished loading"); pluginFragment.Event += (sender, e) => Console.WriteLine("Received plugin event from Comments UI - " + e.Event.GetString("eventName", "")); pluginFragment.Error += (sender, e) => Console.WriteLine("Error in Comments UI - " + e.Error.GetInt("errorCode", -1)); SupportFragmentManager .BeginTransaction() .Add(Resource.Id.comments_container, pluginFragment) .Commit(); }
/// <summary> /// Factory method which creates a strongly typed message from the object data provided. /// </summary> internal static GSMessage CreateMessageFromObject(GSInstance gsInstance, GSObject messageData) { if (messageData.ContainsKey("extCode")) { if (handlers.ContainsKey(messageData.Type + "_" + messageData.GetString("extCode"))) { var message = handlers[messageData.Type + "_" + messageData.GetString("extCode")](messageData); message.gsInstance = gsInstance; return(message); } } if (handlers.ContainsKey(messageData.Type)) { var message = handlers[messageData.Type](messageData); message.gsInstance = gsInstance; return(message); } return(null); }
/// <summary> /// Call to accounts.getJWT to generate an id_token - a JWT to validate after /// </summary> public string GetJWT() { var clientParams = new GSObject(); clientParams.Put("fields", "profile.firstName,profile.lastName,email,data.userKey"); clientParams.Put("targetUID", targetUID); var req = new GSRequest( apiKey, secret, "accounts.getJWT", clientParams) { APIDomain = apiDomain }; var res = req.Send(); Assert.IsTrue(res.GetErrorCode() == 0, "res.GetErrorCode() != 0"); return(res.GetData().GetString("id_token")); }
static void TestGSObjectAndGSArray() { // Test object string st1 = "{'key1': 1.1, 'item1':'ITEM1', 'key2': {'item4':'ITEM4'}, 'array1':[1.3,'hello',{'item2':'ITEM2'},[11,12],[{'item3':'ITEM3'}]]}"; GSObject gsObj = new GSObject(st1); st1 = gsObj.ToString(); // Test array string st2 = "[1, 1.2, 'hello', true, null, {}, {'key1':'val1'}, [11, 22, 33, 33.3, false, null, {}, {'key2':'val2', 'key3':[111,222,333]}]]"; GSArray gsArr = new GSArray(st2); st2 = gsArr.ToString(); // Test extracting values from object object y = gsObj.GetArray("array1").GetArray(4).GetObject(0); foreach (var item in gsObj.GetArray("array1")) { object x = item.ToString(); } }
public async void InitGigya() { GSAPI.Instance.Initialize(this, ApiKey); GSAPI.Instance.SocializeLogin += (sender, e) => { Console.WriteLine("Gigya logged in with " + e.Provider); User = e.User; }; GSAPI.Instance.SocializeLogout += (sender, e) => { Console.WriteLine("Gigya logged out"); User = null; }; GSAPI.Instance.SocializeConnectionAdded += (sender, e) => { Console.WriteLine(e.Provider + " connection was added"); }; GSAPI.Instance.SocializeConnectionRemoved += (sender, e) => { Console.WriteLine(e.Provider + " connection was removed"); }; var response = await GSAPI.Instance.SendRequestAsync("socialize.getUserInfo", null); if (response.ErrorCode == 0) { User = response.Data; } else { User = null; } }
private void PublishGigyaActions(User user, GSResponse res) { GigyaHelpers.setCookie(res, this.ControllerContext); GigyaUserData userData = new GigyaUserData() { City = user.City, CountryCode = 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, Newtonsoft.Json.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 = user.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, user.FirstName), actionLinks = actionlinks, mediaItems = mediaItems }; GigyaMethods.PublishUserAction(action, user.UserId, "external"); action.userMessage = String.Empty; action.title = String.Empty; action.mediaItems = null; GigyaMethods.PublishUserAction(action, user.UserId, "internal"); }
public ActionResult Index(string id, string slug) { var profiler = MiniProfiler.Current; ViewBag.sameUser = false; var isLoggedInUser = false; if (String.IsNullOrEmpty(id)) // id is empty if (MyUtility.isUserLoggedIn()) // if user is logged in, set id to the authenticated user. { id = User.Identity.Name; isLoggedInUser = true; } else // no id, no user is authenticated, redirect to homepage. return RedirectToAction("Index", "Home"); var context = new IPTV2Entities(); Guid userId = new System.Guid(); try { userId = new System.Guid(id); //Checks if the id parameter is in guid format to avoid exception error } catch (FormatException) { if (MyUtility.isUserLoggedIn()) // if user is logged in, set id to the authenticated user. userId = new System.Guid(User.Identity.Name); else // no id, no user is authenticated, redirect to homepage. return RedirectToAction("Index", "Home"); } User user = context.Users.FirstOrDefault(u => u.UserId == userId); if (user != null) // If context returns a user, return view. { var fullName = String.Format("{0} {1}", user.FirstName, user.LastName); var dbSlug = MyUtility.GetSlug(fullName); ViewBag.dbSlug = dbSlug; if (!isLoggedInUser) if (String.Compare(dbSlug, slug, false) != 0) return RedirectToActionPermanent("Index", new { id = id, slug = dbSlug }); string gender = GigyaMethods.GetUserInfoByKey(userId, "gender"); ViewBag.gender = gender; ViewBag.viewedUserUserId = userId; ViewBag.userName = MyUtility.GetFullName(); ViewBag.userCity = user.City; ViewBag.userCountry = context.Countries.FirstOrDefault(c => c.Code == user.CountryCode).Description; ViewBag.UserData = MyUtility.GetUserPrivacySetting(user.UserId); if (userId.ToString() == User.Identity.Name) ViewBag.sameUser = true; if (!Request.Cookies.AllKeys.Contains("version")) { try { Dictionary<string, string> collection = new Dictionary<string, string>(); GSObject obj = null; GSResponse res = null; using (profiler.Step("socialize.getFeed")) { collection.Add("uid", user.UserId.ToString()); collection.Add("feedID", "UserAction"); obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection)); res = GigyaHelpers.createAndSendRequest("socialize.getFeed", obj); var resp = Newtonsoft.Json.JsonConvert.DeserializeObject<FeedObj>(res.GetData().ToJsonString()); ViewBag.FeedObj = resp; } //clear collection using (profiler.Step("socialize.getUserInfo")) { collection.Clear(); collection.Add("uid", user.UserId.ToString()); obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection)); res = GigyaHelpers.createAndSendRequest("socialize.getUserInfo", obj); var resp2 = Newtonsoft.Json.JsonConvert.DeserializeObject<GetUserInfoObj>(res.GetData().ToJsonString()); ViewBag.UserInfoObj = resp2; } } catch (Exception) { } return View("Index2", user); } return View(user); } return RedirectToAction("Index", "Home"); }
protected override GSTypedResponse BuildResponse(GSObject response) { return(new CustomResponse(response)); }
private static GSArray ReadFromFileRetrieveIdentities(string filename) { string line; GSArray array = new GSArray(); StreamReader file = new StreamReader(filename); while ((line = file.ReadLine()) != null) { try { GSObject temp = new GSObject(line); GSArray tempArray = temp.GetArray("identities", new GSArray()); if (tempArray != null) array.Add(tempArray); } catch { throw new GSException("incorrect input string"); } } file.Close(); return array; }
public JsonResult _RegisterAndSubscribe(FormCollection fc) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = String.Empty, info = "Registration", TransactionType = "Registration" }; if (!Request.IsAjaxRequest()) { ReturnCode.StatusMessage = "Invalid request"; return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); } bool isSourceAir = false; string url = Url.Action("Register", "User").ToString(); var field_names = new string[] { "uid", "provider", "full_name", "pid", "cmd", "a1", "p1", "t1", "a3", "t3", "p3", "src", "item_name", "amount", "currency", "custom", "ip" }; try { if (TempData["qs"] != null) { var qs = (NameValueCollection)TempData["qs"]; ViewBag.qs = qs; TempData["qs"] = qs; } DateTime registDt = DateTime.Now; Dictionary<string, string> tmpCollection = fc.AllKeys.ToDictionary(k => k, v => fc[v]); bool isMissingRequiredFields = false; foreach (var x in tmpCollection) { if (!field_names.Contains(x.Key)) if (String.IsNullOrEmpty(x.Value)) { isMissingRequiredFields = true; break; } } if (!isMissingRequiredFields) // process form { var ip = Request.GetUserHostAddressFromCloudflare(); if (!String.IsNullOrEmpty(tmpCollection["ip"])) ip = tmpCollection["ip"]; var location = MyUtility.GetLocationBasedOnIpAddress(ip); string FirstName = tmpCollection["first_name"]; string LastName = tmpCollection["last_name"]; string EMail = tmpCollection["p_login_email"]; string ConfirmEmail = tmpCollection["p_login_email_c"]; string Password = tmpCollection["login_pass"]; //autodetect country, city, state string CountryCode = location.countryCode; string City = location.city; string State = location.region; string provider = String.IsNullOrEmpty(tmpCollection["provider"]) ? String.Empty : tmpCollection["provider"]; string uid = String.IsNullOrEmpty(tmpCollection["uid"]) ? String.Empty : tmpCollection["uid"]; System.Guid userId = System.Guid.NewGuid(); string browser = Request.UserAgent; if (FirstName.Length > 32) ReturnCode.StatusMessage = "First Name cannot exceed 32 characters."; if (LastName.Length > 32) ReturnCode.StatusMessage = "Last Name cannot exceed 32 characters."; if (EMail.Length > 64) ReturnCode.StatusMessage = "Email address cannot exceed 64 characters."; if (State.Length > 30) ReturnCode.StatusMessage = "State cannot exceed 30 characters."; if (City.Length > 50) ReturnCode.StatusMessage = "City cannot exceed 50 characters."; if (String.Compare(EMail, ConfirmEmail, true) != 0) ReturnCode.StatusMessage = "Email addresses do not match"; RegexUtilities util = new RegexUtilities(); //if (!MyUtility.isEmail(EMail)) if (!util.IsValidEmail(EMail)) ReturnCode.StatusMessage = "Email address is invalid."; var context = new IPTV2Entities(); User user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EMail, true) == 0); if (user != null) ReturnCode.StatusMessage = "Email address is already taken."; if (GlobalConfig.ExcludedCountriesFromRegistrationDropDown.Split(',').Contains(CountryCode)) // check if country is part of the exclusion list first ReturnCode.StatusMessage = "Country does not exist."; else if (context.Countries.Count(c => String.Compare(c.Code, CountryCode, true) == 0) <= 0) // then check if country is part of the list ReturnCode.StatusMessage = "Country does not exist."; if (context.States.Count(s => String.Compare(s.CountryCode, CountryCode, true) == 0) > 0) if (context.States.Count(s => String.Compare(s.CountryCode, CountryCode, true) == 0 && (String.Compare(s.StateCode, State, true) == 0 || String.Compare(s.Name, State, true) == 0)) <= 0) ReturnCode.StatusMessage = "State is invalid for this country."; if (!String.IsNullOrEmpty(ReturnCode.StatusMessage)) return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); user = new User() { UserId = userId, FirstName = FirstName, LastName = LastName, City = City, State = State, CountryCode = CountryCode, EMail = EMail, Password = MyUtility.GetSHA1(Password), GigyaUID = userId.ToString(), RegistrationDate = registDt, LastUpdated = registDt, RegistrationIp = ip, StatusId = GlobalConfig.Visible, ActivationKey = Guid.NewGuid(), DateVerified = registDt }; try { if (Request.Cookies.AllKeys.Contains("tuid")) user.RegistrationCookie = Request.Cookies["tuid"].Value; else if (Request.Cookies.AllKeys.Contains("regcook")) user.RegistrationCookie = Request.Cookies["regcook"].Value; } catch (Exception) { } ////check for cookie try { var dt = DateTime.Parse(Request.Cookies["rcDate"].Value); if (registDt.Subtract(dt).Days < 45) { ReturnCode.StatusMessage = "We have detected that you have already registered using this machine."; return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); } } catch (Exception) { } string CurrencyCode = GlobalConfig.DefaultCurrency; var country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, CountryCode, true) == 0); if (country != null) CurrencyCode = country.CurrencyCode; var wallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, CurrencyCode, true) == 0); if (wallet == null) // Wallet does not exist. Create new wallet for User. { wallet = ContextHelper.CreateWallet(0, CurrencyCode, registDt); user.UserWallets.Add(wallet); } var transaction = new RegistrationTransaction() { RegisteredState = user.State, RegisteredCity = user.City, RegisteredCountryCode = user.CountryCode, Amount = 0, Currency = CurrencyCode, Reference = isSourceAir ? "New Registration (air)" : "New Registration", Date = registDt, OfferingId = GlobalConfig.offeringId, UserId = user.UserId, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); context.Users.Add(user); if (context.SaveChanges() > 0) { string verification_email = String.Format("{0}/User/Verify?key={1}", GlobalConfig.baseUrl, user.ActivationKey.ToString()); if (isSourceAir) { try { verification_email = String.Format("{0}&source=air", verification_email); var template = MyUtility.GetUrlContent(GlobalConfig.ProjectAirEmailVerificationBodyTemplateUrl); var htmlBody = String.Format(template, FirstName, EMail, verification_email); if (!Request.IsLocal) try { MyUtility.SendEmailViaSendGrid(EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", htmlBody, MailType.HtmlOnly, String.Empty); } catch (Exception e) { MyUtility.LogException(e, "Unable to send email via SendGrid"); } } catch (Exception) { string emailBody = String.Format(GlobalConfig.EmailVerificationBodyTextOnly, FirstName, EMail, verification_email); if (!Request.IsLocal) try { MyUtility.SendEmailViaSendGrid(EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody, MailType.TextOnly, emailBody); } catch (Exception e) { MyUtility.LogException(e, "Unable to send email via SendGrid"); } } } else { string emailBody = String.Format(GlobalConfig.EmailVerificationBodyTextOnly, FirstName, EMail, verification_email); if (!Request.IsLocal) try { MyUtility.SendEmailViaSendGrid(EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody, MailType.TextOnly, emailBody); } catch (Exception e) { MyUtility.LogException(e, "Unable to send email via SendGrid"); } } GSResponse res = null; if (!String.IsNullOrEmpty(uid) && !String.IsNullOrEmpty(provider)) { Dictionary<string, object> collection = new Dictionary<string, object>(); collection.Add("siteUID", user.UserId); collection.Add("uid", Uri.UnescapeDataString(uid)); collection.Add("cid", String.Format("{0} - New User", provider)); res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(collection)); if (res.GetErrorCode() == 0) //Successful link { if (user != null) { var UserId = user.UserId.ToString(); user.StatusId = GlobalConfig.Visible; //activate account user.DateVerified = DateTime.Now; SetAutheticationCookie(UserId); SetSession(UserId); if (!ContextHelper.SaveSessionInDatabase(context, user)) context.SaveChanges(); } } } else { var info = new GigyaUserInfo() { firstName = FirstName, lastName = LastName, email = EMail }; var registrationInfo = new GigyaNotifyLoginInfo() { siteUID = user.UserId.ToString(), cid = "TFCTV - Registration", sessionExpiration = 0, newUser = true, userInfo = Newtonsoft.Json.JsonConvert.SerializeObject(info) }; GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(registrationInfo)); res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", obj); } if (user != null) { if (user.StatusId == GlobalConfig.Visible) { int freeTrialProductId = 0; if (GlobalConfig.IsFreeTrialEnabled) { freeTrialProductId = MyUtility.GetCorrespondingFreeTrialProductId(); if (GlobalConfig.TfcTvFree2StartDate < registDt && GlobalConfig.TfcTvFree2EndDate > registDt) { string UserCountryCode = user.CountryCode; if (!GlobalConfig.isUAT) try { UserCountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy(); } catch (Exception) { } var countryList = GlobalConfig.TfcTvFree2CountryWhiteList.Split(','); if (countryList.Contains(UserCountryCode) && String.Compare(user.CountryCode, UserCountryCode, true) == 0) freeTrialProductId = GlobalConfig.TfcTvFree2ProductId; } PaymentHelper.PayViaWallet(context, userId, freeTrialProductId, SubscriptionProductType.Package, userId, null); } //authenticate user SetAutheticationCookie(user.UserId.ToString()); SendToGigya(user); SetSession(user.UserId.ToString()); ContextHelper.SaveSessionInDatabase(context, user); //add uid cookie HttpCookie uidCookie = new HttpCookie("uid"); uidCookie.Value = user.UserId.ToString(); uidCookie.Expires = DateTime.Now.AddDays(30); Response.Cookies.Add(uidCookie); } } GigyaHelpers.setCookie(res, this.ControllerContext); GigyaUserData2 userData = new GigyaUserData2() { city = user.City, country = user.CountryCode, email = user.EMail, firstName = user.FirstName, lastName = user.LastName, state = user.State }; //GigyaUserDataInfo userDataInfo = new GigyaUserDataInfo() //{ // UID = user.UserId.ToString(), // data = Newtonsoft.Json.JsonConvert.SerializeObject(userData, Formatting.None) //}; TFCTV.Helpers.UserData privacyData = new UserData() { IsExternalSharingEnabled = "true,false", IsInternalSharingEnabled = "true,false", IsProfilePrivate = "false" }; GigyaUserDataInfo2 userDataInfo = new GigyaUserDataInfo2() { UID = user.UserId.ToString(), profile = Newtonsoft.Json.JsonConvert.SerializeObject(userData, Formatting.None), data = Newtonsoft.Json.JsonConvert.SerializeObject(privacyData, Formatting.None) }; GSObject userDataInfoObj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(userDataInfo)); //res = GigyaHelpers.createAndSendRequest("gcs.setUserData", userDataInfoObj); res = GigyaHelpers.createAndSendRequest("ids.setAccountInfo", userDataInfoObj); var returnCode = res.GetErrorCode(); //Publish to Activity Feed List<ActionLink> actionlinks = new List<ActionLink>(); actionlinks.Add(new ActionLink() { text = SNSTemplates.register_actionlink_text, href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_actionlink_href) }); //mediaItem List<MediaItem> mediaItems = new List<MediaItem>(); mediaItems.Add(new MediaItem() { type = SNSTemplates.register_mediaitem_type, src = String.Format("{0}{1}", GlobalConfig.AssetsBaseUrl, SNSTemplates.register_mediaitem_src), href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_mediaitem_href) }); UserAction action = new UserAction() { actorUID = userId.ToString(), userMessage = SNSTemplates.register_usermessage, title = SNSTemplates.register_title, subtitle = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_subtitle), linkBack = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_linkback), description = String.Format(SNSTemplates.register_description, FirstName), actionLinks = actionlinks, mediaItems = mediaItems }; GigyaMethods.PublishUserAction(action, userId, "external"); action.userMessage = String.Empty; action.title = String.Empty; action.mediaItems = null; GigyaMethods.PublishUserAction(action, userId, "internal"); TempData["qs"] = null; // empty the TempData upon successful registration ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.info7 = user.EMail; if (user.StatusId == GlobalConfig.Visible) { ReturnCode.StatusHeader = "Your 7-Day Free Trial Starts Now!"; ReturnCode.StatusMessage = "Congratulations! You are now registered to TFC.tv."; ReturnCode.StatusMessage2 = "Pwede ka nang manood ng mga piling Kapamilya shows at movies!"; ReturnCode.info3 = user.UserId.ToString(); //Change to social registration ReturnCode.info = "SocialRegistration"; ReturnCode.TransactionType = "SocialRegistration"; } else { ReturnCode.StatusHeader = "Email verification sent!"; ReturnCode.StatusMessage = "Congratulations! You are one step away from completing your registration."; ReturnCode.StatusMessage2 = "An email has been sent to you.<br> Verify your email address to complete your registration."; } TempData["ErrorMessage"] = ReturnCode; //if(xoom) if (Request.Cookies.AllKeys.Contains("xoom")) { var userPromo = new UserPromo(); userPromo.UserId = user.UserId; userPromo.PromoId = GlobalConfig.Xoom2PromoId; userPromo.AuditTrail.CreatedOn = registDt; context.UserPromos.Add(userPromo); context.SaveChanges(); } return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); // successful registration } } else ReturnCode.StatusMessage = "Please fill in all required fields."; url = String.Format("{0}?{1}", Request.UrlReferrer.AbsolutePath, MyUtility.DictionaryToQueryString(tmpCollection)); } catch (Exception e) { MyUtility.LogException(e); } return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); }
public ActionResult Socialize() { var retUrl = String.Empty; try { NameValueCollection qs = Request.QueryString; string gigyaUID = Uri.UnescapeDataString(qs["UID"]); bool isRequestValid = SigUtils.ValidateUserSignature(gigyaUID, Uri.UnescapeDataString(qs["timestamp"]), GlobalConfig.GSsecretkey, Uri.UnescapeDataString(qs["signature"])); if (isRequestValid) { using (var context = new IPTV2Entities()) { User user = null; bool isSiteUID = Convert.ToBoolean(qs["isSiteUID"]); if (isSiteUID) //Old user. Signin to site { var UserId = new Guid(gigyaUID); user = context.Users.FirstOrDefault(u => u.UserId == UserId); if (user != null) { if (user.StatusId == GlobalConfig.Visible) { try { if (TempData["RedirectUrl"] != null) retUrl = (string)TempData["RedirectUrl"]; } catch (Exception) { } SetAutheticationCookie(gigyaUID); SetSession(gigyaUID); ContextHelper.SaveSessionInDatabase(context, user); SetUserTrackingCookie(UserId.ToString()); try { //redirect to RedirectUrl //if (!String.IsNullOrEmpty(retUrl)) // return Redirect(retUrl); //var referrerUrl = Request.UrlReferrer.PathAndQuery; //return Redirect(referrerUrl); if (MyUtility.isTVECookieValid()) { MyUtility.RemoveTVECookie(); return RedirectToAction("RegisterToTFCEverywhere", "User"); } if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("redirectaintone")) { HttpCookie tempCookie = new HttpCookie("redirectaintone"); tempCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(tempCookie); return RedirectToAction("Details", "Subscribe", new { id = "aintone" }); } //redirect to RedirectUrl if (!String.IsNullOrEmpty(retUrl)) { try { if (!String.IsNullOrEmpty(Request.QueryString["source"])) retUrl = new Uri(retUrl).GetLeftPart(UriPartial.Path); } catch (Exception) { } return Redirect(retUrl); } var referrerUrl = Request.UrlReferrer.PathAndQuery; if (!String.IsNullOrEmpty(Request.QueryString["source"])) referrerUrl = Request.UrlReferrer.GetLeftPart(UriPartial.Path); return Redirect(referrerUrl); } catch (Exception) { } } else //user is not active in the database, put code here TempData["LoginErrorMessage"] = "Social networking account is not verified in our system."; } else //user does not exist on database, put code here TempData["LoginErrorMessage"] = "Social networking account does not exist in our system."; } else //New user. allow user to register { bool createUser = true; if (!String.IsNullOrEmpty(qs["email"])) { string email = qs["email"]; user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, email, true) == 0); if (user != null) // link account { Dictionary<string, object> collection = new Dictionary<string, object>(); collection.Add("siteUID", user.UserId); collection.Add("uid", Uri.UnescapeDataString(qs["UID"])); collection.Add("cid", String.Format("{0} - New User", qs["provider"])); GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection)); GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", obj); if (res.GetErrorCode() == 0) //Successful link { try { if (TempData["RedirectUrl"] != null) retUrl = (string)TempData["RedirectUrl"]; } catch (Exception) { } var UserId = user.UserId.ToString(); user.StatusId = GlobalConfig.Visible; //activate account user.DateVerified = DateTime.Now; SetAutheticationCookie(UserId); SetSession(UserId); SetUserTrackingCookie(UserId); if (!ContextHelper.SaveSessionInDatabase(context, user)) context.SaveChanges(); try { //redirect to RedirectUrl if (!String.IsNullOrEmpty(retUrl)) { try { if (!String.IsNullOrEmpty(Request.QueryString["source"])) retUrl = new Uri(retUrl).GetLeftPart(UriPartial.Path); } catch (Exception) { } return Redirect(retUrl); } var referrerUrl = Request.UrlReferrer.PathAndQuery; if (!String.IsNullOrEmpty(Request.QueryString["source"])) referrerUrl = Request.UrlReferrer.GetLeftPart(UriPartial.Path); return Redirect(referrerUrl); } catch (Exception) { } } } } if (createUser) { TempData["qs"] = qs; if (!String.IsNullOrEmpty(Request.QueryString["source"])) return Redirect("/WatchNow"); //return RedirectToAction("Index", "Air"); //redirect to RedirectUrl if (!String.IsNullOrEmpty(retUrl)) { try { if (!String.IsNullOrEmpty(Request.QueryString["source"])) retUrl = new Uri(retUrl).GetLeftPart(UriPartial.Path); } catch (Exception) { } return Redirect(retUrl); } return RedirectToAction("Register", "User"); } } } } } catch (Exception e) { MyUtility.LogException(e); } if (MyUtility.isTVECookieValid()) { MyUtility.RemoveTVECookie(); return RedirectToAction("RegisterToTFCEverywhere", "User"); } if (!String.IsNullOrEmpty(retUrl))//redirect to RedirectUrl { try { if (!String.IsNullOrEmpty(Request.QueryString["source"])) retUrl = new Uri(retUrl).GetLeftPart(UriPartial.Path); } catch (Exception) { } return Redirect(retUrl); } return RedirectToAction("Index", "Home"); }
public ActionResult GenerateSig(string method, string url, string qs) { GSObject dictionaryParams = new GSObject(); dictionaryParams.ParseQuerystring(qs); string baseString = SigUtils.CalcOAuth1Basestring(method, url, dictionaryParams); return Content(SigUtils.CalcSignature(baseString, GlobalConfig.GSsecretkey), "text/plain"); }
protected override GSTypedResponse BuildResponse(GSObject response) { return(new AroundMeLeaderboardResponse_SCORE_LEADERBOARD(response)); }
protected override GSTypedResponse BuildResponse(GSObject response) { return(new AroundMeLeaderboardResponse_LeaderboardRating(response)); }
public PartialViewResult AboutMe(User user) { try { Dictionary<string, object> collection = new Dictionary<string, object>(); collection.Add("UID", user.UserId.ToString()); collection.Add("fields", "about"); GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection)); GSResponse res = GigyaHelpers.createAndSendRequest("gcs.getUserData", obj); } catch (Exception) { } return PartialView(); }
/// <summary> /// This is a utility method for generating a base string for calculating the OAuth1 cryptographic signature. /// </summary> /// <param name="httpMethod">"POST" or "GET"</param> /// <param name="url">the full url without params</param> /// <param name="requestParams">list of params in the form of a GSObject</param> /// <returns>the base string to act on for calculating the OAuth1 cryptographic signature</returns> public static string CalcOAuth1Basestring(string httpMethod, string url, GSObject requestParams) { // Normalize the URL per the OAuth requirements StringBuilder normalizedUrlSB = new StringBuilder(); Uri u = new Uri(url); normalizedUrlSB.Append(u.Scheme.ToLowerInvariant()); normalizedUrlSB.Append("://"); normalizedUrlSB.Append(u.Host.ToLowerInvariant()); if ((u.Scheme == "HTTP" && u.Port != 80) || (u.Scheme == "HTTPS" && u.Port != 443)) { normalizedUrlSB.Append(':'); normalizedUrlSB.Append(u.Port); } normalizedUrlSB.Append(u.LocalPath); // Create a sorted list of query parameters StringBuilder querystring = new StringBuilder(); foreach (string key in requestParams.GetKeys()) { if (requestParams.GetString(key) != null) { querystring.Append(key); querystring.Append("="); querystring.Append(GSRequest.UrlEncode(requestParams.GetString(key) ?? String.Empty)); querystring.Append("&"); } } if (querystring.Length > 0) querystring.Length--; // remove the last ampersand // Construct the base string from the HTTP method, the URL and the parameters string basestring = httpMethod.ToUpperInvariant() + "&" + GSRequest.UrlEncode(normalizedUrlSB.ToString()) + "&" + GSRequest.UrlEncode(querystring.ToString()); return basestring; }
void IGSLoginUIListener.OnLogin(string provider, GSObject user, Java.Lang.Object context) { Console.WriteLine("Gigya loginUI has logged in"); }
public PartialViewResult GetFriends(User user) { try { Dictionary<string, string> collection = new Dictionary<string, string>(); collection.Add("uid", user.UserId.ToString()); GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection)); GSResponse res = GigyaHelpers.createAndSendRequest("socialize.getFriendsInfo", obj); var resp = Newtonsoft.Json.JsonConvert.DeserializeObject<GigyaFriendsInfo>(res.GetData().ToJsonString()); return PartialView(resp); } catch (Exception) { } return PartialView(); }
public PartialViewResult GetFeed(User user, FeedObj feedObj, bool useTabTemplate = false, string group = "friends") { try { if (feedObj != null) { ViewBag.group = group; if (useTabTemplate) return PartialView("GetFeedTab", feedObj); else return PartialView(feedObj); } Dictionary<string, string> collection = new Dictionary<string, string>(); collection.Add("uid", user.UserId.ToString()); collection.Add("feedID", "UserAction"); GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection)); GSResponse res = GigyaHelpers.createAndSendRequest("socialize.getFeed", obj); var resp = Newtonsoft.Json.JsonConvert.DeserializeObject<FeedObj>(res.GetData().ToJsonString()); if (useTabTemplate) { ViewBag.group = group; return PartialView("GetFeedTab", resp); } return PartialView(resp); } catch (Exception) { } if (useTabTemplate) { ViewBag.group = group; return PartialView("GetFeedTab"); } return PartialView(); }
public ActionResult _MobileSocialize(FormCollection fc) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = String.Empty, info = "Registration", TransactionType = "Registration" }; var field_names = new string[] { "uid", "provider", "full_name" }; try { DateTime registDt = DateTime.Now; Dictionary<string, string> tmpCollection = fc.AllKeys.ToDictionary(k => k, v => fc[v]); bool isMissingRequiredFields = false; foreach (var x in tmpCollection) { if (!field_names.Contains(x.Key)) if (String.IsNullOrEmpty(x.Value)) { isMissingRequiredFields = true; break; } } if (!isMissingRequiredFields) // process form { var qs = fc; string gigyaUID = Uri.UnescapeDataString(qs["UID"]); bool isRequestValid = SigUtils.ValidateUserSignature(gigyaUID, Uri.UnescapeDataString(qs["timestamp"]), GlobalConfig.GSsecretkey, Uri.UnescapeDataString(qs["signature"])); isRequestValid = true; if (isRequestValid) { string FirstName = qs["first_name"]; string LastName = qs["last_name"]; //string ip = qs["ip"]; string ip = Request.GetUserHostAddressFromCloudflare(); var location = MyUtility.GetLocationBasedOnIpAddress(ip); string City = location.city; string CountryCode = location.countryCode; string State = (String.Compare(CountryCode, GlobalConfig.DefaultCountry, true) == 0) ? location.region : location.regionName; string EMail = qs["email"]; string Password = Membership.GeneratePassword(10, 3); string provider = qs["provider"]; GSResponse res = null; using (var context = new IPTV2Entities()) { User user = null; bool isSiteUID = Convert.ToBoolean(qs["isSiteUID"]); bool IsUserCreateSuccessful = false; if (isSiteUID) //Old user. Signin to site { var UserId = new Guid(gigyaUID); user = context.Users.FirstOrDefault(u => u.UserId == UserId); if (user != null) { if (user.StatusId == GlobalConfig.Visible) //User found login user { SetAuthenticationCookie(gigyaUID); SetSession(gigyaUID); ContextHelper.SaveSessionInDatabase(context, user); ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusMessage = "Successful login."; } else //user is not active in the database, put code here ReturnCode.StatusMessage = "Social networking account is not verified in our system."; } else //user does not exist on database, put code here { //Social networking account does not exist in our system; //Create user user = new User() { UserId = UserId, FirstName = FirstName, LastName = LastName, City = City, State = State, CountryCode = CountryCode, EMail = EMail, Password = MyUtility.GetSHA1(Password), GigyaUID = gigyaUID, RegistrationDate = registDt, LastUpdated = registDt, RegistrationIp = MyUtility.GetClientIpAddress(), StatusId = GlobalConfig.Visible, ActivationKey = Guid.NewGuid(), DateVerified = registDt }; context.Users.Add(user); SetAuthenticationCookie(UserId.ToString()); SetSession(UserId.ToString()); if (!ContextHelper.SaveSessionInDatabase(context, user)) { if (context.SaveChanges() > 0) { IsUserCreateSuccessful = true; ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusMessage = "Enabled account on database."; } } } } else //New user. allow user to register { bool createUser = true; if (!String.IsNullOrEmpty(qs["email"])) { string email = qs["email"]; user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, email, true) == 0); if (user != null) // link account { Dictionary<string, object> collection = new Dictionary<string, object>(); collection.Add("siteUID", user.UserId); collection.Add("uid", Uri.UnescapeDataString(qs["UID"])); collection.Add("cid", String.Format("{0} - New User", qs["provider"])); GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection)); res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", obj); if (res.GetErrorCode() == 0) //Successful link { var UserId = user.UserId.ToString(); user.StatusId = GlobalConfig.Visible; //activate account user.DateVerified = DateTime.Now; SetAuthenticationCookie(UserId); SetSession(UserId); if (!ContextHelper.SaveSessionInDatabase(context, user)) context.SaveChanges(); } } } if (createUser) //user not found on database. create new user { System.Guid UserId = System.Guid.NewGuid(); 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 = MyUtility.GetClientIpAddress(), StatusId = GlobalConfig.Visible, ActivationKey = Guid.NewGuid(), DateVerified = registDt }; context.Users.Add(user); Dictionary<string, object> collection = new Dictionary<string, object>(); collection.Add("siteUID", user.UserId); collection.Add("uid", Uri.UnescapeDataString(qs["UID"])); collection.Add("cid", String.Format("{0} - New User", qs["provider"])); GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection)); res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", obj); if (res.GetErrorCode() == 0) //Successful link { SetAuthenticationCookie(UserId.ToString()); SetSession(UserId.ToString()); if (!ContextHelper.SaveSessionInDatabase(context, user)) { if (context.SaveChanges() > 0) { IsUserCreateSuccessful = true; ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusMessage = "User registration successful."; } } } } if (IsUserCreateSuccessful) { if (user != null) { if (user.StatusId == GlobalConfig.Visible) { int freeTrialProductId = 0; if (GlobalConfig.IsFreeTrialEnabled) { freeTrialProductId = MyUtility.GetCorrespondingFreeTrialProductId(); PaymentHelper.PayViaWallet(context, user.UserId, freeTrialProductId, SubscriptionProductType.Package, user.UserId, null); } } PublishGigyaActions(user, res); string emailBody = String.Format(GlobalConfig.EmailVerificationBodyTextOnly, FirstName, EMail, String.Format("Your new TFC.tv password is {0}", Password)); if (!Request.IsLocal) try { MyUtility.SendEmailViaSendGrid(EMail, GlobalConfig.NoReplyEmail, "Your new TFC.tv password", emailBody, MailType.TextOnly, emailBody); } catch (Exception e) { MyUtility.LogException(e, "Unable to send email via SendGrid"); } } } } } } else ReturnCode.StatusMessage = "Request is not valid."; } } catch (Exception e) { MyUtility.LogException(e); } return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); }
protected override GSTypedResponse BuildResponse(GSObject response) { return(new LeaderboardDataResponse_HIGH_SCORE(response)); }
private void RunAsync(bool secure, Action <TestRunResult> cb, Action <TestRunResult> onDone) { try { var ret = new TestRunResult(); ret.RunStarted = DateTime.Now; ret.Results = new List <MethodResult>(); var methods = this.Methods; if (!this.RunAll) { methods = this.Methods.Where(m => m.Include).ToList(); } foreach (var method in methods) { try { if (method.Params == null) { method.Params = string.Empty; } var methodRes = new MethodResult(); methodRes.RunStarted = DateTime.Now; methodRes.TestName = method.TestName; methodRes.TestDescription = method.TestDescription; var dict = new GSObject(); if (Program.MainForm.chkPreEncodeParams.Checked) { dict.ParseQuerystring(this.getEncodedValues(method.Params.Trim())); } else { dict.ParseQuerystring(method.Params.Trim()); } dict.Put("uid", dict.GetString("uid", null)); if (GetSecure().HasValue) { secure = GetSecure().Value; } GSRequest g = new GSRequest(this.APIKey, this.SecKey, method.Name, dict, secure); var req = new GSRequest(this.APIKey, this.SecKey, method.Name, dict, secure); var res = req.Send(); ret.Results.Add(methodRes); methodRes.Request = req; methodRes.Response = res; methodRes.SchemaValidation = new SchemaValidation("http://socialize.api.gigya.com/schema"); if (dict.GetString("format").Equals("xml", StringComparison.InvariantCultureIgnoreCase)) { var xc = new XmlComparer(); xc.Compare(method.Expected, res.GetResponseText(), method.Schema); methodRes.Differences = xc.Differences; var xdoc = XDocument.Parse(res.GetResponseText()); var xroot = (xdoc.Document.FirstNode as XContainer); var errCode = xroot.Element(XName.Get("errorCode", "urn:com:gigya:api")); int iErrCode; if (errCode != null && int.TryParse(errCode.Value, out iErrCode)) { methodRes.ErrorCode = iErrCode; var errMsg = xroot.Element(XName.Get("errorMessage", "urn:com:gigya:api")); methodRes.ErrorMessage = errMsg == null ? string.Empty : errMsg.Value; } else { methodRes.ErrorCode = 0; methodRes.ErrorMessage = ""; } if (methodRes.Differences.Count > 0 && methodRes.ErrorCode == 0) { methodRes.ErrorCode = -1; } var statusCode = xroot.Element(XName.Get("statusCode", "urn:com:gigya:api")); int iStatusCode; if (statusCode != null && int.TryParse(statusCode.Value, out iStatusCode)) { methodRes.StatusCode = iStatusCode; } else { methodRes.StatusCode = 200; } var sr = new StringReader(res.GetResponseText()); methodRes.Validation = methodRes.SchemaValidation.Validate(sr); } else { var jc = new JsonComparer(); jc.Compare(method.Expected, res.GetResponseText(), method.Schema); methodRes.Differences = jc.Differences; if (methodRes.Differences.Count > 0 && res.GetErrorCode() == 0) { methodRes.ErrorCode = -1; } else { methodRes.ErrorCode = res.GetErrorCode(); } methodRes.ErrorMessage = res.GetErrorMessage(); methodRes.StatusCode = res.GetData().GetInt("statusCode", 200); methodRes.Validation = true; } methodRes.RunEnded = DateTime.Now; //invoke the callback under the UI thread. Program.MainForm.Invoke(cb, ret); } catch (Exception ex) { MessageBox.Show(ex.Message, ex.Message); } } //invoke the callback under the UI thread. Program.MainForm.Invoke(cb, ret); //invoke the callback under the UI thread. Program.MainForm.Invoke(onDone, ret); ret.RunEnded = DateTime.Now; } catch (Exception ex) { MessageBox.Show(ex.Message, ex.Message); } }
public JsonResult GetUser(string id) { UserObj obj = new UserObj() { code = ErrorCode.UnidentifiedError }; try { Guid UserId; try { UserId = Guid.Parse(id); } catch (Exception) { throw new Exception("UserId is invalid"); } var context = new IPTV2Entities(); var user = context.Users.FirstOrDefault(u => u.UserId == UserId); if (user != null) { obj.user = new UserO { City = user.City, CountryCode = user.CountryCode, UserId = user.UserId, DateVerified = user.DateVerified.HasValue ? user.DateVerified.Value.ToString("MM/dd/yyyy hh:mm:ss tt") : String.Empty, EMail = user.EMail, FirstName = user.FirstName, IsTVEverywhere = user.IsTVEverywhere , LastName = user.LastName, RegistrationDate = user.RegistrationDate.ToString("MM/dd/yyyy hh:mm:ss tt"), State = user.State }; obj.code = ErrorCode.Success; } //Gigya try { Dictionary<string, object> collection = new Dictionary<string, object>(); collection.Add("UID", user.UserId.ToString()); GSObject gsObj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection)); GSRequest req = new GSRequest(Global.GSapikey, Global.GSsecretkey, "socialize.getUserInfo", gsObj, true); ; GSResponse res = req.Send(); obj.gUser = Newtonsoft.Json.JsonConvert.DeserializeObject<GetUserInfoObj>(res.GetData().ToJsonString()); } catch (Exception) { } } catch (Exception e) { obj.message = e.Message; } return this.Json(obj, JsonRequestBehavior.AllowGet); }
protected override GSTypedResponse BuildResponse(GSObject response) { return(new AroundMeLeaderboardResponse_HighScoreLB(response)); }
public static GSRequest createRequest(string method, GSObject obj) { return new GSRequest(GlobalConfig.GSapikey, GlobalConfig.GSsecretkey, method, obj, true); }
public JsonResult GSocialize() { var ReturnCode = new SocializeReturnCodeObj() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = String.Empty }; var registDt = DateTime.Now; var skipValidation = false; try { if (!String.IsNullOrEmpty(Request.QueryString["sv"])) { var svTemp = Convert.ToInt32(Request.QueryString["sv"]); if (svTemp == 1) skipValidation = true; } } catch (Exception) { } try { NameValueCollection qs = Request.QueryString; string gigyaUID = Uri.UnescapeDataString(qs["UID"]); bool isRequestValid = SigUtils.ValidateUserSignature(gigyaUID, Uri.UnescapeDataString(qs["timestamp"]), GlobalConfig.GSsecretkey, Uri.UnescapeDataString(qs["signature"])); if (isRequestValid || skipValidation) { using (var context = new IPTV2Entities()) { User user = null; bool isSiteUID = Convert.ToBoolean(qs["isSiteUID"]); if (isSiteUID) //Old user. Signin to site { var UserId = new Guid(gigyaUID); user = context.Users.FirstOrDefault(u => u.UserId == UserId); if (user != null) { if (user.StatusId == GlobalConfig.Visible) //Successful Login ReturnCode.StatusCode = (int)ErrorCodes.Success; else ReturnCode.StatusMessage = "Account is not verified in our system."; } else { //ReturnCode.StatusMessage = "Social networking account does not exist in our system."; //Create user string FirstName = qs["first_name"]; string LastName = qs["last_name"]; string EMail = qs["login_email"]; string uid = qs["uid"]; string provider = qs["provider"]; string Password = Membership.GeneratePassword(10, 2); string City = String.Empty; string State = String.Empty; string CountryCode = GlobalConfig.DefaultCountry; var id = UserId; var ip = qs["ip"]; try { var location = MyUtility.GetLocationBasedOnIpAddress(ip); City = location.city; CountryCode = location.countryCode; State = String.Compare(CountryCode, GlobalConfig.DefaultCountry, true) == 0 ? location.region : location.regionName; } catch (Exception) { } user = new User() { UserId = id, FirstName = FirstName, LastName = LastName, City = City, State = State, CountryCode = CountryCode, EMail = EMail, Password = MyUtility.GetSHA1(Password), GigyaUID = id.ToString(), RegistrationDate = registDt, LastUpdated = registDt, RegistrationIp = ip ?? MyUtility.GetClientIpAddress(), DateVerified = registDt, StatusId = GlobalConfig.Visible, ActivationKey = Guid.NewGuid() }; var 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 = 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 (AIR PLUS)", Date = registDt, OfferingId = GlobalConfig.offeringId, UserId = user.UserId, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); context.Users.Add(user); if (context.SaveChanges() > 0) { ReturnCode.StatusCode = (int)ErrorCodes.Success; GSResponse res = null; GigyaUserData2 userData = new GigyaUserData2() { city = user.City, country = user.CountryCode, email = user.EMail, firstName = user.FirstName, lastName = user.LastName, state = user.State }; 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); //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 = user.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, user.UserId, "external"); action.userMessage = String.Empty; action.title = String.Empty; action.mediaItems = null; GigyaMethods.PublishUserAction(action, user.UserId, "internal"); } } } else //New user. allow user to register { bool createUser = true; if (!String.IsNullOrEmpty(qs["email"])) { string email = qs["email"]; user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, email, true) == 0); if (user != null) // link account { Dictionary<string, object> collection = new Dictionary<string, object>(); collection.Add("siteUID", user.UserId); collection.Add("uid", Uri.UnescapeDataString(qs["UID"])); collection.Add("cid", String.Format("{0} - New User", qs["provider"])); GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection)); GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", obj); if (res.GetErrorCode() == 0) //Successful link { createUser = false; var UserId = user.UserId.ToString(); user.StatusId = GlobalConfig.Visible; //activate account user.DateVerified = DateTime.Now; if (context.SaveChanges() > 0) ReturnCode.StatusCode = (int)ErrorCodes.Success; else ReturnCode.StatusMessage = "Create user failed"; } else ReturnCode.StatusMessage = res.GetErrorMessage(); } } if (createUser) { string FirstName = qs["first_name"]; string LastName = qs["last_name"]; string EMail = qs["login_email"]; string uid = qs["uid"]; string provider = qs["provider"]; string Password = Membership.GeneratePassword(10, 2); string City = String.Empty; string State = String.Empty; string CountryCode = GlobalConfig.DefaultCountry; var id = Guid.NewGuid(); var ip = qs["ip"]; try { var location = MyUtility.GetLocationBasedOnIpAddress(ip); City = location.city; CountryCode = location.countryCode; State = String.Compare(CountryCode, GlobalConfig.DefaultCountry, true) == 0 ? location.region : location.regionName; } catch (Exception) { } user = new User() { UserId = id, FirstName = FirstName, LastName = LastName, City = City, State = State, CountryCode = CountryCode, EMail = EMail, Password = MyUtility.GetSHA1(Password), GigyaUID = id.ToString(), RegistrationDate = registDt, LastUpdated = registDt, RegistrationIp = ip ?? MyUtility.GetClientIpAddress(), ActivationKey = Guid.NewGuid() }; var 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 = 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 (AIR PLUS)", Date = registDt, OfferingId = GlobalConfig.offeringId, UserId = user.UserId, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); context.Users.Add(user); if (context.SaveChanges() > 0) { 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; if (context.SaveChanges() > 0) ReturnCode.StatusCode = (int)ErrorCodes.Success; } } } else ReturnCode.StatusMessage = "Missing parameters uid & provider"; //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); // ReturnCode.StatusCode = (int)ErrorCodes.Success; //} if (ReturnCode.StatusCode == (int)ErrorCodes.Success) { GigyaUserData2 userData = new GigyaUserData2() { city = user.City, country = user.CountryCode, email = user.EMail, firstName = user.FirstName, lastName = user.LastName, state = user.State }; 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); //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 = user.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, user.UserId, "external"); action.userMessage = String.Empty; action.title = String.Empty; action.mediaItems = null; GigyaMethods.PublishUserAction(action, user.UserId, "internal"); } } } } if (ReturnCode.StatusCode == (int)ErrorCodes.Success) { ReturnCode.StatusMessage = "Success!"; //GenerateToken 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) { HttpCookie authCookie = SetCookie(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), }; ReturnCode.tk = token; ReturnCode.gs = cookie; } else { ReturnCode.StatusCode = res.GetErrorCode(); ReturnCode.StatusMessage = res.GetErrorMessage(); } } } } else ReturnCode.StatusMessage = "Request is not valid"; } catch (Exception e) { MyUtility.LogException(e); ReturnCode.StatusMessage = String.Format("Exception: {0} | Inner Exception: {1}", e.Message, e.InnerException.Message); } return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); }
public static GSResponse createAndSendRequest(string method, GSObject obj) { GSRequest req = new GSRequest(GlobalConfig.GSapikey, GlobalConfig.GSsecretkey, method, obj, true); return req.Send(); }
public JsonResult RemoveConnection(FormCollection fc) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = String.Empty }; try { if (User.Identity.IsAuthenticated) { using (var context = new IPTV2Entities()) { var user = context.Users.FirstOrDefault(u => u.UserId == new Guid(User.Identity.Name)); if (user != null) { Dictionary<string, string> collection = new Dictionary<string, string>(); collection.Add("uid", user.UserId.ToString()); if (!String.IsNullOrEmpty(fc["provider"])) collection.Add("provider", fc["provider"]); collection.Add("format", "json"); GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection)); GSResponse res = GigyaHelpers.createAndSendRequest("socialize.removeConnection", obj); var resp = Newtonsoft.Json.JsonConvert.DeserializeObject<DeleteAccountObj>(res.GetData().ToJsonString()); ReturnCode.StatusCode = resp.errorCode; } } } } catch (Exception e) { MyUtility.LogException(e); } return Json(ReturnCode, JsonRequestBehavior.AllowGet); }
protected override GSTypedResponse BuildResponse(GSObject response) { return(new LeaderboardDataResponse_highscore(response)); }
protected override GSTypedResponse BuildResponse(GSObject response) { return(new LogChallengeEventResponse(response)); }
protected override GSTypedResponse BuildResponse(GSObject response) { return(new LeaderboardDataResponse_LEADERBOARD(response)); }