/// <summary>
            /// Sets a parameter of the interface whose data type is <see cref="int"/>.
            /// </summary>
            /// <param name="opCode">The opcode of the parameter.</param>
            /// <param name="value">The value to set.</param>
            private void SetInterfaceInt(Wlan.WlanIntfOpcode opCode, int value)
            {
                IntPtr valuePtr = Marshal.AllocHGlobal(sizeof(int));

                Marshal.WriteInt32(valuePtr, value);
                try
                {
                    Wlan.ThrowIfError(
                        Wlan.WlanSetInterface(client.clientHandle, info.interfaceGuid, opCode, sizeof(int), valuePtr, IntPtr.Zero));
                }
                finally
                {
                    Marshal.FreeHGlobal(valuePtr);
                }
            }
            /// <summary>
            /// Retrieves the basic service sets (BSS) list of all available networks.
            /// </summary>
            public Wlan.WlanBssEntry[] GetNetworkBssList()
            {
                IntPtr bssListPtr;

                Wlan.ThrowIfError(
                    Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, Wlan.Dot11BssType.Any, false, IntPtr.Zero, out bssListPtr));
                try
                {
                    return(ConvertBssListPtr(bssListPtr));
                }
                finally
                {
                    Wlan.WlanFreeMemory(bssListPtr);
                }
            }
            /// <summary>
            /// Retrieves the list of available networks.
            /// </summary>
            /// <param name="flags">Controls the type of networks returned.</param>
            /// <returns>A list of the available networks.</returns>
            public Wlan.WlanAvailableNetwork[] GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags flags)
            {
                IntPtr availNetListPtr;

                Wlan.ThrowIfError(
                    Wlan.WlanGetAvailableNetworkList(client.clientHandle, info.interfaceGuid, flags, IntPtr.Zero, out availNetListPtr));
                try
                {
                    return(ConvertAvailableNetworkListPtr(availNetListPtr));
                }
                finally
                {
                    Wlan.WlanFreeMemory(availNetListPtr);
                }
            }
Example #4
0
 /// <summary>
 /// Creates a new instance of a Native Wifi service client.
 /// </summary>
 public WlanClient()
 {
     Wlan.ThrowIfError(Wlan.WlanOpenHandle(Wlan.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle));
     try
     {
         Wlan.WlanNotificationSource prevSrc;
         wlanNotificationCallback = new Wlan.WlanNotificationCallbackDelegate(OnWlanNotification);
         Wlan.ThrowIfError(Wlan.WlanRegisterNotification(clientHandle, Wlan.WlanNotificationSource.All, false, wlanNotificationCallback, IntPtr.Zero, IntPtr.Zero, out prevSrc));
     }
     catch
     {
         Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero);
         throw;
     }
 }
    private static bool SetRadioState(Guid interfaceGuid, Wlan.Dot11RadioState radioState)
    {
        var state = new Wlan.WlanPhyRadioState
        {
            dwPhyIndex = (int)Wlan.Dot11PhyType.Any,
            dot11SoftwareRadioState = radioState,
        };
        var size    = Marshal.SizeOf(state);
        var pointer = IntPtr.Zero;

        try
        {
            pointer = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(state, pointer, false);
            var clientHandle = IntPtr.Zero;
            try
            {
                uint negotiatedVersion;
                var  result = Wlan.WlanOpenHandle(
                    Wlan.WLAN_CLIENT_VERSION_LONGHORN,
                    IntPtr.Zero,
                    out negotiatedVersion,
                    out clientHandle);
                if (result != 0)
                {
                    return(false);
                }
                result = Wlan.WlanSetInterface(
                    clientHandle,
                    interfaceGuid,
                    Wlan.WlanIntfOpcode.RadioState,
                    (uint)size,
                    pointer,
                    IntPtr.Zero);
                return(result == 0);
            }
            finally
            {
                Wlan.WlanCloseHandle(
                    clientHandle,
                    IntPtr.Zero);
            }
        }
        finally
        {
            Marshal.FreeHGlobal(pointer);
        }
    }
 public bool bValidateGHZRadioAssociation(int APIndex, string expectedBssid)
 {
     for (int i = 0; i < 4; i++)
     {
         string associatedWith = Helpers.GetBSSID(Api, TestInterface);
         if (associatedWith == expectedBssid)
         {
             Log("bValidateGHZRadioAssociation Associated with Radio " + APIndex + " having bssid " + expectedBssid + " as expected");
             return(true);
         }
         Log("bValidateGHZRadioAssociation Not associated with Radio " + APIndex + " having bssid " + expectedBssid + ". Assoicated with" + associatedWith + ". Will Retry to account for propogation issues");
         Wlan.Sleep(500);
     }
     LogError("bValidateGHZRadioAssociation Giving up. Not associated with Radio " + APIndex + " having bssid " + expectedBssid);
     return(false);
 }
