Esempio n. 1
0
    public void GetProfileOfUser()
    {
        GetProfile.GetUserProfile(
            (response) => {
            ProfileResponse profileResponse = (ProfileResponse)response;

            State.UserProfile = profileResponse.profile;

            StartCoroutine(showPopUpT("successfully signed in", "success"));

            StartCoroutine(GotoMainMenu());
        },
            (statusCode, error) => {
            GoToLogin();

            if (statusCode == StatusCodes.CODE_VALIDATION_ERROR)
            {
                ValidationError validationError = (ValidationError)error;
                StartCoroutine(showPopUpT(validationError.errors.First().Value[0], "error"));
            }
            else
            {
                GenericError genericError = (GenericError)error;
                StartCoroutine(showPopUpT(genericError.message, "error"));
            }
        }
            );
    }
Esempio n. 2
0
        public ProfileResponse CreateProfileResponse(ProfileEN pProfileID)
        {
            ProfileResponse response = new ProfileResponse();
            UserProfile     profile  = new UserProfile();

            response.profile = new UserProfile();

            try
            {
                response.profile.Id          = pProfileID.ProfileID;
                response.profile.birthday    = pProfileID.Birthday;
                response.profile.first_name  = pProfileID.FirstName;
                response.profile.last_name   = pProfileID.LastName;
                response.profile.verified    = pProfileID.Verified;
                response.profile.email       = pProfileID.Email;
                response.profile.NickName    = pProfileID.Nickname;
                response.profile.vendorId    = pProfileID.VendorID;
                response.profile.Iso2code    = pProfileID.Iso2Code;
                response.profile.Symbol      = pProfileID.Symbol;
                response.profile.Personphone = pProfileID.PersonPhone;
                response.profile.LastSale    = pProfileID.LastSale;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerBL.LogError(ex.Message);
            }

            return(response);
        }
Esempio n. 3
0
        void m_reGetTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                m_reGetTimer.Stop();

                var response = m_CompanionIO.GetProfileData(true);

                if (!response.Cached)
                {
                    String json = response.Json ?? "{}";

                    m_joCompanion = JsonConvert.DeserializeObject <JObject>(json);

                    CompanionStatus = response.LoginStatus;
                }

                m_cachedResponse = response;

                AsyncDataRecievedEvent.Raise(this, new EventArgs());
            }
            catch (Exception ex)
            {
                CErr.processError(ex, "Error in m_reGetTimer_Elapsed");
            }
        }
Esempio n. 4
0
        private async Task SyncProfileAsync(ProfileResponse response)
        {
            var stamp = await _stateService.GetSecurityStampAsync();

            if (stamp != null && stamp != response.SecurityStamp)
            {
                if (_logoutCallbackAsync != null)
                {
                    await _logoutCallbackAsync(new Tuple <string, bool, bool>(response.Id, false, true));
                }
                return;
            }
            await _cryptoService.SetEncKeyAsync(response.Key);

            await _cryptoService.SetEncPrivateKeyAsync(response.PrivateKey);

            await _cryptoService.SetOrgKeysAsync(response.Organizations);

            await _stateService.SetSecurityStampAsync(response.SecurityStamp);

            var organizations = response.Organizations.ToDictionary(o => o.Id, o => new OrganizationData(o));
            await _organizationService.ReplaceAsync(organizations);

            await _stateService.SetEmailVerifiedAsync(response.EmailVerified);

            await _stateService.SetNameAsync(response.Name);

            await _keyConnectorService.SetUsesKeyConnector(response.UsesKeyConnector);
        }
Esempio n. 5
0
    private void getProfileCallback(UnityWebRequest response)
    {
        ProfileResponse profileResponse = new ProfileResponse();

        profileResponse = JsonUtility.FromJson <ProfileResponse>(response.downloadHandler.text);
        if (profileResponse.isSuccessful || profileResponse.successful)
        {
            username.text = $"{profileResponse.firstName} {profileResponse.lastName}";

            fullName.text = $"{profileResponse.firstName} {profileResponse.lastName}";
            PlayerPrefs.SetString(LocalStorageUtil.Keys.firstName.ToString(), profileResponse.firstName);
            PlayerPrefs.SetString(LocalStorageUtil.Keys.lastName.ToString(), profileResponse.lastName);

            email.text = profileResponse.email;
            PlayerPrefs.SetString(LocalStorageUtil.Keys.email.ToString(), profileResponse.email);

            games.text = (profileResponse.wins + profileResponse.draws + profileResponse.losses).ToString();
            PlayerPrefs.SetFloat(LocalStorageUtil.Keys.games.ToString(), profileResponse.wins + profileResponse.draws + profileResponse.losses);

            wins.text = profileResponse.wins.ToString();
            PlayerPrefs.SetFloat(LocalStorageUtil.Keys.wins.ToString(), profileResponse.wins);

            draws.text = profileResponse.draws.ToString();
            PlayerPrefs.SetFloat(LocalStorageUtil.Keys.draws.ToString(), profileResponse.draws);

            losses.text = profileResponse.draws.ToString();
            PlayerPrefs.SetFloat(LocalStorageUtil.Keys.losses.ToString(), profileResponse.losses);

            cash.text = $"N{(profileResponse.walletBalance/100).ToString("N0")}";
            PlayerPrefs.SetString(LocalStorageUtil.Keys.cash.ToString(), profileResponse.walletBalance.ToString());
        }
        else
        {
        }
    }
