Beispiel #1
0
        public async Task <IActionResult> CreateOrUpdateAssignment(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = AssignmentsRoutePath)] HttpRequest req,
            [Table(AssignmentsTableName)] CloudTable assignmentsTable,
            [User] UsersClient usersClient)
        {
            string result = await req.ReadAsStringAsync();

            AssignmentDto    assignmentDto    = JsonConvert.DeserializeObject <AssignmentDto>(result);
            AssignmentEntity assignmentEntity = _mapper.Map <AssignmentEntity>(assignmentDto);

            assignmentEntity.ETag = "*";

            #if !DEBUG
            //While debugging, authorization header is empty when this API gets called from either Lti1 API or LtiAdvantage API
            // So to enable seamless debugging, putting this code in #if !DEBUG block

            bool isSystemCallOrUserWithValidEmail = req.Headers.TryGetUserEmails(out List <string> userEmails);
            if (!isSystemCallOrUserWithValidEmail)
            {
                _logger.LogError("Could not get user email.");
                return(new BadRequestErrorMessageResult("Could not get user email."));
            }

            if (userEmails.Count > 0)
            {
                _logger.LogInformation($"Getting user information for '{string.Join(';', userEmails)}'.");

                User[] allUsers = await usersClient.GetAllUsers(assignmentDto.Id);

                User user = allUsers.FirstOrDefault(member => userEmails.Any(userEmail => (member.Email ?? String.Empty).Equals(userEmail)));
                if (user == null || !user.Role.Equals("teacher"))
                {
                    return(new UnauthorizedResult());
                }
            }
            #endif

            ValidationContext context = new ValidationContext(assignmentDto, null, null);
            if (!Validator.TryValidateObject(assignmentDto, context, new List <ValidationResult>(), true))
            {
                _logger.LogError("One or more enteries are incorrect. The length of provided assignment name / course name / assignment description is too long.");
                return(new BadRequestErrorMessageResult("One or more enteries are incorrect. The length of provided assignment name / course name / assignment description is too long."));
            }

            TableOperation insertOrMergeAssignment = TableOperation.InsertOrMerge(assignmentEntity);
            TableResult    insertOrMergeResult     = await assignmentsTable.ExecuteAsync(insertOrMergeAssignment);

            if (insertOrMergeResult.HttpStatusCode < 200 || insertOrMergeResult.HttpStatusCode >= 300)
            {
                _logger.LogError($"Could not save assignment {assignmentEntity.ToAssignmentId()}. Error code: {insertOrMergeResult.HttpStatusCode}.");
                return(new InternalServerErrorResult());
            }

            _logger.LogInformation($"Saved assignment {assignmentEntity.ToAssignmentId()}.");

            string        assignmentUrl      = $"{req.Scheme}://{req.Host}/api/{AssignmentsRoutePath}/{assignmentEntity.ToAssignmentId()}";
            AssignmentDto savedAssignmentDto = _mapper.Map <AssignmentDto>(assignmentEntity);

            return(new CreatedResult(assignmentUrl, savedAssignmentDto));
        }