Example #7
0
        public void Configure(TestMode testMode, Guid localInterfaceGuid, string address, bool ipv6, UInt16 port)
        {
            this.ipv6Mode = ipv6;
            localPort     = port;

            if (testMode == TestMode.Wlan)
            {
                localAddress = NetworkInterfaceDataPathTests.GetWirelessEndpoint(ipv6Mode);
            }
            else
            {
                localAddress = NetworkInterfaceDataPathTests.GetLanEndpoint(ipv6Mode, localInterfaceGuid);
            }

            this.identifier = String.Format(CultureInfo.InvariantCulture, "{0}:{1}", localAddress, localPort);
            testLogger.LogComment("MulticastReceiver[{0}]  local address", this.identifier);


            testLogger.LogTrace("Creating Multicast Receive Socket");
            if (ipv6Mode)
            {
                if (testMode == TestMode.Wlan)
                {
                    using (Wlan wlanApi = new Wlan())
                    {
                        var wlanInterfaceList = wlanApi.EnumWlanInterfaces();
                        if (wlanInterfaceList.Count < 1)
                        {
                            throw new TestConfigException("No WLAN Interfaces were discovered.  Ensure that WLAN interfaces are enabled, discoverable, and operational.");
                        }
                        var wlanInterface = wlanInterfaceList[0];

                        UInt32 wlanInterfaceIndex = NetworkInterfaceDataPathTests.GetNetworkIndex(wlanInterface.Id);
                        listenSocket = sockets.CreateMulticastSocket(localAddress, localPort, address, port, wlanInterfaceIndex);
                    }
                }
                else
                {
                    UInt32 lanInterfaceIndex = NetworkInterfaceDataPathTests.GetNetworkIndex(localInterfaceGuid);
                    listenSocket = sockets.CreateMulticastSocket(localAddress, localPort, address, port, lanInterfaceIndex);
                }
            }
            else
            {
                listenSocket = sockets.CreateMulticastSocket(localAddress, localPort, address, port);
            }
        }
        private void SendThread(object obj)
        {
            CancellationToken token = (CancellationToken)obj;

            IntPtr socket = IntPtr.Zero;

            try
            {
                testLogger.LogComment("TCP Sends from {0}:{1} to {2}:{3}", localAddress, localPort, remoteAddress, remotePort);
                socket = sockets.CreateTcpSocket(localAddress, localPort, ipv6Mode);
                sockets.Connect(socket, remoteAddress, remotePort, ipv6Mode);
                testLogger.LogComment("Connected to TCP Server at {0}:{1}", remoteAddress, remotePort);

                Byte[] sendData;
                while (!token.IsCancellationRequested)
                {
                    sendData = NetworkInterfaceDataPathTests.GeneratePayload(1000);
                    testLogger.LogTrace("TcpSender[{0}]  Sending Data", this.identifier);
                    sockets.Send(socket, sendData);
                    UnitsTransfered += sendData.Length;
                    Wlan.Sleep(NetworkInterfaceDataPathTests.RandomWaitTime());
                    DateTime nextLogTime = DateTime.Now;
                    if (DateTime.Now > nextLogTime)
                    {
                        testLogger.LogComment(string.Format(CultureInfo.InvariantCulture, "Sending TCP Data to {0}:{1}.  Bytes Sent {2}", remoteAddress, remotePort, UnitsTransfered));
                        nextLogTime = DateTime.Now.Add(logInterval);
                    }
                    testLogger.LogTrace("TcpSender[{0}]  Total Bytes Sent: {1}", this.identifier, UnitsTransfered);
                }

                testLogger.LogComment("TCP Send Completed from {0}:{1} to {2}:{3} Bytes Count = {4}",
                                      localAddress, localPort, remoteAddress, remotePort, UnitsTransfered);
            }
            catch (Exception error)
            {
                testLogger.LogError(string.Format(CultureInfo.InvariantCulture, "Error when sending TCP Data from {0}:{1} to {2}:{3} : {4}", localAddress, localPort, remoteAddress, remotePort, error.ToString()));
                throw;
            }
            finally
            {
                if (socket != IntPtr.Zero)
                {
                    testLogger.LogTrace("TcpSender[{0}] Closing Send Socket", this.identifier);
                    sockets.CloseSocket(socket);
                }
            }
        }
Example #9
0
        private List <Object> GetAvailableNetworkList1()
        {
            WlanClient wlanClient = null;

            WlanClient.WlanInterface wlanInterface = null;
            List <Object>            wlanList      = null;

            try
            {
                wlanClient = new WlanClient();
            }
            catch (Exception exception)
            {
                Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero);
                LogHelper.Log(new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name, exception.Message);
                LogHelper.Error(exception);
                MessageBox.Show(exception.Message, "信息", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }

            if (wlanClient != null && wlanClient.Interfaces.Length != 0)
            {
                wlanList      = new List <object>();
                wlanInterface = wlanClient.Interfaces[0];
                WlanClient.WlanInterface    wlanInterfaceTmp  = wlanClient.Interfaces[0];
                Wlan.WlanAvailableNetwork[] availableNetworks = wlanInterfaceTmp.GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags.IncludeAllAdhocProfiles);
                wlanAvailableNetworks = availableNetworks;

                int index = 1;
                foreach (Wlan.WlanAvailableNetwork wlanAvailableNetworkTmp in availableNetworks)
                {
                    bool isConnected = Wlan.WlanAvailableNetworkFlags.Connected.ToString() == wlanAvailableNetworkTmp.flags.ToString().Split(',')[0] && wlanAvailableNetworkTmp.networkConnectable;
                    wlanList.Add(new
                    {
                        IndexID         = index,
                        NetworkName     = GetStringForSSID(wlanAvailableNetworkTmp.dot11Ssid),
                        SignalQuality   = wlanAvailableNetworkTmp.wlanSignalQuality.ToString() + "%",
                        SignalStrength  = StringHelper.ClassifySignalByStrength(Convert.ToInt32(wlanAvailableNetworkTmp.wlanSignalQuality)),
                        NetworkSecurity = wlanAvailableNetworkTmp.securityEnabled ? "安全" : "不安全",
                        NetworkFlag     = Convert.ToInt32(wlanAvailableNetworkTmp.flags),
                        Connectable     = wlanAvailableNetworkTmp.networkConnectable ? "可连接" : "不可访问",
                        ConnectState    = isConnected ? "已连接使用中" : "未连接",
                    });
                    index++;
                }
            }
            return(wlanList);
        }
Example #10
0
 /// <summary>
 /// Creates a new instance of a Native Wifi service client.
 /// </summary>
 public WlanClient()
 {
     Wlan.ThrowIfError(
         Wlan.WlanOpenHandle(Wlan.WLAN_CLIENT_VERSION_LONGHORN, IntPtr.Zero, out negotiatedVersion, out clientHandle));
     try
     {
         Wlan.WlanNotificationSource prevSrc;
         wlanNotificationCallback = OnWlanNotification;
         Wlan.ThrowIfError(
             Wlan.WlanRegisterNotification(clientHandle, Wlan.WlanNotificationSource.All, false, wlanNotificationCallback, IntPtr.Zero, IntPtr.Zero, out prevSrc));
     }
     catch
     {
         Close();
         throw;
     }
 }
