void SetupGridView(GridListEditorBase columnViewEditor) { var gridView = columnViewEditor.GridView as XpandGridView; if ((gridView != null) && (columnViewEditor.DataSource != null)) { gridView.OptionsView.ShowIndicator = false; var errorMessages = new ErrorMessages(); foreach (object obj in ListHelper.GetList(columnViewEditor.DataSource)) { errorMessages.AddMessage("ErrorMessage", obj, CaptionHelper.GetLocalizedText("Messages", "ValidationErrorMessage")); } gridView.ErrorMessages = errorMessages; } }
public static string GetErrorMessage(ErrorMessages errorMessage) { switch (errorMessage) { case ErrorMessages.EnterCorrectDate: return "ERROR! Enter A Correctly Formatted Date"; case ErrorMessages.ExitIsBeforeEntry: return "ERROR! Your Exit Date Or Time Is Before Your Entry Date or Time"; } // required to compile return ""; }
public ActionResult Login(string username, string password) { if (!_session.IsAuthenticated) { LoginAttemptResult loginAttemptResult = _userAuthenticationService.Authenticate(new Username(username), new Password(password)); if (!loginAttemptResult.Succeeded) { var errorMessages = new ErrorMessages {GetLoginFailureMessage(loginAttemptResult)}; TempData.ErrorMessages.Store(errorMessages); TempData.LoginReturnPage.Keep(); return RedirectToRoute(_siteMap.LoginPage); } _session.BeginAuthenticatedSession(loginAttemptResult.Account); } return RedirectToRoute(TempData.LoginReturnPage.Get() ?? _siteMap.GetLandingPage(_session.AuthenticatedAccount)); }
protected override void OnExit(ExitEventArgs e) { var messages = new ErrorMessages(); if (Globals.CurrentExceptionsCollection.Count > 0) { messages.AddRange( Globals.CurrentExceptionsCollection.Select(exception => new ErrorMessage (exception, Assembly.GetExecutingAssembly()) { CurrentUser = Globals.MainUser.UserName, UsesWebservice = Globals.MainUser.WebserviceUsed })); messages.WriteExceptions2File(null, true); } base.OnExit(e); Component.Dispose(); }
public override async Task <PublicTradesResponse> GetPublicTrades(PublicTradesRequest request, ServerCallContext context) { var result = new PublicTradesResponse(); if (string.IsNullOrEmpty(request.AssetPairId)) { result.Error = new ErrorResponseBody { Code = ErrorCode.InvalidField, Message = ErrorMessages.CantBeEmpty(nameof(request.AssetPairId)) }; result.Error.Fields.Add(nameof(request.AssetPairId), result.Error.Message); return(result); } var response = await _tradesAdapterClient.GetTradesByAssetPairIdAsync(request.AssetPairId, request.Skip, request.Take); if (response.Records != null) { result.Body = new PublicTradesResponse.Types.Body(); result.Body.Result.AddRange(_mapper.Map <List <PublicTrade> >(response.Records)); } if (response.Error != null) { result.Error = new ErrorResponseBody { Code = ErrorCode.Runtime, Message = response.Error.Message }; } return(result); }
public long GetAttributeLongValue(SourceLineNumber sourceLineNumbers, XAttribute attribute, long minimum, long maximum) { Debug.Assert(minimum > CompilerConstants.LongNotSet && minimum > CompilerConstants.IllegalLong, "The legal values for this attribute collide with at least one sentinel used during parsing."); var value = this.GetAttributeValue(sourceLineNumbers, attribute); if (0 < value.Length) { try { var longValue = Convert.ToInt64(value, CultureInfo.InvariantCulture.NumberFormat); if (CompilerConstants.LongNotSet == longValue || CompilerConstants.IllegalLong == longValue) { this.Messaging.Write(ErrorMessages.IntegralValueSentinelCollision(sourceLineNumbers, longValue)); } else if (minimum > longValue || maximum < longValue) { this.Messaging.Write(ErrorMessages.IntegralValueOutOfRange(sourceLineNumbers, attribute.Parent.Name.LocalName, attribute.Name.LocalName, longValue, minimum, maximum)); longValue = CompilerConstants.IllegalLong; } return(longValue); } catch (FormatException) { this.Messaging.Write(ErrorMessages.IllegalLongValue(sourceLineNumbers, attribute.Parent.Name.LocalName, attribute.Name.LocalName, value)); } catch (OverflowException) { this.Messaging.Write(ErrorMessages.IllegalLongValue(sourceLineNumbers, attribute.Parent.Name.LocalName, attribute.Name.LocalName, value)); } } return(CompilerConstants.IllegalLong); }
/// <summary> /// Checks for a valid Windows PE signature (IMAGE_NT_SIGNATURE) in the current exe. /// </summary> /// <returns>true if the exe is a Windows executable; false otherwise</returns> private bool EnsureNTHeader(BinaryReader reader) { if (UInt32.MaxValue == this.firstSectionOffset) { if (!this.EnsureDosHeader(reader)) { return(false); } reader.BaseStream.Seek(this.peOffset, SeekOrigin.Begin); byte[] bytes = reader.ReadBytes((int)IMAGE_NT_HEADER_SIZE); // Verify the NT signature... if (IMAGE_NT_SIGNATURE != BurnCommon.ReadUInt32(bytes, IMAGE_NT_HEADER_OFFSET_SIGNATURE)) { this.Messaging.Write(ErrorMessages.InvalidStubExe(this.fileExe)); return(false); } ushort sizeOptionalHeader = BurnCommon.ReadUInt16(bytes, IMAGE_NT_HEADER_OFFSET_SIZEOFOPTIONALHEADER); this.sections = BurnCommon.ReadUInt16(bytes, IMAGE_NT_HEADER_OFFSET_NUMBEROFSECTIONS); this.firstSectionOffset = this.peOffset + IMAGE_NT_HEADER_SIZE + sizeOptionalHeader; this.checksumOffset = this.peOffset + IMAGE_NT_HEADER_SIZE + IMAGE_OPTIONAL_OFFSET_CHECKSUM; this.certificateTableSignatureOffset = this.peOffset + IMAGE_NT_HEADER_SIZE + sizeOptionalHeader - IMAGE_OPTIONAL_NEGATIVE_OFFSET_CERTIFICATETABLE; this.certificateTableSignatureSize = this.certificateTableSignatureOffset + 4; // size is in the DWORD after the offset. bytes = reader.ReadBytes(sizeOptionalHeader); this.Checksum = BurnCommon.ReadUInt32(bytes, IMAGE_OPTIONAL_OFFSET_CHECKSUM); this.SignatureOffset = BurnCommon.ReadUInt32(bytes, sizeOptionalHeader - IMAGE_OPTIONAL_NEGATIVE_OFFSET_CERTIFICATETABLE); this.SignatureSize = BurnCommon.ReadUInt32(bytes, sizeOptionalHeader - IMAGE_OPTIONAL_NEGATIVE_OFFSET_CERTIFICATETABLE + 4); } return(true); }
public async Task WorkerTemplateAsync(string language) { var project = await ProjectFactory.GetOrCreateProject( $"worker-{ language.ToLowerInvariant()[0] }sharp", Output); var createResult = await project.RunDotNetNewAsync("worker", language : language); Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", project, createResult)); var publishResult = await project.RunDotNetPublishAsync(); Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", project, publishResult)); // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build // later, while the opposite is not true. var buildResult = await project.RunDotNetBuildAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", project, buildResult)); using (var aspNetProcess = project.StartBuiltProjectAsync(hasListeningUri: false)) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", project, aspNetProcess.Process)); } using (var aspNetProcess = project.StartPublishedProjectAsync(hasListeningUri: false)) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", project, aspNetProcess.Process)); } }
private bool TryParseBindPath(string bindPath, out IBindPath bp) { var namedPath = bindPath.Split(BindPathSplit, 2); bp = this.ServiceProvider.GetService <IBindPath>(); if (1 == namedPath.Length) { bp.Path = namedPath[0]; } else { bp.Name = namedPath[0]; bp.Path = namedPath[1]; } if (File.Exists(bp.Path)) { this.Messaging.Write(ErrorMessages.ExpectedDirectoryGotFile("-bindpath", bp.Path)); return(false); } return(true); }
public async Task <IEnumerable <IForecastResult> > GetForecasts(IQuery <string, Forecast> currentQuery) { if (currentQuery == null) { throw new ArgumentNullException(ErrorMessages.ArgumentNullMessage(nameof(currentQuery))); } var tasksToExecute = currentQuery.Queries.Select(queryLocation => UrlProvider.SetLocation(queryLocation).GetUriAsString()) .Select(urlToCall => Client.GetForecastAsync(urlToCall)); var results = await Task.WhenAll(tasksToExecute).ConfigureAwait(false); return(results.Where(response => response.Any()) .Select(response => response.Single()) .Select(response => { var tempResult = new ForecastResult(response.City.DisplayName); var Satisfied = response.Forecasts.Where(forecast => currentQuery.IsSatisfiedBy(forecast)); tempResult.AddRange(Satisfied); return tempResult; }). Where(matchedForecast => matchedForecast.ForecastData.Any()) // Filter out, if no match was found .ToList()); }
private void SetDatabaseCodepage(Database db, int codepage, string idtDirectory) { // write out the _ForceCodepage IDT file string idtPath = Path.Combine(idtDirectory, "_ForceCodepage.idt"); using (StreamWriter idtFile = new StreamWriter(idtPath, false, Encoding.ASCII)) { idtFile.WriteLine(); // dummy column name record idtFile.WriteLine(); // dummy column definition record idtFile.Write(codepage); idtFile.WriteLine("\t_ForceCodepage"); } // try to import the table into the MSI try { db.Import(idtPath); } catch (WixInvalidIdtException) { // the IDT should be valid, so an invalid code page was given throw new WixException(ErrorMessages.IllegalCodepage(codepage)); } }
protected void ShowCRUDForm(CRUDAction action, Persistent persistentParent, Persistent persistent) { SetBusy(); if (crudForm == null) { ErrorMessages msgError = new ErrorMessages(); if (!CRUDActionAllowed(action, persistentParent, persistent, msgError)) { MessageBox.Show(msgError.GetAllMessages(), "", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } CreateCRUDForm(); if (crudForm is CRUDChildForm) { (crudForm as CRUDChildForm).Open(action, persistentParent, persistent); } } crudForm.Show(); crudForm.BringToFront(); ClearBusy(); }
/// <summary> /// Validate that there are no duplicate GUIDs in the output. /// </summary> /// <remarks> /// Duplicate GUIDs without conditions are an error condition; with conditions, it's a /// warning, as the conditions might be mutually exclusive. /// </remarks> private void ValidateComponentGuids(Output output) { Table componentTable = output.Tables["Component"]; if (null != componentTable) { Dictionary <string, bool> componentGuidConditions = new Dictionary <string, bool>(componentTable.Rows.Count); foreach (Data.WindowsInstaller.Rows.ComponentRow row in componentTable.Rows) { // we don't care about unmanaged components and if there's a * GUID remaining, // there's already an error that prevented it from being replaced with a real GUID. if (!String.IsNullOrEmpty(row.Guid) && "*" != row.Guid) { bool thisComponentHasCondition = !String.IsNullOrEmpty(row.Condition); bool allComponentsHaveConditions = thisComponentHasCondition; if (componentGuidConditions.ContainsKey(row.Guid)) { allComponentsHaveConditions = componentGuidConditions[row.Guid] && thisComponentHasCondition; if (allComponentsHaveConditions) { this.Messaging.Write(WarningMessages.DuplicateComponentGuidsMustHaveMutuallyExclusiveConditions(row.SourceLineNumbers, row.Component, row.Guid)); } else { this.Messaging.Write(ErrorMessages.DuplicateComponentGuids(row.SourceLineNumbers, row.Component, row.Guid)); } } componentGuidConditions[row.Guid] = allComponentsHaveConditions; } } } }
private void InvalidOption(string option) { ErrorMessages.Add("Invalid option: " + option); }
public async Task RazorPagesTemplate_NoAuth(bool useProgramMain, bool noHttps) { var project = await ProjectFactory.CreateProject(Output); var args = useProgramMain ? noHttps ? new[] { ArgConstants.UseProgramMain, ArgConstants.NoHttps } : new[] { ArgConstants.UseProgramMain } : noHttps ? new[] { ArgConstants.NoHttps } : null; var createResult = await project.RunDotNetNewAsync("razor", args : args); Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("razor", project, createResult)); var expectedLaunchProfileNames = noHttps ? new[] { "http", "IIS Express" } : new[] { "http", "https", "IIS Express" }; await project.VerifyLaunchSettings(expectedLaunchProfileNames); var projectFileContents = ReadFile(project.TemplateOutputDir, $"{project.ProjectName}.csproj"); Assert.DoesNotContain(".db", projectFileContents); Assert.DoesNotContain("Microsoft.EntityFrameworkCore.Tools", projectFileContents); Assert.DoesNotContain("Microsoft.VisualStudio.Web.CodeGeneration.Design", projectFileContents); Assert.DoesNotContain("Microsoft.EntityFrameworkCore.Tools.DotNet", projectFileContents); Assert.DoesNotContain("Microsoft.Extensions.SecretManager.Tools", projectFileContents); var publishResult = await project.RunDotNetPublishAsync(); Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", project, createResult)); // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build // later, while the opposite is not true. var buildResult = await project.RunDotNetBuildAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", project, createResult)); var pages = new List <Page> { new Page { Url = PageUrls.HomeUrl, Links = new [] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.DocsUrl, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.PrivacyUrl, Links = new [] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.PrivacyUrl } } }; using (var aspNetProcess = project.StartBuiltProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } using (var aspNetProcess = project.StartPublishedProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } }
private async Task RazorPagesTemplate_IndividualAuth_Core(bool useLocalDB, bool useProgramMain, bool noHttps) { var project = await ProjectFactory.CreateProject(Output); var args = useProgramMain ? noHttps ? new[] { ArgConstants.UseProgramMain, ArgConstants.NoHttps } : new[] { ArgConstants.UseProgramMain } : noHttps ? new[] { ArgConstants.NoHttps } : null; var createResult = await project.RunDotNetNewAsync("razor", auth : "Individual", useLocalDB : useLocalDB, args : args); Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", project, createResult)); // Individual auth supports no https OK var expectedLaunchProfileNames = noHttps ? new[] { "http", "IIS Express" } : new[] { "http", "https", "IIS Express" }; await project.VerifyLaunchSettings(expectedLaunchProfileNames); var projectFileContents = ReadFile(project.TemplateOutputDir, $"{project.ProjectName}.csproj"); if (!useLocalDB) { Assert.Contains(".db", projectFileContents); } var publishResult = await project.RunDotNetPublishAsync(); Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", project, publishResult)); // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build // later, while the opposite is not true. var buildResult = await project.RunDotNetBuildAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", project, buildResult)); var migrationsResult = await project.RunDotNetEfCreateMigrationAsync("razorpages"); Assert.True(0 == migrationsResult.ExitCode, ErrorMessages.GetFailedProcessMessage("run EF migrations", project, migrationsResult)); project.AssertEmptyMigration("razorpages"); // Note: if any links are updated here, MvcTemplateTest.cs should be updated as well var pages = new List <Page> { new Page { Url = PageUrls.ForgotPassword, Links = new [] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.HomeUrl, Links = new [] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.DocsUrl, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.PrivacyUrl, Links = new [] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.LoginUrl, Links = new [] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.ForgotPassword, PageUrls.RegisterUrl, PageUrls.ResendEmailConfirmation, PageUrls.ExternalArticle, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.RegisterUrl, Links = new [] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.ExternalArticle, PageUrls.PrivacyUrl } } }; using (var aspNetProcess = project.StartBuiltProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } using (var aspNetProcess = project.StartPublishedProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } }
private async Task <MsSqlAppendResult> AppendToStreamExpectedVersion( SqlConnection connection, SqlTransaction transaction, SqlStreamId sqlStreamId, int expectedVersion, NewStreamMessage[] messages, CancellationToken cancellationToken) { var sqlDataRecords = CreateSqlDataRecords(messages); using (var command = new SqlCommand(_scripts.AppendStreamExpectedVersion, connection, transaction)) { command.Parameters.Add(new SqlParameter("streamId", SqlDbType.Char, 42) { Value = sqlStreamId.Id }); command.Parameters.AddWithValue("expectedStreamVersion", expectedVersion); var eventsParam = CreateNewMessagesSqlParameter(sqlDataRecords); command.Parameters.Add(eventsParam); try { using (var reader = await command .ExecuteReaderAsync(cancellationToken) .NotOnCapturedContext()) { await reader.ReadAsync(cancellationToken).NotOnCapturedContext(); var currentVersion = reader.GetInt32(0); var currentPosition = reader.GetInt64(1); int?maxCount = null; await reader.NextResultAsync(cancellationToken); if (await reader.ReadAsync(cancellationToken).NotOnCapturedContext()) { var jsonData = reader.GetString(0); var metadataMessage = SimpleJson.DeserializeObject <MetadataMessage>(jsonData); maxCount = metadataMessage.MaxCount; } return(new MsSqlAppendResult(maxCount, currentVersion, currentPosition)); } } catch (SqlException ex) { if (ex.Errors.Count == 1) { var sqlError = ex.Errors[0]; if (sqlError.Message == "WrongExpectedVersion") { // Idempotency handling. Check if the Messages have already been written. var page = await ReadStreamInternal( sqlStreamId, expectedVersion + 1, // when reading for already written Messages, it's from the one after the expected messages.Length, ReadDirection.Forward, false, null, connection, transaction, cancellationToken); if (messages.Length > page.Messages.Length) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, expectedVersion), ex); } // Iterate all messages an check to see if all message ids match for (int i = 0; i < Math.Min(messages.Length, page.Messages.Length); i++) { if (messages[i].MessageId != page.Messages[i].MessageId) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, expectedVersion), ex); } } return(new MsSqlAppendResult( null, page.LastStreamVersion, page.LastStreamPosition)); } } if (ex.IsUniqueConstraintViolation()) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, expectedVersion), ex); } throw; } } }
private async Task <MsSqlAppendResult> AppendToStreamExpectedVersionNoStream( SqlConnection connection, SqlTransaction transaction, SqlStreamId sqlStreamId, NewStreamMessage[] messages, CancellationToken cancellationToken) { using (var command = new SqlCommand(_scripts.AppendStreamExpectedVersionNoStream, connection, transaction)) { command.Parameters.Add(new SqlParameter("streamId", SqlDbType.Char, 42) { Value = sqlStreamId.Id }); command.Parameters.AddWithValue("streamIdOriginal", sqlStreamId.IdOriginal); if (messages.Length != 0) { var sqlDataRecords = CreateSqlDataRecords(messages); var eventsParam = CreateNewMessagesSqlParameter(sqlDataRecords); command.Parameters.Add(eventsParam); command.Parameters.AddWithValue("hasMessages", true); } else { // Must use a null value for the table-valued param if there are no records var eventsParam = CreateNewMessagesSqlParameter(null); command.Parameters.Add(eventsParam); command.Parameters.AddWithValue("hasMessages", false); } try { using (var reader = await command .ExecuteReaderAsync(cancellationToken) .NotOnCapturedContext()) { await reader.ReadAsync(cancellationToken).NotOnCapturedContext(); var currentVersion = reader.GetInt32(0); var currentPosition = reader.GetInt64(1); int?maxCount = null; if (await reader.ReadAsync(cancellationToken).NotOnCapturedContext()) { var jsonData = reader.GetString(0); var metadataMessage = SimpleJson.DeserializeObject <MetadataMessage>(jsonData); maxCount = metadataMessage.MaxCount; } return(new MsSqlAppendResult(maxCount, currentVersion, currentPosition)); } } catch (SqlException ex) { // Check for unique constraint violation on // https://technet.microsoft.com/en-us/library/aa258747%28v=sql.80%29.aspx if (ex.IsUniqueConstraintViolationOnIndex("IX_Streams_Id")) { // Idempotency handling. Check if the Messages have already been written. var page = await ReadStreamInternal( sqlStreamId, StreamVersion.Start, messages.Length, ReadDirection.Forward, false, null, connection, transaction, cancellationToken) .NotOnCapturedContext(); if (messages.Length > page.Messages.Length) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, ExpectedVersion.NoStream), ex); } for (int i = 0; i < Math.Min(messages.Length, page.Messages.Length); i++) { if (messages[i].MessageId != page.Messages[i].MessageId) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, ExpectedVersion.NoStream), ex); } } return(new MsSqlAppendResult( null, page.LastStreamVersion, page.LastStreamPosition)); } if (ex.IsUniqueConstraintViolation()) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, ExpectedVersion.NoStream), ex); } throw; } } }
private void _timer_Elapsed(object sender, ElapsedEventArgs e) { ErrorMessages.Add($"Error @ {e.SignalTime}"); }
public void Execute() { var mediaSymbols = this.Section.Symbols.OfType <MediaSymbol>().ToList(); var mediaTemplateSymbols = this.Section.Symbols.OfType <WixMediaTemplateSymbol>().ToList(); // If both symbols are authored, it is an error. if (mediaTemplateSymbols.Count > 0 && mediaSymbols.Count > 1) { throw new WixException(ErrorMessages.MediaTableCollision(null)); } // If neither symbol is authored, default to a media template. if (SectionType.Product == this.Section.Type && mediaTemplateSymbols.Count == 0 && mediaSymbols.Count == 0) { var mediaTemplate = new WixMediaTemplateSymbol() { CabinetTemplate = "cab{0}.cab", }; this.Section.AddSymbol(mediaTemplate); mediaTemplateSymbols.Add(mediaTemplate); } // When building merge module, all the files go to "#MergeModule.CABinet". if (SectionType.Module == this.Section.Type) { var mergeModuleMediaSymbol = this.Section.AddSymbol(new MediaSymbol { Cabinet = "#MergeModule.CABinet", }); this.FileFacadesByCabinetMedia = new Dictionary <MediaSymbol, IEnumerable <FileFacade> > { { mergeModuleMediaSymbol, this.FileFacades } }; this.UncompressedFileFacades = Array.Empty <FileFacade>(); } else if (mediaTemplateSymbols.Count == 0) { var filesByCabinetMedia = new Dictionary <MediaSymbol, List <FileFacade> >(); var uncompressedFiles = new List <FileFacade>(); this.ManuallyAssignFiles(mediaSymbols, filesByCabinetMedia, uncompressedFiles); this.FileFacadesByCabinetMedia = filesByCabinetMedia.ToDictionary(kvp => kvp.Key, kvp => (IEnumerable <FileFacade>)kvp.Value); this.UncompressedFileFacades = uncompressedFiles; } else { var filesByCabinetMedia = new Dictionary <MediaSymbol, List <FileFacade> >(); var uncompressedFiles = new List <FileFacade>(); this.AutoAssignFiles(mediaSymbols, filesByCabinetMedia, uncompressedFiles); this.FileFacadesByCabinetMedia = filesByCabinetMedia.ToDictionary(kvp => kvp.Key, kvp => (IEnumerable <FileFacade>)kvp.Value); this.UncompressedFileFacades = uncompressedFiles; } }
/// <summary> /// Assign files to cabinets based on MediaTemplate authoring. /// </summary> /// <param name="fileFacades">FileRowCollection</param> private void AutoAssignFiles(List <MediaSymbol> mediaTable, Dictionary <MediaSymbol, List <FileFacade> > filesByCabinetMedia, List <FileFacade> uncompressedFiles) { const int MaxCabIndex = 999; ulong currentPreCabSize = 0; ulong maxPreCabSizeInBytes; var maxPreCabSizeInMB = 0; var currentCabIndex = 0; MediaSymbol currentMediaRow = null; var mediaTemplateTable = this.Section.Symbols.OfType <WixMediaTemplateSymbol>(); // Remove all previous media symbols since they will be replaced with // media template. foreach (var mediaSymbol in mediaTable) { this.Section.Symbols.Remove(mediaSymbol); } // Auto assign files to cabinets based on maximum uncompressed media size var mediaTemplateRow = mediaTemplateTable.Single(); if (!String.IsNullOrEmpty(mediaTemplateRow.CabinetTemplate)) { this.CabinetNameTemplate = mediaTemplateRow.CabinetTemplate; } var mumsString = Environment.GetEnvironmentVariable("WIX_MUMS"); try { // Override authored mums value if environment variable is authored. if (!String.IsNullOrEmpty(mumsString)) { maxPreCabSizeInMB = Int32.Parse(mumsString); } else { maxPreCabSizeInMB = mediaTemplateRow.MaximumUncompressedMediaSize ?? DefaultMaximumUncompressedMediaSize; } maxPreCabSizeInBytes = (ulong)maxPreCabSizeInMB * 1024 * 1024; } catch (FormatException) { throw new WixException(ErrorMessages.IllegalEnvironmentVariable("WIX_MUMS", mumsString)); } catch (OverflowException) { throw new WixException(ErrorMessages.MaximumUncompressedMediaSizeTooLarge(null, maxPreCabSizeInMB)); } var mediaSymbolsByDiskId = new Dictionary <int, MediaSymbol>(); foreach (var facade in this.FileFacades) { // When building a product, if the current file is not to be compressed or if // the package set not to be compressed, don't cab it. if (SectionType.Product == this.Section.Type && (facade.Uncompressed || !this.FilesCompressed)) { uncompressedFiles.Add(facade); continue; } if (currentCabIndex == MaxCabIndex) { // Associate current file with last cab (irrespective of the size) and cab index is not incremented anymore. } else { // Update current cab size. currentPreCabSize += (ulong)facade.FileSize; // Overflow due to current file if (currentPreCabSize > maxPreCabSizeInBytes) { currentMediaRow = this.AddMediaSymbol(mediaTemplateRow, ++currentCabIndex); mediaSymbolsByDiskId.Add(currentMediaRow.DiskId, currentMediaRow); filesByCabinetMedia.Add(currentMediaRow, new List <FileFacade>()); // Now files larger than MaxUncompressedMediaSize will be the only file in its cabinet so as to respect MaxUncompressedMediaSize currentPreCabSize = (ulong)facade.FileSize; } else // file fits in the current cab. { if (currentMediaRow == null) { // Create new cab and MediaRow currentMediaRow = this.AddMediaSymbol(mediaTemplateRow, ++currentCabIndex); mediaSymbolsByDiskId.Add(currentMediaRow.DiskId, currentMediaRow); filesByCabinetMedia.Add(currentMediaRow, new List <FileFacade>()); } } } // Associate current file with current cab. var cabinetFiles = filesByCabinetMedia[currentMediaRow]; facade.DiskId = currentCabIndex; cabinetFiles.Add(facade); } // If there are uncompressed files and no MediaRow, create a default one. if (uncompressedFiles.Count > 0 && !this.Section.Symbols.OfType <MediaSymbol>().Any()) { var defaultMediaRow = this.Section.AddSymbol(new MediaSymbol(null, new Identifier(AccessModifier.Private, 1)) { DiskId = 1, }); mediaSymbolsByDiskId.Add(1, defaultMediaRow); } }
/// <summary> /// Parses the WixLocalization element. /// </summary> /// <param name="node">Element to parse.</param> private static Localization ParseWixLocalizationElement(IMessaging messaging, XElement node) { int codepage = -1; string culture = null; SourceLineNumber sourceLineNumbers = SourceLineNumber.CreateFromXObject(node); foreach (XAttribute attrib in node.Attributes()) { if (String.IsNullOrEmpty(attrib.Name.NamespaceName) || Localizer.WxlNamespace == attrib.Name.Namespace) { switch (attrib.Name.LocalName) { case "Codepage": codepage = Common.GetValidCodePage(attrib.Value, true, false, sourceLineNumbers); break; case "Culture": culture = attrib.Value; break; case "Language": // do nothing; @Language is used for locutil which can't convert Culture to lcid break; default: Common.UnexpectedAttribute(messaging, sourceLineNumbers, attrib); break; } } else { Common.UnexpectedAttribute(messaging, sourceLineNumbers, attrib); } } Dictionary <string, BindVariable> variables = new Dictionary <string, BindVariable>(); Dictionary <string, LocalizedControl> localizedControls = new Dictionary <string, LocalizedControl>(); foreach (XElement child in node.Elements()) { if (Localizer.WxlNamespace == child.Name.Namespace) { switch (child.Name.LocalName) { case "String": Localizer.ParseString(messaging, child, variables); break; case "UI": Localizer.ParseUI(messaging, child, localizedControls); break; default: messaging.Write(ErrorMessages.UnexpectedElement(sourceLineNumbers, node.Name.ToString(), child.Name.ToString())); break; } } else { messaging.Write(ErrorMessages.UnsupportedExtensionElement(sourceLineNumbers, node.Name.ToString(), child.Name.ToString())); } } return(messaging.EncounteredError ? null : new Localization(codepage, culture, variables, localizedControls)); }
private async Task BlazorWasmHostedTemplate_IndividualAuth_Works(BrowserKind browserKind, bool useLocalDb) { // Additional arguments are needed. See: https://github.com/dotnet/aspnetcore/issues/24278 Environment.SetEnvironmentVariable("EnableDefaultScopedCssItems", "true"); var project = await ProjectFactory.GetOrCreateProject("blazorhostedindividual" + browserKind + (useLocalDb ? "uld" : ""), Output); var createResult = await project.RunDotNetNewAsync("blazorwasm", args : new[] { "--hosted", "-au", "Individual", useLocalDb ? "-uld" : "" }); Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", project, createResult)); var serverProject = GetSubProject(project, "Server", $"{project.ProjectName}.Server"); var serverProjectFileContents = ReadFile(serverProject.TemplateOutputDir, $"{serverProject.ProjectName}.csproj"); if (!useLocalDb) { Assert.Contains(".db", serverProjectFileContents); } var appSettings = ReadFile(serverProject.TemplateOutputDir, "appsettings.json"); var element = JsonSerializer.Deserialize <JsonElement>(appSettings); var clientsProperty = element.GetProperty("IdentityServer").EnumerateObject().Single().Value.EnumerateObject().Single(); var replacedSection = element.GetRawText().Replace(clientsProperty.Name, serverProject.ProjectName.Replace(".Server", ".Client")); var appSettingsPath = Path.Combine(serverProject.TemplateOutputDir, "appsettings.json"); File.WriteAllText(appSettingsPath, replacedSection); var publishResult = await serverProject.RunDotNetPublishAsync(); Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", serverProject, publishResult)); // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build // later, while the opposite is not true. var buildResult = await serverProject.RunDotNetBuildAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", serverProject, buildResult)); var migrationsResult = await serverProject.RunDotNetEfCreateMigrationAsync("blazorwasm"); Assert.True(0 == migrationsResult.ExitCode, ErrorMessages.GetFailedProcessMessage("run EF migrations", serverProject, migrationsResult)); serverProject.AssertEmptyMigration("blazorwasm"); if (useLocalDb) { var dbUpdateResult = await serverProject.RunDotNetEfUpdateDatabaseAsync(); Assert.True(0 == dbUpdateResult.ExitCode, ErrorMessages.GetFailedProcessMessage("update database", serverProject, dbUpdateResult)); } await BuildAndRunTest(project.ProjectName, serverProject, browserKind, usesAuth : true); UpdatePublishedSettings(serverProject); if (Fixture.BrowserManager.IsAvailable(browserKind)) { using var aspNetProcess = serverProject.StartPublishedProjectAsync(); Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", serverProject, aspNetProcess.Process)); await aspNetProcess.AssertStatusCode("/", HttpStatusCode.OK, "text/html"); await using var browser = await Fixture.BrowserManager.GetBrowserInstance(browserKind, BrowserContextInfo); var page = await browser.NewPageAsync(); await aspNetProcess.VisitInBrowserAsync(page); await TestBasicNavigation(project.ProjectName, page, usesAuth : true); await page.CloseAsync(); } else { EnsureBrowserAvailable(browserKind); } }
public void AddErrorMessage(string message) { Successed = false; ErrorMessages.Add(message); }
public async Task RazorPagesTemplate_IndividualAuth(bool useLocalDB) { Project = await ProjectFactory.GetOrCreateProject("razorpagesindividual" + (useLocalDB ? "uld" : ""), Output); var createResult = await Project.RunDotNetNewAsync("razor", auth : "Individual", useLocalDB : useLocalDB); Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", Project, createResult)); var projectFileContents = ReadFile(Project.TemplateOutputDir, $"{Project.ProjectName}.csproj"); if (!useLocalDB) { Assert.Contains(".db", projectFileContents); } var publishResult = await Project.RunDotNetPublishAsync(); Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", Project, publishResult)); // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build // later, while the opposite is not true. var buildResult = await Project.RunDotNetBuildAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", Project, buildResult)); var migrationsResult = await Project.RunDotNetEfCreateMigrationAsync("razorpages"); Assert.True(0 == migrationsResult.ExitCode, ErrorMessages.GetFailedProcessMessage("run EF migrations", Project, migrationsResult)); Project.AssertEmptyMigration("razorpages"); var pages = new List <Page> { new Page { Url = PageUrls.ForgotPassword, Links = new string [] { PageUrls.HomeUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.HomeUrl, Links = new string[] { PageUrls.HomeUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.DocsUrl, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.PrivacyUrl, Links = new string[] { PageUrls.HomeUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.LoginUrl, Links = new string[] { PageUrls.HomeUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.ForgotPassword, PageUrls.RegisterUrl, PageUrls.ResendEmailConfirmation, PageUrls.ExternalArticle, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.RegisterUrl, Links = new string [] { PageUrls.HomeUrl, PageUrls.RegisterUrl, PageUrls.LoginUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.ExternalArticle, PageUrls.PrivacyUrl } } }; using (var aspNetProcess = Project.StartBuiltProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", Project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } using (var aspNetProcess = Project.StartPublishedProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", Project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } }
public static NotSupportedException unsupported(string feature, [CallerFilePath] string caller = null, [CallerFilePath] string file = null, [CallerLineNumber] int?line = null) => new NotSupportedException(ErrorMessages.FeatureUnsupported(feature, caller, file, line).ToString());
public static bool SpecificErrorIsShown(ErrorMessages errorMessage) { Assert.AreEqual(EnumValues.GetErrorMessage(errorMessage), Physical.Parking.GetResult()); // if the error is shown, return true return true; }
public async Task MvcTemplate_NoAuthImplAsync(string languageOverride) { Project = await ProjectFactory.GetOrCreateProject("mvcnoauth" + (languageOverride == "F#" ? "fsharp" : "csharp"), Output); var createResult = await Project.RunDotNetNewAsync("mvc", language : languageOverride); Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", Project, createResult)); var projectExtension = languageOverride == "F#" ? "fsproj" : "csproj"; var projectFileContents = Project.ReadFile($"{Project.ProjectName}.{projectExtension}"); Assert.DoesNotContain(".db", projectFileContents); Assert.DoesNotContain("Microsoft.EntityFrameworkCore.Tools", projectFileContents); Assert.DoesNotContain("Microsoft.VisualStudio.Web.CodeGeneration.Design", projectFileContents); Assert.DoesNotContain("Microsoft.EntityFrameworkCore.Tools.DotNet", projectFileContents); Assert.DoesNotContain("Microsoft.Extensions.SecretManager.Tools", projectFileContents); var publishResult = await Project.RunDotNetPublishAsync(); Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", Project, publishResult)); // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release // The output from publish will go into bin/Release/netcoreapp3.0/publish and won't be affected by calling build // later, while the opposite is not true. var buildResult = await Project.RunDotNetBuildAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", Project, buildResult)); IEnumerable <string> menuLinks = new List <string> { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyFullUrl }; if (languageOverride == null) { menuLinks = menuLinks.Append(PageUrls.PrivacyFullUrl); } var footerLinks = new string[] { PageUrls.PrivacyFullUrl }; var pages = new List <Page> { new Page { Url = PageUrls.HomeUrl, Links = menuLinks.Append(PageUrls.DocsUrl).Concat(footerLinks) }, new Page { Url = PageUrls.PrivacyFullUrl, Links = menuLinks.Concat(footerLinks) } }; using (var aspNetProcess = Project.StartBuiltProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", Project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } using (var aspNetProcess = Project.StartPublishedProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", Project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } }
public static void GetVerificationFailed() => Assert.That(ErrorMessages.GetVerificationFailed("a", "b", "c"), Is.EqualTo("Type: a, method: b, message: c"));
public async Task RazorPagesTemplate_NoAuth() { Project = await ProjectFactory.GetOrCreateProject("razorpagesnoauth", Output); var createResult = await Project.RunDotNetNewAsync("razor"); Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("razor", Project, createResult)); var projectFileContents = ReadFile(Project.TemplateOutputDir, $"{Project.ProjectName}.csproj"); Assert.DoesNotContain(".db", projectFileContents); Assert.DoesNotContain("Microsoft.EntityFrameworkCore.Tools", projectFileContents); Assert.DoesNotContain("Microsoft.VisualStudio.Web.CodeGeneration.Design", projectFileContents); Assert.DoesNotContain("Microsoft.EntityFrameworkCore.Tools.DotNet", projectFileContents); Assert.DoesNotContain("Microsoft.Extensions.SecretManager.Tools", projectFileContents); var publishResult = await Project.RunDotNetPublishAsync(); Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", Project, createResult)); // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build // later, while the opposite is not true. var buildResult = await Project.RunDotNetBuildAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", Project, createResult)); var pages = new List <Page> { new Page { Url = PageUrls.HomeUrl, Links = new string[] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.DocsUrl, PageUrls.PrivacyUrl } }, new Page { Url = PageUrls.PrivacyUrl, Links = new string[] { PageUrls.HomeUrl, PageUrls.HomeUrl, PageUrls.PrivacyUrl, PageUrls.PrivacyUrl } } }; using (var aspNetProcess = Project.StartBuiltProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", Project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } using (var aspNetProcess = Project.StartPublishedProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", Project, aspNetProcess.Process)); await aspNetProcess.AssertPagesOk(pages); } }
public static void GetCannotMockSealedType() => Assert.That(ErrorMessages.GetCannotMockSealedType("a"), Is.EqualTo("Cannot mock the sealed type a."));
public async Task BlazorWasmHostedPwaTemplate_Works(BrowserKind browserKind) { // Additional arguments are needed. See: https://github.com/dotnet/aspnetcore/issues/24278 Environment.SetEnvironmentVariable("EnableDefaultScopedCssItems", "true"); var project = await ProjectFactory.GetOrCreateProject("blazorhostedpwa", Output); var createResult = await project.RunDotNetNewAsync("blazorwasm", args : new[] { "--hosted", "--pwa" }); Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", project, createResult)); var serverProject = GetSubProject(project, "Server", $"{project.ProjectName}.Server"); var publishResult = await serverProject.RunDotNetPublishAsync(); Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", serverProject, publishResult)); var buildResult = await serverProject.RunDotNetBuildAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", serverProject, buildResult)); await BuildAndRunTest(project.ProjectName, serverProject, browserKind); ValidatePublishedServiceWorker(serverProject); string listeningUri = null; if (Fixture.BrowserManager.IsAvailable(browserKind)) { await using var browser = await Fixture.BrowserManager.GetBrowserInstance(browserKind, BrowserContextInfo); IPage page = null; using (var aspNetProcess = serverProject.StartPublishedProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", serverProject, aspNetProcess.Process)); await aspNetProcess.AssertStatusCode("/", HttpStatusCode.OK, "text/html"); page = await browser.NewPageAsync(); await aspNetProcess.VisitInBrowserAsync(page); await TestBasicNavigation(project.ProjectName, page); // Note: we don't want to use aspNetProcess.ListeningUri because that isn't necessarily the HTTPS URI listeningUri = new Uri(page.Url).GetLeftPart(UriPartial.Authority); } // The PWA template supports offline use. By now, the browser should have cached everything it needs, // so we can continue working even without the server. // Since this is the hosted project, backend APIs won't work offline, so we need to skip "fetchdata" await page.GoToAsync("about:blank"); await browser.SetOfflineAsync(true); await page.GoToAsync(listeningUri); await TestBasicNavigation(project.ProjectName, page, skipFetchData : true); await page.CloseAsync(); } else { EnsureBrowserAvailable(browserKind); } }
private string MustResolveUsingBindPaths(string source, IntermediateSymbolDefinition symbolDefinition, SourceLineNumber sourceLineNumbers, BindStage bindStage, List <string> checkedPaths) { string resolved = null; // If the file exists, we're good to go. checkedPaths.Add(source); if (CheckFileExists(source)) { resolved = source; } else if (Path.IsPathRooted(source)) // path is rooted so bindpaths won't help, bail since the file apparently doesn't exist. { resolved = null; } else // not a rooted path so let's try applying all the different source resolution options. { string bindName = null; var path = source; string pathWithoutSourceDir = null; if (source.StartsWith(BindPathOpenString, StringComparison.Ordinal)) { int closeParen = source.IndexOf(')', BindPathOpenString.Length); if (-1 != closeParen) { bindName = source.Substring(BindPathOpenString.Length, closeParen - BindPathOpenString.Length); path = source.Substring(BindPathOpenString.Length + bindName.Length + 1); // +1 for the closing brace. path = path.TrimStart('\\'); // remove starting '\\' char so the path doesn't look rooted. } } else if (source.StartsWith("SourceDir\\", StringComparison.Ordinal) || source.StartsWith("SourceDir/", StringComparison.Ordinal)) { pathWithoutSourceDir = path.Substring(10); } var bindPaths = this.BindPaths[bindStage]; foreach (var bindPath in bindPaths) { if (!String.IsNullOrEmpty(bindName) && !String.IsNullOrEmpty(bindPath.Name)) { if (String.Equals(bindName, bindPath.Name, StringComparison.OrdinalIgnoreCase) && String.IsNullOrEmpty(resolved)) { var filePath = Path.Combine(bindPath.Path, path); checkedPaths.Add(filePath); if (CheckFileExists(filePath)) { resolved = filePath; } } } else { if (!String.IsNullOrEmpty(pathWithoutSourceDir)) { var filePath = Path.Combine(bindPath.Path, pathWithoutSourceDir); checkedPaths.Add(filePath); if (CheckFileExists(filePath)) { resolved = filePath; } } if (String.IsNullOrEmpty(resolved)) { var filePath = Path.Combine(bindPath.Path, path); checkedPaths.Add(filePath); if (CheckFileExists(filePath)) { resolved = filePath; } } } } } if (null == resolved) { throw new WixException(ErrorMessages.FileNotFound(sourceLineNumbers, source, symbolDefinition.Name, checkedPaths)); } return(resolved); }
/// <summary> /// Recursive helper function to resolve all references of passed in section. /// </summary> /// <param name="section">Section with references to resolve.</param> /// <remarks>Note: recursive function.</remarks> private void RecursivelyResolveReferences(IntermediateSection section) { // If we already resolved this section, move on to the next. if (!this.resolvedSections.Add(section)) { return; } // Process all of the references contained in this section using the collection of // symbols provided. Then recursively call this method to process the // located symbol's section. All in all this is a very simple depth-first // search of the references per-section. foreach (var wixSimpleReferenceRow in section.Symbols.OfType <WixSimpleReferenceSymbol>()) { // If we're building a Merge Module, ignore all references to the Media table // because Merge Modules don't have Media tables. if (this.BuildingMergeModule && wixSimpleReferenceRow.Table == "Media") { continue; } if (!this.symbolsWithSections.TryGetValue(wixSimpleReferenceRow.SymbolicName, out var symbolWithSection)) { this.Messaging.Write(ErrorMessages.UnresolvedReference(wixSimpleReferenceRow.SourceLineNumbers, wixSimpleReferenceRow.SymbolicName)); } else // see if the symbol (and any of its duplicates) are appropriately accessible. { var accessible = this.DetermineAccessibleSymbols(section, symbolWithSection); if (!accessible.Any()) { this.Messaging.Write(ErrorMessages.UnresolvedReference(wixSimpleReferenceRow.SourceLineNumbers, wixSimpleReferenceRow.SymbolicName, symbolWithSection.Access)); } else if (1 == accessible.Count) { var accessibleSymbol = accessible[0]; this.referencedSymbols.Add(accessibleSymbol); if (null != accessibleSymbol.Section) { this.RecursivelyResolveReferences(accessibleSymbol.Section); } } else // display errors for the duplicate symbols. { var accessibleSymbol = accessible[0]; var referencingSourceLineNumber = wixSimpleReferenceRow.SourceLineNumbers?.ToString(); if (String.IsNullOrEmpty(referencingSourceLineNumber)) { this.Messaging.Write(ErrorMessages.DuplicateSymbol(accessibleSymbol.Symbol.SourceLineNumbers, accessibleSymbol.Name)); } else { this.Messaging.Write(ErrorMessages.DuplicateSymbol(accessibleSymbol.Symbol.SourceLineNumbers, accessibleSymbol.Name, referencingSourceLineNumber)); } foreach (var accessibleDuplicate in accessible.Skip(1)) { this.Messaging.Write(ErrorMessages.DuplicateSymbol2(accessibleDuplicate.Symbol.SourceLineNumbers)); } } } } }
/// <summary> /// Parse a localized control. /// </summary> /// <param name="node">Element to parse.</param> /// <param name="localizedControls">Dictionary of localized controls.</param> private static void ParseUI(IMessaging messaging, XElement node, IDictionary <string, LocalizedControl> localizedControls) { string dialog = null; string control = null; int x = CompilerConstants.IntegerNotSet; int y = CompilerConstants.IntegerNotSet; int width = CompilerConstants.IntegerNotSet; int height = CompilerConstants.IntegerNotSet; int attribs = 0; string text = null; SourceLineNumber sourceLineNumbers = SourceLineNumber.CreateFromXObject(node); foreach (XAttribute attrib in node.Attributes()) { if (String.IsNullOrEmpty(attrib.Name.NamespaceName) || Localizer.WxlNamespace == attrib.Name.Namespace) { switch (attrib.Name.LocalName) { case "Dialog": dialog = Common.GetAttributeIdentifierValue(messaging, sourceLineNumbers, attrib); break; case "Control": control = Common.GetAttributeIdentifierValue(messaging, sourceLineNumbers, attrib); break; case "X": x = Common.GetAttributeIntegerValue(messaging, sourceLineNumbers, attrib, 0, short.MaxValue); break; case "Y": y = Common.GetAttributeIntegerValue(messaging, sourceLineNumbers, attrib, 0, short.MaxValue); break; case "Width": width = Common.GetAttributeIntegerValue(messaging, sourceLineNumbers, attrib, 0, short.MaxValue); break; case "Height": height = Common.GetAttributeIntegerValue(messaging, sourceLineNumbers, attrib, 0, short.MaxValue); break; case "RightToLeft": if (YesNoType.Yes == Common.GetAttributeYesNoValue(messaging, sourceLineNumbers, attrib)) { attribs |= MsiInterop.MsidbControlAttributesRTLRO; } break; case "RightAligned": if (YesNoType.Yes == Common.GetAttributeYesNoValue(messaging, sourceLineNumbers, attrib)) { attribs |= MsiInterop.MsidbControlAttributesRightAligned; } break; case "LeftScroll": if (YesNoType.Yes == Common.GetAttributeYesNoValue(messaging, sourceLineNumbers, attrib)) { attribs |= MsiInterop.MsidbControlAttributesLeftScroll; } break; default: Common.UnexpectedAttribute(messaging, sourceLineNumbers, attrib); break; } } else { Common.UnexpectedAttribute(messaging, sourceLineNumbers, attrib); } } text = Common.GetInnerText(node); if (String.IsNullOrEmpty(control) && 0 < attribs) { if (MsiInterop.MsidbControlAttributesRTLRO == (attribs & MsiInterop.MsidbControlAttributesRTLRO)) { messaging.Write(ErrorMessages.IllegalAttributeWithoutOtherAttributes(sourceLineNumbers, node.Name.ToString(), "RightToLeft", "Control")); } else if (MsiInterop.MsidbControlAttributesRightAligned == (attribs & MsiInterop.MsidbControlAttributesRightAligned)) { messaging.Write(ErrorMessages.IllegalAttributeWithoutOtherAttributes(sourceLineNumbers, node.Name.ToString(), "RightAligned", "Control")); } else if (MsiInterop.MsidbControlAttributesLeftScroll == (attribs & MsiInterop.MsidbControlAttributesLeftScroll)) { messaging.Write(ErrorMessages.IllegalAttributeWithoutOtherAttributes(sourceLineNumbers, node.Name.ToString(), "LeftScroll", "Control")); } } if (String.IsNullOrEmpty(control) && String.IsNullOrEmpty(dialog)) { messaging.Write(ErrorMessages.ExpectedAttributesWithOtherAttribute(sourceLineNumbers, node.Name.ToString(), "Dialog", "Control")); } if (!messaging.EncounteredError) { LocalizedControl localizedControl = new LocalizedControl(dialog, control, x, y, width, height, attribs, text); string key = localizedControl.GetKey(); if (localizedControls.ContainsKey(key)) { if (String.IsNullOrEmpty(localizedControl.Control)) { messaging.Write(ErrorMessages.DuplicatedUiLocalization(sourceLineNumbers, localizedControl.Dialog)); } else { messaging.Write(ErrorMessages.DuplicatedUiLocalization(sourceLineNumbers, localizedControl.Dialog, localizedControl.Control)); } } else { localizedControls.Add(key, localizedControl); } } }