I am wondering if there is a way to enumerate the collection of applications pools (not the applications in a given pool - but the pools themselves) on the local IIS server using ASP.net 3.5 without the use of WMI, and if so can someone provide a link or example to how this is done?
(I forgot to add the IIS version is 6.0).
Another way that might be helpful.
using System.IO;
using Microsoft.Web.Administration;
namespace AppPoolEnum
{
class Program
{
static void Main(string[] args)
{
foreach (var appPool in new ServerManager().ApplicationPools)
{
Console.WriteLine(appPool.Name);
}
}
}
}
This should help:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
namespace AppPoolEnum
{
class Program
{
static void Main(string[] args)
{
DirectoryEntries appPools =
new DirectoryEntry("IIS://localhost/W3SVC/AppPools").Children;
foreach (DirectoryEntry appPool in appPools)
{
Console.WriteLine(appPool.Name);
}
}
}
}
I should also add this won't work in partial trust.
Related
I am trying to use hangfire as windows service by using Topshelf in console app .net core 2.2 . I just want to load hangfire dashboard, not adding any job or anything else.
Program.cs
using System;
using Topshelf;
namespace HangfireAsService
{
class Program
{
static void Main(string[] args)
{
HostFactory.Run(config =>
{
config.Service<Bootstrap>(service =>
{
service.ConstructUsing(s => new Bootstrap());
service.WhenStarted(s => s.Start());
service.WhenStopped(s => s.Stop());
});
config.RunAsLocalSystem();
config.SetDescription("Hangfire as windows Service for DataCrawling Project");
config.SetDisplayName("Hangfire Service Custom");
});
}
}
}
Bootstrap.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Owin.Hosting;
namespace HangfireAsService
{
public class Bootstrap
{
private IDisposable _host;
public void Start()
{
var options = new StartOptions { Port = 8999 };
_host = WebApp.Start<Startup>(options);
Console.WriteLine();
Console.WriteLine("Hangfire has started");
Console.WriteLine("Dashboard is available at http://localhost:8999/hangfire");
Console.WriteLine();
}
public void Stop()
{
_host.Dispose();
}
}
}
Startup.cs
using Hangfire;
using Microsoft.AspNetCore.Builder;
using Owin;
using System;
using System.Collections.Generic;
using System.Text;
namespace HangfireAsService
{
public class Startup
{
public void Configuration(IApplicationBuilder appBuilder)
{
GlobalConfiguration.Configuration
.UseSqlServerStorage("Server=111.111.11.1\\INS2017; Database=Hangfire; user=sa;
password=;");
appBuilder.UseHangfireDashboard();
appBuilder.UseHangfireServer();
}
}
}
As you can see, I created 2 classes for my self-host owin and after reviewing the event viewer I got the error displayed below:
The description for Event ID 0 from source HangfireAsService cannot be
found. Either the component that raises this event is not installed on
your local computer or the installation is corrupted. You can install
or repair the component on the local computer.
If the event originated on another computer, the display information
had to be saved with the event.
The following information was included with the event:
Service cannot be started. System.NullReferenceException: Object
reference not set to an instance of an object. at
Microsoft.Owin.Hosting.Utilities.SettingsLoader.FromConfigImplementation..ctor()
at
Microsoft.Owin.Hosting.Utilities.SettingsLoader.<>c.b__1_0()
at System.Threading.LazyInitializer.EnsureInitializedCore[T](T&
target, Func1 valueFactory) at
Microsoft.Owin.Hosting.Utilities.SettingsLoader.LoadFromConfig(IDictionary2
settings) at
Microsoft.Owin.Hosting.Engine.StartContext..ctor(StartOptions options)
at
Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions
options) at
Microsoft.Owin.Hosting.Starter.HostingStarter.Start(StartOptions
options) at HangfireAsService.Bootstrap.Start() in
C:\MyWorkSpace\Data
Crawling\dataCrawlingConsole\HangfireAsService\Bootstrap.cs:line 17
at HangfireAsService.Program.<>c.b__0_3(Bootstrap s) in
C:\MyWorkSpace\Data
Crawling\dataCrawlingConsole\HangfireAsService\Program.cs:line 15
at
Topshelf.ServiceConfiguratorExtensions.<>c__DisplayClass2_01.<WhenStarted>b__0(T
service, HostControl control) at
Topshelf.Builders.DelegateServiceBuilder1.DelegateServiceHandle.Start(HostControl
hostControl) at
Topshelf.Runtime.Windows.WindowsServiceHost.OnStart(String[] args)
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object
state)
The message resource is present, but the message was not found in the message table.
i used same code inside .net framework instead of .net core and work perfectly.after a test something else i notice this problem because of OWIN happened so after i removed it and use using .net core self-host instead of OWIN everything work perfectly.
below link will help you a lot.
https://medium.com/#tocalai/create-windows-service-using-net-core-console-application-dc2f278bbe42
I have used System.DirectoryServices.ActiveDirectory but when I tried to use Domain.Name or Domain.GetDomain methods, I get an error
'Domain' does not contain a definition for 'GetDomain'.
Here's my code:
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.DirectoryServices.ActiveDirectory;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DirectoryContext s = new DirectoryContext(DirectoryContextType.Domain, "my domain", "myuser", "mypass");
Domain domain = Domain.GetDomain(s);
Forest forest = domain.Forest;
DomainCollection domains = forest.Domains;
foreach (Domain objDomain in domains)
{
Response.Write(objDomain.Name.ToString());
Response.Write("<br/>");
}
}
}
What's the problem?
According to MSDN, GetDomain() is a static method, which means it cannot be accessed outside of a static context - that is why you're getting that particular error. To prove this was the case, I just copied and pasted your code into a console app, which by default will be run from a static void method called Main() :
using System;
using System.DirectoryServices.ActiveDirectory;
namespace LDAPTEST
{
public class Program
{
static void Main(string[] args)
{
DirectoryContext s = new DirectoryContext(DirectoryContextType.Domain, "DC=hq,DC=xxxxxxxxx,DC=com", "TestUsername", "TestPassword");
Domain domain = Domain.GetDomain(s);
Forest forest = domain.Forest;
DomainCollection domains = forest.Domains;
foreach (Domain objDomain in domains)
{
Console.Write("");
}
}
}
}
This will compile and run. However, since you're developing an Asp.Net web application, I would advise using the lower level System.DirectoryServices.Protocols or even the System.DirectoryServices.AccountManagement namespace to accomplish your task.
I' trying to do port forwarding. I've done following:
NATUPNPLib.dll was added to references
NATUPNPLib was added to using section of page
Following codes were written
But a null reference exception thrown
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Net.Sockets;
using System.Net;
using NATUPNPLib;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
UPnPNATClass upnpnat = new UPnPNATClass();
IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection;
foreach (IStaticPortMapping map in mappings)
{
Console.WriteLine(map.ExternalIPAddress);
}
Console.ReadKey();
}
}
}
How can I overcome this problem?
I am trying to use ManagementEventWatcher in a service to keep track of when a computer goes in and out of sleep mode. I am new to .NET and C# so I am struggling quite a bit to come up with syntax to make this work.
I have found a blog post that details how he used ManagementEventWatcher to keep track of this status, but he did not post up his entire code. I am trying to go through and make a simple service that creates a .txt log file stating that the computer has been suspended/resumed but am running into problems with the namespaces and types.
Here is the code to the service.cs file:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Management;
namespace SleepNotifierService
{
public class WqlEventQuery : EventQuery { }
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WqlEventQuery query = new WqlEventQuery("Win32_PowerManagementEvent");
_watcher = new ManagementEventWatcher(query);
_watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
_watcher.Start();
}
protected override void OnStop()
{
_watcher.Stop();
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
try
{
int eventType = Convert.ToInt32(e.NewEvent.Properties["EventType"].Value);
switch (eventType)
{
case 4:
Sleep();
break;
case 7:
Resume();
break;
}
}
catch (Exception ex)
{
//Log(ex.Message);
}
}
public void Sleep()
{
}
public void Resume()
{
}
}
}
Again, this is the first time that I am programming with .NET and C# so I apologize for my ignorance.
I am getting namespace errors such as:
The type or namespace name
'ManagementEventWatcher' could not be
found (are you missing a using
directive or an assembly reference?)
Thanks,
Tomek
You need the System.Management namespace, which is included in the code sample provided by you. I believe you need to reference the System.Management library in your project settings. Follow the following steps to do this( I am assuming you are suing Visual Studio):
Go to the Solution Explorer, and expand your project, right click on the References folder/option and select Add References from the context menu. Now select the .Net tab and select the System.Management from the list and click OK.
I'm experimenting with MEF and created a test program to call "plugins" that implement some given interface, which follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProbeContract
{
public interface IProbe
{
int DoProbe(string what);
List<string> GetCapabilities();
}
}
I created a sample console program which loads the "plugins" from its own assembly and, if any found, from a diretory in which one puts additional DLLs. The program works OK whether the plugins directory is empty (only the "native" plugins are called) or it has compatible DLLs to start with. BUT... if a new DLL is added between loop iterations, the Refresh() method of DirectoryCatalog throws a ChangeRejectedException, which is explained thusly:
The composition remains unchanged. The
changes were rejected because of the
following error(s): The composition
produced a single composition error.
The root cause is provided below.
Review the CompositionException.Errors
property for more detailed
information.
1) Change in exports prevented by
non-recomposable import
'MEFTest.Program.ProberSet
(ContractName="ProbeContract.IProbe")'
on part 'MEFTest.Program'.
The program is below, follow by the code for the DLL I try to add. What am I doing wrong?
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProbeContract;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace MEFTest
{
class Program
{
[ImportMany]
IEnumerable<IProbe> ProberSet { get; set; }
CompositionContainer exportContainer;
DirectoryCatalog pluginCatalog;
AggregateCatalog catalog;
private void Run()
{
catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
string myExecName = Assembly.GetExecutingAssembly().Location;
string myPath = Path.GetDirectoryName(myExecName);
pluginCatalog = new DirectoryCatalog(myPath + "/Plugins");
catalog.Catalogs.Add(pluginCatalog);
exportContainer = new CompositionContainer(catalog);
CompositionBatch compBatch = new CompositionBatch();
compBatch.AddPart(this);
compBatch.AddPart(catalog);
exportContainer.Compose(compBatch);
for (; ; )
{
Console.Write("Press any key to run all probes: ");
Console.ReadKey(true);
Console.WriteLine();
pluginCatalog.Refresh();
foreach (var Prober in ProberSet)
{
Prober.DoProbe("gizmo");
}
}
}
static void Main(string[] args)
{
Program p = new Program();
p.Run();
}
}
}
The plugin. The other two plugins are similar, the only difference being they reside in the same assembly as the main program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using ProbeContract;
namespace OtherProbes
{
[Export(typeof(IProbe))]
public class SpankyNewProber : IProbe
{
public int DoProbe(string what)
{
Console.WriteLine("I'm Spanky and New and I'm probing [{0}]", what);
return 0;
}
public List<string> GetCapabilities()
{
List<string> retVal = new List<string>();
retVal.Add("spanky");
retVal.Add("new");
return retVal;
}
}
}
I'm assuming you are using MEF preview 6 because you are seeing rejection exceptions. The reason you are seeing the change being rejected is because your ProberSet is not recomposable. Try changing your ProberSet import to:
[ImportMany(AllowRecomposition=true)]
IEnumerable<IProbe> ProberSet { get; set; }
Doing so will allow for new IProbe exports to be introduced into the Catalog/Container after this import has already been composed.
The idea here is that once you get a stable composition we reject any changes that could potentially destablize that composition and in your case you stated you want a set of non-recomposable IProbe objects so adding new IProbe's after it was intially set would violate that requirement.