Example #11
0
            /// <summary>
            /// Gets a parameter of the interface whose data type is <see cref="int"/>.
            /// </summary>
            /// <param name="opCode">The opcode of the parameter.</param>
            /// <returns>The integer value.</returns>
            private int GetInterfaceInt(Wlan.WlanIntfOpcode opCode)
            {
                IntPtr valuePtr;
                int    valueSize;

                Wlan.WlanOpcodeValueType opcodeValueType;
                Wlan.ThrowIfError(
                    Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, opCode, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
                try
                {
                    return(Marshal.ReadInt32(valuePtr));
                }
                finally
                {
                    Wlan.WlanFreeMemory(valuePtr);
                }
            }
        public override void Run(string profileName1, string profileName2)
        {
            DateTime endTime = DateTime.Now.Add(new TimeSpan(0, 10, 0));

            using (Wlan wlanApi = new Wlan())
            {
                var wlanInterfaceList = wlanApi.EnumWlanInterfaces();
                Verify.IsTrue(wlanInterfaceList.Count >= 1, string.Format(CultureInfo.InvariantCulture, "wlanInterfaceList.Count = {0}", wlanInterfaceList.Count));
                var wlanInterface = wlanInterfaceList[0];

                if (wlanInterface.State == WLAN_INTERFACE_STATE.wlan_interface_state_connected)
                {
                    wlanApi.Disconnect(wlanInterface.Id, WlanStress.DisconnectWait);
                }


                while (DateTime.Now < endTime)
                {
                    testLogger.LogComment(string.Format(CultureInfo.InvariantCulture, "Connecting to {0}", profileName1));
                    ConnectionAttempts++;
                    var waiter1 = wlanApi.TryProfileConnect(wlanInterface.Id, profileName1, WlanStress.ConnectWait);
                    if (waiter1 != null)
                    {
                        if (waiter1.WlanReasonCode == 0)
                        {
                            ConnectionSuccess++;
                            testLogger.LogComment(string.Format(CultureInfo.InvariantCulture, "Disconnecting from {0}", profileName1));
                            wlanApi.Disconnect(wlanInterface.Id, WlanStress.DisconnectWait);
                        }
                    }

                    testLogger.LogComment(string.Format(CultureInfo.InvariantCulture, "Connecting to {0}", profileName2));
                    ConnectionAttempts++;
                    var waiter2 = wlanApi.TryProfileConnect(wlanInterface.Id, profileName2, WlanStress.ConnectWait);
                    if (waiter2 != null)
                    {
                        if (waiter2.WlanReasonCode == 0)
                        {
                            ConnectionSuccess++;
                            testLogger.LogComment(string.Format(CultureInfo.InvariantCulture, "Disconnecting from {0}", profileName2));
                            wlanApi.Disconnect(wlanInterface.Id, WlanStress.DisconnectWait);
                        }
                    }
                }
            }
        }
Example #13
0
            /// <summary>
            /// Gets the profile's XML specification. Key is unencrypted.
            /// </summary>
            /// <param name="profileName">The name of the profile.</param>
            /// <returns>The XML document.</returns>
            public string GetProfileXmlUnencrypted(string profileName)
            {
                IntPtr profileXmlPtr;

                Wlan.WlanProfileFlags flags = Wlan.WlanProfileFlags.GetPlaintextKey;
                Wlan.WlanAccess       access;
                Wlan.ThrowIfError(
                    Wlan.WlanGetProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, out flags, out access));
                try
                {
                    return(Marshal.PtrToStringUni(profileXmlPtr));
                }
                finally
                {
                    Wlan.WlanFreeMemory(profileXmlPtr);
                }
            }
Example #14
0
        //TODO: Buscar un mejor metodo para escribir bytes a unmanaged
        public Wlan.HostedNetworkReason HostedNetworkSetSecondaryKey(string key)
        {
            Wlan.HostedNetworkReason reason_result;

            byte[] byte_key = Encoding.Default.GetBytes(key);

            IntPtr key_ptr = Marshal.AllocHGlobal(byte_key.Length + 1);

            for (int c = 0; c < byte_key.Length; c++)
            {
                Marshal.WriteByte(key_ptr, c, byte_key[c]);
            }
            Marshal.WriteByte(key_ptr, byte_key.Length, 0);

            Wlan.WlanHostedNetworkSetSecondaryKey(clientHandle, (uint)byte_key.Length + 1, key_ptr, true, true, out reason_result, IntPtr.Zero);
            return(reason_result);
        }
Example #15
0
        private void SendThread(object obj)
        {
            CancellationToken token = (CancellationToken)obj;

            IntPtr socket = IntPtr.Zero;

            try
            {
                testLogger.LogComment("Broadcast Sends from {0}:{1} to {2}:{3}", localAddress, localPort, remoteAddress, remotePort);
                socket = sockets.CreateBroadcastSocket(localAddress, localPort);
                UnitsTransfered++;
                Byte[] sendData;
                while (!token.IsCancellationRequested)
                {
                    sendData = NetworkInterfaceDataPathTests.GeneratePayload(100);
                    testLogger.LogTrace("BroadcastSender[{0}]  Sending Packet", this.identifier);
                    sockets.SendTo(socket, sendData, remoteAddress, remotePort, false);
                    Wlan.Sleep(NetworkInterfaceDataPathTests.RandomWaitTime());
                    UnitsTransfered++;
                    DateTime nextLogTime = DateTime.Now;
                    if (DateTime.Now > nextLogTime)
                    {
                        testLogger.LogComment(string.Format(CultureInfo.InvariantCulture, "Sending Broadcast Data to {0}:{1}.  Packets Sent {2}", remoteAddress, remotePort, UnitsTransfered));
                        nextLogTime = DateTime.Now.Add(logInterval);
                    }

                    testLogger.LogTrace("BroadcastSender[{0}] Packets Sent: {1}", this.identifier, UnitsTransfered);
                }

                testLogger.LogComment("Broadcast Send Completed from {0}:{1} to {2}:{3}. Packet Count = {4}",
                                      localAddress, localPort, remoteAddress, remotePort, UnitsTransfered);
            }
            catch (Exception error)
            {
                testLogger.LogError(error.ToString());
                throw;
            }
            finally
            {
                if (socket != IntPtr.Zero)
                {
                    testLogger.LogTrace("BroadcastSender[{0}] Closing Send Socket", this.identifier);
                    sockets.CloseSocket(socket);
                }
            }
        }