Esempio n. 6
0
        private Task SyncProfileKeysAsync(ProfileResponse profile)
        {
            if (profile == null)
            {
                return(Task.FromResult(0));
            }

            if (!string.IsNullOrWhiteSpace(profile.Key))
            {
                _cryptoService.SetEncKey(new CipherString(profile.Key));
            }

            if (!string.IsNullOrWhiteSpace(profile.PrivateKey))
            {
                _cryptoService.SetPrivateKey(new CipherString(profile.PrivateKey));
            }

            if (!string.IsNullOrWhiteSpace(profile.SecurityStamp))
            {
                _appSettingsService.SecurityStamp = profile.SecurityStamp;
            }

            _cryptoService.SetOrgKeys(profile);
            _appSettingsService.OrganizationGivesPremium =
                profile.Organizations?.Any(o => o.UsersGetPremium && o.Enabled) ?? false;
            return(Task.FromResult(0));
        }
Esempio n. 7
0
        public void Response_CreateJson()
        {
            //---------------------------------------------

            var response = ProfileResponse.Create(new JObject());

            Assert.True(response.Success);
            Assert.Equal(ProfileStatus.OK, response.Status);
            Assert.Null(response.Value);
            Assert.NotNull(response.JObject);

            Assert.Empty(response.JObject.Properties());
            Assert.Equal("OK-JSON: {}", response.ToString());

            //---------------------------------------------

            var jObj =
                new JObject(
                    new JProperty("hello", "world!")
                    );

            response = ProfileResponse.Create(jObj);

            Assert.True(response.Success);
            Assert.Equal(ProfileStatus.OK, response.Status);
            Assert.Null(response.Value);
            Assert.NotNull(response.JObject);

            Assert.Single(response.JObject.Properties());
            Assert.Equal("world!", response.JObject["hello"]);
            Assert.Equal("OK-JSON: {\"hello\":\"world!\"}", response.ToString());
        }
        public IProfileResponse CreateProfile(string firstName, string lastName, bool active)
        {
            IProfileResponse AProfileResponse = new ProfileResponse();

            try
            {
                var NextProfileId = (GetJsonProfiles().Max(aItem => aItem.ProfileId) + 1);

                var ProfileNew = new Profile()
                {
                    ProfileId = NextProfileId,
                    FirstName = firstName,
                    LastName  = lastName,
                    Active    = active
                };

                var UpsertProfileResults = UpSertProfile(ProfileNew);

                return(UpsertProfileResults);
            }
            catch (Exception e)
            {
                AProfileResponse.Success = false;
            }

            return(AProfileResponse);
        }
Esempio n. 9
0
        //long? responseTypeID,
        //bool byType)
        public List<long> ExcludeNoPreferenceFromProfile(List<ProfileEntity> matchProfile)
        {
            var response = new List<long>();
            using (var dbEntities = new TICPuppyLoveDbContext())
            {

                var profileRequest = new List<ProfileResponse>();
                var profileResponse = new List<ProfileResponse>();

                foreach (ProfileEntity matchResp in matchProfile)
                {
                    ProfileResponse prof = new ProfileResponse
                    {
                        ProfileEntityResponse = matchResp
                    };
                    profileRequest.Add(prof);

                }

                /*
                profileResponse = (byType) ? dbEntities.ExcludeNoPreferencesByType(profileRequest, responseTypeID)
                                           : dbEntities.ExcludeNoPreferences(profileRequest, responseTypeID);
                 */

                profileResponse = dbEntities.ExcludeNoPreferences(profileRequest);

                response = (from resp in profileResponse
                            select resp.ProfileEntityResponse.ResponseTypeID
                            ).Distinct().ToList();
            }

            return response;
        }
Esempio n. 10
0
        private async Task SyncProfileAsync(ProfileResponse response)
        {
            var stamp = await _userService.GetSecurityStampAsync();

            if (stamp != null && stamp != response.SecurityStamp)
            {
                if (_logoutCallbackAsync != null)
                {
                    await _logoutCallbackAsync(true);
                }
                return;
            }
            await _cryptoService.SetEncKeyAsync(response.Key);

            await _cryptoService.SetEncPrivateKeyAsync(response.PrivateKey);

            await _cryptoService.SetOrgKeysAsync(response.Organizations);

            await _userService.SetSecurityStampAsync(response.SecurityStamp);

            var organizations = response.Organizations.ToDictionary(o => o.Id, o => new OrganizationData(o));
            await _userService.ReplaceOrganizationsAsync(organizations);

            await _userService.SetEmailVerifiedAsync(response.EmailVerified);

            await _userService.SetForcePasswordReset(response.ForcePasswordReset);

            await _keyConnectorService.SetUsesKeyConnector(response.UsesKeyConnector);
        }