Beispiel #2
0
        static async Task Main()
        {
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client = new UsersClient(channel);

            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

            Console.WriteLine($"Sending User Request via gRPC");

            using var streamingCall = client.GetAllUser(new Server.SearchRequest()
            {
                Name = "R"
            }, cancellationToken: cts.Token);

            try
            {
                Console.WriteLine("Response Recived from gRPC \n");
                await foreach (var userData in streamingCall.ResponseStream.ReadAllAsync(cancellationToken: cts.Token))
                {
                    Console.WriteLine($" {userData.Id} | {userData.Name}");
                }

                Console.ReadLine();
            }
            catch (RpcException ex) when(ex.StatusCode == StatusCode.Cancelled)
            {
                Console.WriteLine("Stream cancelled.");
            }
        }
        public static async Task LogOut()
        {
            var request = new HttpRequestMessage(HttpMethod.Delete, "tokens");

            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", $"{_token}:".ToBase64String());
            await Client.SendAsync(request).ConfigureAwait(false);

            _token = Guid.Empty;

            lock (UsersLock)
            {
                _usersClient.Dispose();
                _usersClient  = null;
                _usersCreated = false;
            }

            lock (ChatsLock)
            {
                _chatsClient.Dispose();
                _chatsClient  = null;
                _chatsCreated = false;
            }

            lock (MessagesLock)
            {
                _messagesClient?.Dispose();
                _messagesClient  = null;
                _messagesCreated = false;
            }

            _poller?.Dispose();
            _poller = null;
        }
        public static void Main(string[] args)
        {
            // enter your configuration here
            string APP_ID  = null;
            string API_KEY = null;
            string TOKEN   = null;           // if specified, till take precedence over APP_ID/API_KEY
            // end of configuration

            UsersClient usersClient;

            if (!String.IsNullOrWhiteSpace(TOKEN))
            {
                usersClient = new UsersClient(new Authentication(TOKEN));
            }
            else
            {
                usersClient = new UsersClient(new Authentication(APP_ID, API_KEY));
            }


            Users users = usersClient.List();

            Console.WriteLine("Total number of users: " + users.total_count + "\n");
            Console.WriteLine("Page details: \n");
            Console.WriteLine(JsonConvert.SerializeObject(users.pages));
            Console.WriteLine("\nTotal pages: " + users.pages.total_pages);
            Console.WriteLine("First User (if any): \n");
            foreach (User user in users.users)
            {
                Console.WriteLine(JsonConvert.SerializeObject(user));
                break;
            }
        }
 public UserController(ILogger <UserController> logger, UsersClient usersClient, PanelsBranchClient panelBranchClient, Mapper mapper)
 {
     this.logger            = logger;
     this.usersClient       = usersClient;
     this.panelBranchClient = panelBranchClient;
     this.mapper            = mapper;
 }
Beispiel #6
0
        static async Task Main(string[] args)
        {
            var httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri("https://localhost:44380/");

            var usersClient = new UsersClient(httpClient);

            try
            {
                var users = await usersClient.UsersGetAsync();

                if (users != null && users.Any())
                {
                    users
                    .ToList()
                    .ForEach(x => Console.WriteLine($"User: {x.Name}"));
                }
                else
                {
                    Console.WriteLine("There is no users");
                }
            }
            catch (ApiException ex)
            {
                //do something
                Console.WriteLine($"HTTP Status Error Code: {ex.StatusCode}");
                Console.WriteLine($"Exception Message: {ex.Message}");
            }
            catch (Exception ex)
            {
                //do something
                Console.WriteLine(ex.Message);
            }
        }
        public async Task <IActionResult> Index()
        {
            var sessionToken = HttpContext.Session.GetString("AccessToken");

            if (sessionToken == null)
            {
                Response.Redirect("/Home/Authorize");
            }
            else
            {
                var users = new UsersClient(sessionToken);

                ViewData["me"] = await users.GetSelf();

                ViewData["userById"] = await users.GetUserById("15954374");

                ViewData["selfRecent"] = await users.GetSelfRecentMedia();

                ViewData["userRecent"] = await users.GetUserRecentMedia("15954374");

                ViewData["selfLiked"] = await users.GetSelfLikedMedia();

                ViewData["selfFollows"] = await users.GetSelfFollows();

                ViewData["selfFollwedBy"] = await users.GetSelfFollowedBy();
            }
            return(View());
        }
Beispiel #8
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="managementClient">Auth0 用户管理API Client实例</param>
 /// <param name="dataContext">用户数据的数据库上下文</param>
 /// <param name="configuration">程序配置文件</param>
 /// <param name="roleGetter">可用用户身份获取服务接口</param>
 public UserManagementService(ManagementApiClient managementClient, UserDataContext dataContext, IConfiguration configuration, IAvailableRoleGetterService roleGetter)
 {
     this.dataContext   = dataContext;
     this.configuration = configuration;
     this.roleGetter    = roleGetter;
     userClient         = managementClient.Users;
 }
Beispiel #9
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            UsersClient api = new UsersClient();
            await api.DeleteAsync(id);

            return(RedirectToAction("Index"));
        }
