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.
Related
Solution Explorer
I can get current method name, but currently I can't get really current class name.
From reference: C# getting its own class name, accepted answer is this.GetType().Name.
Test.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string currentMethodName = MethodBase.GetCurrentMethod().Name; // "Page_Load"
string currentClassName1 = this.GetType().Name; // "test_test_aspx" // How to get "Test" only?
string currentClassName2 = this.GetType().FullName; // "ASP.test_test_aspx" // How to get "Test" only?
}
}
}
Try with this:
string className = MethodBase.GetCurrentMethod().DeclaringType.Name;
In my demo solution, I have a two projects DataAccess and WebInterface.
In DataAccess project, I have one EF for Users and a class file UserDataAccessService.cs
Code in UserDataAccessService.cs:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data;
using DataAccess.User;
namespace DataAccess.User
{
public sealed class UserDataAccessService
{
private string efConnectionString;
private string portalConnectionString;
public string ConnectionString
{
get { return efConnectionString; }
}
public UserDataAccessService(string portalConnectionString)
{
this.portalConnectionString = portalConnectionString;
this.efConnectionString = GetConnectionString(portalConnectionString);
}
private string GetConnectionString(string portalConnectionString)
{
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = "System.Data.SqlClient";
entityBuilder.ProviderConnectionString = portalConnectionString;
entityBuilder.Metadata = "res://*/User.ProgramModel.csdl|res://*/User.UserModel.ssdl|res://*/User.UserModel.msl";
return entityBuilder.ToString();
}
public IEnumerable<User> GetUsers(int? userId, bool? status)
{
using (Users objectContext = new Users(efConnectionString))
{
return objectContext.GetUsers(null, null);
}
}
}
}
Now in WebInterface project, I simply have a ManageUsers.aspx page on which I am trying to fetch list of users by below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using DataAccess.User;
namespace WebInterface
{
public partial class ManageUser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UserDataAccessService usrObj = new UserDataAccessService(ConfigurationManager.ConnectionStrings["portalConn"].ToString());
List<User> userLst = new List<User>();
userLst = usrObj.GetUsers(1, null).ToList();
}
}
}
Problem:-
When I am building the solution then I am getting the below error:-
Error 1
The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced.
You must add a reference to assembly 'System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
D:\Practice\PTP\UI\WebInterface\User\ManageUser.aspx.cs
18 13
WebInterface
To fix it, I have included it System.Data.Entity.dll in reference folder of WebInterface project which has fixed the issue.
My Question:
If you look into my the code then you can that code related EF is all in DataAccess project which has all required dll reference in it required for classes related to EF.
and in WebInterface project I have included DataAccess.dll and in it .aspx page I am simply calling it function to the fetch data.
Then why it requires System.Data.Entity.dll in WebInterface project too?
Regards
Varun
I am only 99% sure cause you are using some old school EF :) and you didn't share User class but... I think it's the User class that is EntityFramework aware. Is it the case that User inherits from EntityObject?
You can avoid that by mapping data from entity classes to you UI classes. But that takes all the magic from using EF.
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.
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.