public SavedSearch CreateSavedSearch(SavedSearch savedSearch) { if (savedSearch.EntityId != Guid.Empty) { var existingSavedSearch = _savedSearchReadRepository.Get(savedSearch.EntityId); if (existingSavedSearch != null) { return(existingSavedSearch); } } return(_savedSearchWriteRepository.Save(savedSearch)); }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ReturnToAssetListWrapper.Visible = (WebUtils.GetRequestParam("Source", string.Empty).ToLower() == "assetlist"); if (WebUtils.GetIntRequestParam("AssetId", 0) != 0) { SavedSearch.Reset(); AssetIdTextBox.Text = WebUtils.GetIntRequestParam("AssetId", 0).ToString(); PerformSearchAndBindGrid(1); } } }
protected override void ProcessRecord() { SavedSearch properties = new SavedSearch() { Category = this.Category, DisplayName = this.DisplayName, Query = this.Query, Version = this.Version }; properties.Tags = SearchCommandHelper.PopulateAndValidateTagsForProperties(this.Tags, properties.Query); WriteObject(OperationalInsightsClient.CreateOrUpdateSavedSearch(ResourceGroupName, WorkspaceName, SavedSearchId, properties, Force, ConfirmAction), true); }
public void AlertsEnabled() { var candidateId = Guid.NewGuid(); SavedSearch savedSearch = null; var candidateService = new Mock <ICandidateService>(); candidateService.Setup(cs => cs.CreateSavedSearch(It.IsAny <SavedSearch>())).Callback <SavedSearch>(ss => { savedSearch = ss; }); var provider = new CandidateServiceProviderBuilder().With(candidateService).Build(); var viewModel = new ApprenticeshipSearchViewModelBuilder().Build(); provider.CreateSavedSearch(candidateId, viewModel); savedSearch.AlertsEnabled.Should().BeTrue(); }
public SavedSearch Save(SavedSearch entity) { _logger.Debug("Calling repository to save saved search with Id={0} for CandidateId={1}", entity.EntityId, entity.CandidateId); var mongoEntity = _mapper.Map <SavedSearch, MongoSavedSearch>(entity); UpdateEntityTimestamps(mongoEntity); Collection.Save(mongoEntity); _logger.Debug("Saved saved search to repository with Id={0}", entity.EntityId); return(_mapper.Map <MongoSavedSearch, SavedSearch>(mongoEntity)); }
static async Task DestroySavedSearchAsync(TwitterContext twitterCtx) { ulong savedSearchID = 0; SavedSearch savedSearch = await twitterCtx.DestroySavedSearchAsync(savedSearchID); if (savedSearch != null) { Console.WriteLine( "ID: {0}, Search: {1}", savedSearch.ID, savedSearch.Name); } }
public async Task <IEnumerable <GHLocation> > Search(string address, string latitude, string longitude, string keywords, string distanceType, string radius, int?userId) { try { IEnumerable <GHLocation> locations = new List <GHLocation>(); if (!string.IsNullOrEmpty(keywords)) { locations = SearchByKeywords(keywords); } else if (!string.IsNullOrEmpty(latitude) && !string.IsNullOrEmpty(longitude)) { locations = SearchByLatLong(double.Parse(latitude), double.Parse(longitude), double.Parse(radius), distanceType); } else { locations = await SearchByAddress(address, distanceType, radius); } if (userId != null && locations != null && locations.Any()) { var user = _ur.Find((int)userId); if (user != null) { var savedSearch = new SavedSearch() { Address = address, DistanceType = distanceType, Keywords = keywords, Latitude = latitude, Longitude = longitude, Radius = radius, UserId = (int)userId }; _ur.SaveSearch((long)userId, savedSearch); UserHelper.Dispose(); } } return(locations); } catch (Exception ex) { Log.Error(ex.Message, ex); return(null); } }
private void AddSavedSearchMenuItem(SavedSearch savedSearch) { var searchItem = new ToolStripMenuItem { Name = "savedSearchMenuItem", Size = new System.Drawing.Size(206, 22), Text = savedSearch.Name, Tag = savedSearch, }; searchItem.Click += new System.EventHandler(this.SavedSearchMenuItem_Click); this.savedSearchesSeparator.Visible = true; this.savedSearchesMenuItem.DropDownItems.Add(searchItem); }
public void Success() { var candidateId = Guid.NewGuid(); SavedSearch savedSearch = null; var candidateService = new Mock <ICandidateService>(); candidateService.Setup(cs => cs.CreateSavedSearch(It.IsAny <SavedSearch>())).Callback <SavedSearch>(ss => { savedSearch = ss; }); var provider = new CandidateServiceProviderBuilder().With(candidateService).Build(); var viewModel = new ApprenticeshipSearchViewModelBuilder().Build(); var response = provider.CreateSavedSearch(candidateId, viewModel); response.Should().NotBeNull(); candidateService.Verify(cs => cs.CreateSavedSearch(It.IsAny <SavedSearch>()), Times.Once); savedSearch.Should().NotBeNull(); }
public static SavedSearchViewModel ToViewModel(this SavedSearch savedSearch, int subCategoriesFullNamesLimit) { var viewModel = new SavedSearchViewModel { Id = savedSearch.EntityId, Name = savedSearch.Name(), SearchUrl = savedSearch.SearchUrl(), AlertsEnabled = savedSearch.AlertsEnabled, ApprenticeshipLevel = savedSearch.ApprenticeshipLevel, SubCategoriesFullNames = savedSearch.TruncatedSubCategoriesFullNames(subCategoriesFullNamesLimit), DateCreated = savedSearch.DateCreated, DateProcessed = savedSearch.DateProcessed }; return(viewModel); }
public void DeleteSavedSearch() { mockServer.ExpectNewRequest() .AndExpectUri("https://api.twitter.com/1.1/saved_searches/destroy/26897775.json") .AndExpectMethod(HttpMethod.POST) .AndRespondWith(JsonResource("Saved_Search"), responseHeaders); #if NET_4_0 || SILVERLIGHT_5 SavedSearch deletedSavedSearch = twitter.SearchOperations.DeleteSavedSearchAsync(26897775).Result; #else SavedSearch deletedSavedSearch = twitter.SearchOperations.DeleteSavedSearch(26897775); #endif Assert.AreEqual(26897775, deletedSavedSearch.ID); Assert.AreEqual("#springsocial", deletedSavedSearch.Query); Assert.AreEqual("#springsocial", deletedSavedSearch.Name); Assert.AreEqual(0, deletedSavedSearch.Position); }
protected override void ProcessRecord() { SavedSearch properties = new SavedSearch() { Category = this.Category, DisplayName = this.DisplayName, Query = this.Query, Version = this.Version, FunctionAlias = this.FunctionAlias, FunctionParameters = this.FunctionParameter }; bool patch = this.IsParameterBound(c => c.FunctionParameter); properties.Tags = SearchCommandHelper.PopulateAndValidateTagsForProperties(this.Tag, properties.Query); WriteObject(OperationalInsightsClient.CreateOrUpdateSavedSearch(ResourceGroupName, WorkspaceName, SavedSearchId, properties, patch, true, ConfirmAction, ETag), true); }
public SavedSearch GetSavedSearchFromParameters() { SavedSearch savedSearch = new SavedSearch() { //Id = this.SavedSearchId, Category = this.Category, DisplayName = this.DisplayName, Query = this.Query, Version = this.Version, FunctionAlias = this.FunctionAlias, FunctionParameters = this.FunctionParameters, Etag = this.ETag, Tags = ConvertAndValidateTags(this.Tags) }; return(savedSearch); }
public void SubCategoriesMustBelongToCategory() { var candidateId = Guid.NewGuid(); const string category = "MFP"; var subCategories = new[] { "513", "540", "600" }; const string subCategoriesFullNames = "Surveying|Construction Civil Engineering"; var categories = new List <Category> { new Category(17, category, category, CategoryType.SectorSubjectAreaTier1, CategoryStatus.Active, new List <Category> { new Category(255, "513", "Surveying", CategoryType.Framework, CategoryStatus.Active), new Category(273, "540", "Construction Civil Engineering", CategoryType.Framework, CategoryStatus.Active) } ), new Category(0, "OTHER", "OTHER", CategoryType.SectorSubjectAreaTier1, CategoryStatus.Active, new List <Category> { new Category(329, "600", "Should not be included", CategoryType.Framework, CategoryStatus.Active) } ) }; SavedSearch savedSearch = null; var candidateService = new Mock <ICandidateService>(); candidateService.Setup(cs => cs.CreateSavedSearch(It.IsAny <SavedSearch>())).Callback <SavedSearch>(ss => { savedSearch = ss; }); var provider = new CandidateServiceProviderBuilder().With(candidateService).Build(); var viewModel = new ApprenticeshipSearchViewModelBuilder() .WithCategory(category) .WithSubCategories(subCategories) .WithCategories(categories) .Build(); var response = provider.CreateSavedSearch(candidateId, viewModel); response.Should().NotBeNull(); candidateService.Verify(cs => cs.CreateSavedSearch(It.IsAny <SavedSearch>()), Times.Once); savedSearch.Should().NotBeNull(); savedSearch.CandidateId.Should().Be(candidateId); savedSearch.Category.Should().Be(category); savedSearch.SubCategories.Length.Should().Be(2); savedSearch.SubCategories.Should().NotContain("600"); savedSearch.SubCategoriesFullName.Should().Be(subCategoriesFullNames); }
private static IV1Facade RestClientV1Initializer(IRequestBuilderFactory requestBuilderFactory, IClientProvider clientProvider, IContentFormattersFactory contentFormattersFactory) { var uploadProgressTracker = new UploadProgressTracker(); var parameterHelper = new ParameterHelper(); var executionHelper = new ExecutionHelper(); var cabinet = new CabinetV1(requestBuilderFactory, clientProvider); var customAttributeValues = new CustomAttributeValues(requestBuilderFactory, clientProvider); var document = new DocumentV1(requestBuilderFactory, clientProvider, contentFormattersFactory, uploadProgressTracker); var filter = new Filter(requestBuilderFactory, clientProvider, parameterHelper, executionHelper); var folder = new Folder(requestBuilderFactory, clientProvider, parameterHelper, executionHelper, contentFormattersFactory); var group = new Group(clientProvider, requestBuilderFactory); var repository = new Repository(requestBuilderFactory, clientProvider); var savedSearch = new SavedSearch(requestBuilderFactory, clientProvider, parameterHelper, executionHelper); var search = new SearchV1(requestBuilderFactory, clientProvider, parameterHelper, executionHelper); var sync = new Sync(requestBuilderFactory, clientProvider); var user = new UserV1(requestBuilderFactory, clientProvider, parameterHelper, executionHelper); var workspace = new Workspace(requestBuilderFactory, clientProvider, parameterHelper, executionHelper); return(new V1Facade(cabinet, customAttributeValues, document, filter, folder, group, repository, savedSearch, search, sync, user, workspace)); }
protected void SavedSearchItemLink_Clicked(object sender, EventArgs e) { string name = ((LinkButton)sender).CommandArgument; int userID = this.GetUserId; string searchId = SavedSearchesID; List <SavedSearch> aList = SavedSearchBLL.GetSavedSearch(searchId, userID, name); if (aList == null || aList.Count != 1) { log.Error("Error recovering saved search name:" + name + ", user:"******", searchid:" + searchId); return; } SavedSearch theSavedSearch = aList[0]; Query = theSavedSearch.SearchExpression; }
public PSSavedSearchProperties(SavedSearch properties) { if (properties != null) { this.Category = properties.Category; this.DisplayName = properties.DisplayName; this.Query = properties.Query; this.Version = properties.Version; this.Tags = new Hashtable(); if (properties.Tags != null) { foreach (Tag tag in properties.Tags) { this.Tags[tag.Name] = tag.Value; } } } }
protected override void ProcessRecord() { SavedSearch properties = new SavedSearch() { Category = this.Category, DisplayName = this.DisplayName, Query = this.Query, Version = this.Version, Tags = new List <Tag>() { new Tag() { Name = "Group", Value = "Computer" } } }; WriteObject(OperationalInsightsClient.CreateOrUpdateSavedSearch(ResourceGroupName, WorkspaceName, SavedSearchId, properties, Force, ConfirmAction), true); }
public SavedSearchAlert GetUnsentSavedSearchAlert(SavedSearch savedSearch) { _logger.Debug("Calling repository to get unsent saved search alert for saved search Id={0}", savedSearch.EntityId); var mongoAlert = Collection.AsQueryable <MongoSavedSearchAlert>() .SingleOrDefault(a => a.BatchId == null && a.Parameters.EntityId == savedSearch.EntityId); if (mongoAlert == null) { _logger.Debug("Did not find unsent saved search alert for saved search Id={0}", savedSearch.EntityId); return(null); } _logger.Debug("Found unsent saved search alert for saved search Id={0}", savedSearch.EntityId); var alert = _mapper.Map <MongoSavedSearchAlert, SavedSearchAlert>(mongoAlert); return(alert); }
private void View_SavedSearchChanged(SavedSearch savedSearch) { if (savedSearch.SavedSearchProperties.Count > 0) { ClearSearchCriteria(); foreach (var prop in savedSearch.SavedSearchProperties) { var currentProperty = currentSearch.SavedSearchProperties.FirstOrDefault(p => p.PropertyName == prop.PropertyName && !p.IsReadonly); if (currentProperty != null) { currentProperty.PropertyValue = prop.PropertyValue; } } } currentSearch.Page = 1; currentSearch.PageMax = 1; View.SetSearchInfo(currentSearch.PageSize, currentSearch.Page, currentSearch.PageMax); View.SetSearchColumns(currentSearch.SavedSearchProperties); }
public async Task <IEnumerable <GHLocation> > FromSavedSearch(SavedSearch savedSearch) { try { if (string.IsNullOrEmpty(savedSearch.City) && string.IsNullOrEmpty(savedSearch.State) && string.IsNullOrEmpty(savedSearch.Zip)) { return(await Search(savedSearch.Address, savedSearch.Latitude, savedSearch.Longitude, savedSearch.Keywords, savedSearch.DistanceType, savedSearch.Radius, null)); } else { return(await Search(savedSearch.Address, savedSearch.City, savedSearch.State, savedSearch.Zip, savedSearch.Latitude, savedSearch.Longitude, savedSearch.Keywords, savedSearch.DistanceType, savedSearch.Radius, null)); } } catch (Exception ex) { Log.Error(ex.Message, ex); return(null); } }
protected void btnSavedSearches_Save_Click(object sender, EventArgs e) { if (!Page.IsValid) { return; } // Change the way the application gets the user here int userId = this.GetUserId; string name = txtSavedSearch.Text.Trim(); if (string.IsNullOrEmpty(Query)) { log.Debug("Cannot save a query without an expression"); return; } if (string.IsNullOrEmpty(name)) { log.Debug("Cannot save a query without a name"); return; } SavedSearch obj = new SavedSearch(SavedSearchesIDHidden.Value, userId, name, Query, DateTime.Now); if (SavedSearchBLL.Insert(obj)) { // Inform saved search was inserted log.Info("New saved search for user " + userId.ToString() + " searchId: " + SavedSearchesIDHidden.Value + " name: " + name); } else { // Inform saved search was NOT inserted log.Error("Error Saving new Savedsearch " + userId.ToString() + " searchId: " + SavedSearchesIDHidden.Value + " name: " + name); } SavedSearchesGrid.DataBind(); }
public void GetSavedSearches() { mockServer.ExpectNewRequest() .AndExpectUri("https://api.twitter.com/1.1/saved_searches/list.json") .AndExpectMethod(HttpMethod.GET) .AndRespondWith(JsonResource("Saved_Searches"), responseHeaders); #if NET_4_0 || SILVERLIGHT_5 IList <SavedSearch> savedSearches = twitter.SearchOperations.GetSavedSearchesAsync().Result; #else IList <SavedSearch> savedSearches = twitter.SearchOperations.GetSavedSearches(); #endif Assert.AreEqual(2, savedSearches.Count); SavedSearch search1 = savedSearches[0]; Assert.AreEqual(26897775, search1.ID); Assert.AreEqual("#springsocial", search1.Query); Assert.AreEqual("#springsocial", search1.Name); Assert.AreEqual(0, search1.Position); SavedSearch search2 = savedSearches[1]; Assert.AreEqual(56897772, search2.ID); Assert.AreEqual("#twitter", search2.Query); Assert.AreEqual("#twitter", search2.Name); Assert.AreEqual(1, search2.Position); }
public void CanCreateOrUpdateAndDeleteSavedSearches() { using (MockContext context = MockContext.Start(GetType().FullName)) { var client = TestHelper.GetOperationalInsightsManagementClient(this, context); // Since we are testing search operations, we can't just create a brand new workspace // because there are no ARM APIs to ingest data to a workspace. // But any workspace with data ingested should be good for this test. string resourceGroupName = "mms-eus"; string workspaceName = "workspace-861bd466-5400-44be-9552-5ba40823c3aa"; string newSavedSearchId = "test-new-saved-search-id-2015"; SavedSearch parameters = new SavedSearch(); parameters.Version = 1; parameters.Query = "* | measure Count() by Computer"; parameters.DisplayName = "Create or Update Saved Search Test"; parameters.Category = " Saved Search Test Category"; parameters.Tags = new List <Tag>() { new Tag() { Name = "Group", Value = "Computer" } }; var result = client.SavedSearches.ListByWorkspace(resourceGroupName, workspaceName); var savedSearchCreateResponse = client.SavedSearches.CreateOrUpdate( resourceGroupName, workspaceName, newSavedSearchId, parameters); Assert.NotNull(savedSearchCreateResponse.Id); Assert.NotNull(savedSearchCreateResponse.Etag); Assert.Equal(savedSearchCreateResponse.Query, parameters.Query); Assert.Equal(savedSearchCreateResponse.DisplayName, parameters.DisplayName); Assert.Equal(savedSearchCreateResponse.Tags[0].Name, parameters.Tags[0].Name); Assert.Equal(savedSearchCreateResponse.Tags[0].Value, parameters.Tags[0].Value); // Verify that the saved search was saved var savedSearchesResult = client.SavedSearches.ListByWorkspace(resourceGroupName, workspaceName); Assert.NotNull(savedSearchesResult); Assert.NotNull(savedSearchesResult.Value); Assert.NotEqual(0, savedSearchesResult.Value.Count); Assert.NotNull(savedSearchesResult.Value[0].Id); Assert.NotNull(savedSearchesResult.Value[0].Query); bool foundSavedSearch = false; for (int i = 0; i < savedSearchesResult.Value.Count; i++) { if (savedSearchesResult.Value[i].Category.Equals(parameters.Category) && savedSearchesResult.Value[i].Version == parameters.Version && savedSearchesResult.Value[i].Query.Equals(parameters.Query) && savedSearchesResult.Value[i].DisplayName.Equals(parameters.DisplayName) && savedSearchesResult.Value[i].Tags[0].Name.Equals(parameters.Tags[0].Name) && savedSearchesResult.Value[i].Tags[0].Value.Equals(parameters.Tags[0].Value)) { foundSavedSearch = true; parameters.Etag = savedSearchesResult.Value[i].Etag; } } Assert.True(foundSavedSearch); // Test updating a saved search parameters.Query = "*"; parameters.Tags = new List <Tag>() { new Tag() { Name = "Source", Value = "Test2" } }; var savedSearchUpdateResponse = client.SavedSearches.CreateOrUpdate( resourceGroupName, workspaceName, newSavedSearchId, parameters); Assert.NotNull(savedSearchUpdateResponse.Id); Assert.NotNull(savedSearchUpdateResponse.Etag); Assert.Equal(savedSearchUpdateResponse.Query, parameters.Query); Assert.Equal(savedSearchUpdateResponse.DisplayName, parameters.DisplayName); Assert.Equal(savedSearchUpdateResponse.Tags[0].Name, parameters.Tags[0].Name); Assert.Equal(savedSearchUpdateResponse.Tags[0].Value, parameters.Tags[0].Value); // Verify that the saved search was saved savedSearchesResult = client.SavedSearches.ListByWorkspace(resourceGroupName, workspaceName); Assert.NotNull(savedSearchesResult); Assert.NotNull(savedSearchesResult.Value); Assert.NotEqual(0, savedSearchesResult.Value.Count); Assert.NotNull(savedSearchesResult.Value[0].Id); Assert.Equal("*", savedSearchesResult.Value[0].Query); foundSavedSearch = false; for (int i = 0; i < savedSearchesResult.Value.Count; i++) { if (savedSearchesResult.Value[i].Category.Equals(parameters.Category) && savedSearchesResult.Value[i].Version == parameters.Version && savedSearchesResult.Value[i].Query.Equals(parameters.Query) && savedSearchesResult.Value[i].DisplayName.Equals(parameters.DisplayName) && savedSearchesResult.Value[i].Tags[0].Name.Equals(parameters.Tags[0].Name) && savedSearchesResult.Value[i].Tags[0].Value.Equals(parameters.Tags[0].Value)) { foundSavedSearch = true; } } Assert.True(foundSavedSearch); // Test the function to delete a saved search client.SavedSearches.Delete(resourceGroupName, workspaceName, newSavedSearchId); savedSearchesResult = client.SavedSearches.ListByWorkspace(resourceGroupName, workspaceName); foundSavedSearch = false; for (int i = 0; i < savedSearchesResult.Value.Count; i++) { if (savedSearchesResult.Value[i].Category.Equals(parameters.Category) && savedSearchesResult.Value[i].Version == parameters.Version && savedSearchesResult.Value[i].Query.Equals(parameters.Query) && savedSearchesResult.Value[i].DisplayName.Equals(parameters.DisplayName)) { foundSavedSearch = true; } } Assert.False(foundSavedSearch); } }
/// <summary> /// Asynchronously updates a saved search. /// </summary> /// <param name="name"> /// Name of the saved search to be updated. /// </param> /// <param name="attributes"> /// New attributes for the saved search to be updated. /// </param> /// <param name="dispatchArgs"> /// New dispatch arguments for the saved search to be updated. /// </param> /// <param name="templateArgs"> /// New template arguments for the saved search to be updated. /// </param> /// <returns> /// An object representing the saved search that was updated. /// </returns> /// <remarks> /// This method uses the <a href="http://goo.gl/aV9eiZ">POST /// saved/searches/{name}</a> endpoint to update the saved search /// identified by <see cref="name"/>. /// </remarks> public async Task<SavedSearch> UpdateSavedSearchAsync(string name, SavedSearchAttributes attributes = null, SavedSearchDispatchArgs dispatchArgs = null, SavedSearchTemplateArgs templateArgs = null) { var resource = new SavedSearch(this.Context, this.Namespace, name); await resource.UpdateAsync(attributes, dispatchArgs, templateArgs); return resource; }
/// <summary> /// Asynchronously removes a saved search. /// </summary> /// <param name="name"> /// Name of the saved search to be removed. /// </param> /// <remarks> /// This method uses the <a href="http://goo.gl/sn7qC5">DELETE /// saved/searches/{name}</a> endpoint to remove the saved search /// identified by <see cref="name"/>. /// </remarks> public async Task RemoveSavedSearchAsync(string name) { var resource = new SavedSearch(this.Context, this.Namespace, name); await resource.RemoveAsync(); }
/// <summary> /// Asynchronously retrieves the named <see cref="SavedSearch"/>. /// </summary> /// <param name="name"> /// Name of the <see cref="SavedSearch"/> to be retrieved. /// </param> /// <param name="args"> /// Constrains the information returned about the <see cref= /// "SavedSearch"/>. /// </param> /// <remarks> /// This method uses the <a href="http://goo.gl/L4JLwn">GET /// saved/searches/{name}</a> endpoint to get the <see cref= /// "SavedSearch"/> identified by <see cref="name"/>. /// </remarks> public async Task<SavedSearch> GetSavedSearchAsync(string name, SavedSearchFilterArgs args = null) { var resource = new SavedSearch(this.Context, this.Namespace, name); await resource.GetAsync(args); return resource; }
/// <summary> /// Asynchronously dispatches a <see cref="SavedSearch"/> just like the /// scheduler would. /// </summary> /// <param name="name"> /// The name of the <see cref="SavedSearch"/> to dispatch. /// </param> /// <param name="dispatchArgs"> /// A set of arguments to the dispatcher. /// </param> /// <param name="templateArgs"> /// A set of template arguments to the <see cref="SavedSearch"/>. /// </param> /// <returns> /// The search <see cref="Job"/> that was dispatched. /// </returns> /// <remarks> /// This method uses the <a href="http://goo.gl/AfzBJO">POST /// saved/searches/{name}/dispatch</a> endpoint to dispatch the <see /// cref="SavedSearch"/> identified by <see cref="name"/>. /// </remarks> public async Task<Job> DispatchSavedSearchAsync(string name, SavedSearchDispatchArgs dispatchArgs = null, SavedSearchTemplateArgs templateArgs = null) { var savedSearch = new SavedSearch(this.Context, this.Namespace, name); var job = await savedSearch.DispatchAsync(dispatchArgs, templateArgs); return job; }
public Task GetAsync(SavedSearch.Filter criteria) { Contract.Requires<ArgumentNullException>(criteria != null); return default(Task); }
/// <summary> /// Creates or updates a saved search for a given workspace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// The name of the workspace. /// </param> /// <param name='savedSearchId'> /// The id of the saved search. /// </param> /// <param name='parameters'> /// The parameters required to save a search. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <SavedSearch> > CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string savedSearchId, SavedSearch parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.SubscriptionId != null) { if (Client.SubscriptionId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1); } } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (workspaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workspaceName"); } if (workspaceName != null) { if (workspaceName.Length > 63) { throw new ValidationException(ValidationRules.MaxLength, "workspaceName", 63); } if (workspaceName.Length < 4) { throw new ValidationException(ValidationRules.MinLength, "workspaceName", 4); } if (!System.Text.RegularExpressions.Regex.IsMatch(workspaceName, "^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$")) { throw new ValidationException(ValidationRules.Pattern, "workspaceName", "^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$"); } } if (savedSearchId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "savedSearchId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } string apiVersion = "2020-08-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workspaceName", workspaceName); tracingParameters.Add("savedSearchId", savedSearchId); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/savedSearches/{savedSearchId}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName)); _url = _url.Replace("{savedSearchId}", System.Uri.EscapeDataString(savedSearchId)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <SavedSearch>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <SavedSearch>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Creates or updates a saved search for a given workspace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// The name of the workspace. /// </param> /// <param name='savedSearchId'> /// The id of the saved search. /// </param> /// <param name='parameters'> /// The parameters required to save a search. /// </param> public static SavedSearch CreateOrUpdate(this ISavedSearchesOperations operations, string resourceGroupName, string workspaceName, string savedSearchId, SavedSearch parameters) { return(operations.CreateOrUpdateAsync(resourceGroupName, workspaceName, savedSearchId, parameters).GetAwaiter().GetResult()); }
/// <summary> /// Creates or updates a saved search for a given workspace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// The name of the workspace. /// </param> /// <param name='savedSearchId'> /// The id of the saved search. /// </param> /// <param name='parameters'> /// The parameters required to save a search. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <SavedSearch> CreateOrUpdateAsync(this ISavedSearchesOperations operations, string resourceGroupName, string workspaceName, string savedSearchId, SavedSearch parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, workspaceName, savedSearchId, parameters, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
public SavedSearch UpdateSavedSearch(SavedSearch savedSearch) { return(_savedSearchWriteRepository.Save(savedSearch)); }
/// <summary> /// Asynchronously retrieves the collection of jobs created from a /// saved search. /// </summary> /// <param name="name"> /// Name of a saved search. /// </param> /// <returns> /// An object representing the collection of jobs created from the /// saved search identified by <see cref="name"/>. /// </returns> /// <remarks> /// This method uses the <a href="http://goo.gl/kv9L1l">GET /// saved/searches/{name}/history</a> endpoint to get the collection of /// jobs created from the <see cref="SavedSearch"/> identified by <see /// cref="name"/>. /// </remarks> public async Task<JobCollection> GetSavedSearchHistoryAsync(string name) { var savedSearch = new SavedSearch(this.Context, this.Namespace, name); var jobs = await savedSearch.GetHistoryAsync(); return jobs; }
public async Task SavedSearchHistory() { using (var service = await SdkHelper.CreateService()) { const string name = "sdk-test_SavedSearchHistory"; const string search = "search index=sdk-tests * earliest=-1m"; SavedSearchCollection savedSearches = service.SavedSearches; await savedSearches.GetSliceAsync(new SavedSearchCollection.Filter { Count = 0, SortDirection = SortDirection.Descending }); SavedSearch savedSearch = savedSearches.SingleOrDefault(ss => ss.Name == name); if (savedSearch != null) { await savedSearch.RemoveAsync(); } // Create a saved search savedSearch = await savedSearches.CreateAsync(name, search); // Clear the history - even though we have a newly create saved search // it's possible there was a previous saved search with the same name // that had a matching history. JobCollection history = await savedSearch.GetHistoryAsync(); foreach (Job job in history) { await job.CancelAsync(); } history = await savedSearch.GetHistoryAsync(); Assert.Equal(0, history.Count); Job job1 = await savedSearch.DispatchAsync(); history = await savedSearch.GetHistoryAsync(); Assert.Equal(1, history.Count); Assert.True(history.Any(a => a.Sid == job1.Sid)); // this.Contains(history, job1.Sid)); Job job2 = await savedSearch.DispatchAsync(); history = await savedSearch.GetHistoryAsync(); Assert.Equal(2, history.Count); Assert.True(history.Any(a => a.Sid == job1.Sid)); Assert.True(history.Any(a => a.Sid == job2.Sid)); await job1.CancelAsync(); history = await savedSearch.GetHistoryAsync(); Assert.Equal(1, history.Count); Assert.True(history.Any(a => a.Sid == job2.Sid)); await job2.CancelAsync(); history = await savedSearch.GetHistoryAsync(); Assert.Equal(0, history.Count); //// Delete the saved search await savedSearches.GetSliceAsync(new SavedSearchCollection.Filter { Count = 0, SortDirection = SortDirection.Descending }); savedSearch = savedSearches.SingleOrDefault(ss => ss.Name == name); Assert.NotNull(savedSearch); await savedSearch.RemoveAsync(); savedSearch = await savedSearches.GetOrNullAsync(savedSearch.Name); Assert.Null(savedSearch); } }
public async Task SavedSearchesUpdateProperties() { using (var service = await SdkHelper.CreateService()) { SavedSearchCollection savedSearches = service.SavedSearches; const string name = "sdk-test_UpdateProperties"; const string search = "search index=sdk-tests * earliest=-1m"; //// Ensure test starts in a known good state SavedSearch testSearch = await savedSearches.GetOrNullAsync(name); if (testSearch != null) { await testSearch.RemoveAsync(); } //// Create a saved search testSearch = await savedSearches.CreateAsync(name, search); testSearch = await savedSearches.GetOrNullAsync(name); Assert.NotNull(testSearch); //// Read the saved search await savedSearches.GetAllAsync(); testSearch = savedSearches.SingleOrDefault(a => a.Name == name); Assert.True(testSearch.IsVisible); // CONSIDER: Test some additinal default property values. // Update search properties, but don't specify required args to test // pulling them from the existing object bool updatedSnapshot = await testSearch.UpdateAsync(new SavedSearchAttributes() { IsVisible = false }); Assert.True(updatedSnapshot); Assert.False(testSearch.IsVisible); // Delete the saved search await testSearch.RemoveAsync(); testSearch = await savedSearches.GetOrNullAsync(testSearch.Name); Assert.Null(testSearch); // Create a saved search with some additional arguments testSearch = await savedSearches.CreateAsync(name, search, new SavedSearchAttributes() { IsVisible = false }); Assert.False(testSearch.IsVisible); // Set email param attributes var attributes = new SavedSearchAttributes() { ActionEmailAuthPassword = "******", ActionEmailAuthUsername = "******", ActionEmailBcc = "*****@*****.**", ActionEmailCC = "*****@*****.**", ActionEmailCommand = "$name1$", ActionEmailFormat = EmailFormat.Plain, ActionEmailFrom = "*****@*****.**", //attrs.ActionEmailHostname = "dummy1.host.com", ActionEmailInline = "true", ActionEmailMailServer = "splunk.com", ActionEmailMaxResults = 101, ActionEmailMaxTime = "10s", ActionEmailSendPdf = true, //??ActionEmailPdfView = "dummy", ActionEmailSendResults = true, //??ActionEmailPreProcessResults = "*", ActionEmailReportPaperOrientation = PaperOrientation.Landscape, ActionEmailReportPaperSize = PaperSize.Letter, ActionEmailReportServerEnabled = false, //attrs.ActionEmailReportServerUrl = "splunk.com", ActionEmailSubject = "sdk-subject", ActionEmailTo = "*****@*****.**", ActionEmailTrackAlert = false, ActionEmailTtl = "61", ActionEmailUseSsl = false, ActionEmailUseTls = false, ActionEmailWidthSortColumns = false, ActionPopulateLookupCommand = "$name2$", ActionPopulateLookupDestination = "dummypath", ActionPopulateLookupHostName = "dummy2.host.com", ActionPopulateLookupMaxResults = 102, ActionPopulateLookupMaxTime = "20s", ActionPopulateLookupTrackAlert = false, ActionPopulateLookupTtl = "62", ActionRssCommand = "$name3$", //attrs.ActionRssHostname = "dummy3.host.com", ActionRssMaxResults = 103, ActionRssMaxTime = "30s", ActionRssTrackAlert = "false", ActionRssTtl = "63", ActionScriptCommand = "$name4$", ActionScriptFileName = "action_script_filename", ActionScriptHostName = "dummy4.host.com", ActionScriptMaxResults = 104, ActionScriptMaxTime = "40s", ActionScriptTrackAlert = false, ActionScriptTtl = "64", ActionSummaryIndexName = "default", ActionSummaryIndexCommand = "$name5$", //attrs.ActionSummaryIndexHostname = "dummy5.host.com", ActionSummaryIndexInline = false, ActionSummaryIndexMaxResults = 105, ActionSummaryIndexMaxTime = "50s", ActionSummaryIndexTrackAlert = false, ActionSummaryIndexTtl = "65", Actions = "rss,email,populate_lookup,script,summary_index" }; await testSearch.UpdateAsync(attributes); // check Assert.True(testSearch.Actions.Email != null); //IsActionEmail)); Assert.True(testSearch.Actions.PopulateLookup != null); Assert.True(testSearch.Actions.Rss != null); Assert.True(testSearch.Actions.Script != null); Assert.True(testSearch.Actions.SummaryIndex != null); Assert.Equal("sdk-password", testSearch.Actions.Email.AuthPassword); Assert.Equal("sdk-username", testSearch.Actions.Email.AuthUsername); Assert.Equal("*****@*****.**", testSearch.Actions.Email.Bcc); Assert.Equal("*****@*****.**", testSearch.Actions.Email.CC); Assert.Equal("$name1$", testSearch.Actions.Email.Command); Assert.Equal(EmailFormat.Plain, testSearch.Actions.Email.Format); Assert.Equal("*****@*****.**", testSearch.Actions.Email.From); //Assert.Equal("dummy1.host.com", savedSearch.Actions.Email.Hostname); Assert.True(testSearch.Actions.Email.Inline); //Assert.Equal("splunk.com", savedSearch.Actions.Email.MailServer); Assert.Equal(101, testSearch.Actions.Email.MaxResults); Assert.Equal("10s", testSearch.Actions.Email.MaxTime); //Assert.Equal("dummy", savedSearch.Actions.Email.PdfView); //Assert.Equal("*", savedSearch.Actions.Email.PreProcessResults); Assert.Equal(PaperOrientation.Landscape, testSearch.Actions.Email.ReportPaperOrientation); Assert.Equal(PaperSize.Letter, testSearch.Actions.Email.ReportPaperSize); Assert.False(testSearch.Actions.Email.ReportServerEnabled); //Assert.Equal("splunk.com", savedSearch.Actions.Email.ReportServerUrl); Assert.True(testSearch.Actions.Email.SendPdf); Assert.True(testSearch.Actions.Email.SendResults); Assert.Equal("sdk-subject", testSearch.Actions.Email.Subject); Assert.Equal("*****@*****.**", testSearch.Actions.Email.To); Assert.False(testSearch.Actions.Email.TrackAlert); Assert.Equal("61", testSearch.Actions.Email.Ttl); Assert.False(testSearch.Actions.Email.UseSsl); Assert.False(testSearch.Actions.Email.UseTls); Assert.False(testSearch.Actions.Email.WidthSortColumns); Assert.Equal("$name2$", testSearch.Actions.PopulateLookup.Command); Assert.Equal("dummypath", testSearch.Actions.PopulateLookup.Destination); Assert.Equal("dummy2.host.com", testSearch.Actions.PopulateLookup.Hostname); Assert.Equal(102, testSearch.Actions.PopulateLookup.MaxResults); Assert.Equal("20s", testSearch.Actions.PopulateLookup.MaxTime); Assert.False(testSearch.Actions.PopulateLookup.TrackAlert); Assert.Equal("62", testSearch.Actions.PopulateLookup.Ttl); Assert.Equal("$name3$", testSearch.Actions.Rss.Command); //Assert.Equal("dummy3.host.com", savedSearch.Actions.Rss.Hostname); Assert.Equal(103, testSearch.Actions.Rss.MaxResults); Assert.Equal("30s", testSearch.Actions.Rss.MaxTime); Assert.False(testSearch.Actions.Rss.TrackAlert); Assert.Equal("63", testSearch.Actions.Rss.Ttl); Assert.Equal("$name4$", testSearch.Actions.Script.Command); Assert.Equal("action_script_filename", testSearch.Actions.Script.FileName); Assert.Equal("dummy4.host.com", testSearch.Actions.Script.Hostname); Assert.Equal(104, testSearch.Actions.Script.MaxResults); Assert.Equal("40s", testSearch.Actions.Script.MaxTime); Assert.False(testSearch.Actions.Script.TrackAlert); Assert.Equal("64", testSearch.Actions.Script.Ttl); Assert.Equal("default", testSearch.Actions.SummaryIndex.Name); Assert.Equal("$name5$", testSearch.Actions.SummaryIndex.Command); //Assert.Equal("dummy5.host.com", savedSearch.Actions.SummaryIndex.Hostname); Assert.False(testSearch.Actions.SummaryIndex.Inline); Assert.Equal(105, testSearch.Actions.SummaryIndex.MaxResults); Assert.Equal("50s", testSearch.Actions.SummaryIndex.MaxTime); Assert.False(testSearch.Actions.SummaryIndex.TrackAlert); Assert.Equal("65", testSearch.Actions.SummaryIndex.Ttl); // Delete the saved search await testSearch.RemoveAsync(); try { await testSearch.GetAsync(); Assert.True(false); } catch (ResourceNotFoundException) { } testSearch = await savedSearches.GetOrNullAsync(testSearch.Name); Assert.Null(testSearch); } }