public bool CanHandleRequest(TexImage image, IRequest request) { switch (request.Type) { case RequestType.Loading: { LoadingRequest loader = (LoadingRequest)request; FREE_IMAGE_FORMAT format = FreeImage.GetFIFFromFilename(loader.FilePath); return(format != FREE_IMAGE_FORMAT.FIF_UNKNOWN && format != FREE_IMAGE_FORMAT.FIF_DDS); // FreeImage can load DDS texture, but can't handle their mipmaps.. } case RequestType.Export: { ExportRequest export = (ExportRequest)request; FREE_IMAGE_FORMAT format = FreeImage.GetFIFFromFilename(export.FilePath); return(format != FREE_IMAGE_FORMAT.FIF_UNKNOWN && format != FREE_IMAGE_FORMAT.FIF_DDS); } case RequestType.Rescaling: RescalingRequest rescale = (RescalingRequest)request; return(rescale.Filter != Filter.Rescaling.Nearest); case RequestType.SwitchingChannels: case RequestType.GammaCorrection: case RequestType.Flipping: case RequestType.FlippingSub: case RequestType.Swapping: return(true); default: return(false); } }
public static async Task RunExportOrchestrator( [OrchestrationTrigger] IDurableOrchestrationContext context, ILogger log) { ExportRequest exportRequest = context.GetInput <ExportRequest>(); // Getting the ARM template Skip ResourceName Parameterization. var databases = await context.CallActivityAsync <dynamic>(nameof(AzureResourceManagerActivity.GetArmTemplateForExportSkipParameterization), exportRequest); // Getting the ARM template. dynamic Template = await context.CallActivityAsync <dynamic>(nameof(AzureResourceManagerActivity.GetArmTemplateForExport), exportRequest); string json = JsonConvert.SerializeObject(Template); // Create BatchPool And Job string jobId = await context.CallActivityAsync <string>(nameof(BatchActivity.CreateBatchPoolAndExportJob), exportRequest); string containerUrl = await context.CallActivityAsync <string>(nameof(StorageActivity.GettingJobContainerUrl), (exportRequest.SubscriptionId, exportRequest.ResourceGroupName, exportRequest.StorageAccountName, jobId)); await context.CallActivityAsync <string>(nameof(StorageActivity.UploadingArmTemplate), (containerUrl, json)); BatchActivity.CreateBatchTasks("Export", jobId, containerUrl, exportRequest.BatchAccountUrl, exportRequest.SourceSqlServerName, exportRequest.AccessToken, databases, log); // create output values Tuple <string, string>[] outputValues = { Tuple.Create("jobId", jobId), Tuple.Create("containerUrl", containerUrl) }; context.SetOutput(outputValues); }
public async Task <bool> Handle(ExportRequest message, IOutputPort <ExportResponse> outputPort) { var listRequests = await _requestRepository.GetRequestForExport(message); outputPort.Handle(new ExportResponse(listRequests)); return(true); }
/// <summary> /// Exports a batch of entries to the database /// </summary> /// <param name="csentries">A list of changes to export</param> /// <returns>The results of the batch export</returns> public PutExportEntriesResults PutExportEntries(IList <CSEntryChange> csentries) { try { this.client = new AcmaSyncServiceClient(); PutExportEntriesResults exportEntriesResults = new PutExportEntriesResults(); IList <AttributeChange> anchorchanges = new List <AttributeChange>(); ExportRequest request = new ExportRequest(); request.CSEntryChanges = csentries; Logger.WriteLine("Exporting page of {0} objects", csentries.Count); ExportResponse response = this.client.ExportPage(request); Logger.WriteLine("Got response of {0} objects", response.Results.Count); foreach (CSEntryChangeResult item in response.Results) { exportEntriesResults.CSEntryChangeResults.Add(item); } return(exportEntriesResults); } catch (Exception ex) { Logger.WriteException(ex); throw; } }
public async Task Export_CreateOrUpdateAsync_ShouldInvokeOnce() { // Arrange var controller = this.GetControllerInstance(); var exportRequest = new ExportRequest(); var serviceUrl = "serviceUrl"; var userDataList = new List <UserDataEntity>() { new UserDataEntity() { AadId = this.claimTypeUserId } }; this.userDataRepository.Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <string>())).Returns(Task.FromResult(default(UserDataEntity))); this.appSettingsService.Setup(x => x.GetServiceUrlAsync()).ReturnsAsync(serviceUrl); this.memberService.Setup(x => x.GetAuthorsAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(userDataList); this.userDataRepository.Setup(x => x.CreateOrUpdateAsync(It.IsAny <UserDataEntity>())).Returns(Task.CompletedTask); // Act await controller.ExportNotificationAsync(exportRequest); // Assert this.userDataRepository.Verify(x => x.CreateOrUpdateAsync(It.Is <UserDataEntity>(x => x.AadId == this.claimTypeUserId)), Times.Once); }
/// <summary> /// Exporting multiple Copyleaks data items in single call. /// </summary> /// <param name="scanId">Scan identified to be exporter</param> /// <param name="exportId">Export identifier for tracking</param> /// <param name="request">The export items (results, crawled-version and pdf report file)</param> /// <exception cref="HttpRequestException">In case of reject from the server.</exception> /// <returns></returns> public async Task ExportAsync(string scanId, string exportId, ExportRequest request, string token) { if (string.IsNullOrEmpty(scanId)) { throw new ArgumentException("Mandatory", nameof(scanId)); } if (string.IsNullOrEmpty(exportId)) { throw new ArgumentException("Mandatory", nameof(exportId)); } if (request == null) { throw new ArgumentException("Mandatory", nameof(request)); } if (string.IsNullOrEmpty(token)) { throw new ArgumentException("Mandatory", nameof(token)); } Uri url = new Uri($"{this.CopyleaksApiServer}v3/downloads/{scanId}/export/{exportId}"); HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Post, url); msg.SetupHeaders(token); msg.Content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"); using (var stream = new MemoryStream()) using (var streamContent = new StreamContent(stream)) using (var response = await Client.SendAsync(await msg.CloneAsync(stream, streamContent).ConfigureAwait(false)).ConfigureAwait(false)) { if (!response.IsSuccessStatusCode) { throw new CopyleaksHttpException(response); } } }
public async Task <IActionResult> ApproveExport(string id, ExportRequest request) { if (id != request.Id) { return(NotFound()); } try { request = _context.ExportRequests.Include(r => r.StorageSpace).Include(r => r.Items).Single(r => r.Id == id); request.StorageSpace = _context.StorageSpaces.Single(sp => sp.Id == request.StorageSpaceId); var itemCounts = new List <ItemCount>(); bool requestValid = true; for (int i = 0; i < request.Items.Count; i++) { ItemCount itemCount = _context.ItemCounts.Include(ic => ic.Item).Single(ic => ic.Id == request.Items.ElementAt(i).Id); var numOfItemsOfThisType = _context.Items.Where(item => item.ItemDetails.UPC == itemCount.Item.UPC && item.StorageSpace.Id == request.StorageSpaceId).ToList().Count; //if (itemCount.Count > numOfItemsOfThisType) //{ // requestValid = false; // break; //} itemCounts.Add(itemCount); } //if (requestValid) //{ // _context.Requests.Remove(request); // await _context.SaveChangesAsync(); // return RedirectToAction(nameof(Index)); //} request.Processed = true; for (int i = 0; i < itemCounts.Count; i++) { ItemCount itemCount = itemCounts.ElementAt(i); var toRemove = _context.Items.Where(item => item.ItemDetails.UPC == itemCount.Item.UPC && item.StorageSpace.Id == request.StorageSpaceId).ToList(); for (int j = 0; j < itemCount.Count; j++) { _context.Items.Remove(toRemove.ElementAt(i)); } } _context.Entry(request).Property("Processed").IsModified = true; await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RequestExists(request.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); }
public async Task <IActionResult> Get(string status, string type) { var request = new ExportRequest(status, type); var result = await _mediator.Send(request); return(result != null?File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "transactions.xlsx") : NotFound("{ \"error\":1,\"content\":\"Unable to export data from database!\" }")); }
public static ICommand RequestExport(this IEditor editor, string format, string outputPath) { var req = new ExportRequest(); req.Format = format; req.OutputPath = outputPath; return(editor.PerformRequest(req)); }
public async Task <Stream> Post(ExportOptionsv1 options) { var parsed = Snowflake.TryParse(options.ChannelId); var channelId = parsed ?? Snowflake.Zero; var client = new DiscordClient(options.Token); Channel channel; try { channel = await client.GetChannelAsync(channelId); } catch (DiscordChatExporterException e) { var isUnauthorized = e.Message.Contains("Authentication"); var content = isUnauthorized ? "Invalid Discord token provided." : "Please provide a valid channel"; Response.ContentType = "application/json"; Response.StatusCode = isUnauthorized ? 401 : 409; return(GenerateStreamFromString("{ \"error\": \"" + content + "\" }")); } var guild = await client.GetGuildAsync(channel.GuildId); var res = await client.GetJsonResponseAsync("users/@me"); var me = DiscordChatExporter.Core.Discord.Data.User.Parse(res); _logger.LogInformation($"[{me.FullName} ({me.Id})] Exporting #{channel.Name} ({channel.Id}) within {guild.Name} ({guild.Id})"); var path = GetPath(channel.Id.ToString()); var request = new ExportRequest( guild, channel, path, ExportFormat.HtmlDark, null, null, null, MessageFilter.Null, false, false, "dd-MMM-yy hh:mm tt" ); var exporter = new ChannelExporter(client); await exporter.ExportChannelAsync(request); var stream = new FileStream(path, FileMode.Open); Response.ContentType = "text/html; charset=UTF-8"; Response.StatusCode = 200; deleteFile(path); return(stream); }
public async Task HandleArchiveCommand(ITextChannel channel, [Remainder] string category) { if (string.IsNullOrEmpty(category)) { return; } category = new CultureInfo("en-GB", false).TextInfo.ToTitleCase(category); string env = HARDCODED_ARCHIVE_PATH; Guild g = new Guild(new Snowflake(Context.Guild.Id), Context.Guild.Name, Context.Guild.IconUrl); var discordCategory = channel.CategoryId.HasValue ? await channel.GetCategoryAsync() : null; ChannelCategory cc = new ChannelCategory(new Snowflake(channel.CategoryId.Value), discordCategory.Name, discordCategory.Position); Channel c = new Channel(new Snowflake(channel.Id), ChannelKind.GuildTextChat, g.Id, cc, channel.Name, channel.Position, channel.Topic); ExportRequest req = new ExportRequest(g, c, env + $"/{category}/Light/{channel.Name}.html", ExportFormat.HtmlLight, null, null, PartitionLimit.Null, MessageFilter.Null, true, true, "yyyy-MM-dd hh:mm:ss"); ExportRequest req2 = new ExportRequest(g, c, env + $"/{category}/Dark/{channel.Name}.html", ExportFormat.HtmlDark, null, null, PartitionLimit.Null, MessageFilter.Null, true, true, "yyyy-MM-dd hh:mm:ss"); bool isLight = true; string path = env + $"/{category}/{(isLight ? "Light" : "Dark")}/{channel.Name}.html_Files/"; var message = await Context.Channel.SendMessageAsync("", false, Embeds.Archiving(Context.User, channel, "Starting")).ConfigureAwait(false); //Timer _timer = new Timer(async _ => await OnTick(), null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10)); try { await message.ModifyAsync(x => x.Embed = Embeds.Archiving(Context.User, channel, "Exporting Light Mode")).ConfigureAwait(false); await _exporter.ExportChannelAsync(req).ConfigureAwait(false); await message.ModifyAsync(x => x.Embed = Embeds.Archiving(Context.User, channel, "Exporting Dark Mode")).ConfigureAwait(false); isLight = false; await _exporter.ExportChannelAsync(req2).ConfigureAwait(false); await message.ModifyAsync(x => x.Embed = Embeds.Archiving(Context.User, channel, "Done")); } catch (Exception ex) { await message.ModifyAsync(x => { x.Content = $"Error occured: {ex}"; x.Embed = null; }); } //async Task OnTick() //{ // await message.ModifyAsync(x => x.Content = $"Exported: {Directory.GetFiles(path, "*.*").Length} files."); //} }
protected async ValueTask ExportMultipleAsync(IConsole console, IReadOnlyList <Channel> channels) { // This uses a different route from ExportCommandBase.ExportAsync() because it runs // in parallel and needs another way to report progress to console. console.Output.Write($"Exporting {channels.Count} channels... "); var progress = console.CreateProgressTicker(); var operations = progress.Wrap().CreateOperations(channels.Count); var successfulExportCount = 0; var errors = new ConcurrentBag <(Channel, string)>(); await channels.Zip(operations).ParallelForEachAsync(async tuple => { var(channel, operation) = tuple; try { var guild = await GetDiscordClient().GetGuildAsync(channel.GuildId); var request = new ExportRequest( guild, channel, OutputPath, ExportFormat, After, Before, PartitionLimit, ShouldDownloadMedia, ShouldReuseMedia, DateFormat ); await GetChannelExporter().ExportChannelAsync(request, operation); Interlocked.Increment(ref successfulExportCount); } catch (DiscordChatExporterException ex) when(!ex.IsCritical) { errors.Add((channel, ex.Message)); } finally { operation.Dispose(); } }, ParallelLimit.ClampMin(1)); console.Output.WriteLine(); foreach (var(channel, error) in errors) { console.Error.WriteLine($"Channel '{channel}': {error}"); } console.Output.WriteLine($"Successfully exported {successfulExportCount} channel(s)."); }
/// <summary> /// Exports the specified image to the requested file name. /// </summary> /// <param name="image">The image.</param> /// <param name="libraryData">The library data.</param> /// <param name="request">The request.</param> /// <exception cref="TexLibraryException"> /// Export failure. /// </exception> /// <remarks> /// In case of mipmapping or array texture, may images will be output. /// </remarks> private void Export(TexImage image, FreeImageTextureLibraryData libraryData, ExportRequest request) { String directory = Path.GetDirectoryName(request.FilePath); String fileName = Path.GetFileNameWithoutExtension(request.FilePath); String extension = Path.GetExtension(request.FilePath); String finalName; if (image.Dimension == TexImage.TextureDimension.Texture3D) { Log.Error("Not implemented."); throw new TextureToolsException("Not implemented."); } if (!image.Format.IsInBGRAOrder()) { SwitchChannels(image, libraryData, new SwitchingBRChannelsRequest()); } if (image.SubImageArray.Length > 1 && request.MinimumMipMapSize < FreeImage.GetWidth(libraryData.Bitmaps[0]) && request.MinimumMipMapSize < FreeImage.GetHeight(libraryData.Bitmaps[0])) { int imageCount = 0; for (int i = 0; i < image.ArraySize; ++i) { for (int j = 0; j < image.MipmapCount; ++j) { if (FreeImage.GetWidth(libraryData.Bitmaps[imageCount]) < request.MinimumMipMapSize || FreeImage.GetHeight(libraryData.Bitmaps[imageCount]) < request.MinimumMipMapSize) { break; } finalName = directory + "/" + fileName + "-ind_" + i + "-mip_" + j + extension; FreeImage.FlipVertical(libraryData.Bitmaps[imageCount]); if (!FreeImage.SaveEx(libraryData.Bitmaps[imageCount], finalName)) { Log.Error("Export failure."); throw new TextureToolsException("Export failure."); } FreeImage.FlipVertical(libraryData.Bitmaps[imageCount]); Log.Info("Exporting image to " + finalName + " ..."); ++imageCount; } } } else { FreeImage.FlipVertical(libraryData.Bitmaps[0]); if (!FreeImage.SaveEx(libraryData.Bitmaps[0], request.FilePath)) { Log.Error("Export failure."); throw new TextureToolsException("Export failure."); } FreeImage.FlipVertical(libraryData.Bitmaps[0]); Log.Info("Exporting image to " + request.FilePath + " ..."); } image.Save(request.FilePath); }
private void RaiseExportDataNotification() { ExportRequest.Raise(new ExportNotification() { Title = string.Empty, CurrentHandHistory = _currentHandHistory, PlayersList = PlayersList.Where(x => x.PlayerCards.Count > 0), BoardCards = Board.Cards }); }
protected async ValueTask ExportMultipleAsync(IConsole console, IReadOnlyList <Channel> channels) { // HACK: this uses a separate route from ExportCommandBase because the progress ticker is not thread-safe console.Output.Write($"Exporting {channels.Count} channels... "); var progress = console.CreateProgressTicker(); var operations = progress.Wrap().CreateOperations(channels.Count); var errors = new List <string>(); var successfulExportCount = 0; await channels.Zip(operations).ParallelForEachAsync(async tuple => { var(channel, operation) = tuple; try { var guild = await GetDiscordClient().GetGuildAsync(channel.GuildId); var request = new ExportRequest( guild, channel, OutputPath, ExportFormat, After, Before, PartitionLimit, ShouldDownloadMedia, DateFormat ); await GetChannelExporter().ExportChannelAsync(request, operation); Interlocked.Increment(ref successfulExportCount); } catch (DiscordChatExporterException ex) when(!ex.IsCritical) { errors.Add(ex.Message); } finally { operation.Dispose(); } }, ParallelLimit.ClampMin(1)); console.Output.WriteLine(); foreach (var error in errors) { console.Error.WriteLine(error); } console.Output.WriteLine($"Successfully exported {successfulExportCount} channel(s)."); }
public async Task <ExportResult> Export(ExportRequest input) { var newPath = Path.Combine(_hostingEnvironment.WebRootPath, AppConsts.UploadPath); var fullPath = Path.Combine(newPath, input.FileId); var exportResult = await _appService.Export(fullPath, input); //Requires API gateway domain to expose static files var url = $"{Request.Scheme}://{Request.Host}/{AppConsts.UploadPath}/{exportResult.FileId}"; exportResult.DownloadUrl = url; return(exportResult); }
public ExportContext( ExportRequest request, IReadOnlyCollection <Member> members, IReadOnlyCollection <Channel> channels, IReadOnlyCollection <Role> roles) { Request = request; Members = members; Channels = channels; Roles = roles; _mediaDownloader = new MediaDownloader(request.OutputMediaDirPath, request.ShouldReuseMedia); }
/// <summary> /// Exports the specified image. /// </summary> /// <param name="image">The image.</param> /// <param name="libraryData">The library data.</param> /// <param name="export">The export request.</param> private void Export(TexImage image, PvrTextureLibraryData libraryData, ExportRequest request) { Log.Info("Exporting to " + request.FilePath + " ..."); if (request.MinimumMipMapSize > 1) // if a mimimun mipmap size was requested { int newMipMapCount = image.MipmapCount; for (int i = image.MipmapCount - 1; i > 0; --i) // looking for the mipmap level corresponding to the minimum size requeted. { if (libraryData.Header.GetWidth((uint)i) >= request.MinimumMipMapSize || libraryData.Header.GetHeight((uint)i) >= request.MinimumMipMapSize) { break; } --newMipMapCount; } // Creating a new texture corresponding to the requested mipmap levels PVRTextureHeader header = new PVRTextureHeader(RetrieveNativeFormat(image.Format), image.Height, image.Width, image.Depth, newMipMapCount, image.ArraySize, image.FaceCount); PVRTexture texture = new PVRTexture(header, IntPtr.Zero); try { for (uint i = 0; i < image.FaceCount; ++i) { for (uint j = 0; j < image.ArraySize; ++j) { for (uint k = 0; k < newMipMapCount; ++k) { Core.Utilities.CopyMemory(texture.GetDataPtr(k, j, i), libraryData.Texture.GetDataPtr(k, j, i), (int)libraryData.Header.GetDataSize((int)k, false, false)); } } } } catch (AccessViolationException e) { texture.Dispose(); Log.Error("Failed to export texture with the mipmap minimum size request. ", e); throw new TextureToolsException("Failed to export texture with the mipmap minimum size request. ", e); } // Saving the texture into a file and deleting it texture.Save(request.FilePath); texture.Dispose(); } else { libraryData.Texture.Save(request.FilePath); } image.Save(request.FilePath); }
public ExportResponse CreateSampleExport(ExportRequest exportRequest) { var request = new RestRequest("samples/export"); request.RequestFormat = DataFormat.Json; request.AddObject(exportRequest); request.Method = Method.POST; var response = _client.Execute <ExportResponse>(request); response.ThrowExceptionsForErrors(); return(response.Data); }
public async Task <IActionResult> ExportAsync([FromQuery] ExportRequest request) { switch (request.ExportFormat.ToLower()) { case "csv": return(await ExportCsvAsync()); case "excel": return(await ExportExcelAsync()); default: return(BadRequest($"Unknown format '{request.ExportFormat}'")); } }
public async Task <FileResult> Export([FromQuery] ExportRequest request) { var rule = await _ruleRepository.GetAsync(request.RuleId); var filePath = _pathManager.GetTemporaryFilesPath($"{rule.RuleName}.json"); FileUtils.DeleteFileIfExists(filePath); await _gatherManager.ExportAsync(rule, filePath); var fileBytes = System.IO.File.ReadAllBytes(filePath); return(File(fileBytes, MediaTypeNames.Application.Octet, Path.GetFileName(filePath))); }
public async Task <IActionResult> CreateExport(ExportRequest exportRequest) { if (ModelState.IsValid) { var firm = _context.Firms.Where(u => u.UserName == User.Identity.Name).FirstOrDefault(); exportRequest.Firm = firm; exportRequest.RequestDate = DateTime.Now; _context.Add(exportRequest); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(exportRequest)); }
public string Export(ExportRequest request) { var run = _fileService.Read(request.File); var csvPath = request.File.Replace(".json", ".csv"); using (var writer = new StreamWriter(csvPath)) using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.Configuration.RegisterClassMap <WdaqReadingMap>(); csv.WriteRecords(run.Readings); } return(csvPath); }
public async Task <IActionResult> ExportNotificationAsync( [FromBody] ExportRequest exportRequest) { if (exportRequest == null) { throw new ArgumentNullException(nameof(exportRequest)); } var userId = this.HttpContext.User.FindFirstValue(Common.Constants.ClaimTypeUserId); var user = await this.userDataRepository.GetAsync(UserDataTableNames.AuthorDataPartition, userId); if (user == null) { await this.SyncAuthorAsync(exportRequest.TeamId, userId); } // Ensure the data tables needed by the Azure Function to export the notification exist in Azure storage. await Task.WhenAll( this.sentNotificationDataRepository.EnsureSentNotificationDataTableExistsAsync(), this.exportDataRepository.EnsureExportDataTableExistsAsync()); var exportNotification = await this.exportDataRepository.GetAsync(userId, exportRequest.Id); if (exportNotification != null) { return(this.Conflict()); } await this.exportDataRepository.CreateOrUpdateAsync(new ExportDataEntity() { PartitionKey = userId, RowKey = exportRequest.Id, SentDate = DateTime.UtcNow, Status = ExportStatus.New.ToString(), }); var exportQueueMessageContent = new ExportQueueMessageContent { NotificationId = exportRequest.Id, UserId = userId, }; await this.exportQueue.SendAsync(exportQueueMessageContent); return(this.Ok()); }
public void TestCreateExport() { var exportRequest = new ExportRequest() { Year = DateTime.UtcNow.Year }; var exportResponse = client.CreateSampleExport(exportRequest); Assert.IsNotNull(exportResponse); Assert.IsTrue(exportResponse.ExportId > 0); Assert.IsNotNull(exportResponse.StatusUrl); // check url until ready. int attempts = 0; while (attempts < 20) { attempts += 1; var exportStatus = client.GetSampleExportStatus(exportResponse.ExportId); Assert.IsNotNull(exportStatus); Assert.IsTrue(exportStatus.Status.Length > 0); if (exportStatus.Status.Equals("finished", StringComparison.InvariantCultureIgnoreCase)) { break; } else { System.Threading.Thread.Sleep(2000); } } // get results. var sampleExports = client.GetSampleExport(exportResponse.ExportId); Assert.IsNotNull(sampleExports); Assert.IsTrue(sampleExports.Count > 0); foreach (var sampleExport in sampleExports) { Assert.AreEqual(sampleExport.year_Tested, DateTime.UtcNow.Year); Assert.IsTrue(sampleExport.id > 0); Assert.IsTrue(sampleExport.reference_Number.HasValue && sampleExport.reference_Number.Value > 0); } }
public string HandleCore(ExportRequest request, string separator) { try { var generatedDate = new StringBuilder("Generation" + separator + request.GeneratedDate); if (!string.IsNullOrEmpty(request.Language)) { generatedDate.Append(Environment.NewLine + "Language" + separator + request.Language); } var dates = new StringBuilder("Period" + separator + request.StartDate + separator + request.EndDate); var header = new StringBuilder(); var content = new StringBuilder(); foreach (var val in request.Values) { header.Append(val.Key + separator); content.Append(val.Value + separator); } header.Remove(header.Length - 1, 1); content.Remove(content.Length - 1, 1); string fileName = request.Title + "-" + Environment.TickCount + ".csv"; string filePath = ConfigurationManager.AppSettings["exportsFilePath"] + fileName; using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write)) using (var sw = new StreamWriter(fs)) { sw.WriteLine(generatedDate); sw.WriteLine(dates); sw.WriteLine(header); sw.WriteLine(content); sw.Close(); fs.Close(); } return(fileName); } catch (Exception exception) { Errors = new List <ErrorDto> { new ErrorDto("400", "Unable to export") }; } return(""); }
public async Task <string> Export(ExportRequestBody requestBody) { var request = new ExportRequest { Body = requestBody }; var client = await Connect(); var responseResult = (await client.ExportAsync(request))?.Body?.ExportResult; if (responseResult?.Length > 0) { ((IClientChannel)client).Close(); } return(responseResult); }
public async Task NewVideo(string projectId, string animationId) { var request = new ExportRequest { Name = DateTime.Now.ToShortDateString(), Message = "Default message to hooks and social media", Mappings = new Dictionary <string, string> { { "Time", DateTime.Now.ToLongDateString() } }, Distributions = new Distributions { Twitter = "Message to twitter" } }; await _pavilotService.ExportAsync(projectId, animationId, request); }
public ExportArtifact ExportProject(string projectId, bool exportUsers = false, bool exportData = false) { CheckAuthentication(); var url = Url.Combine(Config.Url, Constants.MD_URI, projectId, Constants.PROJECT_EXPORT_URI); var payload = new ExportRequest { ExportProject = new ExportProject { ExportUsers = Convert.ToInt16(exportUsers), ExportData = Convert.ToInt16(exportData) } }; var response = PostRequest(url, payload); var exportResponse = JsonConvert.DeserializeObject(response, typeof(ExportResponse)) as ExportResponse; return(exportResponse.ExportArtifact); }
public async Task <IList <ExportRequestDetail> > GetRequestForExport(ExportRequest request) { var parameters = new List <SqlParameter>(); var fromDate = new SqlParameter("@FromDateInput", request.fromDate); parameters.Add(fromDate); var toDate = new SqlParameter("@ToDateInput", request.toDate); parameters.Add(toDate); var sql = "EXEC GetRequestExport @FromDate=@FromDateInput, @ToDate=@ToDateInput"; List <SPRequestResultExportView> result = await _context.SPRequestResultExportView.FromSql(sql, parameters.ToArray()).ToListAsync(); if (result != null) { return(_mapper.Map <List <SPRequestResultExportView>, IList <ExportRequestDetail> >(result)); } return(null); }
public ExportArtifact ExportProject(string projectId, bool exportUsers = false, bool exportData = false) { CheckAuthentication(); var url = Url.Combine(Config.ServiceUrl, Constants.MD_URI, projectId, Constants.PROJECT_EXPORT_URI); var payload = new ExportRequest { ExportProject = new ExportProject { ExportUsers = Convert.ToInt16(exportUsers), ExportData = Convert.ToInt16(exportData) } }; var response = JsonPostRequest(url, payload); var exportResponse = JsonConvert.DeserializeObject(response, typeof(ExportResponse)) as ExportResponse; return exportResponse.ExportArtifact; }