Adding a website to IIS7 on remote machine C# - c#

I currently have an application written in C# that adds a website to IIS7 on the current machine and it works perfectly, the code is as follows
var iisManager = new ServerManager();
var sites = iisManager.Sites;
var site = sites.Add("WebsiteName", "C:\Website", 80);
var application = site.Applications[0];
application.ApplicationPoolName = appPool;
iisManager.CommitChanges();
I have to create a version of this code that will add a website to IIS on a remote machine located on the same network. That code is as follows.
var iisManager= ServerManager.OpenRemote("machineName"); //I've also tried machines IP
var sites = iisManager.Sites["Default Web Site"];
var site = Sites.Applications.Add("WebsiteName", "C:\Website", 80);
site.ApplicationPoolName = appPool;
iisManager.CommitChanges();
When machineName is the machine executing the code, it adds the website to IIS. However when machineName is the remote machine, I get the following exception
Retrieving the COM class factory for remote component with CLSID {2B72138B-3F5E-4502-8052-803546CE3364} from "remote machine name" failed due to the following error: 80070005 "remote machine"
The exception occurs when executing
var iisManager= ServerManager.OpenRemote("machineName");
Before executing the above code I use impersonation to impersonate an Administrator.
I can remote into the machine and even create a file on the machine using C# code.
I assume there is an issue with permissions on the remote machine or it could be because it's a VM, I'm really not sure.
The code 80070005, is fairly general and represents restricted access but I don't understand why considering I am impersonating an Admin.
I am executing the code on a Windows 7 sp1 x64 machine and the remote VM is running Windows Server 2008 sp2 x64.
If anyone has any ideas how to fix this issue or another way to add a website to IIS on a remote machine, I'd love to hear them.
Thanks

First of all you run your visual studio as administrator and OFF windows firewall of server then see it will work for Remote server

Related

How do I troubleshoot Microsoft.Windows.Storage.StorageException:The remote name could not be resolved

I am troubleshooting why a particular computer started getting this exception yesterday with code it regularly runs.
I created the following test to reproduce the problem
var account =
CloudStorageAccount.Parse(
$"DefaultEndpointsProtocol=https;AccountName={accountName};" +
$"AccountKey={accountKey}");
var client = account.CreateCloudBlobClient();
var conref = client.GetContainerReference(containerRef);
var blobref = conref.GetBlockBlobReference(filename);
blobref.DownloadToFile(fullDownloadName, FileMode.Create);
On a good pc running windows 2012 Server Release 2 ,the file downloads
On the bad pc running windows 8.1 only a zero length empty file creates
I rebooted the bad PC.
What else can I try?
both pcs have internet access.
Console.WriteLine($"DefaultEndpointsProtocol=https;AccountName={accountName};" + $"AccountKey={accountKey}")
looks the same on both pcs.
The test console app references WindowsAzure.Storage 9.3.2
I am installing the console app via file copy.
Here are the files
[Update]
I am trying to install the client tools from https://learn.microsoft.com/en-au/cli/azure/install-azure-cli?view=azure-cli-latest
I have a this site can't be reached error.
We changed the local DNS to 1.1.1.1
then ran IPConfig /flushdns
then my test started working.
However having the DNS server not be the domain server was problematic ( access errors )
So then we changed the local DNS back to the domain server and set the secondary DNS to 1.1.1.1
Rebooted the domain server and the box

Retrieve Credentials from Windows generic Credentials Store using C# in ASP.net website under IIS

Retrieve Credentials from Windows Credentials Store problem using C# in ASP.net website under IIS I am using following code
Local machine and windows 10 IIS its working fine. but when i try to hosting in windows server 2012 R2 not working.
My code:
var cm = new Credential();
cm.Target = "targetname";
cm.Type = CredentialType.Generic;
if (!cm.Exists())
{
Console.WriteLine("cm is null");
}
cm.Load();
Console.WriteLine(cm.Password);
Console.WriteLine(cm.Username);
Above code running on windows server 2012 R under IIS. But above code is not able to retrieve username and password.(cm is null always) I used same code in my console application and works fine. Please let me know any special instruction need to follow.
You should switch "Load User Profile" parameter of IIS App Pool to true. Then your code should start working.

