How to get app port from IIS Express in C# - c#

I am trying to get The port which an app is running on, from IIS Express.
So far i tried those two approaches:
//first
var iisExpress = new DirectoryEntry("IIS://localhost/W3SVC/AppPools").Children;
//second
var mgr = new ServerManager().Sites;
But both give me only the DefaultAppPool with the Default Web App, while what i need is the apps i'm running localy from Visual Studio.

This will output the names and ports of all your websites running on IIS.
var serverManager = new ServerManager();
foreach (Site site in serverManager.Sites)
{
Console.WriteLine(site.Name);
Console.WriteLine(site.Bindings[0].EndPoint.Port);
}
If you want to save the port of a specific site (ex: MyWebsite) on a variable you can do the following:
var serverManager = new ServerManager();
var mySite = serverManager.Sites.FirstOrDefault(s => s.Name.Contains("MyWebsite"));
int myPort = mySite?.Bindings[0].EndPoint.Port ?? 0;

Related

C# ServerManager, need admin right for IIS

Hi i have some problem with ServerManager in C#
i want to get all sites from IIS
for example:
static ServerManager iismanager = new ServerManager();
foreach (var site in iismanager.Sites)
{
var temp = new ToolStripMenuItem();
temp.Text = site.ToString();
temp.Click += new EventHandler(Change_State);
}
Now if i run this without admin right i got access denied.
So my question ;)
There is any option to force admin right without UAC prompt?

How to get the ApplicationPool object based on a Site in IIS

I've created an application that gets all of my Sites in IIS and checking each URL in Bindings if there's an HTTP error and if a certain error is encountered, my application will reset the IIS Site Instance in IIS, however, it's not enough to fix the error as it should. I would be needing to reset both the Site and the Application pool it belongs to.
Is there any way to get the Application Pool object based on the Site object?
I have tried the code below but this only works if an application pool only has 1 Site/Application in it. The problem is, I don't get the matching App Pool of the Site if I have a number mismatch between the List of Sites vs List of ApplicationPools since 1 AppPool can have multiple Sites/Applications.
ServerManager serverMgr = new ServerManager();
SiteCollection sites;
ApplicationPoolCollection appPools;
public List<(Site, ApplicationPool, string)> getSiteInfo()
{
List<(Site, ApplicationPool, string)> siteInfo = new List<(Site, ApplicationPool, string)>();
List<string> siteUrls = new List<string>();
sites = serverMgr.Sites;
appPools = serverMgr.ApplicationPools;
foreach (Site site in sites)
{
foreach (ApplicationPool appPool in appPools)
{
foreach (Binding binding in site.Bindings)//getting site url
{
string bindingInfo = binding.BindingInformation; // "192.111.1.1:80:google.com" /// *:808:
string[] adrs = bindingInfo.Split(':'); //0 = ip, 1 = port, 2 = hostname
if (adrs[0] == "*")
{
adrs[0] = "localhost";
}
//adding to my list of sites and it's corresponding Application Pool in 1 tuple variable
siteInfo.Add((site, appPool, adrs[0] + ":" + adrs[1] + "/" + adrs[2])); //localhost:80/google.com
}
}
}
return siteInfo;
}
I need something similar to this code: (see comments)
public List<(Site, ApplicationPool, string)> getSiteInfo()
{
List<(Site, ApplicationPool, string)> siteInfo = new List<(Site, ApplicationPool, string)>();
List<string> siteUrls = new List<string>();
sites = serverMgr.Sites;
foreach (Site site in sites)
{
foreach (Binding binding in site.Bindings)
{
//I need something like this to make sure the AppPool I'm getting is of the Site I have.
ApplicationPool appPool = site.ApplicationPoolName;//<-- This Line
string bindingInfo = binding.BindingInformation;
string[] adrs = bindingInfo.Split(':');
if (adrs[0] == "*")
{
adrs[0] = "localhost";
}
//So that I can do this when passing the Site Info tuple Variable with the Site Object together with the corresponding AppPool for later use of the IISReset Class in my project.
siteInfo.Add((site, appPool, adrs[0] + ":" + adrs[1] + "/" + adrs[2]));
}
}
return siteInfo;
}
Sorry for the long and sloppy explanation but I would be happy to clear out if you have questions with this. Thank you.
I figured it out by using Applications attribute of a site. To get the application pool of a Site I did the code below. Where I got the list of applications of a site and used that to identify the app pool from the list of application pools in the server. However this only works if the site only has 1 application, that's why I'm indexing 0(zero) to get the first application (which is the only application of my site) to search for it's corresponding app pool.
ApplicationCollection apps = site.Applications;
ApplicationPool appPool = serverMgr.ApplicationPools[appname[0].ApplicationPoolName];

Why are ASP.NET settings not showing up when I use ServerManager to create site in IIS?