Beispiel #10
0
        public void Setup()
        {
            _httpClient      = new HttpClient();
            _usersClient     = new UsersClient(_httpClient);
            _testsClient     = new TestsClient(_httpClient);
            _questionsClient = new QuestionsClient(_httpClient);
            _sut             = new AnswersClient(_httpClient);

            _user = GetRandomUser();
            _usersClient.RegisterUserAsync(_user).GetAwaiter().GetResult();
            _testId = _testsClient.AddAsync().GetAwaiter().GetResult().Deserialize <Guid>();

            for (var i = 0; i < 10; i++)
            {
                _questionsClient.AddAsync(_testId).GetAwaiter().GetResult();
            }

            _questions = _questionsClient.GetListAsync(_testId).GetAwaiter().GetResult().Deserialize <List <QuestionDto> >();
            foreach (var question in _questions)
            {
                question.Question = GetRandomString();
                question.Answer   = GetRandomString();
                _questionsClient.UpdateAsync(question).GetAwaiter().GetResult();
            }
        }
Beispiel #11
0
 public SignupViewModel(
     INavigator navigator,
     UsersClient usersClient)
 {
     _navigator   = navigator;
     _usersClient = usersClient;
 }
Beispiel #12
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try {
                if (userToken != null)
                {
                    UsersClient            client      = new UsersClient(userToken.access_token);
                    ApiResponse <FeedItem> recentMedia = client.RecentMedia(null, null, null);

                    ViewData["UserData"] = client.User(null).data;

                    if (recentMedia != null)
                    {
                        ViewData["RecentMedia"] = recentMedia.data.Take(6).ToList();
                        ViewData["Following"]   = client.Follows(null).data.Take(12).ToList();
                        ViewData["FollowedBy"]  = client.FollowedBy(null).data.Take(12).ToList();
                    }
                }
                else
                {
                    MediaClient mediaClient = new MediaClient("");
                    ViewData["Popular"]       = mediaClient.Popular(EnvironmentHelpers.GetConfigValue("ClientId")).data;
                    ViewData["Authenticated"] = "false";
                }
            } catch { }

            base.OnActionExecuting(filterContext);
        }
Beispiel #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GoodreadsClient"/> class.
        /// Use this constructor if you already have OAuth permissions for the user.
        /// </summary>
        /// <param name="apiKey">Your Goodreads API key.</param>
        /// <param name="apiSecret">Your Goodreads API secret.</param>
        /// <param name="accessToken">The user's OAuth access token.</param>
        /// <param name="accessSecret">The user's OAuth access secret.</param>
        public GoodreadsClient(string apiKey, string apiSecret, string accessToken, string accessSecret)
        {
            var client = new RestClient(new Uri(GoodreadsUrl))
            {
                UserAgent = "goodreads-dotnet"
            };

            client.AddDefaultParameter("key", apiKey, ParameterType.QueryString);
            client.AddDefaultParameter("format", "xml", ParameterType.QueryString);

            var apiCredentials = new ApiCredentials(client, apiKey, apiSecret, accessToken, accessSecret);

            // Setup the OAuth authenticator if they have passed on the appropriate tokens
            if (!string.IsNullOrWhiteSpace(accessToken) &&
                !string.IsNullOrWhiteSpace(accessSecret))
            {
                client.Authenticator = OAuth1Authenticator.ForProtectedResource(
                    apiKey, apiSecret, accessToken, accessSecret);
            }

            Connection = new Connection(client, apiCredentials);
            Authors    = new AuthorsClient(Connection);
            Books      = new BooksClient(Connection);
            Shelves    = new ShelvesClient(Connection);
            Users      = new UsersClient(Connection);
            Reviews    = new ReviewsClient(Connection);
            Series     = new SeriesClient(Connection);
        }
