Digital Tool Factory blog - Backend web development in Atlanta GA Digital Tool Factory blog - Backend web development in Atlanta GA

The Digital Tool Factory Blog

How to fix problems with IIS caching, OWIN authentication, Visual Studio and application names

The Setup

I was running painfully low on disk space on my C drive and was working with a Visual Studio solution containing 12 projects. A compilation / build got hung up on something, I cancelled the build tried again. That build worked.

So far just business as usual. However, I noticed that while I was successfully authenticating in the application I was getting bounced as not authenticating by several of the projects, though I was listed as authenticated in other projects. After far too much poking around in the code I discovered that most of the OWIN nuget packages where mysteriously gone and this was causing the problem. Strangely the system was not able to authenticate my login but was able to determine I was not authenticated. I got no actual authentication messages during any of this. This happened in four of the 12 projects. I was rebuilding and cleaning the solution many times throughout all of this.

I nuget installed the proper packages in all four of the projects and three of them worked perfectly. The fourth defied all logic and explanation. After much yelling, screaming and gnashing of teeth I was diagnosing with the below code

<code>        [AllowAnonymous]
        public ActionResult DiagnoseAuthentication()
        {
            var authDetails = new
            {
                TempFileLocation = System.Web.HttpRuntime.CodegenDir,

                CoookeValue = Request.Cookies[".AspNet.ApplicationCookie"]?.Value ?? "No Cookie",// 
                IsAuthenticated = User.Identity.IsAuthenticated,
                UserName = User.Identity.Name,
                AuthenticationType = User.Identity.AuthenticationType,

                // Extract claims safely without circular references
                Claims = ((ClaimsIdentity)User.Identity).Claims.Select(c => new
                {
                    Type = c.Type,
                    Value = c.Value
                }).ToList(),

                // Get roles in a safe manner
                Roles = ((ClaimsIdentity)User.Identity).Claims
                                      .Where(c => c.Type == ClaimTypes.Role)
                                      .Select(c => c.Value)
                                      .ToList(),

                // Additional environment information
                Environment = new
                {
                    MachineName = Environment.MachineName,
                    OSVersion = Environment.OSVersion.ToString(),
                    Is64BitProcess = Environment.Is64BitProcess
                }
            };

            return Json(authDetails, JsonRequestBehavior.AllowGet);
        }

        [AllowAnonymous]
        public object CompareAuthenticationSettings()
        {
            return new
            {
                // Machine Key Details
                MachineKeyValidation = ConfigurationManager.AppSettings["MachineKeyValidation"],

                // Authentication Cookie Settings
                CookieName = FormsAuthentication.FormsCookieName,
                CookiePath = FormsAuthentication.FormsCookiePath,

                // Application Pool


                // Identity Configuration
                IdentityConnectionString = ConfigurationManager.ConnectionStrings["IdentityConnection"]?.ConnectionString,

                // Security Stamp Validation
                SecurityStampValidationInterval = GetSecurityStampInterval()
            };
        }


        private TimeSpan GetSecurityStampInterval()
        {
            // Retrieve security stamp validation interval
            // This is typically configured in Startup.cs or similar
            return TimeSpan.FromMinutes(30); // Example default
        }</code>

Which told me that I was simply not logged in, even though the same code listed me as logged into the other projects.

I then started investigating IIS to see if something was amiss there. I had not changed anything in IIS for over a year so this was unlikely, but one never knows.

A quick look around the general settings found nothing amiss, so I made a copy of the application in the main site to experiment with and to my great surprise that exact copy worked perfectly. The original application contined to not work but {ApplicationName}-Test worked just fine.

I then deleted the original IIS site and recreated the entire site, even creating a new app pool. Somehow there was the same error. I was perplexed and was running out of places to look for solutions. I had rebooted, cache deleted, cleaned solutions and rebuilt solutions many, many times over all this, but I decieded to delete as many caches as possible. I did all that, and added in the

TempFileLocation = System.Web.HttpRuntime.CodegenDir,

line above – just to make sure.

Lo and behold, I saw this

Somehow there were two copies of the compiled code in the relevant temp directory. I’ve never actually seen that with a recent version of IIS/Visual Studio. IIS was picking up the older directory which had the problems and never using the repaired directory. Cleaning the solution and rebuilding should have taken care of the older one but in this case it did not.

I guess the moral of the story is, if there is ever a problem with low disk space make sure you delete the caches manually. I’m writing this up as lengthy post so I can find it again


27
Mar 25


Written By Steve French

 

How to fix problems with Application Pools not starting in IIS manager

How can you fix the problem of the application pool refusing to start and throwing the error message of “The service cannot accept control messages at this time”?

Happily all you have to do is to go to task manager and kill the W3WP process – then restart the app pool.


25
Aug 23


Written By Steve French

 

How to run WordPress on Azure App Service Linux with NGINX

I recently had to start moving my various WordPress sites from the standard App Service to a standard app service on Linux, using NGINX. However, this does not work out of the box. After much googling and experimentation I came across this extremely well written blog post on the topic.

Basically just follow those instructions the letter and all your problems will be solved!

I like to do a little value add on these blog posts, but really the first has everything you need – this post is just to give credit and to find the solution again later.