When I create my site using ServerManager for some reason the asp.net settings are not showing up in IIS, but if I manually create the site and point it at the directory everything works fine a I get all the settings. I have been searching for hours trying to figure out what I am doing wrong with no luck.
Here is my code
int sleep = 3000;
Console.WriteLine(#"Installing Connections AD Sync UI\Services...");
//Extract Files
Console.WriteLine(#"Extracting required files...");
FileInfo info = new FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location);
System.IO.File.WriteAllBytes(info.DirectoryName + #"\Payload.zip", ConnectionsADSyncInstaller.Properties.Resources.ConnectionsADSync);
ZipFile.ExtractToDirectory(info.DirectoryName + #"\Payload.zip", info.DirectoryName);
File.Delete(info.DirectoryName + #"\Payload.zip");
Thread.Sleep(sleep);
//Create IIS Site/Settings
ServerManager iisManager = new ServerManager();
Console.WriteLine("Setting up IIS application pool...");
ApplicationPool myApp = iisManager.ApplicationPools.Add("ConnectionsADSync");
myApp.
myApp.AutoStart = true;
myApp.ManagedPipelineMode = ManagedPipelineMode.Integrated;
myApp.ManagedRuntimeVersion = "V4.0";
myApp.ProcessModel.IdentityType = ProcessModelIdentityType.ApplicationPoolIdentity;
myApp.Enable32BitAppOnWin64 = true; //unsure...
Console.WriteLine("Configuring ConnectionsADSync web site in IIS...");
iisManager.CommitChanges();
Thread.Sleep(sleep);
//Give AppPool user permissions
Console.WriteLine("Configuring folder permissions for IIS application pool...");
DirectoryInfo myDirectoryInfo = new DirectoryInfo(info.DirectoryName + #"\ConnectionsADSync\ConnectionsADSyncWeb");
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(#"IIS APPPOOL\ConnectionsADSync", FileSystemRights.ReadAndExecute, AccessControlType.Allow));
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
Thread.Sleep(sleep);
//Create the site
Site newSite = iisManager.Sites.Add("ConnectionsADSync", info.DirectoryName + #"\ConnectionsADSync\ConnectionsADSyncWeb", 8089);//D:\\ConnectionsADSync
newSite.ApplicationDefaults.ApplicationPoolName = "ConnectionsADSync";
newSite.ServerAutoStart = true;
iisManager.CommitChanges();
Thread.Sleep(sleep);
//Install Service
Console.WriteLine("Installing ConnectionsADSyncService (Windows Service)...");
Process proc = Process.Start(info.DirectoryName + #"\ConnectionsADSync\ConnectionsADSyncService\installer.bat");
proc.WaitForExit();
ServiceController service = new ServiceController("~ConnectionSyncServer");
service.Start();
Thread.Sleep(sleep);
Console.WriteLine("Installation complete, press Enter to exit");
Console.ReadLine();
enter code here
ApplicationDefaults is not the right place to set the pool for your web site.
Find the root application from Site.Applications whose path is "/" and then set its ApplicationPoolName to the pool you created earlier.
That can help you associate the proper application pool and it will work just like what you created in IIS Manager.

Assign application pool to website in iis7 programmatically

I'm using the following method to create application pool and assign it to web site.
This is code for application pool creation:
WebSiteName = some website name which existed.
I see that all values are get where they should be in debug mode
private void ConfiugreAppPoolIIS7(targetMachine)
{
var mgr = ServerManager.OpenRemote(targetMachine);
if (AppPoolProp.ContainsKey("SomeTestAppPool"))
{
string reqAppPool = AppPoolProp["SomeTestAppPool"];
if (!mgr.ApplicationPools.Any(pool => pool.Name == reqAppPool))
{
ApplicationPool myApp = mgr.ApplicationPools.Add(reqAppPool);
myApp.AutoStart = true;
myApp.ManagedPipelineMode = ManagedPipelineMode.Classic;
myApp.ManagedRuntimeVersion = "V4.0";
myApp.ProcessModel.IdentityType = ProcessModelIdentityType.NetworkService;
myApp.Enable32BitAppOnWin64 = true;
mgr.CommitChanges();
foreach (Site site in mgr.Sites)
{
if(site.Name == WebSiteName)
{
site.Stop();
site.ApplicationDefaults.ApplicationPoolName = myApp.Name;
site.Start();
mgr.CommitChanges();
}
}
}
}
}
The result is, I see the Aplication pool created successfuly, and the Website created as well, but, I see in the advanced settings of my web site the default appplication pool is assigned.
Could you please help?
The problem has been fixed by fixing reference to right Microsoft.Web.Administration.dll
Cause of this server manage connected to express iis instead of my local iis.

How do I list and create all IIS websites, folders in the websites and virtual web directories in C#

I am trying to first list all the IIS websites and the folders/virtual web directories in each (in a tree view). Then after that I would like to allow the user to select any of the above nodes and create a new virtual web directory there. I can create a virtual web directory if I know the path I plan to use but I cannot get a list of the folders/virtual web directories in a website (I can get the website list).
Use System.DirectoryServices to get the web sites from the IIS. You can find similar discussion at the following URL
http://channel9.msdn.com/forums/TechOff/78084-Extracting-list-of-web-sites-from-IIS-manager/
Funny, I just had a need to do this for IIS 7.5, I created a class IisSiteApplication with the major properties I wanted
using Microsoft.Web.Administration;
public class IisSiteApplicationList : List<IisSiteApplication>
{
public IisSiteApplicationList()
{
ServerManager iisManager = new ServerManager();
SiteCollection sites = iisManager.Sites;
foreach (Site iisSite in sites)
{
foreach (Application iisApp in iisSite.Applications)
{
IisSiteApplication app = new IisSiteApplication
{
SiteId = iisSite.Id,
SiteName = iisSite.Name,
AppName = iisApp.ToString(),
ApplicationPoolName = iisApp.ApplicationPoolName,
Directories =
String.Join(";", iisApp.VirtualDirectories.Select(a => a.PhysicalPath).ToArray())
};
Add(app);
}
}
}
}

Categories