Beispiel #14
0
        public MisskeyClient(Credential credential, HttpClientHandler innerHandler = null) : base(credential, new MisskeyAuthenticationHandler(innerHandler), RequestMode.Json)
        {
            BinaryParameters = new List <string> {
                "file"
            };

            Aggregation   = new AggregationClient(this);
            Ap            = new ApClient(this);
            Admin         = new AdminClient(this);
            App           = new MisskeyAppClient(this);
            Auth          = new AuthClient(this);
            Blocking      = new BlockingClient(this);
            Charts        = new ChartsClient(this);
            Drive         = new DriveClient(this);
            Federation    = new FederationClient(this);
            Following     = new FollowingClient(this);
            Hashtags      = new HashtagsClient(this);
            I             = new IClient(this);
            Messaging     = new MessagingClient(this);
            Mute          = new MuteClient(this);
            My            = new MyClient(this);
            Notes         = new NotesClient(this);
            Notifications = new NotificationsClient(this);
            Streaming     = new StreamingClient(this);
            Username      = new UsernameClient(this);
            Users         = new UsersClient(this);
        }
        public FileResult Export(string id)
        {
            UsersClient     Uc   = new UsersClient();
            ReportFileModel file = Uc.getReportFile(id);

            return(File(file.renderedBytes, file.mimeType));
        }