Example #16
0
            /// <summary>
            /// Retrieves the basic service sets (BSS) list of the specified network.
            /// </summary>
            /// <param name="ssid">Specifies the SSID of the network from which the BSS list is requested.</param>
            /// <param name="bssType">Indicates the BSS type of the network.</param>
            /// <param name="securityEnabled">Indicates whether security is enabled on the network.</param>
            public Wlan.WlanBssEntry[] GetNetworkBssList(Wlan.Dot11Ssid ssid, Wlan.Dot11BssType bssType, bool securityEnabled)
            {
                IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));

                Marshal.StructureToPtr(ssid, ssidPtr, false);
                try {
                    IntPtr bssListPtr;
                    Wlan.ThrowIfError(
                        Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr));
                    try {
                        return(ConvertBssListPtr(bssListPtr));
                    } finally {
                        Wlan.WlanFreeMemory(bssListPtr);
                    }
                } finally {
                    Marshal.FreeHGlobal(ssidPtr);
                }
            }
        private void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this.disposed)
            {
                if (disposing)
                {
                    Log("WhckRoaming : Cleaning up");
                    DeleteProfiles();

                    if (echoClient != null)
                    {
                        Log("WhckRoaming : Cleaning up Echo Client");
                        echoClient.Close();
                        echoClient = null;
                    }
                    if (null != Api)
                    {
                        Api.Dispose();
                        Api = null;
                    }
                    if (null != AC)
                    {
                        if (routers != null && routers.Count == 2)
                        {
                            Log("WhckRoaming: Cleaning up static route from AP server to router");
                            AC.ClearStaticRoute(routers[0]);
                        }

                        Log("WhckRoaming : Cleaning up stopping radius server");
                        AC.StopRadiusServer();
                        Log("WhckRoaming : Cleaning up stopping Echo server");
                        AC.StopEchoServer(); // Service checks if echo server was running or not
                        AC.Dispose();
                        AC = null;
                    }

                    // TODO Dispose here
                }
            }

            disposed = true;
        }
Example #18
0
            public Wlan.WlanInterfaceCapability GetInterfaceCapability()
            {
                IntPtr capabilityPtr;

                Wlan.ThrowIfError(
                    Wlan.WlanGetInterfaceCapability(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out capabilityPtr));
                try
                {
                    //Wlan.WlanInterfaceCapability capability = new Wlan.WlanInterfaceCapability();

                    Wlan.WlanInterfaceCapability capability = (Wlan.WlanInterfaceCapability)Marshal.PtrToStructure(capabilityPtr, typeof(Wlan.WlanInterfaceCapability));

                    return(capability);
                }
                finally
                {
                    Wlan.WlanFreeMemory(capabilityPtr);
                }
            }
Example #19
0
        public override void Run(string profileName1, string profileName2)
        {
            DateTime endTime       = DateTime.Now.Add(new TimeSpan(0, 5, 0));
            TimeSpan waiterTimeout = new TimeSpan(0, 0, 10);

            using (Wlan wlanApi = new Wlan())
            {
                var wlanInterfaceList = wlanApi.EnumWlanInterfaces();
                Verify.IsTrue(wlanInterfaceList.Count >= 1, string.Format(CultureInfo.InvariantCulture, "wlanInterfaceList.Count = {0}", wlanInterfaceList.Count));
                var wlanInterface = wlanInterfaceList[0];

                while (DateTime.Now < endTime)
                {
                    if (Random.Next(0, 2) == 1)
                    {
                        // Slow Scan
                        testLogger.LogComment("Slow Scan");
                        int iterations = Random.Next(10);
                        for (int toggleLooper = 0; toggleLooper < iterations; toggleLooper++)
                        {
                            testLogger.LogComment("Scanning...");
                            wlanApi.TryScan(wlanInterface.Id, false, WlanStress.ScanWait);
                            testLogger.LogComment("Scanning...Complete");
                            SlowScans++;
                        }
                    }
                    else
                    {
                        // Fast Scan
                        testLogger.LogComment("Fast Scan");
                        int iterations = Random.Next(10);
                        for (int toggleLooper = 0; toggleLooper < iterations; toggleLooper++)
                        {
                            testLogger.LogComment("Start Fast Scan");
                            wlanApi.TryScan(wlanInterface.Id, false);
                            FastScans++;
                        }
                        testLogger.LogComment("Sleeping for a few seconds to allow the driver to calm down");
                        Wlan.Sleep(10000);
                    }
                }
            }
        }
Example #20
0
        public Wlan.HostedNetworkReason HostedNetworkQuerySecondaryKey(out string key)
        {
            Wlan.HostedNetworkReason reason_result;

            uint   lenght = 0;
            IntPtr key_ptr;
            bool   pass_phrase = true;
            bool   persistent  = true;

            Wlan.WlanHostedNetworkQuerySecondaryKey(clientHandle, out lenght, out key_ptr, out pass_phrase, out persistent, out reason_result, IntPtr.Zero);

            byte[] result = new byte[lenght];
            for (int c = 0; c < lenght; c++)
            {
                result[c] = Marshal.ReadByte(key_ptr, c);
            }

            key = Encoding.Default.GetString(result);
            return(reason_result);
        }
Example #21
0
            /// <summary>
            /// Gets the information of all profiles on this interface.
            /// </summary>
            /// <returns>The profiles information.</returns>
            public Wlan.WlanProfileInfo[] GetProfiles()
            {
                IntPtr profileListPtr;

                Wlan.ThrowIfError(
                    Wlan.WlanGetProfileList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out profileListPtr));
                try {
                    Wlan.WlanProfileInfoListHeader header       = (Wlan.WlanProfileInfoListHeader)Marshal.PtrToStructure(profileListPtr, typeof(Wlan.WlanProfileInfoListHeader));
                    Wlan.WlanProfileInfo[]         profileInfos = new Wlan.WlanProfileInfo[header.numberOfItems];
                    long profileListIterator = profileListPtr.ToInt64() + Marshal.SizeOf(header);
                    for (int i = 0; i < header.numberOfItems; ++i)
                    {
                        Wlan.WlanProfileInfo profileInfo = (Wlan.WlanProfileInfo)Marshal.PtrToStructure(new IntPtr(profileListIterator), typeof(Wlan.WlanProfileInfo));
                        profileInfos[i]      = profileInfo;
                        profileListIterator += Marshal.SizeOf(profileInfo);
                    }
                    return(profileInfos);
                } finally {
                    Wlan.WlanFreeMemory(profileListPtr);
                }
            }
Example #22
0
        private void EPClosed(object sender, FormClosedEventArgs e)
        {
            if (profile_manager.is_new)
            {
                profile_manager.RestoreForm();

                Wlan.WlanConnectionParameters con_params = new Wlan.WlanConnectionParameters();
                con_params.wlanConnectionMode = Wlan.WlanConnectionMode.Profile;
                con_params.profile            = profile_manager.str_profile_name;
                con_params.dot11BssType       = Wlan.Dot11BssType.Any;
                con_params.flags = 0;

                try {
                    Wlan.WlanConnect(wlan.ClientHandle, adapter.InterfaceGuid, ref con_params, IntPtr.Zero);
                } catch (Exception ex) {
                    MessageBox.Show("Fallo al conectar: " + ex.Message);
                }

                profile_manager.is_new = false;
            }
            CheckProfiles();
        }