Esempio n. 11
0
        public APIResult <ProfileResponse> Get(int id)
        {
            using (var ctx = new DAL.MainEntities())
            {
                ProfileResponse profile = new ProfileResponse();

                profile.Account = ctx.vwProfile.Where(a => a.id == id).FirstOrDefault();

                if (profile.Account == null)
                {
                    return(APIResult <ProfileResponse> .Error(ResponseCode.UserNotFound, "This account not found!"));
                }

                profile.Vehicles = ctx.tbl_vehicles.Where(a => a.owner_id == profile.Account.id && a.is_delete != true)
                                   .Select(
                    c => new VehicleResponse()
                {
                    data = c,

                    images = new ImagesResponse()
                    {
                        Count = ctx.tbl_images.Where(d => d.model_name == "tbl_vehicles" && d.model_id == c.id && d.model_tag == "main").Count(),
                        Url   = (ctx.tbl_images.Where(d => d.model_name == "tbl_vehicles" && d.model_id == c.id && d.model_tag == "main").Count() == 0) ? "" : "/img/scale/tbl_vehicles/" + c.id + "/original/main-{index}.gif"
                    }
                    // .Select(b => "/img/scale/tbl_vehicles/"+ b.model_id + "/original/main-"++".gif").ToList(),
                }).ToList();
                var vchiclesIDs = profile.Vehicles.Select(b => b.data.id).ToList();

                var driversIDs = ctx.tbl_drivers_vehicles_rel.Where(a => vchiclesIDs.Contains((int)a.vehicle_id)).Select(c => c.driver_id).ToList();
                profile.Drivers = ctx.vwProfile.Where(a => driversIDs.Contains(a.id)).ToList();

                return(APIResult <ProfileResponse> .Success(profile, "Data getted success"));
            }
        }
Esempio n. 12
0
        public async Task <Profile> GetUserProfile(string appToken, string slackId)
        {
            using (var httpClient = httpClientFactory.CreateClient(nameof(ISlackClient)))
            {
                httpClient.BaseAddress = new Uri("https://slack.com");
                var request   = new HttpRequestMessage(HttpMethod.Post, "api/users.profile.get");
                var keyValues = new List <KeyValuePair <string, string> >();
                keyValues.Add(new KeyValuePair <string, string>("token", appToken));
                keyValues.Add(new KeyValuePair <string, string>("user", slackId));

                var values   = new FormUrlEncodedContent(keyValues);
                var response = await httpClient.PostAsync("api/users.profile.get", values);

                ProfileResponse profileResponse = new ProfileResponse();
                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();

                    profileResponse = JsonConvert.DeserializeObject <ProfileResponse>(responseBody);
                }
                else
                {
                    logger.LogError($"Error during fetch slack profile, {response.StatusCode}");
                    return(null);
                }

                return(profileResponse.Profile);
            }
        }
Esempio n. 13
0
        public async Task RunAsync(IRestContext context)
        {
            // IUserApi provides all functions for user management
            IUserApi userApi = context.Factory.CreateUserApi();

            // getSession()
            Session session = await userApi.GetSessionAsync();

            Console.WriteLine("Session ID: {0}", session.session_id);

            // getProfile()
            ProfileResponse profile = await userApi.GetProfileAsync();

            Console.WriteLine("Email from your profile: {0}", profile.email);

            // changePassword()
            const string newPassword = Program.Password + "new";
            bool         ok          = await userApi.ChangePasswordAsync(Program.Password, newPassword);

            if (ok)
            {
                // Changing password back
                if (await userApi.ChangePasswordAsync(newPassword, Program.Password))
                {
                    Console.WriteLine("Password was changed and reverted");
                }
            }
        }