Beispiel #16
0
        public async Task <IActionResult> OnPostInitializeAsync()
        {
            if ((await CanAdmin()) == false)
            {
                return(Forbid());
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            HttpClient      httpclient = clientFactory.CreateClient();
            WorkspaceClient client     = new WorkspaceClient(httpclient);
            await client.InitializeAsync();

            UserMetadata rawUser = new UserMetadata {
                Email = "admin@localhost", Name = "Admin"
            };
            await _userManager.CreateAsync(rawUser, "admin");

            {
                UsersClient  ucli = new UsersClient(httpclient);
                UserMetadata user = await ucli.GetByNameAsync(rawUser.NormalizedName);

                ProblemsClient pcli = new ProblemsClient(httpclient);
                await pcli.CreateAsync(Helpers.Problems.GetAPlusB(user.Id));
            }

            return(RedirectToPage());
        }
Beispiel #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="token">OAuth 2.0 token obtained from Egnyte</param>
        /// <param name="domain">Domain on which you connect to egnyte,
        /// i.e.: domain is 'mydomain', when url looks like: mydomain.egnyte.com</param>
        /// <param name="httpClient">You can provide your own httpClient. Optional</param>
        /// <param name="requestTimeout">You can provide timeout for calling Egnyte API,
        /// by default it's 10 minutes. This parameter is optional</param>
        /// <param name="host">Full host name on which you connect to egnyte,
        /// i.e.: host is 'my.custom.host.com', when url looks like: my.custom.host.com</param>
        public EgnyteClient(
            string token,
            string domain           = "",
            HttpClient httpClient   = null,
            TimeSpan?requestTimeout = null,
            string host             = "")
        {
            if (string.IsNullOrWhiteSpace(token))
            {
                throw new ArgumentNullException(nameof(token));
            }

            if (string.IsNullOrWhiteSpace(domain) && string.IsNullOrWhiteSpace(host))
            {
                throw new ArgumentNullException("domain", "Domain or host has to specified");
            }

            httpClient = httpClient ?? new HttpClient();

            httpClient.Timeout = TimeSpan.FromMinutes(10);
            if (requestTimeout.HasValue)
            {
                httpClient.Timeout = requestTimeout.Value;
            }

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            Files       = new FilesClient(httpClient, domain, host);
            Users       = new UsersClient(httpClient, domain, host);
            Links       = new LinksClient(httpClient, domain, host);
            Groups      = new GroupsClient(httpClient, domain, host);
            Permissions = new PermissionsClient(httpClient, domain, host);
            Search      = new SearchClient(httpClient, domain, host);
            Audit       = new AuditClient(httpClient, domain, host);
        }
        public async Task <IActionResult> Index([FromQuery] UserFilterViewModel filter)
        {
            var apiClient = new UsersClient(Configuration.GetValue <String>("UsersApi"), GetHttpClient());
            var users     = await apiClient.FindUsersAsync(
                firstName : "Dejan",
                lastName : "",
                email : "*****@*****.**",
                pageIndex : 0,
                pageSize : 10,
                occupation : "",
                education : "",
                dateOfBirth : null
                );

            var user = users?.FirstOrDefault();

            if (user != null)
            {
                await apiClient.UpdateUserInfoAsync(
                    new UpdateUserInfoCommand()
                {
                    DateOfBirth = user.DateOfBirth,
                    Education   = user.Education,
                    FirstName   = user.FirstName,
                    LastName    = user.LastName,
                    Occupation  = "IT master - level 1"
                }
                    , user.Id.ToString());
            }

            return(View("Index"));
        }
Beispiel #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ManagementApiClient"/> class.
        /// </summary>
        /// <param name="token">A valid Auth0 Management API v2 token.</param>
        /// <param name="baseUri"><see cref="Uri"/> of the tenant to manage.</param>
        /// <param name="managementConnection"><see cref="IManagementConnection"/> to facilitate communication with server.</param>
        public ManagementApiClient(string token, Uri baseUri, IManagementConnection managementConnection = null)
        {
            if (managementConnection == null)
            {
                var ownedManagementConnection = new HttpClientManagementConnection();
                managementConnection = ownedManagementConnection;
                connectionToDispose  = ownedManagementConnection;
            }

            var defaultHeaders = CreateDefaultHeaders(token);

            BlacklistedTokens = new BlacklistedTokensClient(managementConnection, baseUri, defaultHeaders);
            ClientGrants      = new ClientGrantsClient(managementConnection, baseUri, defaultHeaders);
            Clients           = new ClientsClient(managementConnection, baseUri, defaultHeaders);
            Connections       = new ConnectionsClient(managementConnection, baseUri, defaultHeaders);
            CustomDomains     = new CustomDomainsClient(managementConnection, baseUri, defaultHeaders);
            DeviceCredentials = new DeviceCredentialsClient(managementConnection, baseUri, defaultHeaders);
            EmailProvider     = new EmailProviderClient(managementConnection, baseUri, defaultHeaders);
            EmailTemplates    = new EmailTemplatesClient(managementConnection, baseUri, defaultHeaders);
            Guardian          = new GuardianClient(managementConnection, baseUri, defaultHeaders);
            Jobs            = new JobsClient(managementConnection, baseUri, defaultHeaders);
            Logs            = new LogsClient(managementConnection, baseUri, defaultHeaders);
            ResourceServers = new ResourceServersClient(managementConnection, baseUri, defaultHeaders);
            Roles           = new RolesClient(managementConnection, baseUri, defaultHeaders);
            Rules           = new RulesClient(managementConnection, baseUri, defaultHeaders);
            Stats           = new StatsClient(managementConnection, baseUri, defaultHeaders);
            TenantSettings  = new TenantSettingsClient(managementConnection, baseUri, defaultHeaders);
            Tickets         = new TicketsClient(managementConnection, baseUri, defaultHeaders);
            UserBlocks      = new UserBlocksClient(managementConnection, baseUri, defaultHeaders);
            Users           = new UsersClient(managementConnection, baseUri, defaultHeaders);
        }
Beispiel #20
0
            public async Task ReturnsUserIdWhenAuthenticated()
            {
                var id = await UsersClient.GetAuthenticatedUserId();

                Assert.NotNull(id);
                Assert.Equal(id.Value, Helper.GetUserId());
            }
Beispiel #21
0
        private async void DeclineTaskAndPostAsync(object sender, RoutedEventArgs e)
        {
            UsersClient user = (UsersClient)this.AssingmentsBoxDelete.SelectedItem;

            if (user == null)
            {
                return;
            }

            RequestHandler client = new RequestHandler();
            await client.DeleteDataToAPI(task.TaskID + "/" + user.UserID);

            if (PopupUsersDelete.IsOpen)
            {
                PopupUsersDelete.IsOpen = false;
            }

            this.Frame.Navigate(typeof(MainPage));

            if (!PopupConfirmation.IsOpen)
            {
                PopupConfirmation.IsOpen  = true;
                TaskConfirmTextBlock.Text = "The task " + task.Title + "\n" + "has been declined by " + user.FirstName;
            }
        }
Beispiel #22
0
        private async void OpenPopupTaskList(object sender, RoutedEventArgs e)
        {
            RequestHandler client = new RequestHandler();
            IEnumerable <AssignmentsClient> assignments = await client.GetDataFromAPI <AssignmentsClient>("Assignments");

            IEnumerable <TasksClient> tasks = await client.GetDataFromAPI <TasksClient>("Tasks");

            var tasksForUser = new System.Text.StringBuilder();

            UsersClient user = (UsersClient)this.AssingmentsBox.SelectedItem;

            if (PopupUsers.IsOpen)
            {
                PopupUsers.IsOpen = false;
            }

            foreach (var assignment in assignments)
            {
                foreach (var task in tasks)
                {
                    if (assignment.TaskID == task.TaskID && assignment.UserID == user.UserID)
                    {
                        tasksForUser.Append(task.Title + "\n");
                    }
                }
            }

            UserNameTextBlock.Text    = user.FirstName + "'s task(s)";
            ListOfTasksTextBlock.Text = tasksForUser.ToString();

            if (!PopupListOfTasks.IsOpen)
            {
                PopupListOfTasks.IsOpen = true;
            }
        }
Beispiel #23
0
        private async void ConfirmAcceptTaskAndPostAsync(object sender, RoutedEventArgs e)
        {
            UsersClient user = (UsersClient)this.AssingmentsBox.SelectedItem;

            if (user == null)
            {
                return;
            }

            var assignmentToPost = new AssignmentsClient()
            {
                TaskID = task.TaskID,
                UserID = user.UserID
            };

            RequestHandler client = new RequestHandler();
            await client.PostDataToAPI(assignmentToPost);

            if (PopupUsers.IsOpen)
            {
                PopupUsers.IsOpen = false;
            }

            this.Frame.Navigate(typeof(MainPage));

            if (!PopupConfirmation.IsOpen)
            {
                PopupConfirmation.IsOpen  = true;
                TaskConfirmTextBlock.Text = "The task " + task.Title + "\n" + "has been accepted by " + user.FirstName;
            }
        }
Beispiel #24
0
 public static void Logout()
 {
     CurrentUsername = null;
     UsersClient.SetBearerToken(null);
     TransactionsClient.SetBearerToken(null);
     IsLoggedIn = false;
 }
Beispiel #25
0
 public static void Login(string username, string accessToken)
 {
     CurrentUsername = username;
     UsersClient.SetBearerToken(accessToken);
     TransactionsClient.SetBearerToken(accessToken);
     IsLoggedIn = true;
 }
Beispiel #26
0
            public async Task ReturnsAUser()
            {
                var user = await UsersClient.GetByUserId(UserId);

                Assert.NotNull(user);
                Assert.Equal(user.Id, UserId);
            }
Beispiel #27
0
 public HipChatClient(IApiConnection apiConnection) : base(apiConnection)
 {
     Rooms        = new RoomsClient(apiConnection);
     Users        = new UsersClient(apiConnection);
     Emoticons    = new EmoticonsClient(apiConnection);
     Capabilities = new CapabilitiesClient(apiConnection);
 }
Beispiel #28
0
            public async Task ReturnsNullIfNotFound()
            {
                var username = Guid.NewGuid().ToString().Replace("-", string.Empty);
                var user     = await UsersClient.GetByUsername(username);

                Assert.Null(user);
            }
Beispiel #29
0
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                model.Password = tools.Encrypt.MD5Hash(model.Password);
                var result = new UsersClient().findUser(model);

                if (result != null)
                {
                    User _user = new User();
                    _user.Username = result.Username;
                    _user.Name     = result.Name;
                    _user.Password = tools.Encrypt.MD5Hash(result.Password);
                    _user.IdUser   = result.IdUser;
                    _user.RoleID   = result.RoleID;
                    Session.Add("name", _user.Name);
                    if (_user.RoleID == 1)
                    {
                        Session.Add(tools.Constants.RECEPTIONIST_SESSION, _user);
                    }
                    if (_user.RoleID == 2)
                    {
                        Session.Add(tools.Constants.CASHIER_SESSION, _user);
                    }

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", "Sai tên tài khoản hoặc mật khẩu!");
                    return(View("Index"));
                }
            }
            return(View("Index"));
        }