Update March 23rd, 2023

You do have to add the following to the wpconfig file for it to work – that is the missing link – for some reason when the sites “transition” there is something off about their behavior to ssl – this fixes it

define(‘FORCE_SSL_ADMIN’, true);if (strpos($_SERVER[‘HTTP_X_FORWARDED_PROTO’], ‘https’) !== false)   $_SERVER[‘HTTPS’]=’on’;


20
Mar 23


Written By Steve French

 

Remember to await everything in Playwright and Typescript

I’ve recently fallen madly in love with the PlayWright web testing platform. Seemingly is has all of the strengths of every other testing platform, while being legible, transparent and actually working. However, I was thrown for a week by mystery timeouts, failures and heisenbugs.

The culprit happened when I all of the repeatable steps into components. The components themselves contained nothing but await statements, but I was not awaiting the components themselves. Against all logic, awaiting components that consist of nothing but await statements is necessary for playwright to work properly.


02
Feb 23


Written By Steve French

 

How to fix your web.config files not transforming in Azure Pipelines and Releases

After much sturm and drang I finally found that if you change your build arguements to

msbuildArgs: ‘/p:DeployOnBuild=true  /p:WebPublishMethod=Package  /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true  /p:PackageLocation=”$(build.artifactStagingDirectory)”  /p:AutoParameterizationWebConfigConnectionStrings=false’

And do the the other tips listed on this blog then the web.config files should transform like they are supposed to.


06
Jul 22


Written By Steve French

 

A quick write up to document web config changes when deploying to azure using release pipelines in azure devops

So – you want a step by step guide to deploying web apps to azure web apps from azure devops and changing config files in the release pipelines? Look no further.

First create the new web.config files, as seen below

In the file properties – make sure they are set to “Content” and “Copy Always”

In the pipeline properties – make sure that xml transformation is checked, and that there is the proper value of
-ASPNETCORE_ENVIRONMENT ProdAzure

In Make sure your azure stage has the same name as the web.{name}.config file


04
May 22


Written By Steve French

 

How to Get the ID of the logged in user in asp.net mvc web api apicontroller

After much googling, and evening Bing-ing revealed nothing I discovered that for some reason I had the line

config.SuppressDefaultHostAuthentication();

In my WebAPIConfig.cs file – I removed that and everything magically worked and I could use User.Identity.GetUserId();


28
Feb 22


Written By Steve French

 

Dynamic page redirects in TestCafe

So – you need to redirect to a dynamic page in TestCafe you say? Try the below


const setValue = ClientFunction(() => {
var idToUseForRedirection=document.querySelector(‘input[name=”ID”]’).value;
document.location.href=”https://someurl.com?id=” + idToUseForRedirection;

});

await setValue();


02
Jun 21


Written By Steve French

 

More Test Cafe Goodies

Generating a random string in some logical order

const setValue = ClientFunction(() => {
var dt = new Date();
var dateString =”Steve French Test – ” + dt.getTime();
document.querySelector(‘input[name=”ctl00$CPHSIURate$txtRiskName”]’).value =dateString;
document.querySelector(‘input[name=”ctl00$CPHSIURate$txtRiskName”]’).dispatchEvent(new window.Event(‘change’, { bubbles: true }))
});

await setValue();

as well as

const setValue = ClientFunction(() => { document.querySelector(‘input[name=”CaptchaAgentValueAsSupplied”]’).value = document.querySelector(‘input[name=”CaptchaAgentValue”]’).value;});
await setValue();

to play with dates

const setValue = ClientFunction(() => { var dt = new Date(); dt.setDate( dt.getDate() – 10 ); var dateString = ((dt.getMonth() > 8) ? (dt.getMonth() + 1) : (‘0’ + (dt.getMonth() + 1))) + ‘/’ + ((dt.getDate() > 9) ? dt.getDate() : (‘0’ + dt.getDate())) + ‘/’ + dt.getFullYear(); document.querySelector(‘input[name=”ExpirationDateOfPriorCoverage”]’).value =dateString; document.querySelector(‘input[name=”ExpirationDateOfPriorCoverage”]’).dispatchEvent(new window.Event(‘change’, { bubbles: true }))});
await setValue();


01
Mar 21


Written By Steve French

 

How to change out appsettings.json files upon in an Azure DevOps Release

As I continue to explore Blazor I came across an interesting problem – to wit – how does one change the appsettings.json in an Azure Release? Ideally you would want to use the appsettings.QA.json in your QA environment, your appsettings.Dev.json in your dev environment, etc. I could not find any obvious way of doing this.

Were is regular asp.net mvc 5 I could just name the release stage “QA” and the magic of Azure would do the necessary web.config changes (i.e. change web.qa.config to web.config upon release/publish.)

After writing out an email to a friend to ask him how he would do it I came across the answer – on this elmah.io blog post actually. The key is to add an ASPNETCORE_Environment variable to whatever it is you want your environment to be, i.e. if you have appsettings.PublicDev.json you would just need to add an ASPNETCORE_ENVIRONMENT value of “PublicDev” – then release!


23
Dec 20


Written By Steve French

 




Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.