Blazor WebAssembly PWA loses functionality and style in DevOps Pipeline
When first opening the application or after doing a hard reload the isolated CSS does not load. The same is if you open up the application on mobile. In addition, the promps to download the PWA doesn't show.
What I have is a Blazor WebAssembly PWA. The solution has two projects 'server' and 'client'.
The server project contains the start up, caching etc.
The client contains the frontend.
The solution is hosted in an Azure App Service (Deployment Slot).
If deploying manually to the slot everything is fine. (Download the publish profile from Azure AppService and publish server project)
Now to the problem:
I set up two pipelines, a build pipeline and a release pipeline.
The build pipeline:
trigger:
- master
pool:
vmImage: 'windows-latest'
variables:
solution: '**/*.sln'
buildPlatform: 'Any CPU'
buildConfiguration: 'Release'
steps:
- task: NuGetToolInstaller@1
- task: NuGetCommand@2
inputs:
restoreSolution: '$(solution)'
- task: VSBuild@1
inputs:
solution: '$(solution)'
msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
platform: '$(buildPlatform)'
configuration: '$(buildConfiguration)'
- task: VSTest@2
inputs:
platform: '$(buildPlatform)'
configuration: '$(buildConfiguration)'
- task: PublishBuildArtifacts@1
inputs:
PathtoPublish: '$(Build.ArtifactStagingDirectory)'
ArtifactName: 'drop'
publishLocation: 'Container'
The release pipline (Has some CI/CD settings)
Due to building a solution with multiple project I get multiple Zip-files in my drop artifact. The server one is the one I pick up and deploy to the same AppService.
The pipelines work. The problem arises first when the application is opened. If I publish manually everything looks fine and I get the prompt to download the app. However, if I use the pipeline neither the correct CSS is loaded (at least not the isolated) or the prompt to download the PWA is shown.
See also questions close to this topic
-
Convert CSV file data from any language to English in C#
I would like to convert CSV file data from multi languages such as Spanish, Russian, European etc to English language in C# program.
Convert all characters like Ó, É to English characters.
Thanks.
-
I get an error when solving this problem, How can I fix?
I am trying to solve the Climbstairs problem but in reverse, where I want to know the number of steps I have to take to go down.
I can go down 1, 2, 3 or 4 steps at the same time. That is, if I am at step i, I can go down to step i - a for any of the values 1, 2, 3 or 4 of a.
I have the following code but I don't know what happens:
I got this error: System.IndexOutOfRangeException in this line:
steps[i] += steps[i - a];
Why I have this error?
public static int DownStairs(int n) { int[] steps = new int[n + 1]; steps[n] = 1; steps[n - 1] = 1; for (int i = n-2; i>=0; i--) { for(int a = 1; a<=4; a++) { steps[i] += steps[i - a]; } } return steps[n]; } static void Main(string[] args) { int n = 5; DownStairs(n); }
-
How to delete multiple blank lines in a WPF DataGrid imported from an Excel file
I have a WPF DataGrid which I fill with imported data from an Excel file (*. Xlsx) through a class, the problem is that multiple blank lines are added to the end of the DataGrid that I don't see how to delete. I attach my code.
<DataGrid Name="dgvMuros" Height="210" Margin="8" VerticalAlignment="Top" Padding="5,6" ColumnWidth="50" IsReadOnly="False" AlternatingRowBackground="Azure" GridLinesVisibility="All" HeadersVisibility="Column" Loaded="dgvMuros_Loaded" CellEditEnding="DataGrid_CellEditEnding" ItemsSource="{Binding Data}" HorizontalGridLinesBrush="LightGray" VerticalGridLinesBrush="LightGray" > </DataGrid>
With this method I import the data from the Excel file.
public void ImportarMuros() { ExcelData dataFronExcel = new ExcelData(); this.dgvMuros.DataContext = dataFronExcel; txtTotMuros.Text = dataFronExcel.numMuros.ToString(); cmdAgregarMuros.IsEnabled = false; cmdBorrarMuros.IsEnabled = false; cmdImportar.IsEnabled = false; } public class ExcelData { public int numMuros { get; set; } public DataView Data { get { Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook; Excel.Worksheet worksheet; Excel.Range range; workbook = excelApp.Workbooks.Open(Environment.CurrentDirectory + "\\MurosEjemplo.xlsx"); worksheet = (Excel.Worksheet)workbook.Sheets["DatMuros"]; int column = 0; int row = 0; range = worksheet.UsedRange; DataTable dt = new DataTable(); dt.Columns.Add("Muro"); dt.Columns.Add("Long"); dt.Columns.Add("Esp"); dt.Columns.Add("X(m)"); dt.Columns.Add("Y(m)"); dt.Columns.Add("Dir"); for (row = 2; row < range.Rows.Count; row++) { DataRow dr = dt.NewRow(); for (column = 1; column <= range.Columns.Count; column++) { dr[column - 1] = Convert.ToString((range.Cells[row, column] as Excel.Range).Value); } dt.Rows.Add(dr); dt.AcceptChanges(); numMuros = dt.Rows.Count; } workbook.Close(true, Missing.Value, Missing.Value); excelApp.Quit(); return dt.DefaultView; } } }
-
Azure Artifacts - 401 unauthorized error when some users access to organization-scoped feed
Background
Hi, I have a organization with many projects in Azure Devops. One of the project created a organization-scoped feed and built some pipelines do NPM publish to the feed. We can see the packages appear in the feed now. We then follow the instruction in "Connect to feed" to restore package.
.npmrc file
registry=https://pkgs.dev.azure.com/<yourOrganization>/_packaging/<yourFeed>/npm/registry/ always-auth=true ; begin auth token //pkgs.dev.azure.com/<yourOrganization>/_packaging/<yourFeed>/npm/registry/:username=[ANY_VALUE_BUT_NOT_AN_EMPTY_STRING] //pkgs.dev.azure.com/<yourOrganization>/_packaging/<yourFeed>/npm/registry/:_password=[BASE64_ENCODED_PERSONAL_ACCESS_TOKEN] //pkgs.dev.azure.com/<yourOrganization>/_packaging/<yourFeed>/npm/registry/:email=npm requires email to be set but doesn't use the value //pkgs.dev.azure.com/<yourOrganization>/_packaging/<yourFeed>/npm/:username=[ANY_VALUE_BUT_NOT_AN_EMPTY_STRING] //pkgs.dev.azure.com/<yourOrganization>/_packaging/<yourFeed>/npm/:_password=[BASE64_ENCODED_PERSONAL_ACCESS_TOKEN] //pkgs.dev.azure.com/<yourOrganization>/_packaging/<yourFeed>/npm/:email=npm requires email to be set but doesn't use the value ; end auth token
Problem
I as a project administrator can successfully restore package(npm install). However, some users cannot restore and show up "401 unauthorized" after entering command. I have checked the view setting and the .npmrc file as well as PAT with a narrow scope of Packaging (read and write).
I have also checked Manage packages with feed permissions. It said List, install, and restore packages only require "Reader" permission. I added the user into the Reader Group in Project level and Reader Group in Feed Setting.
What Could be Missing?
-
Unable to publish NuGet packages from TeamCity to Azure DevOps
I have installed the Azure Artifacts Credential Provider on my build agent server and can publish to my Azure DevOps feed via command line from the build agent server, but when I try to publish through the TeamCity build step, I get the following error:
[push] in directory: C:\TeamCity\BuildAgent\work\56940dd3b6a0d73e\Nuget\Release [18:16:51] [push] WARNING: The credential plugin model used by 'C:\TeamCity\BuildAgent\plugins\nuget-agent\bin\credential-provider\CredentialProvider.TeamCity.exe' is deprecated. Please contact the provider of the plugin for an alternative. More information about the recommended plugin model can be found at 'https://aka.ms/nuget-cross-platform-authentication-plugin'. [18:16:52] [push] Please provide credentials for: https://pkgs.dev.azure.com/blahblah/_packaging/blahblah/nuget/v3/index.json [18:16:52] [push] Unable to load the service index for source https://pkgs.dev.azure.com/blahblah/_packaging/blahblah/nuget/v3/index.json. [18:16:52] [push] Response status code does not indicate success: 401 (Unauthorized).
I have configured the NuGet feed credentials under Build Features using the Azure DevOps PAT for the specified user, and even tried setting the NUGET_PLUGIN_PATHS environment variable, but still no luck.
I am using the following versions:
- TeamCity 2019.1.5 (build 66605)
- NuGet 5.3.1
- .NET Core SDK 3.1.201
The strange thing is, I am able to publish a different package on a different build agent using the same configuration. The only difference is the working build agent has .NET Core SDK 2.x installed, instead of 3.1.x due to the different requirements needed for each build agent.
Any help in resolving this issue would be gratefully appreciated. Thanks in advance for your support.
Terry
-
Azure DevOps deployment fails with the error message "The operation was canceled."
My Azure DevOps pipeline tasks successfully complete without issues except for the final deployment step:
Job Issues - 1 Error The job running on agent XXXX ran longer than the maximum time of 00:05:00 minutes. For more information, see https://go.microsoft.com/fwlink/?linkid=2077134
The build logs state the operation was canceled:
021-03-02T20:50:00.4223027Z Folders: 695 2021-03-02T20:50:00.4223319Z Files: 10645 2021-03-02T20:50:00.4223589Z Size: 672611102 2021-03-02T20:50:00.4223851Z Compressed: 249144045 2021-03-02T20:50:03.6023001Z ##[warning]Unable to apply transformation for the given package. Verify the following. 2021-03-02T20:50:03.6032907Z ##[warning]1. Whether the Transformation is already applied for the MSBuild generated package during build. If yes, remove the <DependentUpon> tag for each config in the csproj file and rebuild. 2021-03-02T20:50:03.6034584Z ##[warning]2. Ensure that the config file and transformation files are present in the same folder inside the package. 2021-03-02T20:50:04.5268038Z Initiated variable substitution in config file : C:\azagent\A2\_work\_temp\temp_web_package_3012195912183888\Areas\Admin\sitemap.config 2021-03-02T20:50:04.5552027Z Skipped Updating file: C:\azagent\A2\_work\_temp\temp_web_package_3012195912183888\Areas\Admin\sitemap.config 2021-03-02T20:50:04.5553082Z Initiated variable substitution in config file : C:\azagent\A2\_work\_temp\temp_web_package_3012195912183888\web.config 2021-03-02T20:50:04.5642868Z Skipped Updating file: C:\azagent\A2\_work\_temp\temp_web_package_3012195912183888\web.config 2021-03-02T20:50:04.5643366Z XML variable substitution applied successfully. 2021-03-02T20:51:00.8934630Z ##[error]The operation was canceled. 2021-03-02T20:51:00.8938641Z ##[section]Finishing: Deploy IIS Website/App:
When I examine the deployment states, I notice one of my tasks takes quite a while for what should be a fairly simple operation:
The file transform portion takes over half of the allotted 5 minutes? Could this be the issue?
steps: - task: FileTransform@1 displayName: 'File Transform: ' inputs: folderPath: '$(System.DefaultWorkingDirectory)/_site.com/drop/Release/Nop.Web.zip' fileType: json targetFiles: '**/dataSettings.json'
It may be inefficient but FileTransform log shows a significant amount of time spent after the variable has been substituted. Not sure what's causing the long delay, but the logs don't account for the time after the variable has been successfully substituted:
2021-03-02T23:04:44.3796910Z Folders: 695 2021-03-02T23:04:44.3797285Z Files: 10645 2021-03-02T23:04:44.3797619Z Size: 672611002 2021-03-02T23:04:44.3797916Z Compressed: 249143976 2021-03-02T23:04:44.3970596Z Applying JSON variable substitution for **/App_Data/dataSettings.json 2021-03-02T23:04:45.2396016Z Applying JSON variable substitution for C:\azagent\A2\_work\_temp\temp_web_package_0182869515217865\App_Data\dataSettings.json 2021-03-02T23:04:45.2399264Z Substituting value on key DataConnectionString with (string) value: *** **2021-03-02T23:04:45.2446986Z JSON variable substitution applied successfully. 2021-03-02T23:07:25.4881687Z ##[section]Finishing: File Transform:**
-
Require Azure Function to be updated through Azure Pipeline
Is there a way to require that Azure Functions be updated through an Azure pipeline, and not someone using the VSCode integration or azure functions core tools CLI?
-
How do you specify the sourceBranch for a Run of Pipelines via the REST API?
I've been trying to run a pipeline for a particular branch of the repository I'm using.
In the UI, there is a convenient option, but I don't understand what to try in the request.
No matter what I do I always run from master.
How do I change that? I tried filling out the repository parameters but to no avail: https://docs.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/run%20pipeline?view=azure-devops-rest-6.0#repositoryresourceparameters
Here is an example request:
curl --location --request POST 'https://dev.azure.com/<redacted>/<redacted>/_apis/pipelines/<redacted>/runs?api-version=6.0-preview.1' \ --header 'Authorization: Basic <redacted>' \ --header 'Content-Type: application/json' \ --header 'Cookie: VstsSession=<redacted>' \ --data-raw '{ "previewRun": true, "resources": { "repositories": { "refName": "refs/heads/<redacted>" } }, "runParameters": { "namespace" : "<redacted>", "image" : "<redacted>", "tag" : "<redacted>", "package" : "<redacted>", "version" : "8.4.4" } }'
-
How to display data in a reusable Table component in Blazor
I'm trying to create a reusable MasterTable component in Blazor.
So far, I've defined the MasterTable as
@using AntDesign @using MyNamespace.Blazor.ViewModels @typeparam TItem <Table TItem="TItem" DataSource="@Data"> @{ foreach (var col in Columns) { <Column Title="@col.Label" @bind-Field="@col.Key" /> } } </Table> @code { private List<TItem> _data; [Parameter] public List<TItem> Data { get => _data; set => _data = value ?? new List<TItem>(); } [Parameter] public TableColumnViewModel[] Columns { get; set; } }
where TableColumnViewModel is defined simply as
public class TableColumnViewModel { public string Key { get; set; } public string Label { get; set; } }
I would like to create an instance of the MasterTable in a page for Daily Tasks but so far I'm only able to get it to display like this:
My attempt to implement MasterTable is as follows:
@page "/Tasks/Daily"; @using MyNamespace.Blazor.Services; @using MyNamespace.Blazor.ViewModels; @using MyNamespace.Api.Client.Model; @inject ITasksService _tasksService; <h1>Daily Tasks</h1> <MasterTable TItem="TaskStatus" Data="_tasks" Columns="cols"> </MasterTable> @code { private List<TaskStatus> _tasks = new List<TaskStatus>(); protected override async Task OnInitializedAsync() { _tasks = await _tasksService.GetTaskStatusAsync(); } TableColumnViewModel[] cols = { new TableColumnViewModel { Key = "id", Label = "ID" }, new TableColumnViewModel { Key = "description", Label = "ID" }, new c { Key = "type", Label = "Type" } }; }
With TaskStatus defined as
public class TaskStatus { public TaskStatus(int taskStatusId = default(int), string statusDescription = default(string)) { this.TaskStatusId = taskStatusId; this.StatusDescription = statusDescription; } public int TaskStatusId { get; set; } public string StatusDescription { get; set; } }
What do I need to do to get the MasterTable template to display the list of TaskStatus objects instead of the keys from TableColumnViewModel?
To be clear - instead of just using the component without wrapping it, the issue is that I want to isolate the CSS in the context of the 3rd party component, so that only the necessary CSS is loaded.
-
Blazor - app.UseIdentityServer(); with .pfx key file - Unexpected character encountered while parsing number
I have created a new Blazor WebAssembly App with Individual User Accounts, Store user accounts in-app and ASP.NET Core hosted in .NET 5. When deploying my app to Azure App Service I get the following error:
Object reference not set to an instance of an object.at Microsoft.Extensions.DependencyInjection.IdentityServerBuilderConfigurationExtensions
Reading these links I have to provide my own certificate in production for IdentityServer:
Blazor Web Assembly App .Net Core Hosted: publish runtime error
https://stackoverflow.com/a/56904000/3850405
I then created a
.pfx
file like this and I have verified that it works and my password is correct.https://stackoverflow.com/a/48790088/3850405
I then placed the
.pfx
file in myServer
projects root folder and markedCopy to Output Directory
asCopy Always
.I then updated
appsettings.json
to look like this:"IdentityServer": { "Clients": { "BlazorTest.Client": { "Profile": "IdentityServerSPA" } }, "Key": { "Type": "File", "FilePath": "localhost.pfx", "Password": "MySercurePassword123?" } },
Now the project does not work neither locally or on Azure. It fails on
app.UseIdentityServer();
inStartup.cs
with the following error:Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing number: �. Path '', line 1, position 1.'
According to Microsoft docs my certificate should be valid:
A production certificate to use for signing tokens.
- There are no specific requirements for this certificate; it can be a self-signed certificate or a certificate provisioned through a CA authority.
- It can be generated through standard tools like PowerShell or OpenSSL.
- It can be installed into the certificate store on the target machines or deployed as a .pfx file with a strong password.
If I load the key like this it works:
"Key": { "Type": "Store", "StoreName": "My", "StoreLocation": "CurrentUser", "Name": "CN=blazortest" }
-
Is there some how to navigate to a page and pass parameters without use the address bar in Blazor?
This is present in many modern SPA libraries/frameworks...
I will supply an example using React (But it could be Angular or Vue), you can do something like...
this.props.router.push({ pathname: '/login-successfully', state: { userId: 'john', name: 'John Doe } })
and then on the initialization of the "other-page" you will have:
const {state} = useLocation(); const { userId, name } = state;
and you can render things like
<p>Welcome Back, {name}!</p>
Such feature is very useful in many scenarios, but by reading the documentation of routing in Blazor at https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-5.0 I cannot find anything. The NavigationManager just have those parameters:
public void NavigateTo (string uri, bool forceLoad = false);
Is there some equivalent approach that I can use ? I know a workaround by creating a singleton class, store the data over there and display on the login-successfully page, but I really hope to find something better as solution.
-
endpoints.MapFallbackToFile("index.html") messes up routing in asp.net core project
The solution has a web-api project that is also the host for a blazor-webassembly front-end.
With this config all works fine. WebApi endpoint get hit correctly when called from postman.
app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapRazorPages(); });
When adding a MapFallBackToFile suddenly some Api-Endpoint do not get hit anymore but serve that default file.
app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapRazorPages(); endpoints.MapFallbackToFile("index.html"); });
The reason for adding this fallback : serve as landing page for the Blazor front-end.
Any suggestions ?
-
Why is XML validation in a Blazor application giving different messages on localhost and as an Azure Static Web App?
I am building an XML editor in Blazor WebAssembly (TargetFramework=net5.0). Part of the functionality involves validating the XML for completeness and according to a complex xsd schema with three includes.
These are the steps I follow:
- build an XmlSchemaSet and add 4 schemas to it by calling the following method for each xsd:
private async Task loadSchema(string path, string nameSpace) { byte[] byteArrayS = await _client.GetByteArrayAsync(path); Console.WriteLine($"{path}: {byteArrayS.Length}"); MemoryStream streamS = new MemoryStream(byteArrayS); XmlReader xmlSchemaReader = XmlReader.Create(streamS); schemaSet.Add(nameSpace, xmlSchemaReader); }
- Initializing an event handler with:
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
- loading the XML into an XmlDocument:
byte[] byteArrayX = Encoding.ASCII.GetBytes(await _editorTarget.GetValue()); MemoryStream streamX = new MemoryStream(byteArrayX); XmlReader reader = XmlReader.Create(streamX); XmlDocument document = new XmlDocument(); document.Load(reader);
- validating according to the schemaSet:
document.Schemas = schemaSet; document.Validate(eventHandler);
ssteps 3 and 4 are run inside a Try...Catch block and running locally when the XML is not well formed (missing closing tag for example), the
document.Load(reader);
line produces an error with a message like the following:The 'publicationStmt1' start tag on line 9 position 11 does not match the end tag of 'publicationStmt'. Line 11, position 12.
which is great. But validating a similar situation in the application deployed to Azure produces the following error message:
Xml_MessageWithErrorPosition, Xml_TagMismatchEx, 11, 12
.Schema validation errors are caught in the event handler when the line
document.Validate(eventHandler);
is run and a typical message is:The element 'fileDesc' in namespace 'http://www.tei-c.org/ns/1.0' has invalid child element 'publicationStmt1' in namespace 'http://www.tei-c.org/ns/1.0'. List of possible elements expected: 'editionStmt, extent, publicationStmt' in namespace 'http://www.tei-c.org/ns/1.0'.
But when run on Azure the message is
Sch_InvalidElementContentExpecting
.What could the reason for this difference in the validation results between running locally and in Azure?
I tried to disable linking by adding:
<ItemGroup> <BlazorLinkerDescriptor Include="LinkerConfig.xml" /> </ItemGroup>
But that did not make a difference in the deployed application, and running locally with Release instead of Debug did not change anything either.
I also made sure the 4 xsd files are actually loaded when running from Azure.