Esempio n. 14
0
        public void DeserializeProfileResponse()
        {
            string          json     = TestData["ProfileResponse.json"];
            ProfileResponse response = NewtonsoftJsonSerializer
                                       .Create(JsonNamingStrategy.CamelCase)
                                       .Deserialize <ProfileResponse>(json);

            Assert.IsNotNull(response.ProfileUsers);
            Assert.IsNotEmpty(response.ProfileUsers);
            Assert.AreEqual(1, response.ProfileUsers.Length);

            Assert.AreEqual(2580478784034343, response.ProfileUsers[0].Id);
            Assert.AreEqual(2580478784034343, response.ProfileUsers[0].HostId);
            Assert.IsFalse(response.ProfileUsers[0].IsSponsoredUser);
            Assert.IsNotNull(response.ProfileUsers[0].Settings);
            Assert.IsNotEmpty(response.ProfileUsers[0].Settings);
            Assert.AreEqual(6, response.ProfileUsers[0].Settings.Length);

            Assert.AreEqual(ProfileSetting.AppDisplayName, response.ProfileUsers[0].Settings[0].Id);
            Assert.AreEqual("Some Gamertag", response.ProfileUsers[0].Settings[0].Value);
            Assert.AreEqual(ProfileSetting.Gamerscore, response.ProfileUsers[0].Settings[1].Id);
            Assert.AreEqual("1337000", response.ProfileUsers[0].Settings[1].Value);
            Assert.AreEqual(ProfileSetting.Gamertag, response.ProfileUsers[0].Settings[2].Id);
            Assert.AreEqual("Some Gamertag", response.ProfileUsers[0].Settings[2].Value);
            Assert.AreEqual(ProfileSetting.PublicGamerpic, response.ProfileUsers[0].Settings[3].Id);
            Assert.AreEqual("http://images-eds.xboxlive.com/image?url=abcdef",
                            response.ProfileUsers[0].Settings[3].Value);
            Assert.AreEqual(ProfileSetting.XboxOneRep, response.ProfileUsers[0].Settings[4].Id);
            Assert.AreEqual("Superstar", response.ProfileUsers[0].Settings[4].Value);
            Assert.AreEqual(ProfileSetting.RealName, response.ProfileUsers[0].Settings[5].Id);
            Assert.AreEqual("John Doe", response.ProfileUsers[0].Settings[5].Value);
        }
        protected override async Task OnInitializedAsync()
        {
            ProfileResponse Profile = await JSRuntime.InvokeAsync <ProfileResponse>("GetProfile");

            if (Profile.Success)
            {
                CurrentUser.SetCurrentUser(Profile.User);
                CanRender = true;
                StateHasChanged();
                await JSRuntime.InvokeVoidAsync("LoadCards");
            }
            else
            {
                switch (Profile.StatusCode)
                {
                case 503:
                    NavigationManager.NavigateTo("/maintenance");
                    break;

                default:
                    NavigationManager.NavigateTo("/");
                    break;
                }
            }
            MaintenanceCheckResponse Response = await JSRuntime.InvokeAsync <MaintenanceCheckResponse>("MaintenanceCheck");

            MaintenanceMode = Response.IsUndergoingMaintenance;
            if (MaintenanceMode)
            {
                await JSRuntime.InvokeVoidAsync("SetTitle", "🚧 Maintenance Mode");
            }
        }
        public async Task <Boolean> UpdateProfileAndGoals(string jwtToken, Profile profile, List <Goal> goals)
        {
            ProfileUpdateRequest profileUpdateRequest = new ProfileUpdateRequest()
            {
                Id      = "10",
                Method  = "profile.Update",
                JSonRPC = "2.0",
                Profile = profile
            };
            string request     = JsonConvert.SerializeObject(profileUpdateRequest);
            string apiResponse = await CallFilteredApi <string>(request, jwtToken);

            ProfileResponse retProfile = new ProfileResponse();

            //check updatedProfile return is valid
            try
            {
                retProfile = JsonConvert.DeserializeObject <ProfileResponse>(apiResponse);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            //update goals
            foreach (Goal goal in goals)
            {
                await UpdateGoal <GoalResponse>(goal, jwtToken);
            }
            return(true);
        }
Esempio n. 17
0
        private static void ProfileTakePayment()
        {
            Console.WriteLine("Take Payment with Profile... ");

            ProfileResponse response = _bambora.Profiles.CreateProfile(
                new Card()
            {
                Name        = "Jane Doe",
                Number      = "5100000010001004",
                ExpiryMonth = "12",
                ExpiryYear  = "18",
                Cvd         = "123"
            },
                new Address()
            {
                Name         = "Jane Doe",
                AddressLine1 = "123 Fake St.",
                City         = "victoria",
                Province     = "bc",
                Country      = "ca",
                PostalCode   = "v9t2g6",
                PhoneNumber  = "12501234567",
                EmailAddress = "*****@*****.**"
            });

            Console.WriteLine("Created profile with ID: " + response.Id);

            // add a 2nd card
            response = _bambora.Profiles.AddCard(response.Id, new Card()
            {
                Name        = "Jane Doe",
                Number      = "4030000010001234",
                ExpiryMonth = "04",
                ExpiryYear  = "19",
                Cvd         = "123"
            });

            Assert.IsNotNull(response);
            Assert.AreEqual("Operation Successful", response.Message);

            PaymentResponse payment = _bambora.Payments.MakePayment(new ProfilePaymentRequest()
            {
                Amount         = 40.95M,
                OrderNumber    = getRandomOrderId("profile"),
                PaymentProfile = new PaymentProfileField()
                {
                    CardId       = 2,
                    CustomerCode = response.Id
                }
            });

            Console.WriteLine(payment.Message);
            Assert.IsNotNull(payment);
            Assert.AreEqual("Approved", payment.Message);
            Assert.AreEqual("P", payment.TransType);
            Assert.AreEqual("VI", payment.Card.CardType);

            // delete it so when we create a profile again with the same card we won't get an error
            _bambora.Profiles.DeleteProfile(response.Id);
        }
Esempio n. 18
0
        public async Task <IActionResult> Update([FromBody] ProfileResponse profile)
        {
            if (profile == null)
            {
                throw new ArgumentNullException(nameof(profile));
            }

            var subject = User.GetSubject();

            try
            {
                var parameter = profile.ToParameter();
                parameter.Subject = subject;
                if (!await _profileActions.Update(parameter))
                {
                    return(this.GetError(Constants.Errors.ErrUpdateProfile, HttpStatusCode.InternalServerError));
                }

                return(Ok());
            }
            catch (Exception ex)
            {
                return(this.GetError(ex.Message, HttpStatusCode.InternalServerError));
            }
        }
Esempio n. 19
0
        public async Task <ProfileResponse> GetProfile(int id)
        {
            var response = new ProfileResponse();

            var user = await _context.AppUsers.AsNoTracking().FirstOrDefaultAsync(x => x.AppUserId == id);

            if (user == null)
            {
                response.ResponseMessage = "No user account found";
                response.Status          = StatusCodes.Status404NotFound;
                return(response);
            }
            else
            {
                response.Status  = StatusCodes.Status200OK;
                response.Profile = new ProfileViewModel()
                {
                    FirstName = user.FirstName,
                    LastName  = user.LastName,
                    Birthday  = user.Birthday.GetValueOrDefault(),
                    Country   = user.Country,
                    Email     = user.Email,
                    Sex       = user.Sex,
                    Username  = user.Username
                };
            }
            return(response);
        }
Esempio n. 20
0
        public ActionResult DeleteSettings(Guid Id, Guid?userId)
        {
            Guid token = CheckSessionAuthState(CurrentUser, _authService);

            if (token == Guid.Empty)
            {
                return(Json(new { Status = "logoff" }, JsonRequestBehavior.AllowGet));
            }
            ProfileResponse response = _cryptxService.DeleteProfile(Id, token,
                                                                    userId == null ? Guid.Empty : (Guid)userId);

            if (response.Exception == null)
            {
            }
            else
            {
                throw response.Exception;
            }
            if (Request.IsAjaxRequest())
            {
                return(Json(new { response }, JsonRequestBehavior.AllowGet));
            }
            if (userId != null && userId != Guid.Empty)
            {
                return(RedirectToAction("Index", new { userId = (Guid)userId }));
            }
            return(RedirectToAction("Index"));
        }
Esempio n. 21
0
        private Task SyncProfileKeysAsync(ProfileResponse profile)
        {
            if (profile == null)
            {
                return(Task.FromResult(0));
            }

            if (!string.IsNullOrWhiteSpace(profile.Key))
            {
                _cryptoService.SetEncKey(new CipherString(profile.Key));
            }

            if (!string.IsNullOrWhiteSpace(profile.PrivateKey))
            {
                _cryptoService.SetPrivateKey(new CipherString(profile.PrivateKey));
            }

            if (!string.IsNullOrWhiteSpace(profile.SecurityStamp))
            {
                _appSettingsService.SecurityStamp = profile.SecurityStamp;
            }

            _cryptoService.SetOrgKeys(profile);
            return(Task.FromResult(0));
        }
Esempio n. 22
0
        public async Task <ProfileResponse> GetProfile()
        {
            taskCompletion = new TaskCompletionSource <GraphResponse>();
            ProfileResponse profileResponse = null;
            GraphCallback   graphCallback   = new GraphCallback();

            graphCallback.RequestCompleted += GraphCallback_RequestCompleted;

            var graphRequest = new GraphRequest(
                AccessToken.CurrentAccessToken,
                "me",
                null,
                HttpMethod.Get,
                graphCallback
                );

            graphRequest.ExecuteAsync();

            var graphResponse = await taskCompletion.Task;

            profileResponse = Newtonsoft.Json.JsonConvert.DeserializeObject
                              <ProfileResponse>(graphResponse.RawResponse);

            return(profileResponse);
        }
        private List <Claim> ParseClaimsFromAgentProfile(ProfileResponse agentProfile)
        {
            var profileItems = agentProfile.Payload.ProfileItem;

            //var listOfSecondaryLanguages = getProfileItemValues(profileItems, "ALLOW_LANG_OPT").Where(lang => lang.ToLower() != "none");
            var primaryReceiptLanguage = getProfileItemValue(profileItems, ProfileKeyNames.PrimaryReceiptLanguage);

            var secondaryReceiptLanguage = profileItems
                                           .Where(profileItem => profileItem.Key == ProfileKeyNames.AllowLanguageOption)?
                                           .Where(profileItem => !(profileItem.Index == 1 && profileItem.Value == "eng"))?
                                           .FirstOrDefault(x => x.Value != null && x.Value.ToLower() != "none" && x.Value.ToLower() != primaryReceiptLanguage.ToLower())?
                                           .Value;

            var agentProfileClaims = new List <Claim>()
                                     .TryAddClaim(ClaimsNames.AgentName,
                                                  getProfileItemValue(profileItems, ProfileKeyNames.AgentName))
                                     .TryAddClaim(ClaimsNames.StoreName,
                                                  getProfileItemValue(profileItems, ProfileKeyNames.GenericDocumentStore))
                                     .TryAddClaim(ClaimsNames.AgentTimeZone,
                                                  getProfileItemValue(profileItems, ProfileKeyNames.AgentTimeZone))
                                     .TryAddClaim(ClaimsNames.AgentTelNo,
                                                  getProfileItemValue(profileItems, ProfileKeyNames.AgentPhone))
                                     .TryAddClaim(ClaimsNames.PrimaryReceiptLanguage, primaryReceiptLanguage)
                                     .TryAddClaim(ClaimsNames.SecondaryReceiptLanguage, secondaryReceiptLanguage);

            var prodAuthorizationClaims = GetProductAuthorizationsFromAgentProfile(agentProfile);

            agentProfileClaims.AddRange(prodAuthorizationClaims);
            return(agentProfileClaims);
        }
Esempio n. 24
0
        /// <summary>
        /// gets the whole profile data from the FD-servers
        /// </summary>
        /// <returns></returns>
        internal ProfileResponse GetProfileData(Boolean useCachedData)
        {
            ProfileResponse response;

            try
            {
                if ((m_cachedResponse == null) || (!useCachedData))
                {
                    response = m_CompanionIO.GetProfileData();

                    if (!response.Cached)
                    {
                        String json = response.Json ?? "{}";

                        m_joCompanion = JsonConvert.DeserializeObject <JObject>(json);

                        CompanionStatus = response.LoginStatus;
                    }

                    m_cachedResponse = response;
                }
                else
                {
                    response = m_cachedResponse;
                }

                return(response);
            }
            catch (Exception ex)
            {
                throw new Exception("Error while getting data from the servers", ex);
            }
        }
        public IActionResult GetProfile([FromRoute] int userId)
        {
            var user      = _userFacade.GetUser(userId);
            var sanctions = _sanctionFacade.GetAllActiveOfUser(userId).ToList();

            ProfileResponse response;
            var             userProfile = new UserProfileModel(user.UserProfile.Name, user.UserProfile.Email,
                                                               user.UserProfile.AboutUser, user.UserProfile.BirthYear, user.UserProfile.Gender,
                                                               user.UserProfile.IsTeacher, user.UserProfile.AvatarLink, user.UserProfile.Contacts, sanctions);

            if (user.UserProfile.IsTeacher)
            {
                var reviews = new List <ReviewModel>();
                user.TeacherProfile.Reviews.ToList().ForEach(r =>
                {
                    reviews.Add(new ReviewModel(r.FromUser, r.Title, r.Text, r.Date, r.FromGroup));
                });
                var teacherProfile = new TeacherProfileModel(reviews,
                                                             user.TeacherProfile.Skills);
                response = new ProfileResponse(userProfile, teacherProfile);
            }
            else
            {
                response = new ProfileResponse(userProfile);
            }

            return(Ok(response));
        }
Esempio n. 26
0
    public static void GetUserProfile(ResponseCallback callback, ResponseFallback fallback)
    {
        HttpClient httpClient = new HttpClient();

        Request request = new Request(HttpClient.Method.GET, Route.GET_PROFILE);

        httpClient.Request(
            request,
            (statusCode, response) => {
            ProfileResponse profileResponse = Deserialize(response);
            callback(profileResponse);
        },
            (statusCode, error) => {
            if (statusCode == StatusCodes.CODE_VALIDATION_ERROR)
            {
                ValidationError validationError = ErrorDeserilizer.DeserializeValidationErrorData(error);
                fallback(statusCode, validationError);
            }
            else
            {
                GenericError genericError = ErrorDeserilizer.DeserializeGenericErrorData(error);
                fallback(statusCode, genericError);
            }
        }
            );
    }
Esempio n. 27
0
        private static void UpdateCardInProfile()
        {
            Console.WriteLine("Update a Card in a Profile... ");

            Gateway beanstream = new Gateway()
            {
                MerchantId      = 300200578,
                PaymentsApiKey  = "4BaD82D9197b4cc4b70a221911eE9f70",
                ReportingApiKey = "4e6Ff318bee64EA391609de89aD4CF5d",
                ProfilesApiKey  = "D97D3BE1EE964A6193D17A571D9FBC80",
                ApiVersion      = "1"
            };

            ProfileResponse response = beanstream.Profiles.CreateProfile(
                new Card()
            {
                Name        = "Jane Doe",
                Number      = "5100000010001004",
                ExpiryMonth = "12",
                ExpiryYear  = "18",
                Cvd         = "123"
            },
                new Address()
            {
                Name         = "Jane Doe",
                AddressLine1 = "123 Fake St.",
                City         = "victoria",
                Province     = "bc",
                Country      = "ca",
                PostalCode   = "v9t2g6",
                PhoneNumber  = "12501234567",
                EmailAddress = "*****@*****.**"
            });

            Console.WriteLine("Created profile with ID: " + response.Id);
            Assert.IsNotNull(response);
            Assert.AreEqual("Operation Successful", response.Message);

            PaymentProfile profile = beanstream.Profiles.GetProfile(response.Id);

            Assert.IsNotNull(profile);

            // get card
            Card card = profile.getCard(beanstream.Profiles, 1);

            Console.WriteLine("Retrieved card with expiry year: " + card.ExpiryYear);
            Assert.IsNotNull(card);
            Assert.AreEqual("18", card.ExpiryYear);
            card.ExpiryYear = "20";
            profile.UpdateCard(beanstream.Profiles, card);
            Console.WriteLine("Updated card expiry");
            card = profile.getCard(beanstream.Profiles, 1);
            Assert.IsNotNull(card);
            Assert.AreEqual("20", card.ExpiryYear);
            Console.WriteLine("Retrieved updated card with expiry year: " + card.ExpiryYear);

            // delete it so when we create a profile again with the same card we won't get an error
            beanstream.Profiles.DeleteProfile(response.Id);
        }
Esempio n. 28
0
        private ProfileResponse GetProfileDataInternal(bool force)
        {
            //We don't want to allow hammering of the API, so we cache response for 60 seconds.
            var profileResponse = new ProfileResponse();

            profileResponse.LoginStatus = LoginStatus.Ok;

            string cachedResponse = _Cache.Get(Constants.CACHE_PROFILEJSON) as string;

            if (!String.IsNullOrEmpty(cachedResponse) && !force)
            {
                profileResponse.Cached         = true;
                profileResponse.HttpStatusCode = HttpStatusCode.OK;
                profileResponse.Json           = cachedResponse;
                return(profileResponse);
            }

            if (!_CurrentProfile.LoggedIn)
            {
                var loginResponse = LoginInternal();
                if (loginResponse.Status != LoginStatus.Ok)
                {
                    profileResponse.LoginStatus    = loginResponse.Status;
                    profileResponse.HttpStatusCode = loginResponse.HttpStatusCode;
                    profileResponse.Cached         = false;
                    return(profileResponse);
                }
            }

            using (var response = _Http.Get(Constants.URL_PROFILE, null))
            {
                profileResponse.Cached         = false;
                profileResponse.HttpStatusCode = response.StatusCode;
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                    {
                        profileResponse.Json = sr.ReadToEnd();

                        if (profileResponse.Json.ToLower().Equals("profile unavailable"))
                        {
                            profileResponse.LoginStatus = LoginStatus.UnknownError;
                            profileResponse.Json        = "{}";
                        }
                    }
                }
                else
                {
                    profileResponse.LoginStatus = LoginStatus.NotAccessible;
                    profileResponse.Json        = "{}";
                }
            }

            _Cache.Set(Constants.CACHE_PROFILEJSON, profileResponse.Json, DateTimeOffset.Now.AddSeconds(Constants.CACHE_PROFILE_SECONDS));

            _sWatch.Restart();

            return(profileResponse);
        }
