private IReadOnlyList <PlatformVersion> GetCoreVersions(string dotnetPath) { const string frameworkName = "Microsoft.NETCore.App"; var path = Path.Combine(dotnetPath, "shared", frameworkName); var sortedDictionary = new SortedDictionary <NuGetVersion, PlatformVersion>(); foreach (var directory in IOUtilities.EnumerateDirectories(path)) { var versionName = Path.GetFileName(directory); if (NuGetVersion.TryParse(versionName, out var version) && version.Major > 1) { sortedDictionary.Add(version, new PlatformVersion($"netcoreapp{version.Major}.{version.Minor}", frameworkName, versionName)); } } return(sortedDictionary.Values.Reverse().ToImmutableArray()); }
/// <summary> /// Carga el archivo de reglas JSON para validar los registros del Excel /// </summary> /// <returns>El archivo JSON en objetos</returns> private List <TemplateRulesPriorityPatient> GetTemplate() { var cac_template = Configuration.GetValueConf(Constants.PRIORITY_PATIENT_TEMPLATE); var default_path = IOUtilities.GetDefaultPath(@"", FileAttributes.Normal); var local_path = string.Format(@"{0}{1}", default_path, cac_template); string json = IOUtilities.ReadAllText(local_path); if (json != "") { JavaScriptSerializer json_serializer = new JavaScriptSerializer(); var o = json_serializer.Deserialize <TempRulesPriorityPatientCollection>(json); List <TemplateRulesPriorityPatient> template = o.collection.ToList(); return(template); } else { return(new List <TemplateRulesPriorityPatient>()); } }
public DTOUsuario GetById(string id) { DTOUsuario response = null; try { Usuario_Factory usuFactory = new Usuario_Factory(); var temp = db.tbl_usuario.Include("tbl_organizacion").Include("tbl_usuario_rol.tbl_rol").Where(m => m.uid_firebase == id).FirstOrDefault(); if (temp != null) { response = usuFactory.transformDTO(temp); } } catch (Exception ex) { IOUtilities.WriteExceptionLog(ex, Configuration.GetClassName <User>()); } return(response); }
/// <summary> /// Determines thee <see cref="Sprite"/> to be used for this spawnable's icon.<para/> /// Default behavior will look for a PNG file named <see cref="IconFileName"/> inside <see cref="AssetsFolder"/>. /// </summary> /// <returns>Returns the <see cref="Sprite"/> that will be used in the <see cref="SpriteHandler.RegisterSprite(TechType, Sprite)"/> call.</returns> protected virtual Sprite GetItemSprite() { // This is for backwards compatibility with mods that were using the "ModName/Assets" format string path = this.AssetsFolder != modFolderLocation ? IOUtilities.Combine(".", "QMods", this.AssetsFolder.Trim('/'), this.IconFileName) : Path.Combine(this.AssetsFolder, this.IconFileName); if (File.Exists(path)) { return(ImageUtils.LoadSpriteFromFile(path)); } if (HasSprite) { Logger.Error($"Sprite for '{this.PrefabFileName}'{Environment.NewLine}Did not find an image file at '{path}'"); } return(SpriteManager.defaultSprite); }
public static void InputShouldProduceGivenOutput(byte[] input, byte[] output) { (List <Clip> clips, string formula, ushort id, byte trackNo) = UdpConnector.DecodeData(input); var chainedCommandWrapper = Parser.ParseFormulaToChainedCommand(formula, clips, new ClipMetaData(id, trackNo)); Assert.IsTrue(chainedCommandWrapper.Success); var processedClipWrapper = ClipProcessor.ProcessChainedCommand(chainedCommandWrapper.Result); Assert.IsTrue(processedClipWrapper.Success); Assert.IsTrue(processedClipWrapper.Result.Length > 0); var processedClip = processedClipWrapper.Result[0]; byte[] clipData = IOUtilities.GetClipAsBytes(chainedCommandWrapper.Result.TargetMetaData.Id, processedClip).ToArray(); Assert.IsTrue(output.Length == clipData.Length); Assert.IsTrue(output.SequenceEqual(clipData)); }
public static async Task <DesignerAttributeProjectData> ReadAsync( Project project, CancellationToken cancellationToken) { try { var solution = project.Solution; var storageService = (IPersistentStorageService2)solution.Workspace.Services.GetService <IPersistentStorageService>(); using (var persistenceService = storageService.GetStorage(solution, checkBranchId: false)) using (var stream = await persistenceService.ReadStreamAsync(project, StreamName, cancellationToken).ConfigureAwait(false)) using (var reader = ObjectReader.TryGetReader(stream, cancellationToken)) { if (reader != null) { var version = reader.ReadString(); if (version == FormatVersion) { var semanticVersion = VersionStamp.ReadFrom(reader); var resultCount = reader.ReadInt32(); var builder = ImmutableDictionary.CreateBuilder <string, DesignerAttributeDocumentData>(); for (var i = 0; i < resultCount; i++) { var filePath = reader.ReadString(); var attribute = reader.ReadString(); builder[filePath] = new DesignerAttributeDocumentData(filePath, attribute); } return(new DesignerAttributeProjectData(semanticVersion, builder.ToImmutable())); } } } } catch (Exception e) when(IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return(null); }
private static void CountWordsInFile(string filePath, string savePath) { Logger.WriteLine("Processing File: " + filePath + " ...", false); var wordCount = new Dictionary <string, int>(); string[] words = IOUtilities.Read(filePath).SplitByWord(); words.ToList().ForEach(word => { if (!_stopWords.Contains(word)) { wordCount.SetOrIncrement(word); _totalWordCount.SetOrIncrement(word); } }); WriteResults(wordCount, _config.NumberOfWords, Path.GetFileNameWithoutExtension(filePath), savePath); Logger.WriteLine(filePath + " Processing Completed."); }
Task <T> IDataStore.GetAsync <T>(string key) { if (IOUtilities.FileExists(TokenFilePath)) { try { var serialized = File.ReadAllText(TokenFilePath); if (!string.IsNullOrEmpty(serialized)) { var result = NewtonsoftJsonSerializer.Instance.Deserialize <T>(serialized); return(Task.FromResult(result)); } } catch { // continue } } return(Task.FromResult(default(T))); }
public async Task SetAndEvaluateFormula(bool isLive11, byte[] data) { var(trackNo, clipNo, formula) = Decoder.GetFormula(data); Console.WriteLine($"{trackNo}, {clipNo}: Incoming formula {formula}"); var result = CommandHandler.SetAndEvaluateFormula(formula, trackNo, clipNo); PrintErrorsAndWarnings(result); if (result.RanToCompletion == false) { return; } foreach (var clip in result.SuccessfulClips) { await Clients.All.SetClipDataOnClient(isLive11, isLive11 ?IOUtilities.GetClipAsBytesLive11(clip).ToArray() : IOUtilities.GetClipAsBytesV2(clip).ToArray()); } }
public void GetClipDataForTest() { var clip = new Clip(4m, true) { Notes = new SortedList <NoteEvent> { new (36, 0, .25m, 100), new (48, .5m, .15m, 100), new (60, 1, .3m, 100), new (65, 2, 2, 90) } }; var data = IOUtilities.GetClipAsBytesLive11(clip); Console.WriteLine(string.Join(',', data)); var clip2 = Mutateful.IO.Decoder.GetSingleLive11Clip(data.ToArray()); Assert.AreEqual(clip.Notes.Count, clip2.Notes.Count); Assert.AreEqual(clip.Notes[3].Start, clip2.Notes[3].Start); }
public void TestMethod1() { DTOResponse response = new DTOResponse(); byte[] binario = File.ReadAllBytes(@"D:\Users\Candy\Documents\Debugger SND.CAC\Pruebas_mayo\temp_prueba_tipo_datos.xlsx"); try { byte[] buffer = new byte[16 * 1024]; FileProcessBP filebp = new FileProcessBP(); var template = filebp.GetTemplate(); foreach (var item in template) { IOUtilities.WriteLog(item.Name, @"Pruebas_mayo", "template.txt", false); } List <DTOValidacionArchivo> lista = filebp.ValidateFile("nombre", binario); if (lista.Count == 0) { response.Archivo = new DTOArchivo() { Nombre = "file.xls", Id = Guid.NewGuid().ToString(), IdUsuario = "f9587aba-0990-11e7-93ae-92361f002671", FechaCreacion = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), NumFilasImportadas = 534, Tamano = binario.Length.ToString(), UrlArchivo = "" }; //Run(binario, response.Archivo); } if (lista.Count > 0) { response.List = lista; } System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); var stri = js.Serialize(response); File.AppendAllText(@"D:\Users\Candy\Documents\Debugger SND.CAC\Pruebas_mayo\response_testing.json", stri); } catch (Exception ex) { throw ex; } }
/// <summary> /// Reads the subtree of a FieldNode and returns the result. /// </summary> /// <param name="reader"></param> /// <returns></returns> private static FieldNode ReadFieldNode_2_2(XmlReader reader) { FieldNode node = null; foreach (string name in IOUtilities.AllElements(reader)) { switch (name) { case "Node": node = new FieldNode(reader["ID"]); break; case "BXDVector3": // Read the BXDVector3 as the node's position. node.Position = ReadBXDVector3_2_2(reader.ReadSubtree()); break; case "BXDQuaternion": // Read the BXDVector3 as the node's rotation. node.Rotation = ReadBXDQuaternion_2_2(reader.ReadSubtree()); break; case "SubMeshID": // Assign the MeshID attribute value to the SubMeshID property. node.SubMeshID = reader.ReadElementContentAsInt(); break; case "CollisionMeshID": // Assign the CollisionMeshID attribute value to the CollisionMeshID property. node.CollisionMeshID = reader.ReadElementContentAsInt(); break; case "PropertySetID": // Assign the PropertySetID attribute value to the PropertySetID property. node.PropertySetID = reader.ReadElementContentAsString(); break; } } return(node); }
private bool TryCreatePersistentStorage( Solution solution, string workingFolderPath, out AbstractPersistentStorage persistentStorage) { persistentStorage = null; AbstractPersistentStorage database = null; var databaseFilePath = GetDatabaseFilePath(workingFolderPath); try { if (!TryOpenDatabase(solution, workingFolderPath, databaseFilePath, out database)) { return(false); } database.Initialize(solution); persistentStorage = database; return(true); } catch (Exception ex) { StorageDatabaseLogger.LogException(ex); if (database != null) { database.Close(); } if (ShouldDeleteDatabase(ex)) { // this was not a normal exception that we expected during DB open. // Report this so we can try to address whatever is causing this. FatalError.ReportWithoutCrash(ex); IOUtilities.PerformIO(() => Directory.Delete(Path.GetDirectoryName(databaseFilePath), recursive: true)); } return(false); } }
private void CopyBinaryFile(string src, string dst) { IOUtilities.PathCreateDirectory(dst); File.Copy(src, dst, true); if (Settings.ComputeHash) { byte[] hashSrc; byte[] hashDst; using (HashAlgorithm hashAlgorithm = MD5.Create()) { using (Stream stream = File.OpenRead(src)) { hashSrc = hashAlgorithm.ComputeHash(stream); } using (Stream stream = File.OpenRead(dst)) { hashDst = hashAlgorithm.ComputeHash(stream); } } if (!HashEqual(hashSrc, hashDst)) { if (_errorCount > 5) { throw new Exception(string.Format("Error while copying file \"{0}\" to \"{1}\".", src, dst)); } _errorCount += 1; Logger.Current.Log(LogCategory.Verify, "Different hash (" + _errorCount + ")"); CopyBinaryFile(src, dst); } else { _errorCount = 0; Logger.Current.Log(LogCategory.Verify, dst); } } }
// ------[ INITIALIZATION ]------ public void OnEnable(SerializedProperty serializedEditableModProfile, ModProfile baseProfile, UserProfile user) { this.editableProfileProperty = serializedEditableModProfile; this.profile = baseProfile; this.isUndoEnabled = (baseProfile != null); isTagsExpanded = false; isKVPsExpanded = false; // - Game Profile - ModManager.GetGameProfile((g) => { this.gameProfile = g; isRepaintRequired = true; }, null); // - Configure Properties - logoProperty = editableProfileProperty.FindPropertyRelative("logoLocator"); // - Load Textures - if (logoProperty.FindPropertyRelative("isDirty").boolValue == true) { logoLocation = logoProperty.FindPropertyRelative("value.url").stringValue; logoTexture = IOUtilities.ReadImageFile(logoLocation); if (logoTexture != null) { lastLogoWriteTime = (new FileInfo(logoLocation)).LastWriteTime; } } else if (profile != null) { logoLocation = profile.logoLocator.GetSizeURL(LOGO_PREVIEW_SIZE); logoTexture = EditorImages.LoadingPlaceholder; ModManager.GetModLogo(profile, LOGO_PREVIEW_SIZE, (t) => { logoTexture = t; isRepaintRequired = true; }, WebRequestError.LogAsWarning); } else { logoLocation = string.Empty; logoTexture = null; } }
public DTOArchivo GetFileById(string id) { DTOArchivo response = null; try { Archivo_Factory factory = new Archivo_Factory(); Guid idparse = Guid.Parse(id); tbl_archivo_cac modelo = db.tbl_archivo_cac.Where(m => m.id == idparse).FirstOrDefault(); if (modelo != null) { response = factory.transformDTO(modelo); } } catch (Exception ex) { IOUtilities.WriteExceptionLog(ex, Configuration.GetClassName <CACService>()); } return(response); }
public static DateTime GetLastEventTime() { var path = GetLastEventTimeFilePath(); if (IOUtilities.FileExists(path)) { try { var text = File.ReadAllText(path).Nullify(); if (text != null && DateTime.TryParse(text, out var dt)) { return(dt); } } catch { // continue } } return(DateTime.MaxValue); }
public async Task SetAndEvaluateClipData(bool isLive11, byte[] data) { var clip = isLive11 ? Decoder.GetSingleLive11Clip(data) : Decoder.GetSingleClip(data); Console.WriteLine($"{clip.ClipReference.Track}, {clip.ClipReference.Clip} Incoming clip data to evaluate"); var result = CommandHandler.SetAndEvaluateClipData(clip); PrintErrorsAndWarnings(result); if (result.RanToCompletion == false) { return; } foreach (var successfulClip in result.SuccessfulClips) { await Clients.All.SetClipDataOnClient(isLive11, isLive11 ?IOUtilities.GetClipAsBytesLive11(successfulClip).ToArray() : IOUtilities.GetClipAsBytesV2(successfulClip).ToArray()); } }
private string GetMenuIconBitmapPath() { var cachePath = Path.Combine(Path.GetTempPath(), FolderId.ToString("N") + ".png"); if (!IOUtilities.FileExists(cachePath)) { using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(GetType().Namespace + ".UI.CloudFolder.ico")) { if (stream == null) { throw new InvalidOperationException(); } // note the 16 size is a 256 colors, not a full RGB color as the Shell's context menu doesn't like that var bmps = IconUtilities.LoadIconsFromStream(stream); var bmp = bmps.FirstOrDefault(i => i.Height == 16); bmp.Save(cachePath); } } return(cachePath); }
private ImmutableArray <SyntaxTrivia> UpdateEmbeddedFileNames( Document sourceDocument, Document destinationDocument, ImmutableArray <SyntaxTrivia> banner) { var sourceName = IOUtilities.PerformIO(() => Path.GetFileName(sourceDocument.FilePath)); var destinationName = IOUtilities.PerformIO(() => Path.GetFileName(destinationDocument.FilePath)); if (string.IsNullOrEmpty(sourceName) || string.IsNullOrEmpty(destinationName)) { return(banner); } var result = ArrayBuilder <SyntaxTrivia> .GetInstance(); foreach (var trivia in banner) { var updated = CreateTrivia(trivia, trivia.ToFullString().Replace(sourceName, destinationName)); result.Add(updated); } return(result.ToImmutableAndFree()); }
protected sealed override async ValueTask <IChecksummedPersistentStorage?> TryOpenDatabaseAsync( SolutionKey solutionKey, string workingFolderPath, string databaseFilePath, CancellationToken cancellationToken) { var solutionFolder = IOUtilities.PerformIO(() => Path.GetDirectoryName(solutionKey.FilePath)); if (RoslynString.IsNullOrEmpty(solutionFolder)) { return(null); } var cacheService = await this.CreateCacheServiceAsync(solutionFolder, cancellationToken).ConfigureAwait(false); var relativePathBase = await cacheService.GetRelativePathBaseAsync(cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(relativePathBase)) { return(null); } return(new CloudCachePersistentStorage(cacheService, solutionKey, workingFolderPath, relativePathBase, databaseFilePath)); }
public bool Create(DTOUsuario user) { try { Usuario_Factory usuFactory = new Usuario_Factory(); tbl_usuario usuario = usuFactory.transformModel(user); if (usuario != null) { var u = db.tbl_usuario.Add(usuario); int total = db.SaveChanges(); IOUtilities.WriteLog(string.Format("{0}\t{1}\tCreate\t{2}", IOUtilities.GetLocalTime(), Configuration.GetClassName <User>(), total), Configuration.GetClassName <User>(), Configuration.GetValueConf(Constants.LogFile)); } return(true); } catch (Exception ex) { IOUtilities.WriteExceptionLog(ex, Configuration.GetClassName <User>()); throw; } }
// ------[ UPDATE ]------ public void OnUpdate() { if (File.Exists(logoLocation)) { try { FileInfo imageInfo = new FileInfo(logoLocation); if (lastLogoWriteTime < imageInfo.LastWriteTime) { logoTexture = IOUtilities.ReadImageFile(logoLocation); lastLogoWriteTime = imageInfo.LastWriteTime; isRepaintRequired = true; } } catch (Exception e) { Debug.LogWarning("[mod.io] Unable to read updates to the logo image file.\n\n" + Utility.GenerateExceptionDebugString(e)); } } }
private int MySQLStorageRun(DTOArchivo archivo) { int total = -1; try { Archivo_Factory factory = new Archivo_Factory(); tbl_archivo_cac modelo = factory.transformModel(archivo); var temp_modelo = db.tbl_archivo_cac.Where(m => m.id == modelo.id).FirstOrDefault(); if (temp_modelo == null) { db.tbl_archivo_cac.Add(modelo); total = db.SaveChanges(); } } catch (Exception ex) { IOUtilities.WriteExceptionLog(ex, Configuration.GetClassName <FileService>()); } return(total); }
public async Task UpdateVersion(ConfigurationItem configItem, IProgress <double> progress = null) { configItem.AssertNotNull(nameof(configItem)); string appDataOldVersionBackupPath = CommonBLL.CreateTempAppDataFolder(); string appDataPath = CommonBLL.CreateTempAppDataFolder(); string appDataUnzippedPath = Path.Combine(appDataPath, "unzipped"); try { Task <byte[]> zipArchiveTask = RetrieveZipFileWithBackup(configItem.Architecture, appDataPath, progress); Task backupTask = Task.Run(() => { Logger.Info($"Creating a backup of the current version at {appDataOldVersionBackupPath}"); BackupCurrentVersion(configItem.DBeaverInstallPath, appDataOldVersionBackupPath); Logger.Info($"The backup has been created"); }); await Task.WhenAll(zipArchiveTask, backupTask); Logger.Info("Unzipping the downloaded archive"); byte[] zipArchive = zipArchiveTask.Result; UnzipArchive(zipArchive, appDataUnzippedPath, progress); Logger.Info("The archive has been successfully unzipped"); Logger.Info($"Patching DBeaver current version at {configItem.DBeaverInstallPath}"); IOUtilities.EmptyFolder(configItem.DBeaverInstallPath); IOUtilities.CopyFolderTo(Path.Combine(appDataUnzippedPath, "dbeaver"), configItem.DBeaverInstallPath, true); Logger.Info("Patching successful"); } finally { Logger.Info("Deleting temp data"); IOUtilities.DeleteFolder(appDataPath); IOUtilities.DeleteFolder(appDataOldVersionBackupPath); Logger.Info("Temp data deleted successfully"); } }
//ConcurrentBag<string> log = new ConcurrentBag<string>(); public static void SaveAnalysis(double elepsedtime, ValidatorResult <DTOValidacionArchivo> validator_result) { //JavaScriptSerializer json_serializer = new JavaScriptSerializer(); //json_serializer.MaxJsonLength = 2147483647; //Task<string> output = Task<string>.Factory.StartNew(() => json_serializer.Serialize(validator_result.GetResult())); //Task.Factory.StartNew(() => IOUtilities.WriteLog(output.Result, "PILOTO", $"{DateTime.Now.ToString("yyyy-MM-dd HH")}_json_serializer.json", true)); //Task.Factory.StartNew(() => SaveLog($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}\tTiempo actual {elepsedtime}.")); //Task.Factory.StartNew(() => log.ForEach(m => IOUtilities.WriteLog(m, "PILOTO",$"{DateTime.Now.ToString("yyyy-MM-dd HH")}_linea.txt", false))); validator_result.GetResult().OrderBy(m => m.Columna).ForEach(m => IOUtilities.WriteLog(m.ToString(), "PILOTO", $"{DateTime.Now.ToString("yyyy-MM-dd HH")}_result_validation.txt", false)); //Task.Factory.StartNew(() => validator_result.GetResult().OrderBy(m => m.Columna).ForEach(m => IOUtilities.WriteLog(m.ToString(), "PILOTO", $"{DateTime.Now.ToString("yyyy-MM-dd HH")}_result_validation.txt", false))); analisis1.GetList().ForEach(m => IOUtilities.WriteLog(m, "PILOTO", $"{DateTime.Now.ToString("yyyy-MM-dd HH")}_lista_de_errores.txt", false)); //Task task1 = Task.Factory.StartNew(() => analisis1.GetList().ForEach(m => IOUtilities.WriteLog(m, "PILOTO", $"{DateTime.Now.ToString("yyyy-MM-dd HH")}_lista_de_errores.txt", false))); foreach (var keyvalue in analisis1.GetDictionary()) { string concat = ""; //keyvalue.Value.ForEach(m => concat = $"{concat},{m}"); concat = keyvalue.Value.Count() > 0 ? $"@{keyvalue.Value[0]}" : ""; IOUtilities.WriteLog($"{keyvalue.Key}{concat}", "PILOTO", $"{DateTime.Now.ToString("yyyy-MM-dd HH")}_lista_sin_errores.txt", false); } foreach (var keyvalue in analisis2.GetDictionary()) { string concat = ""; keyvalue.Value.ForEach(m => concat = $"{concat}@{m}"); IOUtilities.WriteLog($"{keyvalue.Key}{concat}", "PILOTO", $"{DateTime.Now.ToString("yyyy-MM-dd HH")}_lineas_todos.txt", false); } foreach (var keyvalue in analisis2.GetList()) { IOUtilities.WriteLog($"{keyvalue}", "PILOTO", $"{DateTime.Now.ToString("yyyy-MM-dd HH")}_lineas_todos.txt", false); } analisis1 = new WrapperObject <string, string, string[]>(); analisis2 = new WrapperObject <string, string, string[]>(); //Task.WaitAll(task1); }
private static string GetReferenceDocumentationPath(string path) { string docPath = null; var docPathTemp = Path.Combine(path, "V4.X"); if (File.Exists(Path.Combine(docPathTemp, "System.xml"))) { docPath = docPathTemp; } else { var localeDirectory = IOUtilities.PerformIO(() => Directory.GetDirectories(docPathTemp), Array.Empty <string>()).FirstOrDefault(); if (localeDirectory != null && File.Exists(Path.Combine(localeDirectory, "System.xml"))) { docPath = localeDirectory; } } return(docPath); }
private async Task RepeatIOAsync(Func <Task> action, CancellationToken cancellationToken) { const int repeat = 6; for (var i = 0; i < repeat; i++) { cancellationToken.ThrowIfCancellationRequested(); try { await action().ConfigureAwait(false); return; } catch (Exception e) when(IOUtilities.IsNormalIOException(e) || _service._reportAndSwallowException(e) ) { // The exception filter above might be a little funny looking. We always // want to enter this catch block, but if we ran into a normal IO exception // we shouldn't bother reporting it. We don't want to get lots of hits just // because something like an anti-virus tool locked the file and we // couldn't write to it. The call to IsNormalIOException will shortcut // around the reporting in this case. var delay = _service._delayService.FileWriteDelay; await LogExceptionAsync( e, $"Operation failed. Trying again after {delay}", cancellationToken ) .ConfigureAwait(false); await Task.Delay(delay, cancellationToken).ConfigureAwait(false); } } }
/// <summary> /// Creates a temporary audio file from the next audio chunk in the queue and writes the /// file name to the streaming speech-to-text process so that it can send its data to the server. /// </summary> IEnumerator SaveAndSendNextChunk() { // Save recorded audio to a WAV file and convert it to RAW format. string wavAudioFilePath = SavWav.Save(m_TempAudioComponent.TempAudioRelativePath(), m_AudioChunksQueue.Dequeue()); string rawAudioFilePath = IOUtilities.MakeFilePathUnique(Path.ChangeExtension(wavAudioFilePath, "raw")); var audioConversionJob = new SoXAudioConversionJob(wavAudioFilePath, rawAudioFilePath, 16000, 16, 1, AudioEncoding.EncodingType.SignedInteger, Endianness.EndiannessType.Little); audioConversionJob.Start(); yield return(StartCoroutine(audioConversionJob.WaitFor())); if (audioConversionJob.ErrorMessage != null) { if (m_OnError != null) { m_OnError(audioConversionJob.ErrorMessage); } yield break; } m_StreamingSpeechToTextProcess.StandardInput.WriteLine(rawAudioFilePath); }
private async Task <bool> SaveAsync(Document document, CancellationToken cancellationToken) { var solution = document.Project.Solution; var persistentStorageService = (IChecksummedPersistentStorageService)solution.Workspace.Services.GetRequiredService <IPersistentStorageService>(); try { var storage = await persistentStorageService .GetStorageAsync(solution, checkBranchId : false, cancellationToken) .ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { WriteTo(writer); } stream.Position = 0; return(await storage .WriteStreamAsync( document, PersistenceName, stream, this.Checksum, cancellationToken ) .ConfigureAwait(false)); } catch (Exception e) when(IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return(false); }