Programmatically creating a remote site in IIS7 using Microsoft.Web.Administration: Invalid index. (Exception from HRESULT: 0x80070585)

I'm trying to write a provisioning tool for our web application. I am attempting to create a web site remotely in IIS7.5 using Microsoft.Web.Administration.ServerManager.
CODE:
using (ServerManager serverManager = ServerManager.OpenRemote("MyRemoteHost")) {
serverManager.Sites.Add("Contoso", "http", "*:80:www.contoso.com", #"C:\inetpub\wwwroot\Contoso");
serverManager.CommitChanges();
}
The above code continuously fails with error: Invalid index. (Exception from HRESULT: 0x80070585)
NOTES:
If I run this code locally on the host, I do not encounter the error and the web site is created successfully.
My user has administrative privileges on the remote host.
I am able to perform other operations on the remote host such as reading the listing of sites.
My workstation is running Windows 8
I've managed to successfully execute the above mentioned code against a Server 2012 host. There appears to be some sort of incompatibility when running this code on a Windows 8 client against a Server 2008R2 host.
I'm using Microsoft.Web.Administration.7.0.0.0.
Any help in resolving this issue would be greatly appreciated.
Thank you
I was having the same issue too by using a remote serverManager object connected to my target server on a very large, heavily regulated corporate network.
After some investigation however, it turned out that the website WAS being created on that specific instance of server manager and, despite the error comming back, using the .CommitChanges(); method on that serverManager object would succesfully save the new website.
var serverManager = ServerManager.OpenRemote("ServerName");
var sites = string.Join(";", serverManager.Sites.Select(o => o.ToString()));
Console.WriteLine(sites);
try
{
serverManager.Sites.Add("newWebSite", #"D:\TestSite", 80);
}
catch ( Exception e )
{
Console.WriteLine(e);
}
Console.WriteLine(string.Join(";", serverManager.Sites.Select(o => o.ToString())));
Console.WriteLine(string.Join(";", ServerManager.OpenRemote("ServerName").Sites.Select(o => o.ToString())));
serverManager.CommitChanges();
Console.WriteLine(string.Join(";", ServerManager.OpenRemote("ServerName").Sites.Select(o => o.ToString())));
Console.ReadLine();
Using this sample code, the catch was not hit, indicating that the program still worked and I can clearly see the website added to the remote server in both the original instance of the serverManager and the new one I created.
The Console returned this:
CopyOfLive;Default Web Site
CopyOfLive;Default Web Site;newWebSite
CopyOfLive;Default Web Site
CopyOfLive;Default Web Site;newWebSite
Furthermore, checking IIS on the server proved that the website had been created.
I hope this helps!

Control IIS 7 server from Windows 2003 server programmatically

We run various jobs using a Windows 2003 server. Some of these jobs send app pool commands to web servers running IIS 6 (recycle, start, stop). Now we have a Windows 2008 web server running IIS 7, and we want to send the same commands. This is all done using C#.
This is the code we use to send commands for IIS 6:
var methodToInvoke = "Stop"; // could be "Stop", "Start", or "Recycle"
var co = new ConnectionOptions
{
Impersonation = ImpersonationLevel.Impersonate,
Authentication = AuthenticationLevel.PacketPrivacy
};
var objPath = string.Format("IISApplicationPool.Name='W3SVC/AppPools/{0}'", appPoolName);
var scope = new ManagementScope(string.Format(#"\\{0}\root\MicrosoftIISV2", machineName), co);
using (var mc = new ManagementObject(objPath))
{
mc.Scope = scope;
mc.InvokeMethod(methodToInvoke, null, null);
}
This code doesn't work for IIS 7 due to underlying changes, so we're currently trying this:
using (ServerManager serverManager = ServerManager.OpenRemote(machineName))
{
var appPool = serverManager.ApplicationPools[appPoolName];
if (appPool != null)
{
appPool.Stop(); // or app.Start() or app.Recycle()
serverManager.CommitChanges();
}
}
The above code works fine on my workstation, which runs Windows 7 (and, thus, IIS 7.5). However, it does not work when I deploy this code to our application server. It get this error:
System.InvalidCastException:
Unable to cast COM object of type 'System.__ComObject' to interface type
'Microsoft.Web.Administration.Interop.IAppHostWritableAdminManager'.
This operation failed because the QueryInterface call on the COM component for the
interface with IID '{FA7660F6-7B3F-4237-A8BF-ED0AD0DCBBD9}' failed due to the following error:
Interface not registered (Exception from HRESULT: 0x80040155).
From my research, this is due to the fact that IIS 7 is not available on the Windows Server 2003 server. (I did include the Microsoft.Web.Administration.dll file.)
So my questions are:
Is it possible for the above code for IIS 7 to work at all from a Windows 2003 server?
If no to #1, is there a better way of doing this?
From reading around it doesn't appear to be possible to do what you're looking for. It's not enough to include the dll files.
According to http://forums.iis.net/t/1149274.aspx..
In order to use Microsoft.Web.Administration you need to have IIS installed, at the bare minimum you need to install the Configuration API's which are brought through installing the Management Tools.
Unfortunately there is no SDK that enables this and it has several dependencies on other components that wouldn't let you just take it to another machine and make it work (such as COM objects, DLL's, etc).
I'd be interested in knowing if you've found a way round this.
Thanks
Try controlling the IIS pool with DirectoryEntry instead.
See this topic:
Check the status of an application pool (IIS 6) with C#
Microsoft.Web.Administration, it relies on System.Web.dll which was provided by framework 4, not client profile.

How to programmatically connect to IIS 7

I am trying to connect to IIS programmatically. I find there are a ton of examples online, but I can't seem to get any to work and have tried quite a few variations
Every time I try the following code the object that is returned has this error for each property: ..."threw an exception of type 'System.Runtime.InteropServices.COMException'"
using System.DirectoryServices;
String serverName = "serverName";
DirectoryEntry IIS = new DirectoryEntry("IIS://" + serverName + "/W3SVC");
IIS = new DirectoryEntry("IIS://" + serverName + "/W3SVC", "administrator", "mypassword");
IIS = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/ROOT", "administrator", "mypassword");
I am using Windows Directory user accounts and I have a bunch of sites running on IIS. I am trying this code on a windows xp development machine trying to connect to a windows 2008 Server with IIS 7. Anyone know what I am doing wrong?
Your account may not have launch permissions on the COM object wrapping the IIS calls. You may need to try adding yourself to the admin group on the box hosting IIS to get this to work.
Make sure you have the IIS6 management compatibility feature installed on the target server- you can't do remote management via ADSI on IIS7 without it.
Make sure that IIS is installed on your client machine - your program will throw a System.Runtime.InteropServices.COMException if it isn't installed.
This counts when you are looking at IIS on a remote machine too, the machine running your app will need IIS too.
EDIT: Also, I've recently discovered an assembly specifically for connecting to and configuring IIS7 - Microsoft.Web.Administration. Might be worth looking at whether you have access to this (or can get access, it should be on the machine with IIS7 in any case) and see what it can do. I'm afraid I've not used it myself, so I can't tell you if it'll do what you want, but it's another option to look into.
Finally, there's the option of System.Management and WMI scripts.
Dim scope As New Management.ManagementScope("\\" & server & "\root\MicrosoftIISv2")
scope.Connect()
Dim query As New Management.ObjectQuery("select * from IISWebVirtualDirSetting")
Dim searcher As New Management.ManagementObjectSearcher(scope, query)
For Each obj As Management.ManagementObject In searcher.Get()
DoSomethingWith(obj)
Next
The list of properties on obj is at http://msdn.microsoft.com/en-us/library/ms525005.aspx, there's also some more different queries you can run - just dig around on MSDN for more.

Categories