Example #23
0
            /// <summary>
            /// Gets the profile's XML specification.
            /// </summary>
            /// <param name="profileName">The name of the profile.</param>
            /// <returns>The XML document.</returns>
            public string GetProfileXml(string profileName)
            {
                if (profileName == null)
                {
                    return(string.Empty);
                }
                IntPtr profileXmlPtr;

                Wlan.WlanProfileFlags flags = Wlan.WlanProfileFlags.GET_PLAINTEXT_KEY;
                Wlan.WlanAccess       access;
                Wlan.ThrowIfError(
                    Wlan.WlanGetProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, out flags,
                                        out access));
                try
                {
                    return(Marshal.PtrToStringUni(profileXmlPtr));
                }
                finally
                {
                    Wlan.WlanFreeMemory(profileXmlPtr);
                }
            }
        private void SleepWhileConnected(DateTime endTime, string profileName1)
        {
            testLogger.LogComment("SleepWhileConnected");


            using (Wlan wlanApi = new Wlan())
            {
                var wlanInterfaceList = wlanApi.EnumWlanInterfaces();
                Verify.IsTrue(wlanInterfaceList.Count >= 1, string.Format(CultureInfo.InvariantCulture, "wlanInterfaceList.Count = {0}", wlanInterfaceList.Count));
                var wlanInterface = wlanInterfaceList[0];

                if (wlanInterface.State != WLAN_INTERFACE_STATE.wlan_interface_state_connected)
                {
                    testLogger.LogComment(string.Format(CultureInfo.InvariantCulture, "Connecting to {0}", profileName1));
                    wlanApi.ProfileConnect(wlanInterface.Id, profileName1, WlanStress.ConnectWait);
                }

                while (DateTime.Now < endTime)
                {
                    int sleepTime = Random.Next(1, 60);
                    testLogger.LogComment(string.Format(CultureInfo.InvariantCulture, "Sleeping for {0} seconds", sleepTime));

                    WakeHelper.StaticD2Sleep(new TimeSpan(0, 0, sleepTime));

                    testLogger.LogComment("Verify we are still connected");
                    connectedAfterSleepAttempts++;
                    if (VerifyWeAreConnected(wlanApi))
                    {
                        testLogger.LogComment("We are still connected");
                        connectedAfterSleepSuccess++;
                    }
                    else
                    {
                        testLogger.LogComment("We are not still connected");
                    }
                    Wlan.Sleep(1000);
                }
            }
        }
Example #25
0
        private void DisconnectAndDeleteProfile(Wlan wlanApi)
        {
            var wlanInterfaceList = wlanApi.EnumWlanInterfaces();

            Verify.IsTrue(wlanInterfaceList.Count >= 1, string.Format(CultureInfo.InvariantCulture, "wlanInterfaceList.Count = {0}", wlanInterfaceList.Count));
            if (wlanInterfaceList[0].State == WLAN_INTERFACE_STATE.wlan_interface_state_connected)
            {
                testLogger.LogComment("Disconnecting from AP");
                wlanApi.Disconnect(wlanInterfaceList[0].Id);
                Wlan.Sleep(5000);
            }

            try
            {
                testLogger.LogComment("Deleting Profile");
                wlanApi.DeleteProfile(wlanInterfaceList[0].Id, dot11wSSID);
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                // The profile was not present to delete
            }
        }
Example #26
0
        public WhckScanning(RunTimeConfiguration rc,
                            APConfigParameter AP1Config24GHz,
                            APConfigParameter AP1Config5GHz,
                            APConfigParameter AP2Config24GHz,
                            APConfigParameter AP2Config5GHz,
                            SCAN_TEST_OPTIONS ScanTestOptions)
        {
            if (rc == null)
            {
                throw new ArgumentNullException("rc");
            }
            traceProvider = new TraceProvider("WhckScanning");
            this.ScanningConfiguration = rc;
            this.m_AP1Config24GHz      = AP1Config24GHz;
            this.m_AP1Config5GHz       = AP1Config5GHz;
            this.m_AP2Config24GHz      = AP2Config24GHz;
            this.m_AP2Config5GHz       = AP2Config5GHz;
            this.m_ScanTestOptions     = ScanTestOptions;

            Api = new Wlan();


            TestInterface = Helpers.GetWlanInterface(Api);
            AC            = null;
            AC            = Helpers.ConnectToService(ScanningConfiguration.ServiceBackChannelAddress);


            if (AC == null)
            {
                Log("Helpers.ConnectToService failed");
                AC = null;
                throw new Exception("Helpers.ConnectToService failed");
            }

            routers = Helpers.GetRouterCollection(AC);

            AccessPointSetup = false;
        }
Example #27
0
 public ActionResult Register(Wlan model)
 {
     if (!Request.IsAjaxRequest())
     {
         Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
         return(Content("Sorry, this method can't be called only from AJAX."));
     }
     try
     {
         if (ModelState.IsValid)
         {
             model.Data = DateTime.Now;
             db.Wlan.Add(model);
             db.SaveChanges();
             return(Content("Registro feito com sucesso !"));
         }
         else
         {
             StringBuilder strB = new StringBuilder(500);
             foreach (ModelState modelState in ModelState.Values)
             {
                 foreach (ModelError error in modelState.Errors)
                 {
                     strB.Append(error.ErrorMessage + ".");
                 }
             }
             Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
             return(Content(strB.ToString()));
         }
     }
     catch (Exception ex)
     {
         Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
         return(Content("Sorry, an error occured." + ex.Message));
     }
 }