Esempio n. 29
0
        public async Task <ProfileResponse> GetUserProfile(string username)
        {
            var user = await _userRepository.GetUser(username);

            ProfileResponse response = _mapper.Map <ProfileResponse>(user);

            return(response);
        }
Esempio n. 30
0
        private static void CreateProfileWithToken()
        {
            Console.WriteLine("Creating Payment Profile with a Legato Token... ");

            Gateway beanstream = new Gateway()
            {
                MerchantId      = 300200578,
                PaymentsApiKey  = "4BaD82D9197b4cc4b70a221911eE9f70",
                ReportingApiKey = "4e6Ff318bee64EA391609de89aD4CF5d",
                ProfilesApiKey  = "D97D3BE1EE964A6193D17A571D9FBC80",
                ApiVersion      = "1"
            };

            string url  = "https://www.beanstream.com/scripts/tokenization/tokens";
            var    data = new {
                number       = "5100000010001004",
                expiry_month = "12",
                expiry_year  = "18",
                cvd          = "123"
            };

            var requestInfo             = new RequestObject(HttpMethod.Post, url, null, data);
            var command                 = new ExecuteWebRequest(requestInfo);
            WebCommandExecuter executer = new WebCommandExecuter();
            var result = executer.ExecuteCommand(command);

            LegatoTokenResponse token = JsonConvert.DeserializeObject <LegatoTokenResponse>(result.Response);

            Console.WriteLine("Retrieved Legato Token: " + token.Token);

            // You can create a profile with a token instead of a card.
            // It will save the billing information, but the token is still single-use
            ProfileResponse response = beanstream.Profiles.CreateProfile(
                new Token()
            {
                Name = "Jane Doe",
                Code = token.Token
            },
                new Address()
            {
                Name         = "Jane Doe",
                AddressLine1 = "123 Fake St.",
                City         = "victoria",
                Province     = "bc",
                Country      = "ca",
                PostalCode   = "v9t2g6",
                PhoneNumber  = "12501234567",
                EmailAddress = "*****@*****.**"
            });

            Console.WriteLine("Created profile with ID: " + response.Id);

            Assert.IsNotNull(response);
            Assert.AreEqual("Operation Successful", response.Message);

            // delete it so when we create a profile again with the same card we won't get an error
            beanstream.Profiles.DeleteProfile(response.Id);
        }
