public async Task <IActionResult> AgentHeartbeats( string agentId, [FromQuery(Name = "$filter")] string filter = "", [FromQuery(Name = "$orderby")] string orderBy = "", [FromQuery(Name = "$top")] int top = 100, [FromQuery(Name = "$skip")] int skip = 0 ) { try { Agent agent = _agentRepo.GetOne(new Guid(agentId)); if (agent == null) { return(NotFound("The Agent ID provided does not match any existing Agents")); } ODataHelper <AgentHeartbeat> oDataHelper = new ODataHelper <AgentHeartbeat>(); Guid parentguid = Guid.Parse(agentId); var oData = oDataHelper.GetOData(HttpContext, oDataHelper); var result = _agentHeartbeatRepo.FindAllHeartbeats(parentguid, oData.Predicate, oData.PropertyName, oData.Direction, oData.Skip, oData.Take); return(Ok(result)); } catch (Exception ex) { return(ex.GetActionResult()); } }
public IActionResult Get(string driveId, string type = null, string path = null, [FromQuery(Name = "$filter")] string filter = "", [FromQuery(Name = "$orderby")] string orderBy = "", [FromQuery(Name = "$top")] int top = 100, [FromQuery(Name = "$skip")] int skip = 0) { try { ODataHelper <FileFolderViewModel> oDataHelper = new ODataHelper <FileFolderViewModel>(); var oData = oDataHelper.GetOData(HttpContext, oDataHelper); bool?isFile = true; if (string.IsNullOrEmpty(type)) { isFile = null; } else if (type == "Files") { isFile = true; } else if (type == "Folders") { isFile = false; } var response = _manager.GetFilesFolders(driveId, isFile, oData.Predicate, oData.PropertyName, oData.Direction, oData.Skip, oData.Take, path); return(Ok(response)); //return all files / folders / files and folders } catch (Exception ex) { return(ex.GetActionResult()); } }
public async Task <IActionResult> JobCheckpoints( string jobId, [FromQuery(Name = "$filter")] string filter = "", [FromQuery(Name = "$orderby")] string orderBy = "", [FromQuery(Name = "$top")] int top = 100, [FromQuery(Name = "$skip")] int skip = 0 ) { try { Job job = _repository.GetOne(new Guid(jobId)); if (job == null) { return(NotFound("The Job ID provided does not match any existing Jobs")); } ODataHelper <JobCheckpoint> oDataHelper = new ODataHelper <JobCheckpoint>(); Guid parentguid = Guid.Empty; var oData = oDataHelper.GetOData(HttpContext, oDataHelper); return(Ok(_jobCheckpointRepo.Find(parentguid, oData.Filter, oData.Sort, oData.SortDirection, oData.Skip, oData.Top).Items.Where(c => c.JobId == new Guid(jobId)))); } catch (Exception ex) { return(ex.GetActionResult()); } }
public IQueryable <PlaylistTrackDTO> Get(ODataQueryOptions queryOptions) { IQueryable query = null; try { if (IsSearch(OperationResult)) { var settings = new ODataValidationSettings() { AllowedFunctions = AllowedFunctions.AllMathFunctions }; queryOptions.Validate(settings); query = queryOptions.ApplyTo(Application.QueryDTO); return(query as IQueryable <PlaylistTrackDTO>); } } catch (Exception exception) { OperationResult.ParseException(exception); } throw ODataHelper.OperationResultResponseException(Request, OperationResult); }
public static async Task CheckinFromDrive(this Record record, string driveId, string token, bool saveRecord = false) { string downloadUrl = GraphApiHelper.GetOneDriveItemContentIdUrl(driveId); var fileResult = await ODataHelper.GetItem <OneDriveItem>(GraphApiHelper.GetOneDriveItemIdUrl(driveId), token, null); string filePath = Path.Combine(TrimApplication.WebServerWorkPath, fileResult.Name); await ODataHelper.GetItem <string>(downloadUrl, token, filePath); var inputDocument = new InputDocument(filePath); inputDocument.CheckinAs = record.SuggestedFileName; record.SetDocument(inputDocument, true, false, "checkin from Word Online"); string pdfPath = Path.Combine(TrimApplication.WebServerWorkPath, Path.ChangeExtension(fileResult.Name, "pdf")); string pdfUrl = GraphApiHelper.GetOneDriveItemContentIdUrl(driveId, "pdf"); await ODataHelper.GetItem <string>(pdfUrl, token, pdfPath); var rendition = record.ChildRenditions.NewRendition(pdfPath, RenditionType.Longevity, "Preview"); if (saveRecord) { record.Save(); File.Delete(filePath); File.Delete(pdfPath); } return; }
public IHttpActionResult Patch([FromODataUri] int key, Delta <MediaTypeDTO> patch) { MediaTypeDTO mediaTypeDTO = null; try { if (IsUpdate(OperationResult)) { if (ValidateModelState(OperationResult)) { MediaType mediaType = Application.UnitOfWork.GetRepository <MediaType>().GetById(key); if (mediaType != null) { mediaTypeDTO = new MediaTypeDTO(mediaType); patch.Patch(mediaTypeDTO); LibraryHelper.Clone <MediaType>((MediaType)mediaTypeDTO.ToData(), mediaType, null); Application.UnitOfWork.Save(OperationResult); return(Updated(mediaTypeDTO)); } } } } catch (Exception exception) { OperationResult.ParseException(exception); } throw ODataHelper.OperationResultResponseException(Request, OperationResult); }
/// <summary> /// Gets all the charts in the specified Excel workbook and presents them in a view. /// </summary> /// <param name="id">The internal ID of the workbook.</param> /// <returns>The view with the list of charts.</returns> public async Task <ActionResult> Index(string id) { // Get access token from the local database var token = Data.GetUserSessionToken(Settings.GetUserAuthStateId(ControllerContext.HttpContext), Settings.AzureADAuthority); var sheetsUrl = GraphApiHelper.GetSheetsWithChartsUrl(id, "&$select=name,id"); var sheets = await ODataHelper.GetItems <ExcelSheet>(sheetsUrl, token.AccessToken); // Merge the charts from each worksheet into a single list List <Chart> allChartsInWorkbook = new List <Chart>(); foreach (var sheet in sheets) { var chartsFromSheet = sheet.Charts; // The GetChartImage method requires a clean charts URL, that is, no $select option. string cleanFullChartsUrl = GraphApiHelper.GetChartsUrl(id, sheet.Id, null); foreach (var chart in chartsFromSheet) { // string singleChartImageUrl = GraphApiHelper.GetSingleChartImageUrl(cleanFullChartsUrl, chart.Id); chart.ImageAsBase64String = await GraphApiHelper.GetChartImage(cleanFullChartsUrl, chart.Id, token.AccessToken); } allChartsInWorkbook = allChartsInWorkbook.Concat(chartsFromSheet).ToList(); } return(View(allChartsInWorkbook)); }
public int CreateProduct([FromODataUri] int key, ODataActionParameters parameters) { if (!ModelState.IsValid) { throw new HttpResponseException(Request.CreateODataErrorResponse(HttpStatusCode.BadRequest, new ODataError() { Message = ODataHelper.GetModelStateErrorInformation(ModelState) })); } ProductFamily productFamily = _db.ProductFamilies.SingleOrDefault(p => p.ID == key); string productName = parameters["Name"].ToString(); Product product = new Product { Name = productName, Family = productFamily, ReleaseDate = DateTime.Now, SupportedUntil = DateTime.Now.AddYears(10) }; _db.Products.Add(product); _db.SaveChanges(); return(product.ID); }
private PSKeyVaultRoleAssignment[] FilterAssignments(PSKeyVaultRoleAssignment[] assignments) { if (!string.IsNullOrEmpty(RoleDefinitionName)) { var definition = Track2DataClient.GetHsmRoleDefinitions(HsmName, Scope) .FirstOrDefault(x => string.Equals(x.RoleName, RoleDefinitionName, StringComparison.OrdinalIgnoreCase)); RoleDefinitionId = definition?.Id; } if (!string.IsNullOrEmpty(SignInName)) { var user = GraphClient.Users.GetUser(SignInName); ObjectId = user?.Id; } if (!string.IsNullOrEmpty(ApplicationId)) { var filter = ODataHelper.FormatFilterString <MicrosoftGraphServicePrincipal>(sp => sp.AppId == ApplicationId); var servicePrincipal = GraphClient.ServicePrincipals.ListServicePrincipal(filter: filter).Value.FirstOrDefault(); ObjectId = servicePrincipal?.Id; } if (!string.IsNullOrEmpty(RoleDefinitionId)) { assignments = assignments.Where(assignment => string.Equals(assignment.RoleDefinitionId, RoleDefinitionId, StringComparison.OrdinalIgnoreCase)).ToArray(); } if (!string.IsNullOrEmpty(ObjectId)) { assignments = assignments.Where(assignment => string.Equals(assignment.PrincipalId, ObjectId, StringComparison.OrdinalIgnoreCase)).ToArray(); } return(assignments); }
public IHttpActionResult Patch([FromODataUri] int key, Delta <EmployeeDTO> patch) { EmployeeDTO employeeDTO = null; try { if (IsUpdate(OperationResult)) { if (ValidateModelState(OperationResult)) { Employee employee = Application.UnitOfWork.GetRepository <Employee>().GetById(key); if (employee != null) { employeeDTO = new EmployeeDTO(employee); patch.Patch(employeeDTO); LibraryHelper.Clone <Employee>((Employee)employeeDTO.ToData(), employee, null); Application.UnitOfWork.Save(OperationResult); return(Updated(employeeDTO)); } } } } catch (Exception exception) { OperationResult.ParseException(exception); } throw ODataHelper.OperationResultResponseException(Request, OperationResult); }
public async Task <IActionResult> AllIntegrationEvents( [FromQuery(Name = "$filter")] string filter = "", [FromQuery(Name = "$orderby")] string orderBy = "", [FromQuery(Name = "$top")] int top = 100, [FromQuery(Name = "$skip")] int skip = 0) { try { ODataHelper <IntegrationEvent> oDataHelper = new ODataHelper <IntegrationEvent>(); var oData = oDataHelper.GetOData(HttpContext, oDataHelper); var response = _repository.Find(null, oData.Filter, oData.Sort, oData.SortDirection, oData.Skip, oData.Top); IntegrationEventEntitiesLookupViewModel eventLogList = new IntegrationEventEntitiesLookupViewModel(); if (response != null) { eventLogList.EntityNameList = new List <string>(); foreach (var item in response.Items) { eventLogList.EntityNameList.Add(item.EntityType); } eventLogList.EntityNameList = eventLogList.EntityNameList.Distinct().ToList(); } return(Ok(eventLogList)); } catch (Exception ex) { return(ex.GetActionResult()); } }
public IHttpActionResult Patch([FromODataUri] int key, Delta <InvoiceDTO> patch) { InvoiceDTO invoiceDTO = null; try { if (IsUpdate(OperationResult)) { if (ValidateModelState(OperationResult)) { Invoice invoice = Application.UnitOfWork.GetRepository <Invoice>().GetById(key); if (invoice != null) { invoiceDTO = new InvoiceDTO(invoice); patch.Patch(invoiceDTO); LibraryHelper.Clone <Invoice>((Invoice)invoiceDTO.ToData(), invoice, null); Application.UnitOfWork.Save(OperationResult); return(Updated(invoiceDTO)); } } } } catch (Exception exception) { OperationResult.ParseException(exception); } throw ODataHelper.OperationResultResponseException(Request, OperationResult); }
public IHttpActionResult Patch([FromODataUri] int key, Delta <PlaylistTrackDTO> patch) { PlaylistTrackDTO playlistTrackDTO = null; try { if (IsUpdate(OperationResult)) { if (ValidateModelState(OperationResult)) { PlaylistTrack playlistTrack = Application.UnitOfWork.GetRepository <PlaylistTrack>().GetById(key); if (playlistTrack != null) { playlistTrackDTO = new PlaylistTrackDTO(playlistTrack); patch.Patch(playlistTrackDTO); LibraryHelper.Clone <PlaylistTrack>((PlaylistTrack)playlistTrackDTO.ToData(), playlistTrack, null); Application.UnitOfWork.Save(OperationResult); return(Updated(playlistTrackDTO)); } } } } catch (Exception exception) { OperationResult.ParseException(exception); } throw ODataHelper.OperationResultResponseException(Request, OperationResult); }
public IHttpActionResult Patch([FromODataUri] int key, Delta <ArtistDTO> patch) { ArtistDTO artistDTO = null; try { if (IsUpdate(OperationResult)) { if (ValidateModelState(OperationResult)) { Artist artist = Application.UnitOfWork.GetRepository <Artist>().GetById(key); if (artist != null) { artistDTO = new ArtistDTO(artist); patch.Patch(artistDTO); LibraryHelper.Clone <Artist>((Artist)artistDTO.ToData(), artist, null); Application.UnitOfWork.Save(OperationResult); return(Updated(artistDTO)); } } } } catch (Exception exception) { OperationResult.ParseException(exception); } throw ODataHelper.OperationResultResponseException(Request, OperationResult); }
public IHttpActionResult Patch([FromODataUri] int key, Delta <CustomerDTO> patch) { CustomerDTO customerDTO = null; try { if (IsUpdate(OperationResult)) { if (ValidateModelState(OperationResult)) { Customer customer = Application.UnitOfWork.GetRepository <Customer>().GetById(key); if (customer != null) { customerDTO = new CustomerDTO(customer); patch.Patch(customerDTO); LibraryHelper.Clone <Customer>((Customer)customerDTO.ToData(), customer, null); Application.UnitOfWork.Save(OperationResult); return(Updated(customerDTO)); } } } } catch (Exception exception) { OperationResult.ParseException(exception); } throw ODataHelper.OperationResultResponseException(Request, OperationResult); }
public IActionResult Get(string driveName = null, string file = null, [FromQuery(Name = "$filter")] string filter = "", [FromQuery(Name = "$orderby")] string orderBy = "", [FromQuery(Name = "$top")] int top = 100, [FromQuery(Name = "$skip")] int skip = 0) { try { ODataHelper <FileFolderViewModel> oDataHelper = new ODataHelper <FileFolderViewModel>(); var oData = oDataHelper.GetOData(HttpContext, oDataHelper); bool?isFile = Convert.ToBoolean(file); if (file == null) { isFile = null; } var filesFolders = _manager.GetFilesFolders(isFile, driveName, oData.Predicate, oData.PropertyName, oData.Direction, oData.Skip, oData.Take); return(Ok(filesFolders)); //return all files/folders } catch (Exception ex) { return(ex.GetActionResult()); } }
public IHttpActionResult Patch([FromODataUri] int key, Delta <GenreDTO> patch) { GenreDTO genreDTO = null; try { if (IsUpdate(OperationResult)) { if (ValidateModelState(OperationResult)) { Genre genre = Application.UnitOfWork.GetRepository <Genre>().GetById(key); if (genre != null) { genreDTO = new GenreDTO(genre); patch.Patch(genreDTO); LibraryHelper.Clone <Genre>((Genre)genreDTO.ToData(), genre, null); Application.UnitOfWork.Save(OperationResult); return(Updated(genreDTO)); } } } } catch (Exception exception) { OperationResult.ParseException(exception); } throw ODataHelper.OperationResultResponseException(Request, OperationResult); }
public void Setup() { var claim = new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", _userId.ToString()); Thread.CurrentPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> { claim })); var connectionString = ConfigurationManager.ConnectionStrings["DataContext"].ConnectionString; _context = new DataContext(connectionString); _facade = new ParameterTypeFacade(_context); ODataHelper oDataHelper = new ODataHelper(); _controller = new ParameterTypesController(oDataHelper, _facade); _controller.Request = new HttpRequestMessage(); _controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration()); // Setting the URI of the request here is needed for the API POST method to work _controller.Request.RequestUri = new Uri("http://tempuri.com"); /* * TODO: akrone - Taking on some Techincal Debt doing this, but pulling the Seeder into it's own project would need to * be merged into other development work going on for sprint 60 */ Seeder.SeedWithTestData(_context); }
public async Task ApiV2BaseUrlTest() { string expectedText = @"<atom:title>Packages</atom:title>"; var odataHelper = new ODataHelper(); bool containsResponseText = await odataHelper.ContainsResponseText(UrlHelper.V2FeedRootUrl, expectedText); Assert.IsTrue(containsResponseText); }
public V2FeedExtendedTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { _clientSdkHelper = new ClientSdkHelper(TestOutputHelper); _commandlineHelper = new CommandlineHelper(TestOutputHelper); _odataHelper = new ODataHelper(TestOutputHelper); _packageCreationHelper = new PackageCreationHelper(TestOutputHelper); }
public async Task ApiV2MetadataTest() { string expectedText = @"V2FeedPackage"; var odataHelper = new ODataHelper(); bool containsResponseText = await odataHelper.ContainsResponseText(UrlHelper.V2FeedRootUrl + @"$metadata", expectedText); Assert.IsTrue(containsResponseText); }
public void PackagesApiTest() { string packageId = "newtonsoft.json"; string url = UrlHelper.V2FeedRootUrl + @"Packages()?$filter=tolower(Id) eq '" + packageId + "'&$orderby=Id"; string expectedText = @"<id>" + UrlHelper.V2FeedRootUrl + "Packages(Id='" + packageId; Assert.IsTrue(ODataHelper.ContainsResponseTextIgnoreCase(url, expectedText)); }
public async Task StatsTotalTest() { string url = UrlHelper.BaseUrl + @"/stats/totals"; var odataHelper = new ODataHelper(); var containsResponseText = await odataHelper.ContainsResponseText(url, @"Downloads"); Assert.IsTrue(containsResponseText); }
public void GetDataParsesMultipleProducts() { string document = GetResourceAsString("MultipleProducts.xml"); var result = ODataHelper.GetData(document); Assert.Equal(20, result.Count()); Assert.Equal(productProperties, result.First().Count); }
public async Task Top30PackagesFeedTest() { string url = UrlHelper.V2FeedRootUrl + @"/Search()?$filter=IsAbsoluteLatestVersion&$orderby=DownloadCount%20desc,Id&$skip=0&$top=30&searchTerm=''&targetFramework='net45'&includePrerelease=true"; var odataHelper = new ODataHelper(); bool containsResponseText = await odataHelper.ContainsResponseText(url, "jQuery"); Assert.IsTrue(containsResponseText); }
public void FindPackagesByIdForPredefinedPackage() { string packageId = "PostSharp"; string url = UrlHelper.V2FeedRootUrl + @"/FindPackagesById()?id='" + packageId + "'"; string expectedText = @"<id>" + UrlHelper.V2FeedRootUrl + "Packages(Id='" + packageId; Assert.IsTrue(ODataHelper.ContainsResponseText(url, expectedText)); }
// GET api/values public async Task <IEnumerable <string> > Get() { // OWIN middleware validated the audience and issuer, but the scope must also be validated; must contain "access_as_user". string[] addinScopes = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Split(' '); if (addinScopes.Contains("access_as_user")) { // Get the raw token that the add-in page received from the Office host. var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as BootstrapContext; UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token); // Get the access token for MS Graph. ClientCredential clientCred = new ClientCredential(ConfigurationManager.AppSettings["ida:Password"]); ConfidentialClientApplication cca = new ConfidentialClientApplication(ConfigurationManager.AppSettings["ida:ClientID"], "https://localhost:44355", clientCred, null, null); string[] graphScopes = { "Files.Read.All" }; AuthenticationResult result = null; try { // The AcquireTokenOnBehalfOfAsync method will first look in the MSAL in memory cache for a // matching access token. Only if there isn't one, does it initiate the "on behalf of" flow // with the Azure AD V2 endpoint. result = await cca.AcquireTokenOnBehalfOfAsync(graphScopes, userAssertion, "https://login.microsoftonline.com/common/oauth2/v2.0"); } catch (MsalUiRequiredException e) { // If multi-factor authentication is required by the MS Graph resource an // the user has not yet provided it, AAD will throw an exception containing a // Claims property. if (String.IsNullOrEmpty(e.Claims)) { throw e; } else { // The Claims property value must be passed to the client which will pass it // to the Office host, which will then include it in a request for a new token. // AAD will prompt the user for all required forms of authentication. throw new HttpException(e.Claims); } } // Get the names of files and folders in OneDrive for Business by using the Microsoft Graph API. Select only properties needed. var fullOneDriveItemsUrl = GraphApiHelper.GetOneDriveItemNamesUrl("?$select=name&$top=3"); var getFilesResult = await ODataHelper.GetItems <OneDriveItem>(fullOneDriveItemsUrl, result.AccessToken); // The returned JSON includes OData metadata and eTags that the add-in does not use. // Return to the client-side only the filenames. List <string> itemNames = new List <string>(); foreach (OneDriveItem item in getFilesResult) { itemNames.Add(item.Name); } return(itemNames); } return(new string[] { "Error", "Microsoft Office does not have permission to get Microsoft Graph data on behalf of the current user." }); }
protected async Task <List <TView> > GetListAsync <TView>(Expression <Func <TModel, bool> > predicate, string key, ODataQueryOptions <TModel> queryOptions) where TView : ODataViewModelBase <TDbContext, TModel, TView> { if (queryOptions.Filter != null) { ODataHelper <TModel> .ParseFilter(queryOptions.Filter.FilterClause.Expression, ref predicate); } int? top = queryOptions.Top?.Value; var skip = queryOptions.Skip?.Value ?? 0; RequestPaging request = new RequestPaging() { PageIndex = 0, PageSize = top.HasValue ? top + top * (skip / top + 1) : null, OrderBy = queryOptions.OrderBy?.RawValue //Top = queryOptions.Top?.Value, //Skip = queryOptions.Skip?.Value }; var cacheKey = $"odata_{_lang}_{typeof(TView).FullName}_{key}_{SeoHelper.GetSEOString(queryOptions.Filter?.RawValue, '_')}_ps-{request.PageSize}"; List <TView> data = null; //if (MixService.GetConfig<bool>("IsCache")) //{ // var getData = await MixCacheService.GetAsync<RepositoryResponse<PaginationModel<TView>>>(cacheKey); // if (getData != null) // { // data = getData.Data.Items; // } //} if (data == null) { if (predicate != null) { var getData = await ODataDefaultRepository <TDbContext, TModel, TView> .Instance.GetModelListByAsync(predicate, request.OrderBy, request.Direction, request.PageSize, request.PageIndex, request.Skip, request.Top).ConfigureAwait(false); //if (getData.IsSucceed) //{ // await MixCacheService.SetAsync(cacheKey, getData); // data = getData.Data.Items; //} } else { var getData = await ODataDefaultRepository <TDbContext, TModel, TView> .Instance.GetModelListAsync( request.OrderBy, request.Direction, request.PageSize, request.PageIndex , null, null).ConfigureAwait(false); //if (getData.IsSucceed) //{ // await MixCacheService.SetAsync(cacheKey, getData); // data = getData.Data.Items; //} } } return(data); }
public void GetDataParsesMultipleProductsWithCategory() { string document = GetResourceAsString("MultipleProductsWithCategory.xml"); var result = ODataHelper.GetData(document); Assert.Equal(20, result.Count()); Assert.Equal(productProperties + 1, result.First().Count); Assert.Equal(categoryProperties, (result.First()["Category"] as IDictionary <string, object>).Count); }
public void FindPackagesBySpecificIdAndVersion() { string packageId = "Microsoft.Web.Infrastructure"; string version = "1.0.0.0"; string url = UrlHelper.V2FeedRootUrl + @"Packages(Id='" + packageId + "',Version='" + version + "')"; string expectedText = @"<id>" + UrlHelper.V2FeedRootUrl + "Packages(Id='" + packageId + "',Version='" + version + "')</id>"; Assert.IsTrue(ODataHelper.ContainsResponseText(url, expectedText)); }
public V2FeedTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { _odataHelper = new ODataHelper(testOutputHelper); }