Example #28
0
        private void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (null != Api)
                    {
                        Api.Dispose();
                        Api = null;
                    }
                    if (null != AC)
                    {
                        //AC.StopEchoServer(); // Service checks if echo server was running or not
                        AC.Dispose();
                        AC = null;
                    }
                    // TODO Dispose here
                }
            }

            disposed = true;
        }
 /// <summary>
 /// Connects to a network defined by a connection parameters structure.
 /// </summary>
 /// <param name="connectionParams">The connection paramters.</param>
 protected void Connect(Wlan.WlanConnectionParameters connectionParams)
 {
     Wlan.ThrowIfError(
         Wlan.WlanConnect(client.clientHandle, info.interfaceGuid, ref connectionParams, IntPtr.Zero));
 }
        private void OnWlanNotification(ref Wlan.WlanNotificationData notifyData, IntPtr context)
        {
            WlanInterface wlanIface = ifaces.ContainsKey(notifyData.interfaceGuid) ? ifaces[notifyData.interfaceGuid] : null;

            switch (notifyData.notificationSource)
            {
                case Wlan.WlanNotificationSource.ACM:
                    switch ((Wlan.WlanNotificationCodeAcm)notifyData.notificationCode)
                    {
                        case Wlan.WlanNotificationCodeAcm.AdhocNetworkStateChange:
                            //int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanAdhocNetworkState));
                            //if (notifyData.dataSize >= expectedSize)
                            //{
                                Wlan.WlanAdhocNetworkState adhocNetworkState = (Wlan.WlanAdhocNetworkState)Marshal.ReadInt32(notifyData.dataPtr);
                                if (wlanIface != null)
                                    wlanIface.OnWlanAdhocNetwork(notifyData, adhocNetworkState);
                            //}
                            break;
                        case Wlan.WlanNotificationCodeAcm.ConnectionStart:
                        case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
                        case Wlan.WlanNotificationCodeAcm.ConnectionAttemptFail:
                        case Wlan.WlanNotificationCodeAcm.Disconnecting:
                        case Wlan.WlanNotificationCodeAcm.Disconnected:
                            Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData);
                            if (connNotifyData.HasValue)
                                if (wlanIface != null)
                                    wlanIface.OnWlanConnection(notifyData, connNotifyData.Value);
                            break;
                        case Wlan.WlanNotificationCodeAcm.ScanFail:
                            try
                            {
                                int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanReasonCode));
                                if (notifyData.dataSize >= expectedSize)
                                {
                                    Wlan.WlanReasonCode reasonCode = (Wlan.WlanReasonCode)Marshal.ReadInt32(notifyData.dataPtr);
                                    if (wlanIface != null)
                                        wlanIface.OnWlanReason(notifyData, reasonCode);
                                }
                            }
                            catch (Exception)
                            {

                            }

                            break;
                    }
                    break;
                case Wlan.WlanNotificationSource.MSM:
                    switch ((Wlan.WlanNotificationCodeMsm)notifyData.notificationCode)
                    {
                        case Wlan.WlanNotificationCodeMsm.Associating:
                        case Wlan.WlanNotificationCodeMsm.Associated:
                        case Wlan.WlanNotificationCodeMsm.Authenticating:
                        case Wlan.WlanNotificationCodeMsm.Connected:
                        case Wlan.WlanNotificationCodeMsm.RoamingStart:
                        case Wlan.WlanNotificationCodeMsm.RoamingEnd:
                        case Wlan.WlanNotificationCodeMsm.Disassociating:
                        case Wlan.WlanNotificationCodeMsm.Disconnected:
                        case Wlan.WlanNotificationCodeMsm.PeerJoin:
                        case Wlan.WlanNotificationCodeMsm.PeerLeave:
                        case Wlan.WlanNotificationCodeMsm.AdapterRemoval:
                            Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData);
                            if (connNotifyData.HasValue)
                                if (wlanIface != null)
                                    wlanIface.OnWlanConnection(notifyData, connNotifyData.Value);
                            break;
                    }
                    break;
            }

            if (wlanIface != null)
                wlanIface.OnWlanNotification(notifyData);
        }
        private Wlan.WlanConnectionNotificationData? ParseWlanConnectionNotification(ref Wlan.WlanNotificationData notifyData)
        {
            int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanConnectionNotificationData));
            if (notifyData.dataSize < expectedSize)
                return null;

            Wlan.WlanConnectionNotificationData connNotifyData =
                (Wlan.WlanConnectionNotificationData)
                Marshal.PtrToStructure(notifyData.dataPtr, typeof(Wlan.WlanConnectionNotificationData));
            if (connNotifyData.wlanReasonCode == Wlan.WlanReasonCode.Success)
            {
                IntPtr profileXmlPtr = new IntPtr(
                    notifyData.dataPtr.ToInt64() +
                    Marshal.OffsetOf(typeof(Wlan.WlanConnectionNotificationData), "profileXml").ToInt64());
                connNotifyData.profileXml = Marshal.PtrToStringUni(profileXmlPtr);
            }
            return connNotifyData;
        }
 /// <summary>
 /// Se gatilla para recibir notificaciones en el cambio del estado de la red adhoc (Windows Vista)
 /// Si ocurre un error se informa en informationNetworkingHandler
 /// </summary>
 /// <param name="notifyData">Los datos de notificación</param>
 /// <param name="adhocNetworkState">El estado de la red adhoc que esta siendo notificado</param>
 private void WlanAdhocNetworkAction(Wlan.WlanNotificationData notifyData, Wlan.WlanAdhocNetworkState adhocNetworkState)
 {
     lock(syncPoint)
     {
         try
         {
             if ((notifyData.notificationSource.Equals(Wlan.WlanNotificationSource.ACM) &&
                  notifyData.NotificationCode.Equals(Wlan.WlanNotificationCodeAcm.AdhocNetworkStateChange)))
             {
                 if (adhocNetworkState.Equals(Wlan.WlanAdhocNetworkState.Connected))
                 {
                     if (netData.OpSystem.Equals(OpSystemType.WIN7))
                     {
                         wifiInformation("connection");
                         switch (connectionState)
                         {
                             case WifiConnectionState.CONNECTED:
                                 {
                                     break;
                                 }
                             case WifiConnectionState.DISCONNECTED:
                                 {
                                     connectionState = WifiConnectionState.CONNECTED;
                                     break;
                                 }
                             case WifiConnectionState.WAINTING:
                                 {
                                     connectionState = WifiConnectionState.CONNECTED;
                                     break;
                                 }
                         }
                     }
                 }
                 else if (adhocNetworkState.Equals(Wlan.WlanAdhocNetworkState.Formed))
                 {
                     if (netData.OpSystem.Equals(OpSystemType.WIN7))
                     {
                         wifiInformation("alone connection");
                         switch (connectionState)
                         {
                             case WifiConnectionState.CONNECTED:
                                 {
                                     //connectionState = WifiConnectionState.WAINTING;
                                     break;
                                 }
                             case WifiConnectionState.DISCONNECTED:
                                 {
                                     connectionState = WifiConnectionState.WAINTING;
                                     break;
                                 }
                             case WifiConnectionState.WAINTING:
                                 {
                                     break;
                                 }
                         }
                     }
                 }
             }
         }
         catch (ThreadAbortException e)
         {
             throw e;
         }
         catch (Exception e)
         {
             wifiInformation("error " + e.Message);
         }
     }
 }
 /// <summary>
 /// Se gatilla para recibir notificaciones de conexión a la red inalambrica (Windows XP, SP3)
 /// Si ocurre un error se informa en informationNetworkingHandler
 /// </summary>
 /// <param name="notifyData">Los datos de notificación</param>
 /// <param name="connNotifyData">Los datos de conección</param>
 private void WlanConnectionAction(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData)
 {
     lock(syncPoint)
     {
         try
         {
             if ((notifyData.notificationSource.Equals(Wlan.WlanNotificationSource.ACM) &&
                  notifyData.NotificationCode.Equals(Wlan.WlanNotificationCodeAcm.ConnectionComplete)) ||
                 (notifyData.notificationSource.Equals(Wlan.WlanNotificationSource.MSM) &&
                  notifyData.notificationCode.Equals(Wlan.WlanNotificationCodeMsm.Connected)))
             {
                 if (connNotifyData.profileName == netData.AdhocNetworkName + "-adhoc")
                 {
                     if (netData.OpSystem.Equals(OpSystemType.WINXPSP3))
                     {
                         wifiInformation("connection");
                         switch (connectionState)
                         {
                             case WifiConnectionState.CONNECTED:
                                 {
                                     break;
                                 }
                             case WifiConnectionState.DISCONNECTED:
                                 {
                                     connectionState = WifiConnectionState.CONNECTED;
                                     break;
                                 }
                         }
                     }
                 }
                 else
                 {
                     wifiInformation("unknown connection (" + connNotifyData.profileName + ")");
                     connectionState = WifiConnectionState.DISCONNECTED;
                     closeWLanConnection();
                     openWLanConnection();
                 }
             }
             else if ((notifyData.notificationSource.Equals(Wlan.WlanNotificationSource.ACM) &&
                  notifyData.NotificationCode.Equals(Wlan.WlanNotificationCodeAcm.Disconnected)) ||
                 (notifyData.notificationSource.Equals(Wlan.WlanNotificationSource.MSM) &&
                  notifyData.notificationCode.Equals(Wlan.WlanNotificationCodeMsm.Disconnected)))
             {
                 if (netData.OpSystem.Equals(OpSystemType.WINXPSP3))
                 {
                     wifiInformation("disconnection");
                     switch (connectionState)
                     {
                         case WifiConnectionState.CONNECTED:
                             {
                                 connectionState = WifiConnectionState.DISCONNECTED;
                                 break;
                             }
                         case WifiConnectionState.DISCONNECTED:
                             {
                                 break;
                             }
                     }
                 }
                 else if (netData.OpSystem.Equals(OpSystemType.WIN7))
                 {
                     wifiInformation("disconenction");
                     switch (connectionState)
                     {
                         case WifiConnectionState.CONNECTED:
                             {
                                 connectionState = WifiConnectionState.DISCONNECTED;
                                 break;
                             }
                         case WifiConnectionState.DISCONNECTED:
                             {
                                 break;
                             }
                         case WifiConnectionState.WAINTING:
                             {
                                 connectionState = WifiConnectionState.DISCONNECTED;
                                 break;
                             }
                     }
                 }
             }
         }
         catch (ThreadAbortException e)
         {
             throw e;
         }
         catch (Exception e)
         {
             wifiInformation("error " + e.Message);
         }
     }
 }
 /// <summary>
 /// Retrieves the basic service sets (BSS) list of the specified network.
 /// </summary>
 /// <param name="ssid">Specifies the SSID of the network from which the BSS list is requested.</param>
 /// <param name="bssType">Indicates the BSS type of the network.</param>
 /// <param name="securityEnabled">Indicates whether security is enabled on the network.</param>
 public Wlan.WlanBssEntry[] GetNetworkBssList(Wlan.Dot11Ssid ssid, Wlan.Dot11BssType bssType, bool securityEnabled)
 {
     IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
     Marshal.StructureToPtr(ssid, ssidPtr, false);
     try
     {
         IntPtr bssListPtr;
         Wlan.ThrowIfError(
             Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr));
         try
         {
             return ConvertBssListPtr(bssListPtr);
         }
         finally
         {
             Wlan.WlanFreeMemory(bssListPtr);
         }
     }
     finally
     {
         Marshal.FreeHGlobal(ssidPtr);
     }
 }
 /// <summary>
 /// Sets a parameter of the interface whose data type is <see cref="int"/>.
 /// </summary>
 /// <param name="opCode">The opcode of the parameter.</param>
 /// <param name="value">The value to set.</param>
 private void SetInterfaceInt(Wlan.WlanIntfOpcode opCode, int value)
 {
     IntPtr valuePtr = Marshal.AllocHGlobal(sizeof(int));
     Marshal.WriteInt32(valuePtr, value);
     try
     {
         Wlan.ThrowIfError(
             Wlan.WlanSetInterface(client.clientHandle, info.interfaceGuid, opCode, sizeof(int), valuePtr, IntPtr.Zero));
     }
     finally
     {
         Marshal.FreeHGlobal(valuePtr);
     }
 }
Example #36
0
 /// <summary>
 /// Disconnects to a network
 /// </summary>
 public void Disconnect()
 {
     Wlan.ThrowIfError(
         Wlan.WlanDisconnect(client.clientHandle, info.interfaceGuid, IntPtr.Zero));
 }
 /// <summary>
 /// Gets a string that describes a specified reason code.
 /// </summary>
 /// <param name="reasonCode">The reason code.</param>
 /// <returns>The string.</returns>
 public string GetStringForReasonCode(Wlan.WlanReasonCode reasonCode)
 {
     StringBuilder sb = new StringBuilder(1024); // the 1024 size here is arbitrary; the WlanReasonCodeToString docs fail to specify a recommended size
     Wlan.ThrowIfError(
         Wlan.WlanReasonCodeToString(reasonCode, sb.Capacity, sb, IntPtr.Zero));
     return sb.ToString();
 }
 internal WlanInterface(WlanClient client, Wlan.WlanInterfaceInfo info)
 {
     this.client = client;
     this.info = info;
 }
 /// <summary>
 /// Requests a connection (association) to the specified wireless network.
 /// </summary>
 /// <remarks>
 /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
 /// </remarks>
 public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile)
 {
     Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
     connectionParams.wlanConnectionMode = connectionMode;
     connectionParams.profile = profile;
     connectionParams.dot11BssType = bssType;
     connectionParams.flags = 0;
     Connect(connectionParams);
 }
 internal void OnWlanAdhocNetwork(Wlan.WlanNotificationData notifyData, Wlan.WlanAdhocNetworkState adhocNetworkState)
 {
     if (WlanAdhocNetworkNotification != null)
     {
         WlanAdhocNetworkNotification(notifyData, adhocNetworkState);
     }
     if (queueEvents)
     {
         WlanAdhocNetworkNotificationData queuedEvent = new WlanAdhocNetworkNotificationData();
         queuedEvent.notifyData = notifyData;
         queuedEvent.adhocNetworkState = adhocNetworkState;
         EnqueueEvent(queuedEvent);
     }
 }
 /// <summary>
 /// Sets the profile.
 /// </summary>
 /// <param name="flags">The flags to set on the profile.</param>
 /// <param name="profileXml">The XML representation of the profile. On Windows XP SP 2, special care should be taken to adhere to its limitations.</param>
 /// <param name="overwrite">If a profile by the given name already exists, then specifies whether to overwrite it (if <c>true</c>) or return an error (if <c>false</c>).</param>
 /// <returns>The resulting code indicating a success or the reason why the profile wasn't valid.</returns>
 public Wlan.WlanReasonCode SetProfile(Wlan.WlanProfileFlags flags, string profileXml, bool overwrite)
 {
     Wlan.WlanReasonCode reasonCode;
     int ret = Wlan.WlanSetProfile(client.clientHandle, info.interfaceGuid, flags, profileXml, null, overwrite, IntPtr.Zero, out reasonCode);
     Wlan.ThrowIfError(ret);
     return reasonCode;
 }
 /// <summary>
 /// Gets a parameter of the interface whose data type is <see cref="int"/>.
 /// </summary>
 /// <param name="opCode">The opcode of the parameter.</param>
 /// <returns>The integer value.</returns>
 private int GetInterfaceInt(Wlan.WlanIntfOpcode opCode)
 {
     IntPtr valuePtr;
     int valueSize;
     Wlan.WlanOpcodeValueType opcodeValueType;
     Wlan.ThrowIfError(
         Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, opCode, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
     try
     {
         return Marshal.ReadInt32(valuePtr);
     }
     finally
     {
         Wlan.WlanFreeMemory(valuePtr);
     }
 }
 /// <summary>
 /// Connects to the specified wireless network.
 /// </summary>
 /// <remarks>
 /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
 /// </remarks>
 public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, Wlan.Dot11Ssid ssid, Wlan.WlanConnectionFlags flags)
 {
     Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
     connectionParams.wlanConnectionMode = connectionMode;
     connectionParams.dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
     Marshal.StructureToPtr(ssid, connectionParams.dot11SsidPtr, false);
     connectionParams.dot11BssType = bssType;
     connectionParams.flags = flags;
     Connect(connectionParams);
     Marshal.DestroyStructure(connectionParams.dot11SsidPtr, ssid.GetType());
     Marshal.FreeHGlobal(connectionParams.dot11SsidPtr);
 }
            internal void OnWlanConnection(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData)
            {
                if (WlanConnectionNotification != null)
                    WlanConnectionNotification(notifyData, connNotifyData);

                if (queueEvents)
                {
                    WlanConnectionNotificationEventData queuedEvent = new WlanConnectionNotificationEventData();
                    queuedEvent.notifyData = notifyData;
                    queuedEvent.connNotifyData = connNotifyData;
                    EnqueueEvent(queuedEvent);
                }
            }
 internal void OnWlanReason(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode)
 {
     if (WlanReasonNotification != null)
         WlanReasonNotification(notifyData, reasonCode);
     if (queueEvents)
     {
         WlanReasonNotificationData queuedEvent = new WlanReasonNotificationData();
         queuedEvent.notifyData = notifyData;
         queuedEvent.reasonCode = reasonCode;
         EnqueueEvent(queuedEvent);
     }
 }
 /// <summary>
 /// Connects (associates) to the specified wireless network, returning either on a success to connect
 /// or a failure.
 /// </summary>
 /// <param name="connectionMode"></param>
 /// <param name="bssType"></param>
 /// <param name="profile"></param>
 /// <param name="connectTimeout"></param>
 /// <returns></returns>
 public bool ConnectSynchronously(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile, int connectTimeout)
 {
     queueEvents = true;
     try
     {
         Connect(connectionMode, bssType, profile);
         while (queueEvents && eventQueueFilled.WaitOne(connectTimeout, true))
         {
             lock (eventQueue)
             {
                 while (eventQueue.Count != 0)
                 {
                     object e = eventQueue.Dequeue();
                     if (e is WlanConnectionNotificationEventData)
                     {
                         WlanConnectionNotificationEventData wlanConnectionData = (WlanConnectionNotificationEventData)e;
                         // Check if the conditions are good to indicate either success or failure.
                         if (wlanConnectionData.notifyData.notificationSource == Wlan.WlanNotificationSource.ACM)
                         {
                             switch ((Wlan.WlanNotificationCodeAcm)wlanConnectionData.notifyData.notificationCode)
                             {
                                 case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
                                     if (wlanConnectionData.connNotifyData.profileName == profile)
                                         return true;
                                     break;
                             }
                         }
                         break;
                     }
                 }
             }
         }
     }
     finally
     {
         queueEvents = false;
         eventQueue.Clear();
     }
     return false; // timeout expired and no "connection complete"
 }
 internal void OnWlanNotification(Wlan.WlanNotificationData notifyData)
 {
     if (WlanNotification != null)
         WlanNotification(notifyData);
 }