Beispiel #30
0
        public static async Task <SubmissionModel> GetAsync(SubmissionMetadata metadata, HttpClient client)
        {
            SubmissionModel res = new SubmissionModel
            {
                Metadata = metadata
            };

            try
            {
                SubmissionsClient scli = new SubmissionsClient(client);
                res.Result = await scli.GetResultAsync(metadata.Id);
            }
            catch
            {
                res.Result = new SubmissionResult
                {
                    State = JudgeState.Pending
                };
            }
            try
            {
                SubmissionsClient scli = new SubmissionsClient(client);
                using (FileResponse file = await scli.GetCodeAsync(metadata.Id))
                    using (StreamReader sr = new StreamReader(file.Stream))
                        res.Code = await sr.ReadToEndAsync();
            }
            catch
            {
                res.Code = "<Loading error>.";
            }
            try
            {
                ProblemsClient pcli = new ProblemsClient(client);
                res.Problem = await pcli.GetAsync(metadata.ProblemId);
            }
            catch
            {
                res.Problem = new ProblemMetadata
                {
                    Id   = res.Metadata.ProblemId,
                    Name = $"Not found: {res.Metadata.ProblemId}"
                };
            }
            try
            {
                UsersClient ucli = new UsersClient(client);
                res.User = await ucli.GetAsync(metadata.UserId);
            }
            catch
            {
                res.User = new UserMetadata
                {
                    Id   = res.Metadata.UserId,
                    Name = $"Not found: {res.Metadata.UserId}"
                };
            }

            return(res);
        }
