Question

Context

I use the ServerManager class to perform some actions on sites.

Actually, I delete bindings (http/https) on a site1 and I recreate it on a site2.

I save changes with .CommitChanges().

After that, the issue is that IIS turns off the site. So I use site2.Start() to restart the site.

But this doesn't work... except if I put a breakpoint on site2.Start().

Any idea of ​​what's going on? Do you have a solution?

Full code (restart in the last line)

var serverManager = new ServerManager();
var regex = new Regex("^(http|https)://");
var host = regex.Replace(url, "");
var instance = serverManager.Sites.First(site => site.Bindings.Any(binding => binding.Host == host));
var pool = instance.Applications[0].ApplicationPoolName;
var bindingHttp = instance.Bindings.First(attr => attr.Host == host && attr.Protocol == "http");
var bindingHttps = !host.Contains("xxx") ? instance.Bindings.First(attr => attr.Host == host && attr.Protocol == "https") : null;
var bindingHttpInformation = bindingHttp.BindingInformation;
var bindingHttpsInformation = !host.Contains("xxx") ? bindingHttps.BindingInformation : null;
var certificateHash = !host.Contains("xxx") ? bindingHttps.CertificateHash : null;
var certificateStoreName = !host.Contains("xxx") ? bindingHttps.CertificateStoreName : null;
var newSiteName = getPoolOrSiteName(pool);
var newSite = serverManager.Sites.First(attr => attr.Name == newSiteName);
var bindingCollection = newSite.Bindings;

instance.Bindings.Remove(bindingHttp);

if (!host.Contains("xxx"))
{
    instance.Bindings.Remove(bindingHttps);

    var binding = newSite.Bindings.CreateElement("binding");
    binding["protocol"] = "https";
    binding["certificateHash"] = certificateHash;
    binding["certificateStoreName"] = certificateStoreName;
    binding["bindingInformation"] = bindingHttpsInformation;
    bindingCollection.Add(binding);
}

var binding2 = newSite.Bindings.CreateElement("binding");
binding2["protocol"] = "http";
binding2["bindingInformation"] = bindingHttpInformation;
bindingCollection.Add(binding2);

serverManager.CommitChanges();

newSite.Start(); //only works if I put a breakpoint here
Was it helpful?

Solution

I think it's a timing issue. It's the same when you stop a site with the IIS Management console and you subsequently try to start it. You have to give it some time to finish stopping. So a (warning: ugly) sleep could probably do:

System.Threading.Thread.Sleep(5000);

The fact that it works when debugging, is because you give it the delay before you proceed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top