Example #48
0
 /// <summary>
 /// Deletes a profile.
 /// </summary>
 /// <param name="profileName">
 /// The name of the profile to be deleted. Profile names are case-sensitive.
 /// On Windows XP SP2, the supplied name must match the profile name derived automatically from the SSID of the network. For an infrastructure network profile, the SSID must be supplied for the profile name. For an ad hoc network profile, the supplied name must be the SSID of the ad hoc network followed by <c>-adhoc</c>.
 /// </param>
 public void DeleteProfile(string profileName)
 {
     Wlan.ThrowIfError(
         Wlan.WlanDeleteProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero));
 }
 /// <summary>
 /// Retrieves the list of available networks.
 /// </summary>
 /// <param name="flags">Controls the type of networks returned.</param>
 /// <returns>A list of the available networks.</returns>
 public Wlan.WlanAvailableNetwork[] GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags flags)
 {
     IntPtr availNetListPtr;
     Wlan.ThrowIfError(
         Wlan.WlanGetAvailableNetworkList(client.clientHandle, info.interfaceGuid, flags, IntPtr.Zero, out availNetListPtr));
     try
     {
         return ConvertAvailableNetworkListPtr(availNetListPtr);
     }
     finally
     {
         Wlan.WlanFreeMemory(availNetListPtr);
     }
 }