Beispiel #31
0
 public LunoClient(ApiKeyConnection connection)
     : base(connection)
 {
     Analytics = new AnalyticsClient(connection);
     ApiAuthentication = new ApiAuthenticationClient(connection);
     Event = new EventClient(connection);
     Session = new SessionClient(connection);
     User = new UsersClient(connection);
 }
            public void SendsUpdateToCorrectUrl()
            {
                var endpoint = new Uri("user", UriKind.Relative);
                var client = Substitute.For<IApiConnection>();
                var usersClient = new UsersClient(client);

                usersClient.Update(new UserUpdate());

                client.Received().Patch<User>(endpoint, Args.UserUpdate);
            }
            public void RequestsCorrectUrl()
            {
                var endpoint = new Uri("user", UriKind.Relative);
                var client = Substitute.For<IApiConnection>();
                var usersClient = new UsersClient(client);

                usersClient.Current();

                client.Received().Get<User>(endpoint);
            }
        private void Setup(string apiToken, Uri baseUri)
        {
            settings = new OktaSettings();
            settings.ApiToken = apiToken;
            settings.BaseUri = baseUri;

            client = new OktaClient(settings);
            users = client.GetUsersClient();
            groups = client.GetGroupsClient();
            sessions = client.GetSessionsClient();
            apps = client.GetAppsClient();
            authn = new AuthClient(settings);
            factors = new OrgFactorsClient(settings);
        }
 public async Task EnsuresArgumentsNotNull()
 {
     var userEndpoint = new UsersClient(Substitute.For<IApiConnection>());
     await AssertEx.Throws<ArgumentNullException>(() => userEndpoint.Update(null));
 }
 public async Task ThrowsIfGivenNullUser()
 {
     var userEndpoint = new UsersClient(Substitute.For<IApiConnection>());
     await AssertEx.Throws<ArgumentNullException>(() => userEndpoint.Get(null));
 }
            public void SendsUpdateToCorrectUrl()
            {
                var endpoint = new Uri("user/emails", UriKind.Relative);
                var client = Substitute.For<IApiConnection>();
                var usersClient = new UsersClient(client);

                usersClient.GetEmails();

                client.Received().Get<IReadOnlyCollection<EmailAddress>>(endpoint, null);
            }