protected override void ProcessRecord() { base.ProcessRecord(); ListEventsRequest request; try { request = new ListEventsRequest { CompartmentId = CompartmentId, StartTime = StartTime, EndTime = EndTime, Page = Page, OpcRequestId = OpcRequestId }; IEnumerable <ListEventsResponse> responses = GetRequestDelegate().Invoke(request); foreach (var item in responses) { response = item; WriteOutput(response, response.Items, true); } if (!ParameterSetName.Equals(AllPageSet) && 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); } }
/// <summary> /// Returns all the audit events processed for the specified compartment within the specified /// time range. /// /// </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/audit/ListEvents.cs.html">here</a> to see an example of how to use ListEvents API.</example> public async Task <ListEventsResponse> ListEvents(ListEventsRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default) { logger.Trace("Called listEvents"); Uri uri = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/auditEvents".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 <ListEventsResponse>(responseMessage)); } catch (Exception e) { logger.Error($"ListEvents failed with error: {e.Message}"); throw; } }
/// <summary> /// Gets error events that contain the passed in testId in the message. Will poll /// and wait for the entries to appear. /// </summary> /// <param name="startTime">The earliest error event time that will be looked at.</param> /// <param name="testId">The test id to filter error events on.</param> /// <param name="minEntries">The minimum number of error events that should be waited for. /// If minEntries is zero this method will wait the full timeout before checking for the /// entries.</param> private IEnumerable <ErrorEvent> GetEvents(DateTime startTime, string testId, int minEntries) { TimeSpan totalSleepTime = TimeSpan.Zero; while (totalSleepTime < _timeout) { TimeSpan sleepTime = minEntries > 0 ? _sleepInterval : _timeout; totalSleepTime += sleepTime; Thread.Sleep(sleepTime); List <ErrorEvent> errorEvents = new List <ErrorEvent>(); var groups = _client.ListGroupStats(_projectName, s_oneHour); foreach (var group in groups) { ListEventsRequest request = new ListEventsRequest { ProjectName = _projectName.ToString(), GroupId = group.Group.GroupId, TimeRange = s_oneHour }; var events = _client.ListEvents(request); errorEvents.AddRange(events.Where(e => e.Message.Contains(testId))); } if (minEntries == 0 || errorEvents.Count() >= minEntries) { return(errorEvents); } } return(new List <ErrorEvent>()); }
public ListEventsResponse ListEvents(string userId, string calendarId, ListEventsRequest request) { AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); ListEventsHeaders headers = new ListEventsHeaders(); return(ListEventsWithOptions(userId, calendarId, request, headers, runtime)); }
protected override void ProcessRecord() { base.ProcessRecord(); ListEventsRequest request; try { request = new ListEventsRequest { CompartmentId = CompartmentId, StartTime = StartTime, EndTime = EndTime, Page = Page, OpcRequestId = OpcRequestId }; IEnumerable <ListEventsResponse> responses = GetRequestDelegate().Invoke(request); foreach (var item in responses) { response = item; WriteOutput(response, response.Items, true); } FinishProcessing(response); } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
public static List<SubEntityRecord> GetDropdownValues(EventAdminDetailView parent, int eventId) { var existingPrerequisites = new List<EventPrerequisiteDto>(); if (eventId != 0) existingPrerequisites = GetEventPrerequisites(parent, eventId); var request = new ListEventsRequest() { }; var events = parent.ProcessRequest<ListEventsResponse>(request).Events; var records = new List<SubEntityRecord>(); foreach (var item in events.Where(s => !existingPrerequisites.Any(e => e.AssociatedEventId == s.Id))) { var record = new SubEntityRecord(); record.DisplayName = item.Title; record.Id = item.Id; record.Fields.Add(new Field(_id, "Id", FieldTypes.Hidden, null)); record.Fields.Add(new Field(_associatedEventId, "EventId", FieldTypes.Hidden, item.Id)); record.Fields.Add(new Field(_eventTitle, "Event Title", FieldTypes.Label, item.Title)); record.Fields.Add(new Field(_prerequisiteDescription, "Description", FieldTypes.WYSIWYG, string.Empty)); record.Fields.Add(new Field(_prerequisiteOrder, "Order ", FieldTypes.Text, string.Empty, true)); records.Add(record); } return records; }
private static async Task DisplayAudit( AuditClientAsync client, IdentityClient identityClinet, Compartment compartment, string startDate, string endDate, string requestId = "", string pageId = "") { // get Audit Events var listEventsRequest = new ListEventsRequest() { CompartmentId = compartment.Id, StartTime = startDate, EndTime = endDate, Page = pageId }; var events = await client.ListEvents(listEventsRequest); if (!string.IsNullOrEmpty(events.OpcNextPage)) { await DisplayAudit(client, identityClinet, compartment, startDate, endDate, events.OpcRequestId, events.OpcNextPage); } if (events.Items.Count > 0) { Count += events.Items.Count; Console.WriteLine($"enventset: com={compartment.Name}, start={startDate}, end={endDate}, events.Items:{events.Items.Count}"); } }
/// <summary> /// 查询事件监控列表 /// </summary> public ListEventsResponse ListEvents(ListEventsRequest listEventsRequest) { Dictionary <string, string> urlParam = new Dictionary <string, string>(); string urlPath = HttpUtils.AddUrlPath("/V1.0/{project_id}/events", urlParam); SdkRequest request = HttpUtils.InitSdkRequest(urlPath, "application/json", listEventsRequest); HttpResponseMessage response = DoHttpRequestSync("GET", request); return(JsonUtils.DeSerialize <ListEventsResponse>(response)); }
public ListEventsResponse ListEvents(ListEventsRequest request) { var command = new ListEvents(_apiKey, _secret, _baseUri, _authenticator, _builder) { Parameters = request }; return((ListEventsResponse)((ICommandExecutor)this).Execute(command)); }
/// <summary> /// 获取测试事件列表 /// </summary> public async Task <ListEventsResponse> ListEventsAsync(ListEventsRequest listEventsRequest) { Dictionary <string, string> urlParam = new Dictionary <string, string>(); urlParam.Add("function_urn", listEventsRequest.FunctionUrn.ToString()); string urlPath = HttpUtils.AddUrlPath("/v2/{project_id}/fgs/functions/{function_urn}/events", urlParam); SdkRequest request = HttpUtils.InitSdkRequest(urlPath, "application/json", listEventsRequest); HttpResponseMessage response = await DoHttpRequestAsync("GET", request); return(JsonUtils.DeSerialize <ListEventsResponse>(response)); }
public static async Task <ListEventsResponse> GetEvents(AuditClient client, ListEventsRequest request) { logger.Info("Get events"); try { return(await client.ListEvents(request)); } catch (Exception e) { logger.Error($"Failed at GetEvents:\n{e}"); throw; } }
/// <summary>Snippet for ListEvents</summary> public async Task ListEventsAsync_RequestObject() { // Snippet: ListEventsAsync(ListEventsRequest, CallSettings) // Create client ErrorStatsServiceClient errorStatsServiceClient = await ErrorStatsServiceClient.CreateAsync(); // Initialize request argument(s) ListEventsRequest request = new ListEventsRequest { ProjectNameAsProjectName = new ProjectName("[PROJECT]"), GroupId = "", ServiceFilter = new ServiceContextFilter(), TimeRange = new QueryTimeRange(), }; // Make the request PagedAsyncEnumerable <ListEventsResponse, ErrorEvent> response = errorStatsServiceClient.ListEventsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((ErrorEvent 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((ListEventsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ErrorEvent item in page) { // Do something with each item 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 <ErrorEvent> 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 (ErrorEvent item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet }
/// <summary> /// Creates a new enumerable which will iterate over the responses received from the ListEvents 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 <ListEventsResponse> ListEventsResponseEnumerator(ListEventsRequest request, Common.Retry.RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default) { return(new Common.Utils.ResponseEnumerable <ListEventsRequest, ListEventsResponse>( response => response.OpcNextPage, input => { if (!string.IsNullOrEmpty(input)) { request.Page = input; } return request; }, request => client.ListEvents(request, retryConfiguration, cancellationToken).Result )); }
public static async Task MainChangeRegion() { logger.Info("Starting example"); AuditClient client = null; try { // Assumption: the compartment id has been set in environment variable. var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); logger.Info(compartmentId); // ListEvents var listEventsRequest = new ListEventsRequest { CompartmentId = compartmentId, StartTime = DateTime.Now.AddDays(-1), EndTime = DateTime.Now }; // Create AuditClient var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); using (client = new AuditClient(provider, new ClientConfiguration())) { logger.Info($"AuditClient created. Region is set to: {provider.Region}"); ListEventsResponse listEventsResp = await GetEvents(client, listEventsRequest); logger.Info($"Received {listEventsResp?.Items.Count} items"); } // Change the region to US_ASHBURN_1 using SetRegion Call // We cannot use the same client to change the region. See: // https://stackoverflow.com/questions/51478525/httpclient-this-instance-has-already-started-one-or-more-requests-properties-ca using (client = new AuditClient(provider, new ClientConfiguration())) { client.SetRegion(Region.US_ASHBURN_1); logger.Info("Changing region to US_ASHBURN_1"); ListEventsResponse listEventsRespDiffRegion = await GetEvents(client, listEventsRequest); logger.Info($"Received {listEventsRespDiffRegion?.Items.Count} items"); } } catch (Exception e) { logger.Error($"Failed Change Region example: {e.Message}"); } }
/// <summary> /// Lists the specified events. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="groupId"> /// [Required] The group for which events shall be returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="ErrorEvent"/> resources. /// </returns> public override IPagedEnumerable <ListEventsResponse, ErrorEvent> ListEvents( string projectName, string groupId, string pageToken = null, int?pageSize = null, CallSettings callSettings = null) { ListEventsRequest request = new ListEventsRequest { ProjectName = projectName, GroupId = groupId, PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }; Modify_ListEventsRequest(ref request, ref callSettings); return(new PagedEnumerable <ListEventsRequest, ListEventsResponse, ErrorEvent>(_callListEvents, request, callSettings)); }
/// <summary> /// Returns all the audit events processed for the specified compartment within the specified time range. /// </summary> /// <param name="listRequest"></param> /// <returns></returns> public ListEventsResponse ListEvents(ListEventsRequest listRequest) { var uri = new Uri($"{GetEndPoint(AuditServices.EVENT, this.Region)}?{listRequest.GetOptionQuery()}"); using (var webResponse = this.RestClient.Get(uri, new HttpRequestHeaderParam() { OpcRequestId = listRequest.OpcRequestId })) using (var stream = webResponse.GetResponseStream()) using (var reader = new StreamReader(stream)) { var response = reader.ReadToEnd(); return(new ListEventsResponse() { Items = JsonSerializer.Deserialize <List <AuditEvent> >(response), OpcRequestId = webResponse.Headers.Get("opc-request-id"), OpcNextPage = webResponse.Headers.Get("opc-next-page") }); } }
/// <summary> /// Gets error events that contain the passed in testId in the message. Will poll /// and wait for the entries to appear. /// </summary> /// <param name="startTime">The earliest error event time that will be looked at.</param> /// <param name="testId">The test id to filter error events on.</param> /// <param name="minEntries">The minimum number of error events that should be waited for. /// If minEntries is zero this method will wait the full timeout before checking for the /// entries.</param> public IEnumerable <ErrorEvent> GetEvents(DateTime startTime, string testId, int minEntries) { return(GetEntries(minEntries, () => { List <ErrorEvent> errorEvents = new List <ErrorEvent>(); var groups = _client.ListGroupStats(_projectName, s_oneHour); foreach (var group in groups) { ListEventsRequest request = new ListEventsRequest { ProjectName = _projectName.ToString(), GroupId = group.Group.GroupId, TimeRange = s_oneHour }; var events = _client.ListEvents(request); errorEvents.AddRange(events.Where(e => e.Message.Contains(testId))); } return errorEvents; })); }
protected override void ProcessRecord() { base.ProcessRecord(); ListEventsRequest request; try { request = new ListEventsRequest { ManagedInstanceId = ManagedInstanceId, CompartmentId = CompartmentId, EventId = EventId, Limit = Limit, Page = Page, SortOrder = SortOrder, SortBy = SortBy, OpcRequestId = OpcRequestId, EventType = EventType, LatestTimestampLessThan = LatestTimestampLessThan, LatestTimestampGreaterThanOrEqualTo = LatestTimestampGreaterThanOrEqualTo }; IEnumerable <ListEventsResponse> responses = GetRequestDelegate().Invoke(request); foreach (var item in responses) { response = item; WriteOutput(response, response.EventCollection, 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); } }
public static async Task <ListEventsResponse> CancellationTokenExample(AuditClient client, ListEventsRequest request) { logger.Info("Starting CancellationToken Example"); var cts = new CancellationTokenSource(); cts.Cancel(); // Pass cancelled cancellation token to the list events list events operations and verify that // OperationCanceledException is thrown! try { return(await client.ListEvents(request, null, cts.Token)); } catch (OperationCanceledException e) { logger.Info(e.Message); return(null); } catch (Exception e) { logger.Error($"Failed at CancellationTokenExample:\n{e}"); throw; } }
public async Task <ListEventsResponse> ListEventsWithOptionsAsync(string userId, string calendarId, ListEventsRequest request, ListEventsHeaders headers, AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime) { AlibabaCloud.TeaUtil.Common.ValidateModel(request); Dictionary <string, object> query = new Dictionary <string, object>() { }; if (!AlibabaCloud.TeaUtil.Common.IsUnset(request.TimeMin)) { query["timeMin"] = request.TimeMin; } if (!AlibabaCloud.TeaUtil.Common.IsUnset(request.TimeMax)) { query["timeMax"] = request.TimeMax; } if (!AlibabaCloud.TeaUtil.Common.IsUnset(request.ShowDeleted)) { query["showDeleted"] = request.ShowDeleted; } if (!AlibabaCloud.TeaUtil.Common.IsUnset(request.MaxResults)) { query["maxResults"] = request.MaxResults; } if (!AlibabaCloud.TeaUtil.Common.IsUnset(request.NextToken)) { query["nextToken"] = request.NextToken; } if (!AlibabaCloud.TeaUtil.Common.IsUnset(request.SyncToken)) { query["syncToken"] = request.SyncToken; } Dictionary <string, string> realHeaders = new Dictionary <string, string>() { }; if (!AlibabaCloud.TeaUtil.Common.IsUnset(headers.CommonHeaders)) { realHeaders = headers.CommonHeaders; } if (!AlibabaCloud.TeaUtil.Common.IsUnset(headers.XAcsDingtalkAccessToken)) { realHeaders["x-acs-dingtalk-access-token"] = headers.XAcsDingtalkAccessToken; } AlibabaCloud.OpenApiClient.Models.OpenApiRequest req = new AlibabaCloud.OpenApiClient.Models.OpenApiRequest { Headers = realHeaders, Query = AlibabaCloud.OpenApiUtil.Client.Query(query), }; return(TeaModel.ToObject <ListEventsResponse>(await DoROARequestAsync("ListEvents", "calendar_1.0", "HTTP", "GET", "AK", "/v1.0/calendar/users/" + userId + "/calendars/" + calendarId + "/events", "json", req, runtime))); }
private static async void DisplayAudit(ClientConfig config, AuditClientAsync client, IdentityClient identityClinet, string compartmentId, string startDate, string endDate, string requestId, string pageId) { // get Audit Events var listEventsRequest = new ListEventsRequest() { CompartmentId = compartmentId, StartTime = startDate, EndTime = endDate, //Page = pageId //CompartmentId = "ocid1.compartment.oc1..aaaaaaaarj2edeedyk4o7rvcpdh6fckmeevwyog3k7zd4wjlyzcejib53yuq", //StartTime = "2019-10-29T09:33:57Z", //EndTime = "2019-10-29T11:33:57Z", OpcRequestId = requestId, Page = pageId }; var events = await client.ListEvents(listEventsRequest); if (!string.IsNullOrEmpty(events.OpcNextPage)) { DisplayAudit(config, client, identityClinet, compartmentId, startDate, endDate, events.OpcRequestId, events.OpcNextPage); } if (events.Items.Count > 0) { events.Items.ForEach(e => { Console.WriteLine($"* eventName:{e.Data.EventName}"); Console.WriteLine($"\t id:{e.EventId}"); Console.WriteLine($"\t type:{e.EventType}"); Console.WriteLine($"\t source:{e.Source}"); Console.WriteLine($"\t time:{e.EventTime}"); Console.WriteLine($"\t resourceName:{e.Data.ResourceName}"); if (e.Data.Identity != null) { Console.WriteLine($"\t principal:{e.Data.Identity.PrincipalId}"); try { var getUserRequest = new GetUserRequest() { UserId = e.Data.Identity.PrincipalId }; var user = identityClinet.GetUser(getUserRequest); Console.WriteLine($"\t user:{user.User.Name}"); } catch (WebException we) { if (we.Status.Equals(WebExceptionStatus.ProtocolError)) { var code = ((HttpWebResponse)we.Response).StatusCode; if (code == HttpStatusCode.NotFound) { // エラーだけ残す Console.WriteLine($"\t user not found"); return; } } } } }); } }
public static async Task <ListEventsResponse> RetryExample(AuditClient client, ListEventsRequest request) { logger.Info("Starting RetryExample"); try { return(await client.ListEvents(request, new RetryConfiguration { MaxAttempts = 5 })); } catch (Exception e) { logger.Error($"Failed at RetryExample:\n{e}"); throw; } }
partial void Modify_ListEventsRequest(ref ListEventsRequest request, ref CallSettings settings);
public static async Task Main() { logger.Info("Starting example"); AuditClient client = null; try { // Assumption: the compartment id has been set in environment variable. var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); logger.Info(compartmentId); // ListEvents var listEventsRequest = new ListEventsRequest { CompartmentId = compartmentId, StartTime = DateTime.Now.AddDays(-1), EndTime = DateTime.Now }; // Create AuditClient var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); using (client = new AuditClient(provider, new ClientConfiguration())) { logger.Info("AuditClient created."); ListEventsResponse listEventsResp = await NoRetryExample(client, listEventsRequest); logger.Info($"Received {listEventsResp?.Items.Count} items"); ListEventsResponse listEventsRespFromRetry = await RetryExample(client, listEventsRequest); logger.Info($"Received {listEventsRespFromRetry?.Items.Count} items"); await CancellationTokenExample(client, listEventsRequest); // GetConfiguration var getConfigurationRequest = new GetConfigurationRequest { CompartmentId = compartmentId }; logger.Info("GetConfigurationRequest created."); GetConfigurationResponse getConfigurationResp = await client.GetConfiguration(getConfigurationRequest); logger.Info($"Retention period days: {getConfigurationResp?.Configuration.RetentionPeriodDays}"); // UpdateConfiguration var updateConfigurationRequest = new UpdateConfigurationRequest { CompartmentId = compartmentId, UpdateConfigurationDetails = new UpdateConfigurationDetails { RetentionPeriodDays = 90 } }; logger.Info("UpdateConfigurationRequest created."); UpdateConfigurationResponse updateConfigurationResp = await client.UpdateConfiguration(updateConfigurationRequest); logger.Info($"opc work request id: {updateConfigurationResp.OpcRequestId}"); } } catch (Exception e) { logger.Error($"Failed Audit example: {e.Message}"); } }
public static async Task <ListEventsResponse> NoRetryExample(AuditClient client, ListEventsRequest request) { logger.Info("Starting NoRetryExample"); try { return(await client.ListEvents(request)); } catch (Exception e) { logger.Error($"Failed at NoRetryExample:\n{e}"); throw; } }