Esempio n. 31
0
        public void Response_Parse()
        {
            var response = ProfileResponse.Parse("OK: HELLO WORLD!");

            Assert.True(response.Success);
            Assert.Equal("HELLO WORLD!", response.Value);
            Assert.Null(response.JObject);
            Assert.Equal("OK: HELLO WORLD!", response.ToString());
        }
Esempio n. 32
0
        private async Task<ProfileResponse> GetProfileDataInternal(bool force)
        {
            //We don't want to allow hammering of the API, so we cache response for 60 seconds.
            var profileResponse = new ProfileResponse();
            profileResponse.LoginStatus = LoginStatus.Ok;
            string cachedResponse = _Cache.Get(Constants.CACHE_PROFILEJSON) as string;
            if (!String.IsNullOrEmpty(cachedResponse) && !force)
            {
                profileResponse.Cached = true;
                profileResponse.HttpStatusCode = HttpStatusCode.OK;
                profileResponse.Json = cachedResponse;
                return profileResponse;
            }

            if (!_CurrentProfile.LoggedIn)
            {
                var loginResponse = await LoginInternal();
                if (loginResponse.Status != LoginStatus.Ok)
                {
                    profileResponse.LoginStatus = loginResponse.Status;
                    profileResponse.HttpStatusCode = loginResponse.HttpStatusCode;
                    profileResponse.Cached = false;
                    return profileResponse;
                }
            }

            using (var response = await _Http.Get(Constants.URL_PROFILE, null))
            {
                profileResponse.Cached = false;
                profileResponse.HttpStatusCode = response.StatusCode;
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                    {
                        profileResponse.Json = sr.ReadToEnd();
                    }
                }
            }
            _Cache.Set(Constants.CACHE_PROFILEJSON, profileResponse.Json, DateTimeOffset.Now.AddSeconds(Constants.CACHE_PROFILE_SECONDS));

            return profileResponse;
        }
Esempio n. 33
0
 private void StaffInfoEvent(ProfileResponse response)
 {
     if (response != null)
     {
         IDKin.IM.Core.Staff staff = this.dataService.GetStaff(response.uid);
         if (staff != null)
         {
             staff.Name = response.name;
             staff.Signature = response.signature;
             staff.Age = response.age;
             staff.Birthday = response.birthday;
             staff.BirthdayType = response.birthdayType;
             staff.BloodType = response.bloodType;
             staff.City = response.city;
             staff.Constellation = response.constellation;
             staff.Country = response.country;
             staff.CreateTime = response.createTime.ToString();
             staff.DepartmentId = response.department_id;
             staff.Email = response.email;
             staff.HeaderFileName = response.img;
             staff.Job = response.job;
             staff.Level = response.level.ToString();
             staff.Mobile = response.mobile;
             staff.MyDescription = response.description;
             staff.MyHome = response.site;
             staff.Nickname = response.nickname;
             staff.Province = response.province;
             staff.School = response.school;
             if (response.sex == 0)
             {
                 staff.Sex = Sex.Female;
             }
             else
             {
                 if (response.sex == 1)
                 {
                     staff.Sex = Sex.Male;
                 }
                 else
                 {
                     staff.Sex = Sex.Unknow;
                 }
             }
             staff.ShowScope = response.showScope;
             staff.Telephone = response.telephone;
             staff.Uid = response.uid;
             staff.UserName = response.username;
             staff.Zodiac = response.zodiac;
             if (this.sessionService.Uid == response.uid)
             {
                 SelfProfilePage selpage = WindowModel.Instance.GetSelfProfilePage();
                 if (selpage != null)
                 {
                     selpage.InitStafInfo(staff);
                 }
             }
             else
             {
                 UserProfilePage page = WindowModel.Instance.GetUserProfilePage(staff.Uid);
                 page.InitStafInfo(staff);
             }
         }
         System.Collections.Generic.ICollection<CooperationStaff> cooperationStaffs = this.dataService.GetCooperationStaff(response.uid);
         if (cooperationStaffs != null)
         {
             foreach (CooperationStaff item in cooperationStaffs)
             {
                 item.SynchronizeTo(response);
             }
         }
     }
 }