public override IQuestHandler.QuestState GetState() { ListSessionsRequest listSessionsRequest = new ListSessionsRequest(); listSessionsRequest.StartTime = Quest.CreationDate.ToString(); listSessionsRequest.EndTime = Quest.ExpirationDate.ToString(); ListSessionstResponse listSessionstResponse = GoogleFitService.ListSessions(_user, listSessionsRequest).GetAwaiter().GetResult(); if (Quest.IsClaimed) { return(IQuestHandler.QuestState.Claimed); } else if (listSessionstResponse.Sessions.Count >= Quest.ProgressCount) { return(IQuestHandler.QuestState.Finished); } else if (Quest.ExpirationDate > DateTime.Now) { return(IQuestHandler.QuestState.InProgress); } else { return(IQuestHandler.QuestState.Failed); } }
/// <summary> /// Retrieves a list of SessionSummary objects for an existing bastion. Bastion sessions let authorized users connect to a target resource for a predetermined amount of time. /// /// </summary> /// <param name="request">The request object containing the details to send. Required.</param> /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param> /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param> /// <returns>A response object containing details about the completed operation</returns> /// <example>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/dot-net-examples/latest/bastion/ListSessions.cs.html">here</a> to see an example of how to use ListSessions API.</example> public async Task <ListSessionsResponse> ListSessions(ListSessionsRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default) { logger.Trace("Called listSessions"); Uri uri = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/sessions".Trim('/'))); HttpMethod method = new HttpMethod("GET"); HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request); requestMessage.Headers.Add("Accept", "application/json"); GenericRetrier retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration); HttpResponseMessage responseMessage; try { if (retryingClient != null) { responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken).ConfigureAwait(false); } else { responseMessage = await this.restClient.HttpSend(requestMessage).ConfigureAwait(false); } this.restClient.CheckHttpResponseMessage(requestMessage, responseMessage); return(Converter.FromHttpResponseMessage <ListSessionsResponse>(responseMessage)); } catch (Exception e) { logger.Error($"ListSessions failed with error: {e.Message}"); throw; } }
/// <summary> /// 查询实例节点会话 /// </summary> public ListSessionsResponse ListSessions(ListSessionsRequest listSessionsRequest) { Dictionary <string, string> urlParam = new Dictionary <string, string>(); urlParam.Add("node_id", listSessionsRequest.NodeId.ToString()); string urlPath = HttpUtils.AddUrlPath("/v3/{project_id}/nodes/{node_id}/sessions", urlParam); SdkRequest request = HttpUtils.InitSdkRequest(urlPath, "application/json", listSessionsRequest); HttpResponseMessage response = DoHttpRequestSync("GET", request); return(JsonUtils.DeSerialize <ListSessionsResponse>(response)); }
/// <summary> /// Creates a new enumerable which will iterate over the responses received from the ListSessions operation. This enumerable /// will fetch more data from the server as needed. /// </summary> /// <param name="request">The request object containing the details to send</param> /// <param name="retryConfiguration">The configuration for retrying, may be null</param> /// <param name="cancellationToken">The cancellation token object</param> /// <returns>The enumerator, which supports a simple iteration over a collection of a specified type</returns> public IEnumerable <ListSessionsResponse> ListSessionsResponseEnumerator(ListSessionsRequest request, Common.Retry.RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default) { return(new Common.Utils.ResponseEnumerable <ListSessionsRequest, ListSessionsResponse>( response => response.OpcNextPage, input => { if (!string.IsNullOrEmpty(input)) { request.Page = input; } return request; }, request => client.ListSessions(request, retryConfiguration, cancellationToken) )); }
/// <summary>Snippet for ListSessionsAsync</summary> public async Task ListSessionsAsync_RequestObject() { // Snippet: ListSessionsAsync(ListSessionsRequest,CallSettings) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) ListSessionsRequest request = new ListSessionsRequest { Database = new Google.Cloud.Spanner.Common.V1.DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString(), }; // Make the request PagedAsyncEnumerable <ListSessionsResponse, Session> response = spannerClient.ListSessionsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Session item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSessionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Session item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page <Session> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Session item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet }
public void CreateListDeleteSession() { Session session; { CreateSessionRequest request = new CreateSessionRequest { Database = DatabaseUrl }; session = client.CreateSession(request); Assert.IsNotNull(session); AssertAffinityCount(1); } { ListSessionsRequest request = new ListSessionsRequest { Database = DatabaseUrl }; ListSessionsResponse response = client.ListSessions(request); Assert.IsNotNull(response); Assert.IsNotNull(response.Sessions); Assert.IsTrue(response.Sessions.Any(item => item.Name == session.Name)); AssertAffinityCount(1); } { DeleteSessionRequest request = new DeleteSessionRequest { Name = session.Name }; client.DeleteSession(request); AssertAffinityCount(0); } { ListSessionsRequest request = new ListSessionsRequest { Database = DatabaseUrl }; ListSessionsResponse response = client.ListSessions(request); Assert.IsNotNull(response); Assert.IsNotNull(response.Sessions); Assert.IsFalse(response.Sessions.Any(item => item.Name == session.Name)); AssertAffinityCount(0); } }
/* * Probes to test session related grpc call from Spanner stub. * * Includes tests against CreateSession, GetSession, ListSessions, and * DeleteSession of Spanner stub. * * Args: * stub: An object of SpannerStub. * metrics: A list of metrics. * */ public static void sessionManagement(Spanner.SpannerClient client, ref Dictionary <string, long> metrics) { long latency; CreateSessionRequest createSessionRequest = new CreateSessionRequest(); createSessionRequest.Database = _DATABASE; //Create Session test //Create stopwatch.Start(); Session session = client.CreateSession(createSessionRequest); stopwatch.Stop(); latency = stopwatch.ElapsedMilliseconds; metrics.Add("create_session_latency_ms", latency); //Get Session GetSessionRequest getSessionRequest = new GetSessionRequest(); getSessionRequest.Name = session.Name; stopwatch.Start(); client.GetSession(getSessionRequest); stopwatch.Stop(); latency = stopwatch.ElapsedMilliseconds; metrics.Add("get_session_latency_ms", latency); //List Session ListSessionsRequest listSessionsRequest = new ListSessionsRequest(); listSessionsRequest.Database = _DATABASE; stopwatch.Start(); client.ListSessions(listSessionsRequest); stopwatch.Stop(); latency = stopwatch.ElapsedMilliseconds; metrics.Add("list_sessions_latency_ms", latency); //Delete Session DeleteSessionRequest deleteSessionRequest = new DeleteSessionRequest(); deleteSessionRequest.Name = session.Name; stopwatch.Start(); client.DeleteSession(deleteSessionRequest); stopwatch.Stop(); latency = stopwatch.ElapsedMilliseconds; metrics.Add("delete_session_latency_ms", latency); }
protected override void ExecuteRequest(HttpContext context) { (bool isOk, User user) = CheckClaimsForUser(Request, context, _userRepository); if (!isOk || user == null) { return; } ListSessionsRequest listSessionsRequest = new ListSessionsRequest(); ListSessionstResponse listSessionstResponse = GoogleFitService.ListSessions(user, listSessionsRequest).GetAwaiter().GetResult(); List <Session> sessions = listSessionstResponse.Sessions; List <GetSleepEntriesDTOResponse.SessionDTOResponse> sessionsReponseDTO = sessions.Select( session => new GetSleepEntriesDTOResponse.SessionDTOResponse( session.Id, session.Name, session.Description, session.StartTimeMillis, session.EndTimeMillis, session.ModifiedTimeMillis, new GetSleepEntriesDTOResponse.SessionDTOResponse.AppliactionDTOResponse( session.Application.PackageName, session.Application.Version, session.Application.DetailUrl, session.Application.Name ), ((ActivityType)session.ActivityType).ToString(), session.ActiveTimeMillis )).ToList(); GetSleepEntriesDTOResponse responseDTO = new GetSleepEntriesDTOResponse(sessionsReponseDTO); string questsJson = JsonSerializer.Serialize(responseDTO.Sessions); context.Response.StatusCode = StatusCodes.Status200OK; context.Response.WriteAsync(questsJson).GetAwaiter().GetResult(); }
protected override void ProcessRecord() { base.ProcessRecord(); ListSessionsRequest request; try { request = new ListSessionsRequest { BastionId = BastionId, OpcRequestId = OpcRequestId, DisplayName = DisplayName, SessionLifecycleState = SessionLifecycleState, SessionId = SessionId, Limit = Limit, Page = Page, SortOrder = SortOrder, SortBy = SortBy }; IEnumerable <ListSessionsResponse> responses = GetRequestDelegate().Invoke(request); foreach (var item in responses) { response = item; WriteOutput(response, response.Items, true); } if (!ParameterSetName.Equals(AllPageSet) && !ParameterSetName.Equals(LimitSet) && response.OpcNextPage != null) { WriteWarning("This operation supports pagination and not all resources were returned. Re-run using the -All option to auto paginate and list all resources."); } FinishProcessing(response); } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
private static List<Session> searchForSessions(AuthenticationInfo auth, SessionManagementClient smc, Folder folder) { List<Session> sessionsToIndex = new List<Session>(); try { // Search for all sessions in this folder Guid folderId = folder.Id; Pagination pagination = new Pagination { PageNumber = 0, MaxNumberResults = maxPerPage }; ListSessionsRequest sessionRequest = new ListSessionsRequest { Pagination = pagination, FolderId = folderId}; ListSessionsResponse response = smc.GetSessionsList(auth, sessionRequest, ""); if (response.TotalNumberResults == 0) { Console.WriteLine("Found 0 results."); } else { int pagesOfResults = response.TotalNumberResults / maxPerPage; // List the sessions from the initial request foreach (Session session in response.Results) { // Add sessions to the list. sessionsToIndex.Add(session); } // If there are more pages, make additional network requests for (int page = 1; page < pagesOfResults; page++) { pagination = new Pagination { PageNumber = page, MaxNumberResults = maxPerPage }; sessionRequest = new ListSessionsRequest { Pagination = pagination, FolderId = folderId }; response = smc.GetSessionsList(auth, sessionRequest, ""); // List the sessions from the initial request foreach (Session session in response.Results) { // Add sessions to the list. sessionsToIndex.Add(session); } } } } catch (Exception e) { Console.WriteLine(string.Format("Error while searching for sessions in folder: {0} - {1}", folder.Name, e.Message)); } return sessionsToIndex; }
/// <summary> /// Get stats for all sessions user has access to. /// </summary> /// <param name="serverName">Server name</param> /// <param name="authUserKey">User name</param> /// <param name="authPassword">Password</param> /// <param name="errorMessage">Error message</param> /// <returns>String containing stats of all sessions</returns> public static string GetAllSessionStats(string serverName, string authUserKey, string authPassword, out string errorMessage) { string sessionStats = "Session ID, Session Name, Username, % Viewed, Last View Date, Folder Name\n"; //List<Guid> sessionIds = new List<Guid>(); errorMessage = "Query in progress."; if (!String.IsNullOrWhiteSpace(serverName) && !String.IsNullOrWhiteSpace(authUserKey) && !String.IsNullOrWhiteSpace(authPassword)) { try { // Permissions for user management SessionManagement.AuthenticationInfo sessionAuth = new SessionManagement.AuthenticationInfo() { UserKey = authUserKey, Password = authPassword }; SessionManagementClient smc = new SessionManagementClient( new BasicHttpsBinding(), new EndpointAddress(string.Format(SessionManagementEndpointFormat, serverName))); ListSessionsRequest request = new ListSessionsRequest(); SessionManagement.Pagination pagination = new SessionManagement.Pagination(); pagination.MaxNumberResults = MaxPerPage; pagination.PageNumber = 0; request.Pagination = pagination; // Query newer sessions first. request.SortBy = SessionSortField.Date; request.SortIncreasing = false; int totalPages = int.MaxValue; // not set yet while (request.Pagination.PageNumber < totalPages) { ListSessionsResponse sessionsResponse = smc.GetSessionsList(sessionAuth, request, null); Session[] sessions = sessionsResponse.Results; foreach (Session session in sessions) { sessionStats += GetAllStatsForSession(serverName, authUserKey, authPassword, session.Id, session.Name, session.FolderName, session.Duration); } // This is examined at the first call. if (totalPages == int.MaxValue) { int maxEntries = Math.Min(sessionsResponse.TotalNumberResults, CapSessions); totalPages = (maxEntries + MaxPerPage - 1) / MaxPerPage; } request.Pagination.PageNumber++; } } catch (Exception e) { errorMessage = e.Message; } } else { errorMessage = "Please enter servername, username, and password."; } return(sessionStats); }
partial void Modify_ListSessionsRequest(ref ListSessionsRequest request, ref CallSettings settings) => ApplyResourcePrefixHeaderFromDatabase(ref settings, request.Database);
/// <summary> /// Lists the current test sessions. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Session"/> resources.</returns> public override gax::PagedAsyncEnumerable <ListSessionsResponse, Session> ListSessionsAsync(ListSessionsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListSessionsRequest(ref request, ref callSettings); return(new gaxgrpc::GrpcPagedAsyncEnumerable <ListSessionsRequest, ListSessionsResponse, Session>(_callListSessions, request, callSettings)); }
partial void Modify_ListSessionsRequest(ref ListSessionsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary> /// Lists the current test sessions. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Session"/> resources.</returns> public virtual gax::PagedAsyncEnumerable <ListSessionsResponse, Session> ListSessionsAsync(ListSessionsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException();