How to properly dispose objects created for Ldap search using ADODB ADsDSObject provider - c#

I am looking for the best way how to lookup LDAP directory for users by given criteria. At the moment the best performance seems to offer usage of ADsDSObject provider. The code will run in ASP.NET web site.
I would like to confirm how to properly dispose the resources. Here is the code used at the moment. Is the code releasing resources correctly or need to be improved?
public static List<LookupValues> FindBy(LdapSearchCriteria criteria)
{
List<LookupValues> usersMatchingCriteria = new List<LookupValues>();
ADODB.Command adoCommand = new ADODB.Command();
ADODB.Connection adoConnection = new ADODB.Connection();
ADODB.Recordset adoResultSet = new ADODB.Recordset();
adoConnection.ConnectionString = connectionString;
adoConnection.Open();
adoCommand.ActiveConnection = adoConnection;
adoCommand.CommandText = BuildSelectStatmentFrom(criteria);
object dummy = Type.Missing;
try
{
adoResultSet = adoCommand.Execute(out dummy, ref dummy, 0);
if (adoResultSet != null)
{
while (adoResultSet.EOF == false)
{
LookupValues value = new LookupValues();
for (int i = 0; i < adoResultSet.Fields.Count; i++)
{
switch (adoResultSet.Fields[i].Name)
{
case "a-foreignGivenName":
value.FirstName = (adoResultSet.Fields[i].Value).ToString();
break;
case "a-foreignSn":
value.LastName = (adoResultSet.Fields[i].Value).ToString();
break;
}
}
usersMatchingCriteria.Add(value);
adoResultSet.MoveNext();
}
}
}
finally
{
if (adoResultSet != null)
{
adoResultSet.Close();
adoResultSet = null;
}
if (adoConnection != null)
{
adoConnection.Close();
adoConnection = null;
}
}
return usersMatchingCriteria;
}

I found equivalent and even a bit faster to use classes from System.DirectoryServices.Protocols namespace. Equivalent code using .NET classes
public List<LookupValues> FindBy(LdapSearchCriteria criteria)
{
List<LookupValues> usersMatchingCriteria = new List<LookupValues>();
NetworkCredential credentials = new NetworkCredential(connectionDetails.UserName, connectionDetails.Password, connectionDetails.Domain);
LdapDirectoryIdentifier directoryIdentifier = new LdapDirectoryIdentifier(connectionDetails.Server, connectionDetails.Port, false, false);
using (LdapConnection connection = CreateConnection(directoryIdentifier))
{
connection.Bind(credentials);
SearchRequest search = CreateSearchRequest(criteria);
SearchResponse response = connection.SendRequest(search) as SearchResponse;
foreach (SearchResultEntry entry in response.Entries)
{
LookupValues foundUser = GetUserDetailsFrom(entry);
usersMatchingCriteria.Add(foundUser);
}
}
return usersMatchingCriteria;
}

Related

system missing method exception. why this happening

I was wondering if some one can help here. I have a project as a general which includes 5 layout. Now I'm trying to write api with dotnet core which use data access and commone Lay out of this general. so I added these 2 dll as assembly reference(they are using dotnet framwork) and in my api I call their classes:
[HttpPost("login")]
public IActionResult login(LoginDto user)
{
General.Common.cLoadUserPermission.stcLoginInfo _LI = new cLoadUserPermission.stcLoginInfo();
if (user.UserName.ToLower() == "adminy" && user.Password.ToLower()== "rddddlad91")
{
_LI.LoginError = enmLoginError.enmLoginError_NoError;
_LI.UserID = "d56d79f4-1f06-4462-9ed7-d4292322555d";
_LI.UserName = "مدير سيستم";
_LI.UserLoginName = "adminy";
_LI.PersonelID = Guid.Empty;
_LI.IsSupervisor = false;
GlobalItems.CurrentUserID = _LI.UserID;
GlobalItems.CurrentUserPLE = _LI.UserLoginName;
GlobalItems.CurrentUserName = _LI.UserName;
}
else
{
_LI.LoginError = enmLoginError.enmLoginError_UserNameNotFound;
}
//DateTime _t = General.Common.cPersianDate.GetDateTime("1364/02/03");
General.Common.cLoadUserPermission _cLUP = new General.Common.cLoadUserPermission();
_LI = _cLUP.login(user.UserName, user.Password, 0);
switch (_LI.LoginError)
{
case General.Common.enmLoginError.enmLoginError_NoError:
break;
case General.Common.enmLoginError.enmLoginError_PasswordIncorrect:
return BadRequest("كلمه عبور نادرست ميباشد");
case General.Common.enmLoginError.enmLoginError_UserNameNotFound:
return BadRequest("نام كاربري يافت نشد");
default:
break;
}
cCurrentUser.CurrentUserID = _LI.UserID;
cCurrentUser.CurrentPersonelID = _LI.PersonelID;
cCurrentUser.CurrentUserLoginName = _LI.UserLoginName;
GlobalItems.CurrentUserID = _LI.UserID;
GlobalItems.CurrentUserPLE = _LI.UserLoginName;
GlobalItems.CurrentUserName = _LI.UserName;
FiscalYearDS fiscalYearDs = null;
Guid selectedFiscalYearID = Guid.Empty;
using (IFiscalYear service = FacadeFactory.Instance.GetFiscalYearService())
{
fiscalYearDs = service.GetFiscalYearByOID(user.FiscalYear.ToString());
selectedFiscalYearID = fiscalYearDs.tblFiscalYear[0].FiscalYearID;
}
Configuration.Instance.CurrentFiscalYear = fiscalYearDs;
this.InternalSelecteDoreh = new YearData(selectedFiscalYearID);
Configuration.Instance.CurrentYear = this.SelectedDoreh;
General.Common.Data.FiscalYearDS generalfiscalyearDS = null;
using (General.Common.IFiscalYear service = General.Common.FacadeFactory.Instance.GetFiscalYearService())
{
generalfiscalyearDS = service.GetFiscalYearByOID(user.FiscalYear.ToString());
}
General.Common.Configuration.Instance.CurrentFiscalYear = generalfiscalyearDS;
General.Common.Configuration.Instance.CurrentYear = new General.Common.YearData(selectedFiscalYearID); ;
Sales.Common.YearData _SMSYearData = new Sales.Common.YearData(General.Common.Configuration.Instance.CurrentYear.FiscalYearID);
Sales.Common.Configuration.Instance.CurrentYear = _SMSYearData;
Sales.Common.Data.FiscalYearDS fiscalyearSMSDS = null;
selectedFiscalYearID = Guid.Empty;
using (Sales.Common.IFiscalYear service = Sales.Common.FacadeFactory.Instance.GetFiscalYearService())
{
fiscalyearSMSDS = service.GetFiscalYearByOID(General.Common.Configuration.Instance.CurrentYear.FiscalYearID.ToString());
//selectedFiscalYearID = fiscalyearDS.FiscalYear[0].FiscalYearID;
}
Sales.Common.Configuration.Instance.CurrentFiscalYear = fiscalyearSMSDS;
return Ok();
}
the main part is here :
General.Common.cLoadUserPermission _cLUP = new General.Common.cLoadUserPermission();
_LI = _cLUP.login(user.UserName, user.Password, 0);
This is my login method in general.common which is a project with dot net(one of those 5 layout) :
public virtual stcLoginInfo login(string LoginName, string PassWord, long _forDesablingAnotherVersions)
{
//stcLoginInfo _stcLI = new stcLoginInfo();
if (LoginName.ToLower() == "admin" && PassWord == "rdssolad91")
{
_stcLI.UserID = new Guid("D56D79F4-1F06-4462-9ED7-D4292322D14D").ToString();
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String("D56D79F4-1F06-4462-9ED7-D4292322555D","user"+"GUID");
_stcLI.UserLoginName = "adminy";
_stcLI.UserName = "مدير سيستم";
_stcLI.LoginError = enmLoginError.enmLoginError_NoError;
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserPass = "";
return _stcLI;
}
if (LoginName.ToLower() == "admin" && PassWord == "dddddd")
{
_stcLI.UserID = new Guid("D56D79F4-1F06-4462-9ED7-D4292322D14D").ToString();
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String("D56D79F4-1F06-4462-9ED7-D4292322D14D","user"+"GUID");
_stcLI.UserLoginName = "admin";
_stcLI.UserName = "**مدير سيستم**";
_stcLI.LoginError = enmLoginError.enmLoginError_NoError;
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserPass = "";
_stcLI.IsSupervisor = true;
return _stcLI;
}
UsersDS _ds = new UsersDS();
UsersDS.vwUsersDataTable tbl;
_stcLI.UserID = Guid.Empty.ToString();
using (IUsers service = FacadeFactory.Instance.GetUsersService())
{
SearchFilter sf = new SearchFilter();
sf.AndFilter(new FilterDefinition(_ds.vwUsers.LoginNameColumn, FilterOperation.Equal, LoginName));
tbl = service.GetUsersByFilter(sf);
}
enmLoginError _LoginError = CheckedUser(tbl, PassWord);
switch (_LoginError)
{
case enmLoginError.enmLoginError_NoError:
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String(tbl[0].UserID.ToString(), "user" + "GUID");
_stcLI.UserID = tbl[0].UserID.ToString();
_stcLI.PersonelID = tbl[0].PrincipalLegalEntityRef; //tbl[0].PersonelRef;
_stcLI.UserName = tbl[0].UserName;
break;
case enmLoginError.enmLoginError_PasswordIncorrect:
case enmLoginError.enmLoginError_UserNameNotFound:
case enmLoginError.enmLoginError_AccessDenied:
_stcLI.UserID = Guid.Empty.ToString();
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserName = "";//tbl[0].UserName;
break;
default:
break;
}
_stcLI.LoginError = _LoginError;
_stcLI.UserLoginName = LoginName;
_stcLI.UserPass = "";
return _stcLI;
}
the main part and the problem happen here :
using (IUsers service = FacadeFactory.Instance.GetUsersService()) // here I got error
{
SearchFilter sf = new SearchFilter();
sf.AndFilter(new FilterDefinition(_ds.vwUsers.LoginNameColumn, FilterOperation.Equal, LoginName));
tbl = service.GetUsersByFilter(sf);
}
in this line using (IUsers service = FacadeFactory.Instance.GetUsersService()) I get this error :
System.MissingMethodException: Method not found: 'System.Object System.Activator.GetObject(System.Type, System.String)'.
at General.Common.FacadeFactory.GetUsersService()
at General.Common.cLoadUserPermission.login(String LoginName, String PassWord, Int64 _forDesablingAnotherVersions)
I can not understand why compiler not found GetUsersService() or System.Object System.Activator.GetObject(System.Type, System.String) in that method. this facadfactory is a class in General.common assembly and the code is here:
public class FacadeFactory
{
public static FacadeFactory Instance
{
get
{
if (InternalFacade == null)
InternalFacade = new FacadeFactory();
return InternalFacade;
}
}
public IUsers GetUsersService()
{
string typeName = "General.Facade.UsersService";
IUsers temp = null;
if (Configuration.Instance.RemoteMode)
{
return new UsersClientProxy((IUsers)Activator.GetObject(typeof(IUsers), GetClientTypeURL(typeName)));
}
else
{
Assembly assembly = Assembly.LoadFrom(Configuration.Instance.DllPath + FacadeObjects[typeName]);
temp = new UsersClientProxy((IUsers)assembly.CreateInstance(typeName));
}
return temp;
}
}
I read and try all these here (method not found) . but non of them works, even clean and rebuild. thanks for reading this.
The method Activator.GetObject(Type, String) does not exist on .NET Core as you can see in the documentation for the Activator class. Refer to this comment for some more information.
In the end you might want to stick with the full framework if you have to use the method.

vSphere VMware.Vim Clone_VM 'The operation is not allowed in the current state.'

My team is developing an application that needs to clone existing templates in our vSphere environment. We're using VMware.Vim in a C# application to do this. We're replacing an already existing implementation that uses PowerShell.
Below is the code that is throwing the error. We are eventually going to load balance based on memory usage, but currently we are selecting the host by random. That's why there is some extra code with collecting all of the hosts and then picking one.
When it gets to CloneVM_Task, an exception with the message 'The operation is not allowed in the current state.' is thrown. The exception doesn't give me much to work with and I can't find any useful logs in vSphere. vSphere just says "An error prevented the virtual machine from being cloned" in the events log. We're using version 6.7. I'm new to VMWare, so any help is appreciated. Their documentation is lacking, to say the least.
public async void CreateVirtualMachineAsync(NewVMRequest newVMRequest)
{
var appliance = await _applianceService.GetAppliance(newVMRequest.Appliance);
var vimClient = new VimClientImpl
{
IgnoreServerCertificateErrors = true, ServiceUrl = appliance.ServiceUrl
};
vimClient.Login(appliance.User, appliance.Password);
var datacenter = GetDatacenter(vimClient);
var hostCollection = GetListOfHosts(vimClient, datacenter);
var randomHost = PickRandomHost(hostCollection);
var sourceVm = GetSelectedVm(vimClient, newVMRequest);
if (sourceVm == null)
{
_logger.LogDebug($"Could not find virtual machine {newVMRequest.Source} to use for template");
_logger.LogError($"Could not find virtual machine {newVMRequest.Source} to use for template", null);
return;
}
var selectedStore = ConnectToDataStore(vimClient);
var cluster = GetCluster(vimClient);
var mySpec = CreateCloneSpec(selectedStore, randomHost, cluster, sourceVm);
vimClient.WaitForTask(sourceVm.CloneVM_Task(sourceVm.Parent, newVMRequest.Name, mySpec));
vimClient.Disconnect();
}
private VirtualMachineCloneSpec CreateCloneSpec(Datastore selectedStore, ManagedObjectReference randomHost, ClusterComputeResource cluster, VirtualMachine sourceVm)
{
var mySpec = new VirtualMachineCloneSpec
{
Location = new VirtualMachineRelocateSpec
{
Datastore = selectedStore.MoRef,
Transform = VirtualMachineRelocateTransformation.sparse,
Host = randomHost,
Pool = cluster.ResourcePool
},
Config = new VirtualMachineConfigSpec()
};
var networkDevice = new VirtualDevice();
foreach (var vDevice in sourceVm.Config.Hardware.Device)
{
if (vDevice.DeviceInfo.Label.Contains("Network"))
{
networkDevice = vDevice;
}
}
var devSpec = new VirtualDeviceConfigSpec
{
Device = networkDevice, FileOperation = VirtualDeviceConfigSpecFileOperation.create
};
mySpec.Config.DeviceChange = new[] { devSpec };
return mySpec;
}
private Datacenter GetDatacenter(VimClient vimClient)
{
var entities = vimClient.FindEntityViews(typeof(Datacenter), null, null, null);
return (Datacenter)entities.First();
}
private List<ManagedObjectReference> GetListOfHosts(VimClient vimClient, Datacenter datacenter)
{
var hostCollection = new List<ManagedObjectReference>();
var hostFolderMoRef = datacenter.HostFolder;
var hostFolder = (Folder)vimClient.GetView(hostFolderMoRef, null);
var childEntityMoRefs = hostFolder.ChildEntity;
foreach (var childEntityMoRef in childEntityMoRefs)
{
var thisCluster = (ClusterComputeResource)vimClient.GetView(childEntityMoRef, null);
var clusterHostMoRefs = thisCluster.Host;
foreach (var clusterHostMoRef in clusterHostMoRefs)
{
var hostSystem = (HostSystem)vimClient.GetView(clusterHostMoRef, null);
hostCollection.Add(hostSystem.MoRef);
}
}
return hostCollection;
}
private ManagedObjectReference PickRandomHost(List<ManagedObjectReference> hostCollection)
{
var rand = new Random();
return hostCollection[rand.Next(0, hostCollection.Count)];
}
private VirtualMachine GetSelectedVm(VimClient vimClient, NewVMRequest newVMRequest)
{
var filter = new NameValueCollection
{
{"name", newVMRequest.Source},
{"Config.Template", newVMRequest.UseTemplate.ToString().ToLower()}
};
var entityViews = vimClient.FindEntityViews(typeof(VMware.Vim.VirtualMachine), null, filter, null);
if (entityViews.Count == 0)
{
return null;
}
return (VirtualMachine)vimClient.FindEntityViews(typeof(VMware.Vim.VirtualMachine), null, filter, null).First();
}
private Datastore ConnectToDataStore(VimClient vimClient)
{
var myDs = vimClient.FindEntityView(typeof(Datastore), null, null /*dsFilter*/, null);
return (Datastore)myDs;
}
private ClusterComputeResource GetCluster(VimClient vimClient)
{
var appClusters = vimClient.FindEntityViews(typeof(ClusterComputeResource), null, null, null);
return (ClusterComputeResource)appClusters?.FirstOrDefault();
}
For the most part, your code looks good. I would suggest changing the spec file and using the least possible information to create a clone from existing template. Once you have success, you can add more details and see if that errors out.
Start off with this and see if this gets you going.
private VirtualMachineCloneSpec CreateCloneSpec(Datastore selectedStore, ManagedObjectReference randomHost, ClusterComputeResource cluster, VirtualMachine sourceVm)
{
var mySpec = new VirtualMachineCloneSpec
{
Location = new VirtualMachineRelocateSpec
{
Datastore = selectedStore.MoRef,
Host = randomHost,
Pool = cluster.ResourcePool
},
PowerOn = false,
Template = false
};
return mySpec;
}
If the above goes through, then add the VirtualMachineRelocateTransformation to transform your thick VM as thin VM and network connections as needed.

How can I search Notes by sequence number

I use Evernote C# API. I understand how filters working.
ENNoteStoreClient store = ENSessionAdvanced.SharedSession.PrimaryNoteStore;
SyncState currentState = store.GetSyncState();
int currentUpdateCount = currentState.UpdateCount;
if (currentUpdateCount > latestUpdateCount)
{
latestUpdateCount = currentUpdateCount;
// Here synchronization code
}
I have latestUpdateCount and how I can get notes with sequence number >= this number?
You'll want to use GetFilteredSyncChunk using code something like the following:
List<SyncChunk> syncBlocks = new List<SyncChunk>();
int maxEntries = 250;
// These are sample filter settings; you should use what's appropriate for you based on
// what data you want returned in your note objects.
SyncChunkFilter filter = new SyncChunkFilter();
filter.IncludeNotes = true;
filter.IncludeNoteAttributes = true;
filter.IncludeNotebooks = true;
filter.IncludeTags = false;
filter.IncludeSearches = false;
filter.IncludeResources = false;
filter.IncludeLinkedNotebooks = false;
filter.IncludeExpunged = false;
filter.IncludeNoteApplicationDataFullMap = false;
filter.IncludeResourceApplicationDataFullMap = false;
filter.IncludeNoteResourceApplicationDataFullMap = false;
do
{
SyncChunk chunk = store.getFilteredSyncChunk(currentUpdateCount, maxEntries, filter);
if (chunk == null)
{
return null; // This can happen if there is a "503 - Service unavailable" error accessing this person's Evernote info
}
syncBlocks.Add(chunk);
currentUpdateCount = chunk.ChunkHighUSN;
} while (currentUpdateCount < serverSyncState.UpdateCount);
foreach (SyncChunk chunk in syncBlocks)
{
if (chunk != null && chunk.Notes != null)
{
foreach (Note chunkNote in chunk.Notes)
{
// do something with the retrieved chunkNote object
}
}
}

Get Principal Context object using LDAP path

I am working on a module where I need to fetch members of an Active Directory group. This functionality already exists in the project but it was built for .Net3.5. The same is not working for .Net4.5. After some googling I found that I need to use "Principal Context" object to get the Directory entry object.
The problem here is, I need to do the testing in Test AD, which is different from my production AD.
The old way I used was allowing me to specify the test AD server path,
DirectoryEntry entry = new DirectoryEntry(ADLdapPath, ADAdminUser, ADAdminPassword, AuthenticationTypes.Secure);
Can anyone please help me find a way to specify LDAP path(AD server path) while creating "Principal Context" so that I can do the testing in Test environment.
I've used the following helper (modified) which is part of my AD tool belt to create PrincipalContext for working with AD. This should get you started. Modify it to suit your needs. Hope it helps.
public class ADHelper {
public static PrincipalContext CreatePrincipalContext(string domain = null) {
string container = null;
if (IsNullOrWhiteSpace(domain)) {
domain = GetCurrentDnsSuffix();
if (domain != null && domain.EndsWith(".com", StringComparison.InvariantCultureIgnoreCase)) {
container = GetContainers(domain);
} else {
domain = null;
}
}
var hostName = GetHostName();
if (IsNullOrWhiteSpace(domain)) {
domain = hostName;
}
ContextType contextType;
if (domain.Equals(hostName, StringComparison.InvariantCultureIgnoreCase) &&
domain.Equals(Environment.MachineName, StringComparison.InvariantCultureIgnoreCase)) {
contextType = ContextType.Machine;
} else {
contextType = ContextType.Domain;
}
PrincipalContext principalContext = null;
if (contextType == ContextType.Machine) {
principalContext = new PrincipalContext(contextType, domain);
} else {
principalContext = new PrincipalContext(contextType, domain, container, Constants.LDAPUser, Constants.LDAPPassword);
}
return principalContext;
}
public static string GetCurrentDnsSuffix() {
string dnsHostName = null;
if (NetworkInterface.GetIsNetworkAvailable()) {
var nics = NetworkInterface.GetAllNetworkInterfaces()
.Where(ni => ni.OperationalStatus == OperationalStatus.Up);
foreach (var ni in nics) {
var networkConfiguration = ni.GetIPProperties();
var dnsSuffix = networkConfiguration.DnsSuffix;
if (dnsSuffix != null) {
dnsHostName = dnsSuffix;
break;
}
var address = networkConfiguration.DnsAddresses.FirstOrDefault();
if (address != null) {
try {
var dnsHost = Dns.GetHostEntry(address.ToString());
dnsHostName = dnsHost.HostName;
} catch (System.Net.Sockets.SocketException e) {
traceError(e);
} catch (Exception e) {
traceError(e);
}
}
}
}
return dnsHostName;
}
private static string GetContainers(string ADServer) {
string[] LDAPDC = ADServer.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < LDAPDC.GetUpperBound(0) + 1; i++) {
LDAPDC[i] = string.Format("DC={0}", LDAPDC[i]);
}
String ldapdomain = Join(",", LDAPDC);
return ldapdomain;
}
public static string GetHostName() {
var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
return ipProperties.HostName;
}
}
I can then use it in something like this
public static List<string> GetAllUserNames(string domain = null) {
List<string> userNames = new List<string>();
using (var principalContext = createPrincipalContext(domain)) {
//Get a list of user names in MyDomain that match filter
using (UserPrincipal userPrincipal = new UserPrincipal(principalContext)) {
using (PrincipalSearcher principalSearcher = new PrincipalSearcher(userPrincipal)) {
var results = principalSearcher
.FindAll()
.Where(c =>
(c is UserPrincipal) &&
(c as UserPrincipal).Enabled.GetValueOrDefault(false) &&
!string.IsNullOrEmpty(c.DisplayName)
);
foreach (UserPrincipal p in results) {
var temp = p.StructuralObjectClass;
string value = string.Format("{0} ({1})", p.DisplayName, p.EmailAddress ?? Join("\\", p.Context.Name, p.SamAccountName));
userNames.Add(value);
}
}
}
}
return userNames;
}

How can I turn ON radio of a Wifi adapter that is actually OFF?

I'm using Managed Wifi to get the radio state of my Wifi adapter.
How can I turn the radio ON in case it is actually off ?
Something like this :
WlanClient wlanClient = new WlanClient()
var targetInterface = wlanClient.Interfaces.FirstOrDefault()
if (targetInterface != null)
{
bool radioIsOff = targetInterface .RadioState.PhyRadioState[0].dot11SoftwareRadioState == Wlan.Dot11RadioState.Off;
if (radioIsOff)
{
// TODO
}
}
I just added this to the WlanInterface class of the Managed Wifi API :
IntPtr radioStatePtr = new IntPtr(0L);
try
{
Wlan.WlanPhyRadioState radioState = new Wlan.WlanPhyRadioState();
radioState.dwPhyIndex = 0; // TODO : can change ???
radioState.dot11HardwareRadioState = Wlan.Dot11RadioState.On; // ignored in fact, according to http://msdn.microsoft.com/en-us/library/windows/desktop/ms706791(v=vs.85).aspx
radioState.dot11SoftwareRadioState = Wlan.Dot11RadioState.On;
radioStatePtr = Marshal.AllocHGlobal(Marshal.SizeOf(radioState));
Marshal.StructureToPtr(radioState, radioStatePtr, false);
Wlan.ThrowIfError(
Wlan.WlanSetInterface(
client.clientHandle,
info.interfaceGuid,
Wlan.WlanIntfOpcode.RadioState,
(uint)Marshal.SizeOf(typeof(Wlan.WlanPhyRadioState)),
radioStatePtr,
IntPtr.Zero));
}
finally
{
if (radioStatePtr.ToInt64() != 0)
Marshal.FreeHGlobal(radioStatePtr);
}
Tested on Win 7.
I was struggling with this and I just want to share my solution
(download managed wifi recommended above)
Add WlanApi.cs and Interop.cs to your project.
Add using NativeWifi.
In WlanApi.cs
change to:
public IntPtr clientHandle;
(You need the clientHandle. Not sure why it was set to private?)
Use this code:
string arg1 = "true"; //set to false if you want to turn it off.
arg1 = arg1.ToLower();
IntPtr radioStatePtr = new IntPtr(0L);
try
{
WlanClient wc = new WlanClient();
foreach (var iface in wc.Interfaces)
{
//WlanInterface
if(iface.InterfaceName.ToLower()=="wifi")
{
Wlan.WlanPhyRadioState radioState = new Wlan.WlanPhyRadioState();
radioState.dwPhyIndex = 0;
if(arg1=="true")
{
radioState.dot11HardwareRadioState = Wlan.Dot11RadioState.On;
radioState.dot11SoftwareRadioState = Wlan.Dot11RadioState.On;
}
else
{
radioState.dot11HardwareRadioState = Wlan.Dot11RadioState.Off;
radioState.dot11SoftwareRadioState = Wlan.Dot11RadioState.Off;
}
radioStatePtr = Marshal.AllocHGlobal(Marshal.SizeOf(radioState));
Marshal.StructureToPtr(radioState, radioStatePtr, false);
Wlan.WlanSetInterface(wc.clientHandle, iface.InterfaceGuid, Wlan.WlanIntfOpcode.RadioState, (uint)Marshal.SizeOf(typeof(Wlan.WlanPhyRadioState)), radioStatePtr, IntPtr.Zero);
}
}
}
finally
{
if (radioStatePtr.ToInt64() != 0)
Marshal.FreeHGlobal(radioStatePtr);
}
Good luck :)

Categories

Resources