internal static string MakeSynthesizedInstrumentationPayloadLocalFieldName(int uniqueId) { return(SynthesizedLocalNamePrefix + "InstrumentationPayload" + StringExtensions.GetNumeral(uniqueId)); }
internal static string MakeDynamicCallSiteFieldName(int uniqueId) { Debug.Assert((char)GeneratedNameKind.DynamicCallSiteField == 'p'); return("<>p__" + StringExtensions.GetNumeral(uniqueId)); }
public static List <Program> GetUWPApps() { var apps = new List <Program>(); var manager = new PackageManager(); IEnumerable <Package> packages = manager.FindPackagesForUser(WindowsIdentity.GetCurrent().User.Value); foreach (var package in packages) { if (package.IsFramework || package.IsResourcePackage || package.SignatureKind != PackageSignatureKind.Store) { continue; } try { if (package.InstalledLocation == null) { continue; } } catch { // InstalledLocation accessor may throw Win32 exception for unknown reason continue; } try { string manifestPath; if (package.IsBundle) { manifestPath = @"AppxMetadata\AppxBundleManifest.xml"; } else { manifestPath = "AppxManifest.xml"; } manifestPath = Path.Combine(package.InstalledLocation.Path, manifestPath); var manifest = new XmlDocument(); manifest.Load(manifestPath); var apxApp = manifest.SelectSingleNode(@"/*[local-name() = 'Package']/*[local-name() = 'Applications']//*[local-name() = 'Application'][1]"); var appId = apxApp.Attributes["Id"].Value; var visuals = apxApp.SelectSingleNode(@"//*[local-name() = 'VisualElements']"); var iconPath = visuals.Attributes["Square150x150Logo"]?.Value; if (iconPath.IsNullOrEmpty()) { iconPath = visuals.Attributes["Square70x70Logo"]?.Value; if (iconPath.IsNullOrEmpty()) { iconPath = visuals.Attributes["Square44x44Logo"]?.Value; if (iconPath.IsNullOrEmpty()) { iconPath = visuals.Attributes["Logo"]?.Value; } } } if (!iconPath.IsNullOrEmpty()) { iconPath = Path.Combine(package.InstalledLocation.Path, iconPath); iconPath = GetUWPGameIcon(iconPath); } var name = manifest.SelectSingleNode(@"/*[local-name() = 'Package']/*[local-name() = 'Properties']/*[local-name() = 'DisplayName']").InnerText; if (name.StartsWith("ms-resource")) { name = Resources.GetIndirectResourceString(package.Id.FullName, package.Id.Name, name); if (name.IsNullOrEmpty()) { name = manifest.SelectSingleNode(@"/*[local-name() = 'Package']/*[local-name() = 'Identity']").Attributes["Name"].Value; } } var app = new Program() { Name = StringExtensions.NormalizeGameName(name), WorkDir = package.InstalledLocation.Path, Path = "explorer.exe", Arguments = $"shell:AppsFolder\\{package.Id.FamilyName}!{appId}", Icon = iconPath, AppId = package.Id.FamilyName }; apps.Add(app); } catch (Exception e) { logger.Error(e, $"Failed to parse UWP game info."); } } return(apps); }
internal static string MakeBaseMethodWrapperName(int uniqueId) { Debug.Assert((char)GeneratedNameKind.BaseMethodWrapper == 'n'); return("<>n__" + StringExtensions.GetNumeral(uniqueId)); }
public override string ToString() { return("{0} - {1}".FormatWith(FileName, BinaryFile?.Let(bf => StringExtensions.ToComputerSize(bf.Length)) ?? "??")); }
private void Nouveau_client_click(object sender, RoutedEventArgs e) { DAL_Client.AjouterClient(Mail.Text, StringExtensions.CiviliteToBoolean(Cocivilite.Text), int.Parse(Fidelite.Text), Nom.Text, Prenom.Text, BCrypt.Net.BCrypt.HashPassword((string)Password.Password)); AfficherClient(); }
/// <summary> /// Parses a string into an Enum /// </summary> /// <typeparam name="T">The type of the Enum</typeparam> /// <param name="value">String value to parse</param> /// <returns>The Enum corresponding to the stringExtensions</returns> public static T EnumParse <T>(this string value) { return(StringExtensions.EnumParse <T>(value, false)); }
private void ProcessResult(UPCRMResult result) { UPRecordCopyStep currentStep = this.stepQueue[0]; this.stepQueue.RemoveAt(0); UPConfigQueryTable queryTable = currentStep.QueryTable; int count = result.RowCount; int resultTableCount = result.NumberOfResultTables; UPContainerInfoAreaMetaInfo copyResultInfoArea = null; if (queryTable.InfoAreaId == currentStep.FieldControl.InfoAreaId) { copyResultInfoArea = result.MetaInfo.ResultInfoAreaMetaInfoAtIndex(0); } for (int i = 0; i < count; i++) { UPCRMResultRow row = (UPCRMResultRow)result.ResultRowAtIndex(i); UPCRMRecord record = new UPCRMRecord(queryTable.InfoAreaId); if (currentStep.DestinationRecord != null) { record.AddLink(new UPCRMLink(currentStep.DestinationRecord, queryTable.LinkId)); } for (int j = 1; j < resultTableCount; j++) { string linkRecordIdentification = row.RecordIdentificationAtIndex(j); if (string.IsNullOrEmpty(linkRecordIdentification) && !result.IsServerResult) { UPContainerInfoAreaMetaInfo resultInfoArea = result.MetaInfo.ResultInfoAreaMetaInfoAtIndex(j); UPCRMLinkReader linkReader = new UPCRMLinkReader(StringExtensions.InfoAreaIdRecordId(currentStep.FieldControl.InfoAreaId, row.RootRecordId), $"{resultInfoArea.InfoAreaId}:{resultInfoArea.LinkId}", null); linkRecordIdentification = linkReader.RequestLinkRecordOffline(); } int linkId = -1; if (linkRecordIdentification?.Length > 8) { if (currentStep.DestinationRecord == null || queryTable.LinkId != linkId || linkRecordIdentification.InfoAreaId() != currentStep.DestinationRecord.InfoAreaId) { record.AddLink(new UPCRMLink(linkRecordIdentification, linkId)); } } } Dictionary <string, object> fieldsWithFunctions = row.ValuesWithFunctions(); UPConfigQueryTable replacedTable = queryTable.QueryTableByApplyingValueDictionary(fieldsWithFunctions); if (copyResultInfoArea != null) { foreach (UPContainerFieldMetaInfo field in copyResultInfoArea.Fields) { string val = row.RawValueAtIndex(field.PositionInResult); if (!string.IsNullOrEmpty(val)) { record.AddValue(new UPCRMFieldValue(val, field.InfoAreaId, field.FieldId)); } } } if (replacedTable != null) { record.ApplyValuesFromTemplateFilter(replacedTable, true); } int numberOfSubTables = queryTable.NumberOfSubTables; if (numberOfSubTables > 0) { for (int k = 0; k < numberOfSubTables; k++) { UPRecordCopyStep subStep = new UPRecordCopyStep(); subStep.QueryTable = queryTable.SubTableAtIndex(k); subStep.SourceRecordIdentification = row.RootRecordIdentification; subStep.DestinationRecord = record; this.ConfigForStepFromQueryTable(subStep, subStep.QueryTable); this.stepQueue.Add(subStep); } } this.recordArray.Add(record); } this.ExecuteNextStep(); }
protected override int ExecuteCommand(CommandLineApplication app, IConsole console) { Out.WriteResultOnNewLine(StringExtensions.ToQuotedArgs(new UoeProcessArgs().AppendFromPfFilePath(File))); return(0); }
public List <IGame> GetInstalledGames(bool useDataCache = false) { var contentPath = Path.Combine(OriginPaths.DataPath, "LocalContent"); var games = new List <IGame>(); if (Directory.Exists(contentPath)) { var packages = Directory.GetFiles(contentPath, "*.mfst", SearchOption.AllDirectories); foreach (var package in packages) { try { var gameId = Path.GetFileNameWithoutExtension(package); if (!gameId.StartsWith("Origin")) { // Get game id by fixing file via adding : before integer part of the name // for example OFB-EAST52017 converts to OFB-EAST:52017 var match = Regex.Match(gameId, @"^(.*?)(\d+)$"); if (!match.Success) { logger.Warn("Failed to get game id from file " + package); continue; } gameId = match.Groups[1].Value + ":" + match.Groups[2].Value; } var newGame = new Game() { Provider = Provider.Origin, ProviderId = gameId }; GameLocalDataResponse localData = null; try { localData = GetLocalManifest(gameId, package, useDataCache); } catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors) { logger.Error(e, $"Failed to get Origin manifest for a {gameId}, {package}"); continue; } if (localData.offerType != "Base Game" && localData.offerType != "DEMO") { continue; } newGame.Name = StringExtensions.NormalizeGameName(localData.localizableAttributes.displayName); var platform = localData.publishing.softwareList.software.FirstOrDefault(a => a.softwarePlatform == "PCWIN"); if (platform == null) { logger.Warn(gameId + " game doesn't have windows platform, skipping install import."); continue; } var installPath = GetPathFromPlatformPath(platform.fulfillmentAttributes.installCheckOverride); if (string.IsNullOrEmpty(installPath) || !File.Exists(installPath)) { continue; } newGame.InstallDirectory = Path.GetDirectoryName(installPath); newGame.PlayTask = GetGamePlayTask(localData); if (newGame.PlayTask.Type == GameTaskType.File) { newGame.PlayTask.WorkingDir = newGame.PlayTask.WorkingDir.Replace(newGame.InstallDirectory, "{InstallDir}"); newGame.PlayTask.Path = newGame.PlayTask.Path.Replace(newGame.InstallDirectory, "{InstallDir}"); } games.Add(newGame); } catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors) { logger.Error(e, $"Failed to import installed Origin game {package}."); } } } return(games); }
static XmlData() { StringExtensions.AddConvertTypeCreation(typeof(XmlData), value => new XmlSnippet(value).Root); }
private static async Task <(string errorMessage, JsonValue value)> _TryParseInterpretedStringAsync(StringBuilder builder, TextReader stream, char[] scratch) { // NOTE: `builder` contains the portion of the string found in `stream`, up to the first // (possible) escape sequence. System.Diagnostics.Debug.Assert('\\' == (char)stream.Peek()); System.Diagnostics.Debug.Assert(scratch.Length >= 4); bool complete = false; int?previousHex = null; while (stream.Peek() != -1) { await stream.TryRead(scratch, 0, 1); // eat this character var c = scratch[0]; if (c == '\\') { if (stream.Peek() == -1) { StringBuilderCache.Release(builder); SmallBufferCache.Release(scratch); return("Could not find end of string value.", null); } // escape sequence var lookAhead = (char)stream.Peek(); if (!_MustInterpretComplex(lookAhead)) { await stream.TryRead(scratch, 0, 1); // eat the simple escape c = _InterpretSimpleEscapeSequence(lookAhead); } else { // NOTE: Currently we only handle 'u' here if (lookAhead != 'u') { StringBuilderCache.Release(builder); SmallBufferCache.Release(scratch); return($"Invalid escape sequence: '\\{lookAhead}'.", null); } await stream.TryRead(scratch, 0, 1); // eat the 'u' var charsRead = await stream.ReadAsync(scratch, 0, 4); if (charsRead < 4) { StringBuilderCache.Release(builder); SmallBufferCache.Release(scratch); return("Could not find end of string value.", null); } var hexString = new string(scratch, 0, 4); var currentHex = int.Parse(hexString, NumberStyles.HexNumber); if (previousHex != null) { // Our last character was \u, so combine and emit the UTF32 codepoint currentHex = StringExtensions.CalculateUtf32(previousHex.Value, currentHex); if (currentHex.IsValidUtf32CodePoint()) { builder.Append(char.ConvertFromUtf32(currentHex)); } else { return("Invalid UTF-32 code point.", null); } previousHex = null; } else { previousHex = currentHex; } continue; } } else if (c == '"') { complete = true; break; } // Check if last character was \u, and if so emit it as-is, because // this character is not a continuation of a UTF-32 escape sequence if (previousHex != null) { builder.Append(char.ConvertFromUtf32(previousHex.Value)); previousHex = null; } // non-escape sequence builder.Append(c); } SmallBufferCache.Release(scratch); // if we had a hanging UTF32 escape sequence, apply it now if (previousHex != null) { builder.Append(char.ConvertFromUtf32(previousHex.Value)); } if (!complete) { StringBuilderCache.Release(builder); return("Could not find end of string value.", null); } JsonValue value = StringBuilderCache.GetStringAndRelease(builder); return(null, value); }
public void StringFormattedWithTwoPropertiesIsUpdatedWithPropertyValues() { var result = new StringExtensions("A {Thing} with a {MatchingProperty}").Format(new { Thing = "string", MatchingProperty = "replaced value" }); Assert.That(result, Is.EqualTo("A string with a replaced value")); }
internal static string LambdaCopyParameterName(int ordinal) { return("<p" + StringExtensions.GetNumeral(ordinal) + ">"); }
public IHttpResponse PostCreateAlbum(DoAlbumInputViewModel model) { Regex albumNameRegex = new Regex(@"^\w{3,30}$"); Regex coverUrlRegex = new Regex(@"^\b((http|https):\/\/?)[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/?))$"); string cookieValue = this.Request.Cookies.GetCookie(AuthenticationCookieKey).Value; string username = this.UserCookieService.DecryptString(cookieValue, EncryptKey); string userId = this.Context .Users .First(user => user.Username == username) .Id; string albumId = Guid.NewGuid().ToString(); model.Cover = StringExtensions.UrlDecode(model.Cover); Album album = new Album() { Id = albumId, Name = model.Name, Cover = model.Cover }; UserAlbum userAlbum = new UserAlbum() { Id = Guid.NewGuid().ToString(), UserId = userId, AlbumId = albumId }; if (!albumNameRegex.Match(model.Name).Success || !coverUrlRegex.Match(model.Cover).Success) { GetCreateAlbumPageViewModel createPageViewModel = new GetCreateAlbumPageViewModel() { ErrorMessage = InvalidAlbumInformationError }; return(this.View("AlbumsCreate", HttpResponseStatusCode.BadRequest, createPageViewModel)); } else if (this.Context.UserAlbums.Where(ua => ua.UserId == userId).Any(a => a.Album.Name == model.Name)) { GetCreateAlbumPageViewModel createPageViewModel = new GetCreateAlbumPageViewModel() { ErrorMessage = AlbumAlreadyExistsError }; return(this.View("AlbumsCreate", HttpResponseStatusCode.BadRequest, createPageViewModel)); } using (this.Context) { this.Context .Add(album); this.Context .UserAlbums .Add(userAlbum); this.Context.SaveChanges(); } AlbumDetailsViewModel viewModel = new AlbumDetailsViewModel() { Name = model.Name, Price = $"{album.Price.ToString(CultureInfo.InvariantCulture):F2}", Tracks = new AlbumTrack[0], Cover = model.Cover, CreateTrack = $"'/Tracks/Create?albumId={album.Id}'" }; return(this.View("album", HttpResponseStatusCode.Ok, viewModel)); }
public void StringFormattedWithNoPropertiesIsNotUpdated() { var result = new StringExtensions("A string with a {MatchingProperty}").Format(new {}); Assert.That(result, Is.EqualTo("A string with a {MatchingProperty}")); }
private static void InternalInit() { try { if (_validationResult == null) { _validationResult = new List <ValidationResult>(); } var section = ConfigurationSectionBase.GetSection <SmptProviderSettingsSection>("smptProviderSettingsSection"); var settings = section.SmptSettings; if (settings.Contains("Path")) { var settingValue = settings["Path"].Value; if (string.IsNullOrWhiteSpace(settingValue)) { LoggerManager.WriteWarningToEventLog("Path cannot be empty"); _validationResult.Add(new ValidationResult("Path cannot be empty")); } else { _path = settingValue; } } else { _validationResult.Add(new ValidationResult("Path does not exist in configuration section")); } if (settings.Contains("Port")) { var settingValue = settings["Port"].Value; int portNumeric; if (!ReflectionHelper.TryParseOrDefault <int>(settingValue, out portNumeric)) { _validationResult.Add(new ValidationResult(string.Format("Port setting is not numerical. Value is {0}", settingValue))); LoggerManager.WriteWarningToEventLog(string.Format("Port setting is not numerical. Value is {0}", settingValue)); } else { _port = portNumeric; } } if (settings.Contains("IsSSLEnabled")) { var settingValue = settings["IsSSLEnabled"].Value; if (!ReflectionHelper.TryParseOrDefault <bool>(settingValue, out _isSSLEnabled)) { _validationResult.Add(new ValidationResult(string.Format("Port setting is not numerical. Value is {0}", settingValue))); LoggerManager.WriteWarningToEventLog(string.Format("Port setting is not numerical. Value is {0}", settingValue)); } } if (settings.Contains("UserName")) { var settingValue = settings["UserName"].Value; if (string.IsNullOrWhiteSpace(settingValue)) { LoggerManager.WriteWarningToEventLog("UserName cannot be empty"); _validationResult.Add(new ValidationResult("UserName cannot be empty")); } else if (!EmailValidator.ValidateEmail(settingValue)) { LoggerManager.WriteWarningToEventLog(string.Format("UserName is not a valid e-mail format. Value is {0}", settingValue)); _validationResult.Add(new ValidationResult(string.Format("UserName is not a valid e-mail format. Value is {0}", settingValue))); } else { _userName = settingValue; } } else { _validationResult.Add(new ValidationResult("UserName does not exist in configuration section")); } #if DEBUG _password = StringExtensions.ToSecureString("Password1"); #else if (settings.Contains("Password")) { var encryptedPassword = settings["Password"].Value; var secureString = Kernel.Cryptography.DPAPIEncryption.DecryptString(encryptedPassword); _password = secureString; } else { _validationResult.Add(new ValidationResult("Password does not exist in configuration section")); } #endif } catch (Exception ex) { _error = ex; LoggerManager.WriteExceptionToEventLog(ex); } finally { _isValid = _error == null && _validationResult.Count == 0; } }
public ActionResult Index(string gridState = "") { //string returnUrl = Request.Path; string returnUrl = "/Home/Index"; IQueryCollection query = Request.Query; if (!string.IsNullOrWhiteSpace(gridState)) { try { query = new QueryCollection(StringExtensions.GetQuery(gridState)); } catch (Exception) { // do nothing, gridState was not a valid state } } ViewBag.ActiveMenuTitle = "Demo"; var requestCulture = HttpContext.Features.Get <IRequestCultureFeature>(); var locale = requestCulture.RequestCulture.UICulture.TwoLetterISOLanguageName; SharedResource.Culture = requestCulture.RequestCulture.UICulture; var shipperList = _shippersRepository.GetAll() .Select(s => new SelectItem(s.ShipperID.ToString(), s.CompanyName)) .ToList(); Action <IGridColumnCollection <Order> > columns = c => { /* Adding not mapped column, that renders body, using inline Razor html helper */ c.Add() .Encoded(false) .Sanitized(false) .SetWidth(30) .Css("hidden-xs") //hide on phones .RenderComponentAs <ButtonCellViewComponent>(returnUrl); /* Adding "OrderID" column: */ c.Add(o => o.OrderID) .Titled(SharedResource.Number) .SetWidth(100); /* Adding "OrderDate" column: */ c.Add(o => o.OrderDate, "OrderCustomDate") .Titled(SharedResource.OrderCustomDate) .SortInitialDirection(GridSortDirection.Descending) .ThenSortByDescending(o => o.OrderID) .SetCellCssClassesContraint(o => o.OrderDate.HasValue && o.OrderDate.Value >= DateTime.Parse("1997-01-01") ? "red" : "") .Format("{0:yyyy-MM-dd}") .SetWidth(110) .Max(true).Min(true); c.Add(o => o.ShipVia) .Titled("Via") .SetWidth(250) .RenderValueAs(o => o.Shipper.CompanyName) .SetListFilter(shipperList); /* Adding "CompanyName" column: */ c.Add(o => o.Customer.CompanyName) .Titled(SharedResource.CompanyName) .ThenSortByDescending(o => o.ShipVia) .ThenSortByDescending(o => o.Freight) .SetWidth(250) .SetInitialFilter(GridFilterType.StartsWith, "a") .SetFilterWidgetType("CustomCompanyNameFilterWidget") .Max(true).Min(true); /* Adding "ContactName" column: */ c.Add(o => o.Customer.ContactName).Titled(SharedResource.ContactName).SetWidth(250) .Max(true).Min(true); /* Adding "Customer.Country" hidden column: */ c.Add(o => o.Customer.Country, true); /* Adding "Freight" column: */ c.Add(o => o.Freight) .Titled(SharedResource.Freight) .SetWidth(100) .Format("{0:F}") .Sum(true).Average(true).Max(true).Min(true); /* Adding "Vip customer" column: */ c.Add(o => o.Customer.IsVip) .Titled(SharedResource.IsVip) .SetWidth(70) .Css("hidden-xs") //hide on phones .RenderValueAs(o => o.Customer.IsVip ? Strings.BoolTrueLabel : Strings.BoolFalseLabel); }; var server = new GridServer <Order>(_orderRepository.GetAll(), query, false, "ordersGrid", columns, 10, locale) .SetRowCssClasses(item => item.Customer.IsVip ? "success" : string.Empty) .Sortable() .Filterable() .WithMultipleFilters() .Searchable(true, false) .Groupable(true) .ClearFiltersButton(true) .Selectable(true) .SetStriped(true) .ChangePageSize(true) .WithGridItemsCount(); return(View(server.Grid)); }
/// <summary> /// Make an identifier from an external module name by extracting the string after the last "/" and replacing /// all non-alphanumeric characters with underscores /// </summary> public static string MakeIdentifierFromModuleName(string moduleName) { return(StringExtensions.Replace(StringExtensions.Replace(Path.GetBaseFileName(moduleName), "^(\\d)", "_$1"), "\\W", "_")); }
/// <summary> /// Extracts the mod from the archive. The caller should handle exception that may be thrown. /// </summary> /// <param name="archivePath"></param> /// <param name="outputFolderPath"></param> /// <param name="compressPackages"></param> /// <param name="updateTextCallback"></param> /// <param name="extractingCallback"></param> /// <param name="compressedPackageCallback"></param> /// <param name="testRun"></param> public void ExtractFromArchive(string archivePath, string outputFolderPath, bool compressPackages, Action <string> updateTextCallback = null, Action <DetailedProgressEventArgs> extractingCallback = null, Action <string, int, int> compressedPackageCallback = null, bool testRun = false, Stream archiveStream = null) { if (!IsInArchive) { throw new Exception(@"Cannot extract a mod that is not part of an archive."); } if (archiveStream == null && !File.Exists(archivePath)) { throw new Exception(M3L.GetString(M3L.string_interp_theArchiveFileArchivePathIsNoLongerAvailable, archivePath)); } compressPackages &= Game >= MEGame.ME2; SevenZipExtractor archive; var isExe = archivePath.EndsWith(@".exe", StringComparison.InvariantCultureIgnoreCase); bool closeStreamOnFinish = true; if (archiveStream != null) { archive = isExe ? new SevenZipExtractor(archiveStream, InArchiveFormat.Nsis) : new SevenZipExtractor(archiveStream); closeStreamOnFinish = false; } else { archive = isExe ? new SevenZipExtractor(archivePath, InArchiveFormat.Nsis) : new SevenZipExtractor(archivePath); } var fileIndicesToExtract = new List <int>(); var filePathsToExtractTESTONLY = new List <string>(); var referencedFiles = GetAllRelativeReferences(!IsVirtualized, archive); if (isExe) { //remap to mod root. Not entirely sure if this needs to be done for sub mods? referencedFiles = Enumerable.Select <string, string>(referencedFiles, x => FilesystemInterposer.PathCombine(IsInArchive, ModPath, x)).ToList(); //remap to in-archive paths so they match entry paths } foreach (var info in archive.ArchiveFileData) { if (!info.IsDirectory && (ModPath == "" || info.FileName.Contains((string)ModPath))) { var relativedName = isExe ? info.FileName : info.FileName.Substring(ModPath.Length).TrimStart('\\'); if (referencedFiles.Contains(relativedName)) { Log.Information(@"Adding file to extraction list: " + info.FileName); fileIndicesToExtract.Add(info.Index); filePathsToExtractTESTONLY.Add(relativedName); } } } void archiveExtractionProgress(object?sender, DetailedProgressEventArgs args) { extractingCallback?.Invoke(args); } archive.Progressing += archiveExtractionProgress; string outputFilePathMapping(ArchiveFileInfo entryInfo) { Log.Information(@"Mapping extraction target for " + entryInfo.FileName); string entryPath = entryInfo.FileName; if (ExeExtractionTransform != null && Enumerable.Any <(int index, string outfile)>(ExeExtractionTransform.PatchRedirects, x => x.index == entryInfo.Index)) { Log.Information(@"Extracting vpatch file at index " + entryInfo.Index); return(Path.Combine(Utilities.GetVPatchRedirectsFolder(), Enumerable.First <(int index, string outfile)>(ExeExtractionTransform.PatchRedirects, x => x.index == entryInfo.Index).outfile)); } if (ExeExtractionTransform != null && Enumerable.Any <int>(ExeExtractionTransform.NoExtractIndexes, x => x == entryInfo.Index)) { Log.Information(@"Extracting file to trash (not used): " + entryPath); return(Path.Combine(Utilities.GetTempPath(), @"Trash", @"trashfile")); } if (ExeExtractionTransform != null && Enumerable.Any <(int index, string outfile)>(ExeExtractionTransform.AlternateRedirects, x => x.index == entryInfo.Index)) { var outfile = Enumerable.First <(int index, string outfile)>(ExeExtractionTransform.AlternateRedirects, x => x.index == entryInfo.Index).outfile; Log.Information($@"Extracting file with redirection: {entryPath} -> {outfile}"); return(Path.Combine(outputFolderPath, outfile)); } //Archive path might start with a \. Substring may return value that start with a \ var subModPath = entryPath /*.TrimStart('\\')*/.Substring(ModPath.Length).TrimStart('\\'); var path = Path.Combine(outputFolderPath, subModPath); //Debug.WriteLine("remapping output: " + entryPath + " -> " + path); return(path); } if (compressPackages) { compressionQueue = new BlockingCollection <string>(); } int numberOfPackagesToCompress = Enumerable.Count <string>(referencedFiles, x => StringExtensions.RepresentsPackageFilePath(x)); int compressedPackageCount = 0; NamedBackgroundWorker compressionThread; if (compressPackages) { compressionThread = new NamedBackgroundWorker(@"ImportingCompressionThread"); compressionThread.DoWork += (a, b) => { try { while (true) { var package = compressionQueue.Take(); var p = MEPackageHandler.OpenMEPackage(package); bool shouldNotCompress = Game == MEGame.ME1; if (!shouldNotCompress) { //updateTextCallback?.Invoke(M3L.GetString(M3L.string_interp_compressingX, Path.GetFileName(package))); FileInfo fileInfo = new FileInfo(package); var created = fileInfo.CreationTime; //File Creation var lastmodified = fileInfo.LastWriteTime; //File Modification compressedPackageCallback?.Invoke(M3L.GetString(M3L.string_interp_compressingX, Path.GetFileName(package)), compressedPackageCount, numberOfPackagesToCompress); Log.Information(@"Compressing package: " + package); p.Save(compress: true); File.SetCreationTime(package, created); File.SetLastWriteTime(package, lastmodified); } else { Log.Information(@"Skipping compression for ME1 package file: " + package); } Interlocked.Increment(ref compressedPackageCount); compressedPackageCallback?.Invoke(M3L.GetString(M3L.string_interp_compressedX, Path.GetFileName(package)), compressedPackageCount, numberOfPackagesToCompress); } } catch (InvalidOperationException) { //Done. lock (compressionCompletedSignaler) { Monitor.Pulse(compressionCompletedSignaler); } } }; compressionThread.RunWorkerAsync(); } void compressPackage(object?sender, FileInfoEventArgs args) { if (compressPackages) { var fToCompress = outputFilePathMapping(args.FileInfo); if (fToCompress.RepresentsPackageFilePath()) { //Debug.WriteLine("Adding to blocking queue"); compressionQueue.TryAdd(fToCompress); } } } archive.FileExtractionFinished += compressPackage; if (!testRun) { Log.Information(@"Extracting files..."); archive.ExtractFiles(outputFolderPath, outputFilePathMapping, fileIndicesToExtract.ToArray()); } else { // test run mode // exes can have duplicate filenames but different indexes so we must check for those here. if (fileIndicesToExtract.Count != referencedFiles.Count && filePathsToExtractTESTONLY.Distinct().ToList().Count != referencedFiles.Count) { throw new Exception(@"The amount of referenced files does not match the amount of files that are going to be extracted!"); } } Log.Information(@"File extraction completed."); archive.Progressing -= archiveExtractionProgress; compressionQueue?.CompleteAdding(); if (compressPackages && numberOfPackagesToCompress > 0 && numberOfPackagesToCompress > compressedPackageCount) { Log.Information(@"Waiting for compression of packages to complete."); while (!compressionQueue.IsCompleted) { lock (compressionCompletedSignaler) { Monitor.Wait(compressionCompletedSignaler); } } Log.Information(@"Package compression has completed."); } archive.FileExtractionFinished -= compressPackage; ModPath = outputFolderPath; if (IsVirtualized) { var parser = new IniDataParser().Parse(VirtualizedIniText); parser[@"ModInfo"][@"modver"] = ModVersionString; //In event relay service resolved this if (!testRun) { File.WriteAllText(Path.Combine(ModPath, @"moddesc.ini"), parser.ToString()); } IsVirtualized = false; //no longer virtualized } if (ExeExtractionTransform != null) { if (EnumerableExtensions.Any <ModArchiveImporter.ExeTransform.VPatchDirective>(ExeExtractionTransform.VPatches)) { // MEHEM uses Vpatching for its alternates. var vpat = Utilities.GetCachedExecutablePath(@"vpat.exe"); if (!testRun) { Utilities.ExtractInternalFile(@"MassEffectModManagerCore.modmanager.executables.vpat.exe", vpat, true); } //Handle VPatching foreach (var transform in ExeExtractionTransform.VPatches) { var patchfile = Path.Combine(Utilities.GetVPatchRedirectsFolder(), transform.patchfile); var inputfile = Path.Combine(ModPath, transform.inputfile); var outputfile = Path.Combine(ModPath, transform.outputfile); var args = $"\"{patchfile}\" \"{inputfile}\" \"{outputfile}\""; //do not localize if (!testRun) { Directory.CreateDirectory(Directory.GetParent(outputfile).FullName); //ensure output directory exists as vpatch will not make one. } Log.Information($@"VPatching file into alternate: {inputfile} to {outputfile}"); updateTextCallback?.Invoke(M3L.GetString(M3L.string_interp_vPatchingIntoAlternate, Path.GetFileName(inputfile))); if (!testRun) { Utilities.RunProcess(vpat, args, true, false, false, true); } } } //Handle copyfile foreach (var copyfile in ExeExtractionTransform.CopyFiles) { string srcfile = Path.Combine(ModPath, copyfile.inputfile); string destfile = Path.Combine(ModPath, copyfile.outputfile); Log.Information($@"Applying transform copyfile: {srcfile} -> {destfile}"); if (!testRun) { File.Copy(srcfile, destfile, true); } } if (ExeExtractionTransform.PostTransformModdesc != null) { //fetch online moddesc for this mod. Log.Information(@"Fetching post-transform third party moddesc."); var moddesc = OnlineContent.FetchThirdPartyModdesc(ExeExtractionTransform.PostTransformModdesc); if (!testRun) { File.WriteAllText(Path.Combine(ModPath, @"moddesc.ini"), moddesc); } } } //int packagesCompressed = 0; //if (compressPackages) //{ // var packages = Utilities.GetPackagesInDirectory(ModPath, true); // extractingCallback?.Invoke(new ProgressEventArgs((byte)(packagesCompressed * 100.0 / packages.Count), 0)); // foreach (var package in packages) // { // updateTextCallback?.Invoke(M3L.GetString(M3L.string_interp_compressingX, Path.GetFileName(package))); // Log.Information("Compressing package: " + package); // var p = MEPackageHandler.OpenMEPackage(package); // p.save(true); // packagesCompressed++; // extractingCallback?.Invoke(new ProgressEventArgs((byte)(packagesCompressed * 100.0 / packages.Count), 0)); // } //} if (closeStreamOnFinish) { archive?.Dispose(); } else { archive?.DisposeObjectOnly(); } }
private static void ProcessTrace(Trace trace, MutableObject traceMutable, bool memTrace = false) { //trace.GenerateCallGraph(); //Dictionary< int, FlaggedAnnotation > foundAnnotations = new Dictionary< int, FlaggedAnnotation >(); // foreach ( var annotationElement in trace.Annotations ) // { // foundAnnotations.Add( (int)annotationElement.Header.InstructionCount, new FlaggedAnnotation { Flagged = false, Annotation = annotationElement } ); // } Dictionary <int, MutableObject> instructionMutables = new Dictionary <int, MutableObject>(); Dictionary <int, string> comms = new Dictionary <int, string>(); int instructionCount = 0; foreach (var element in trace.Elements) { if (instructionMutables.ContainsKey(element.Header.InstructionCount)) { continue; } var newInstruction = CreateInstructionMutable(element, instructionCount); instructionMutables.Add(element.Header.InstructionCount, newInstruction); instructionCount++; } int lateAddedAnnotationCount = 0; // Add any annotations that were not interleaved in the trace (announcer additions; crashes...) foreach (var annotation in trace.Annotations) //foundAnnotations.Where( p => p.Value.Flagged == false ) ) { //instructionMutables.FirstOrDefault( i => (int)i["Original Index"] == (int)pair.Key ); MutableObject foundInstructionMutable; if (!instructionMutables.ContainsKey(annotation.Header.InstructionCount)) { var lastElement = trace.Elements.Last(); var newHeader = new TraceElementHeader( lastElement.Header.RawTypeIndex, lastElement.Header.Length, lastElement.Header.WallTime, lastElement.Header.InstructionCount + 1 + lateAddedAnnotationCount++); var newElement = new InstructionOnlyElement(newHeader) { Eip = lastElement.Eip }; foundInstructionMutable = CreateInstructionMutable(newElement, instructionCount++); //foundInstructionMutable[ "Annotated" ] = true; instructionMutables.Add(newHeader.InstructionCount, foundInstructionMutable); } else { foundInstructionMutable = instructionMutables[annotation.Header.InstructionCount]; } SetAnnotationOnInstructionMutable(foundInstructionMutable, annotation, comms); } traceMutable.Add("Instructions", instructionMutables.Values); traceMutable.Add("InstructionCount", instructionMutables.Count); if (memTrace) { var memReads = new List <MutableObject>(); foreach (var memRead in trace.MemoryReads) { var newRead = new MutableObject() { { "Read Address", (uint)memRead.Addr }, { "Read Hex", StringExtensions.ByteArrayToString(memRead.BytesRead) }, { "Read Size", memRead.NumberOfBytesRead }, { "Original Index", memRead.Header.InstructionCount } }; // match original index to get processed index if (instructionMutables.ContainsKey(memRead.Header.InstructionCount)) { newRead["Processed Index"] = instructionMutables[memRead.Header.InstructionCount]["Processed Index"]; } else { newRead["Processed Index"] = 0; } memReads.Add(newRead); } traceMutable.Add("Memory Reads", memReads); var memWrites = new List <MutableObject>(); foreach (var memWrite in trace.MemoryWrites) { var newWrite = new MutableObject() { { "Write Address", (uint)memWrite.Addr }, { "Write Hex", StringExtensions.ByteArrayToString(memWrite.BytesWritten) }, { "Write Size", memWrite.NumberOfBytesWritten }, { "Original Index", memWrite.Header.InstructionCount } //memWrite.Header.InstructionCount } }; // match original index to get processed index if (instructionMutables.ContainsKey(memWrite.Header.InstructionCount)) { newWrite["Processed Index"] = instructionMutables[memWrite.Header.InstructionCount]["Processed Index"]; } else { newWrite["Processed Index"] = 0; } memWrites.Add(newWrite); } ; traceMutable.Add("Memory Writes", memWrites); } var sb = new StringBuilder("Comms:\n"); foreach (var c in comms) { sb.AppendLine(string.Format("{0:D5} {1}", c.Key, c.Value)); } //Debug.Log( sb.ToString() ); }
internal override int Execute(IServiceProvider serviceProvider, IConsole console) { var logger = serviceProvider.GetRequiredService <ILogger <ExecCommand> >(); var env = serviceProvider.GetRequiredService <IEnvironment>(); var generator = serviceProvider.GetRequiredService <IBuildScriptGenerator>(); var opts = serviceProvider.GetRequiredService <IOptions <BuildScriptGeneratorOptions> >().Value; if (string.IsNullOrWhiteSpace(Command)) { logger.LogDebug("Command is empty; exiting"); return(ProcessConstants.ExitSuccess); } var shellPath = env.GetEnvironmentVariable("BASH") ?? FilePaths.Bash; logger.LogInformation("Using shell {shell}", shellPath); var ctx = BuildScriptGenerator.CreateContext(serviceProvider, operationId: null); ctx.DisableMultiPlatformBuild = false; var tools = generator.GetRequiredToolVersions(ctx); int exitCode; using (var timedEvent = logger.LogTimedEvent("ExecCommand")) { // Build envelope script var scriptBuilder = new ShellScriptBuilder("\n") .AddShebang(shellPath) .AddCommand("set -e"); if (tools.Count > 0) { scriptBuilder.Source($"{FilePaths.Benv} {StringExtensions.JoinKeyValuePairs(tools)}"); } var script = scriptBuilder.AddCommand(Command).ToString(); logger.LogDebug("Script content:\n{script}", script); // Create temporary file to store script var tempScriptPath = Path.GetTempFileName(); File.WriteAllText(tempScriptPath, script); timedEvent.AddProperty(nameof(tempScriptPath), tempScriptPath); if (DebugMode) { console.WriteLine($"Temporary script @ {tempScriptPath}:"); console.WriteLine("---"); console.WriteLine(script); console.WriteLine("---"); } exitCode = ProcessHelper.RunProcess( shellPath, new[] { tempScriptPath }, opts.SourceDir, (sender, args) => { if (args.Data != null) { console.WriteLine(args.Data); } }, (sender, args) => { if (args.Data != null) { console.Error.WriteLine(args.Data); } }, waitTimeForExit: null); timedEvent.AddProperty("exitCode", exitCode.ToString()); } return(exitCode); }
public override GameMetadata GetMetadata(Game game) { var resources = library.PlayniteApi.Resources; var storeMetadata = DownloadGameMetadata(game.GameId); var gameInfo = new GameInfo { Name = StringExtensions.NormalizeGameName(storeMetadata.StoreDetails.i18n.displayName), Description = storeMetadata.StoreDetails.i18n.longDescription, ReleaseDate = storeMetadata.StoreDetails.platforms.First(a => a.platform == "PCWIN").releaseDate, Links = new List <Link>() { new Link(resources.GetString("LOCCommonLinksStorePage"), @"https://www.origin.com/store" + storeMetadata.StoreDetails.offerPath), new Link("PCGamingWiki", @"http://pcgamingwiki.com/w/index.php?search=" + game.Name) } }; if (!storeMetadata.StoreDetails.publisherFacetKey.IsNullOrEmpty()) { gameInfo.Publishers = new List <string>() { storeMetadata.StoreDetails.publisherFacetKey }; } if (!storeMetadata.StoreDetails.developerFacetKey.IsNullOrEmpty()) { gameInfo.Developers = new List <string>() { storeMetadata.StoreDetails.developerFacetKey }; } if (!storeMetadata.StoreDetails.genreFacetKey.IsNullOrEmpty()) { gameInfo.Genres = new List <string>(storeMetadata.StoreDetails.genreFacetKey?.Split(',')); } var metadata = new GameMetadata() { GameInfo = gameInfo, Icon = storeMetadata.Icon, CoverImage = storeMetadata.CoverImage, BackgroundImage = storeMetadata.BackgroundImage }; if (!string.IsNullOrEmpty(storeMetadata.StoreDetails.i18n.gameForumURL)) { gameInfo.Links.Add(new Link(resources.GetString("LOCCommonLinksForum"), storeMetadata.StoreDetails.i18n.gameForumURL)); } if (!string.IsNullOrEmpty(storeMetadata.StoreDetails.i18n.gameManualURL)) { game.OtherActions = new ObservableCollection <GameAction>() { new GameAction() { IsHandledByPlugin = false, Type = GameActionType.URL, Path = storeMetadata.StoreDetails.i18n.gameManualURL, Name = "Manual" } }; } // There's not icon available on Origin servers so we will load one from EXE if (game.IsInstalled && string.IsNullOrEmpty(game.Icon)) { var playAction = library.PlayniteApi.ExpandGameVariables(game, game.PlayAction); var executable = string.Empty; if (File.Exists(playAction.Path)) { executable = playAction.Path; } else if (!string.IsNullOrEmpty(playAction.WorkingDir)) { executable = Path.Combine(playAction.WorkingDir, playAction.Path); } if (string.IsNullOrEmpty(executable)) { return(storeMetadata); } using (var ms = new MemoryStream()) { if (IconExtractor.ExtractMainIconFromFile(executable, ms)) { var iconName = Guid.NewGuid() + ".ico"; metadata.Icon = new MetadataFile(iconName, ms.ToArray()); } } } return(metadata); }
public void LevenshteinDistance_Should_Throw_When_Input_Is_Null() { Assert.Throws <ArgumentNullException>(() => StringExtensions.LevenshteinDistance(null, "")); }
public Dictionary <string, GameInfo> GetInstalledGames(bool useDataCache = false) { var contentPath = Path.Combine(Origin.DataPath, "LocalContent"); var games = new Dictionary <string, GameInfo>(); if (Directory.Exists(contentPath)) { var packages = Directory.GetFiles(contentPath, "*.mfst", SearchOption.AllDirectories); foreach (var package in packages) { try { var gameId = Path.GetFileNameWithoutExtension(package); if (!gameId.StartsWith("Origin")) { // Get game id by fixing file via adding : before integer part of the name // for example OFB-EAST52017 converts to OFB-EAST:52017 var match = Regex.Match(gameId, @"^(.*?)(\d+)$"); if (!match.Success) { logger.Warn("Failed to get game id from file " + package); continue; } gameId = match.Groups[1].Value + ":" + match.Groups[2].Value; } var newGame = new GameInfo() { Source = "Origin", GameId = gameId, IsInstalled = true }; GameLocalDataResponse localData = null; try { localData = GetLocalManifest(gameId, package, useDataCache); } catch (Exception e) when(!Environment.IsDebugBuild) { logger.Error(e, $"Failed to get Origin manifest for a {gameId}, {package}"); continue; } if (localData.offerType != "Base Game" && localData.offerType != "DEMO") { continue; } newGame.Name = StringExtensions.NormalizeGameName(localData.localizableAttributes.displayName); var platform = localData.publishing.softwareList.software.FirstOrDefault(a => a.softwarePlatform == "PCWIN"); if (platform == null) { logger.Warn(gameId + " game doesn't have windows platform, skipping install import."); continue; } var installPath = GetPathFromPlatformPath(platform.fulfillmentAttributes.installCheckOverride); if (string.IsNullOrEmpty(installPath) || !File.Exists(installPath)) { continue; } newGame.PlayAction = GetGamePlayTask(localData); if (newGame.PlayAction?.Type == GameActionType.File) { newGame.InstallDirectory = newGame.PlayAction.WorkingDir; newGame.PlayAction.WorkingDir = newGame.PlayAction.WorkingDir.Replace(newGame.InstallDirectory, ExpandableVariables.InstallationDirectory); newGame.PlayAction.Path = newGame.PlayAction.Path.Replace(newGame.InstallDirectory, "").Trim(new char[] { '\\', '/' }); } else { newGame.InstallDirectory = Path.GetDirectoryName(installPath); } // If game uses EasyAntiCheat then use executable referenced by it if (Origin.GetGameUsesEasyAntiCheat(newGame.InstallDirectory)) { var eac = EasyAntiCheat.GetLauncherSettings(newGame.InstallDirectory); if (newGame.PlayAction == null) { newGame.PlayAction = new GameAction { Type = GameActionType.File }; } newGame.PlayAction.Path = eac.Executable; if (!string.IsNullOrEmpty(eac.Parameters) && eac.UseCmdlineParameters == "1") { newGame.PlayAction.Arguments = eac.Parameters; } if (!string.IsNullOrEmpty(eac.WorkingDirectory)) { newGame.PlayAction.WorkingDir = Path.Combine(ExpandableVariables.InstallationDirectory, eac.WorkingDirectory); } else { newGame.PlayAction.WorkingDir = ExpandableVariables.InstallationDirectory; } } games.Add(newGame.GameId, newGame); } catch (Exception e) when(!Environment.IsDebugBuild) { logger.Error(e, $"Failed to import installed Origin game {package}."); } } } return(games); }
internal static string AsyncAwaiterFieldName(int slotIndex) { Debug.Assert((char)GeneratedNameKind.AwaiterField == 'u'); return("<>u__" + StringExtensions.GetNumeral(slotIndex + 1)); }
private void Map(XContainer root, object obj) { Type type1 = obj.GetType(); IEnumerable <PropertyInfo> enumerable = Enumerable.Select(Enumerable.OrderBy(Enumerable.Where(Enumerable.Select((IEnumerable <PropertyInfo>)type1.GetProperties(), p => new { p = p, indexAttribute = ReflectionExtensions.GetAttribute <SerializeAsAttribute>((MemberInfo)p) }), param0 => { if (param0.p.CanRead) { return(param0.p.CanWrite); } return(false); }), param0 => { if (param0.indexAttribute != null) { return(param0.indexAttribute.Index); } return(int.MaxValue); }), param0 => param0.p); SerializeAsAttribute attribute1 = ReflectionExtensions.GetAttribute <SerializeAsAttribute>(type1); foreach (PropertyInfo propertyInfo in enumerable) { string str = propertyInfo.Name; object obj1 = propertyInfo.GetValue(obj, (object[])null); if (obj1 != null) { string serializedValue = this.GetSerializedValue(obj1); Type propertyType = propertyInfo.PropertyType; bool flag = false; SerializeAsAttribute attribute2 = ReflectionExtensions.GetAttribute <SerializeAsAttribute>((MemberInfo)propertyInfo); if (attribute2 != null) { str = StringExtensions.HasValue(attribute2.Name) ? attribute2.Name : str; flag = attribute2.Attribute; } SerializeAsAttribute attribute3 = ReflectionExtensions.GetAttribute <SerializeAsAttribute>((MemberInfo)propertyInfo); if (attribute3 != null) { str = attribute3.TransformName(str); } else if (attribute1 != null) { str = attribute1.TransformName(str); } XElement xelement1 = new XElement(XmlExtensions.AsNamespaced(str, this.Namespace)); if (propertyType.IsPrimitive || propertyType.IsValueType || propertyType == typeof(string)) { if (flag) { root.Add((object)new XAttribute((XName)str, (object)serializedValue)); continue; } xelement1.Value = serializedValue; } else if (obj1 is IList) { string name = ""; foreach (object obj2 in (IEnumerable)obj1) { if (name == "") { Type type2 = obj2.GetType(); SerializeAsAttribute attribute4 = ReflectionExtensions.GetAttribute <SerializeAsAttribute>(type2); name = attribute4 == null || !StringExtensions.HasValue(attribute4.Name) ? type2.Name : attribute4.Name; } XElement xelement2 = new XElement(XmlExtensions.AsNamespaced(name, this.Namespace)); this.Map((XContainer)xelement2, obj2); xelement1.Add((object)xelement2); } } else { this.Map((XContainer)xelement1, obj1); } root.Add((object)xelement1); } } }
internal static string MakeLambdaDisplayLocalName(int uniqueId) { Debug.Assert((char)GeneratedNameKind.DisplayClassLocalOrField == '8'); return(SynthesizedLocalNamePrefix + "<>8__locals" + StringExtensions.GetNumeral(uniqueId)); }
ObjectCreateExpression ConvertXmlElementExpression(XmlElementExpression xmlElementExpression) { var newNode = new ObjectCreateExpression(new TypeReference("XElement"), xmlElementExpression.NameIsExpression ? new List <Expression> { xmlElementExpression.NameExpression } : Expressions(xmlElementExpression.XmlName)); foreach (XmlExpression attr in xmlElementExpression.Attributes) { if (attr is XmlAttributeExpression) { var a = attr as XmlAttributeExpression; newNode.Parameters.Add(new ObjectCreateExpression(new TypeReference("XAttribute"), new List <Expression> { new PrimitiveExpression(a.Name), a.IsLiteralValue ? new PrimitiveExpression(ConvertEntities(a.LiteralValue)) : a.ExpressionValue })); } else if (attr is XmlEmbeddedExpression) { newNode.Parameters.Add((attr as XmlEmbeddedExpression).InlineVBExpression); } } foreach (XmlExpression expr in xmlElementExpression.Children) { XmlContentExpression c = expr as XmlContentExpression; // skip whitespace text if (!(expr is XmlContentExpression && c.Type == XmlContentType.Text && StringExtensions.IsNullOrWhiteSpace(c.Content))) { newNode.Parameters.Add(ConvertXmlExpression(expr)); } } return(newNode); }
internal static string ReusableHoistedLocalFieldName(int number) { Debug.Assert((char)GeneratedNameKind.ReusableHoistedLocalField == '7'); return("<>7__wrap" + StringExtensions.GetNumeral(number)); }
/// <summary> /// Returns the xml rss string /// </summary> /// <returns></returns> public string GetSearchRssXml() { Item currentItem = Sitecore.Context.Item; I_Base_Rss_Feed rssFeedItem = currentItem.GlassCast <I_Base_Rss_Feed>(inferType: false); SyndicationFeed feed = null; Stopwatch sw = Stopwatch.StartNew(); var feedGenerator = _RssFeedGeneration; StringExtensions.WriteSitecoreLogs("Time taken to Create Feedgenerator", sw, "feedGenerator"); if (feedGenerator == null) { Log.Error("Could Not Create RSS Feed Geneartor " + rssFeedItem.Rss_Feed_Generation, this); return(string.Empty); } sw = Stopwatch.StartNew(); feed = feedGenerator.GetRssFeed(rssFeedItem, _sitecoreContext, _itemReferences); StringExtensions.WriteSitecoreLogs("Time taken to Create GetRssFeed", sw, "GetRssFeed"); if (feed == null) { Log.Error("Could Not Create RSS Feed With " + rssFeedItem.Rss_Feed_Generation, this); return(string.Empty); } var formatter = new Rss20FeedFormatter(feed); formatter.SerializeExtensionsAsAtom = false; sw = Stopwatch.StartNew(); var itemRetriever = _RssSitecoreItemRetrieval; StringExtensions.WriteSitecoreLogs("Time taken to Create itemRetriever", sw, "itemRetriever"); if (itemRetriever == null) { Log.Error("Could Not Create Item Retriever With " + rssFeedItem.Sitecore_Item_Retrieval, this); return(string.Empty); } var rssItemGenerator = _RssItemGeneration; if (rssItemGenerator == null) { Log.Error("Could Not Create Item Generator With " + rssFeedItem.Rss_Item_Generation, this); return(string.Empty); } sw = Stopwatch.StartNew(); var sitecoreItems = itemRetriever.GetSitecoreItems(currentItem); StringExtensions.WriteSitecoreLogs("Time taken to Create sitecoreItems", sw, "GetSitecoreItems"); List <SyndicationItem> syndicationItems = new List <SyndicationItem>(); foreach (Item sitecoreItem in sitecoreItems) { var syndicationItem = rssItemGenerator.GetSyndicationItemFromSitecore(_sitecoreContext, sitecoreItem); if (syndicationItem == null) { continue; } syndicationItems.Add(syndicationItem); } feed.Items = syndicationItems; var output = new StringBuilder(); using (var writer = XmlWriter.Create(output, new XmlWriterSettings { Indent = true })) { feed.SaveAsRss20(writer); writer.Flush(); writer.Close(); string rs = output.ToString().Replace("utf-16", "utf-8"); rs = RemoveInvalidXmlChars(rs); return(rs); } }
public void Test_StringExtensions_PtrToStringUtf8_NullPtr() { string result = StringExtensions.PtrToStringUtf8(IntPtr.Zero); Assert.AreEqual(String.Empty, result, "Failed to marshal nullptr to .NET empty string"); }
public void StringFormattedWithMatchingPropertyIsUpdatedWithReplacedValue() { var result = new StringExtensions("A string with a {MatchingProperty}").Format(new { MatchingProperty = "replaced value" }); Assert.That(result, Is.EqualTo("A string with a replaced value")); }