I have a WPF app that has a control(checkbox /toggle switch) . I want to turn Wi-Fi On/Off by using those buttons. I have tried the following code but it doesnt seem to help
I am using Windows 10 and Visual Studio 2015
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// string name = "Hello World";
}
static void Enable(string interfaceName)
{
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" enable");
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = psi;
p.Start();
}
static void Disable(string interfaceName)
{
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" disable");
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = psi;
p.Start();
}
private void checkBox_Checked(object sender, RoutedEventArgs e)
{
string interfaceName = "Local Area Connection";
Disable(interfaceName);
}
}
}
I went through the following link with the first answer but there is no help .
I need some help so that I can programatically turn off/On Wi-Fi with the click of a button.
You can turn on/off Wi-Fi by changing software radio state (not hardware radio state) by Native Wifi API. Using some codes of Managed Wifi API project, I wrote a sample.
using System;
using System.Linq;
using System.Runtime.InteropServices;
using NativeWifi;
public static class WlanRadio
{
public static string[] GetInterfaceNames()
{
using (var client = new WlanClient())
{
return client.Interfaces.Select(x => x.InterfaceName).ToArray();
}
}
public static bool TurnOn(string interfaceName)
{
var interfaceGuid = GetInterfaceGuid(interfaceName);
if (!interfaceGuid.HasValue)
return false;
return SetRadioState(interfaceGuid.Value, Wlan.Dot11RadioState.On);
}
public static bool TurnOff(string interfaceName)
{
var interfaceGuid = GetInterfaceGuid(interfaceName);
if (!interfaceGuid.HasValue)
return false;
return SetRadioState(interfaceGuid.Value, Wlan.Dot11RadioState.Off);
}
private static Guid? GetInterfaceGuid(string interfaceName)
{
using (var client = new WlanClient())
{
return client.Interfaces.FirstOrDefault(x => x.InterfaceName == interfaceName)?.InterfaceGuid;
}
}
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 static string[] GetAvailableNetworkProfileNames(string interfaceName)
{
using (var client = new WlanClient())
{
var wlanInterface = client.Interfaces.FirstOrDefault(x => x.InterfaceName == interfaceName);
if (wlanInterface == null)
return Array.Empty<string>();
return wlanInterface.GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags.IncludeAllManualHiddenProfiles)
.Select(x => x.profileName)
.Where(x => !string.IsNullOrEmpty(x))
.ToArray();
}
}
public static void ConnectNetwork(string interfaceName, string profileName)
{
using (var client = new WlanClient())
{
var wlanInterface = client.Interfaces.FirstOrDefault(x => x.InterfaceName == interfaceName);
if (wlanInterface == null)
return;
wlanInterface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName);
}
}
}
Check available interface names by GetInterfaceNames and then call TurnOn/TurnOff with one of the names. According to MSDN, it should require administrator priviledge but it doesn't on my environment.
SUPPLEMENT
I added two more methods to this class. So the sequence will be something like this.
Get existing Wi-Fi interface names by GetInterfaceNames.
Select an interface and turn it on by TurnOn.
Get profile names associated to available Wi-Fi networks through the interface by GetAvailableNetworkProfileNames.
Select a profile and connect to the network by ConnectNetwork.
After finished using the network, turn the interface off by TurnOff.
You could use the device library from windows universal apps.
Documentation:
https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.wifi.aspx
Microsoft sample:
https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples
In order to use this library with WPF application you could add
< TargetPlatformVersion > 8.0< / TargetPlatformVersion >
to your .csproj file between
< PropertyGroup>.... < /PropertyGroup>
Related
I have the below code and I want to get some VPN with some settings that I need to setup:
What I need is to
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotRas;
namespace vpnConsole
{
class Program
{
static void Main(string[] args)
{
string vpnName = "VPN Essai";
string destination = "113.244.66.3";
string preSharedKey = "Gs0r2!-8753";
try
{
RasPhoneBook phoneBook = new RasPhoneBook();
phoneBook.Open();
RasEntry vpnEntry = RasEntry.CreateVpnEntry(vpnName,destination,RasVpnStrategy.L2tpFirst,RasDevice.Create(vpnName,RasDeviceType.Vpn),false);
vpnEntry.Options.UsePreSharedKey = true;
vpnEntry.Options.UseLogOnCredentials = true;
vpnEntry.Options.RequirePap = true;
phoneBook.Entries.Add(vpnEntry);
vpnEntry.UpdateCredentials(RasPreSharedKey.Client, preSharedKey);
vpnEntry.Options.RequirePap = true;
bool isUpdated = vpnEntry.Update();
Console.WriteLine(#"Connection created and Updated with PreSharedKey=true, LogOnCredentials=true,RequirePap=true, RecordIsUpdated=" + isUpdated);
}
catch (Exception ex)
{
Console.WriteLine(#"ERROR: " + ex.Message + " Details: " + ex.Source );
Environment.Exit(999);
}
}
}
}
When I ran this code, it creates the VPN but does not keep settings I want to setup, for instance: RequirePap = true;
Configuration as I need it to be
i want to connect the myo wristband to the hololens. This is the end goal, but I am anyway but close to that :-/
The idea is to set up a Bluetooth LE Connection with UWP.
I wanted to do this, as explanined in this Microsoft Document
The search for the devices workes fine, but when I try to connect to a device, this line (Point "Connecting to the device"
): GattDeviceServicesResult result = await device.GetGattServicesAsync();
raises the error:
System.InvalidCastException: "Unable to cast object of type
'Windows.Devices.Bluetooth.BluetoothLEDevice' to type
'Windows.Devices.Bluetooth.IBluetoothLEDevice3'."
I have no idea what the IBluetoothLEDevice3 has to do there :-)
I was not able to find a solution for this on the microsoft documentation or the internet :-/
I work on Visual Studio 2017, build for Windows 10 (15063) and Bluetooth is enabled in the manifest.
This is my code so fare. I added only one thing and that is the Task. I wanted to make sure, that the BluetoothLEDDevice is not null or anything, since it is not synchron. Without its not working either.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Diagnostics;
using Windows.Devices.Enumeration;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth.Advertisement;
// Die Elementvorlage "Leere Seite" wird unter https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x407 dokumentiert.
namespace Bluetooth17
{
/// <summary>
/// Eine leere Seite, die eigenständig verwendet oder zu der innerhalb eines Rahmens navigiert werden kann.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
blue();
}
void blue()
{
// Query for extra properties you want returned
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
DeviceWatcher deviceWatcher =
DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
// Added, Updated and Removed are required to get all nearby devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
// EnumerationCompleted and Stopped are optional to implement.
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start the watcher.
deviceWatcher.Start();
}
private void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
{
Debug.WriteLine("Stopped");
}
private void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object args)
{
Debug.WriteLine("Enum complete");
}
private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
{
Debug.WriteLine(args.Id + " Removed");
}
private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
{
Debug.WriteLine(args.Id + " Update");
}
private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
{
Debug.WriteLine(args.Id + " " + args.Name);
if (args.Name.Equals("Myo"))
{
Debug.WriteLine("Try to connect to Myo");
getServices(args);
}
}
async Task<BluetoothLEDevice> ConnectDevice(DeviceInformation deviceInfo)
{
Debug.WriteLine("Asyc");
// Note: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
return await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
}
async void getServices(DeviceInformation deviceInfo)
{
Task<BluetoothLEDevice> task = ConnectDevice(deviceInfo);
task.Wait();
BluetoothLEDevice device = task.Result;
GattDeviceServicesResult result = await device.GetGattServicesAsync();
if (result.Status == GattCommunicationStatus.Success)
{
var services = result.Services;
// ...
}
}
}
}
Thank you
If you target your application to Build 15063 and you know the device you are connecting to than just use:
device = await BluetoothLEDevice.FromBluetoothAddressAsync(blueToothAddress);
This is much more stable than your code and no need for device watcher.
Here is an example that works for my device(not a MIO but a HM10) :
using System;
using System.Diagnostics;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.UI.Xaml.Controls;
namespace App1
{
public sealed partial class MainPage : Page
{
private BluetoothLEDevice device;
GattDeviceServicesResult serviceResult = null;
public MainPage()
{
this.InitializeComponent();
StartDevice();
}
private async void StartDevice()
{
//To get your blueToothAddress add: ulong blueToothAddress = device.BluetoothAddress to your old code.
ulong blueToothAddress = 88396936323791; //fill in your device address!!
device = await BluetoothLEDevice.FromBluetoothAddressAsync(blueToothAddress);
if (device != null)
{
string deviceName = device.DeviceInformation.Name;
Debug.WriteLine(deviceName);
int servicesCount = 3;//Fill in the amount of services from your device!!
int tryCount = 0;
bool connected = false;
while (!connected)//This is to make sure all services are found.
{
tryCount++;
serviceResult = await device.GetGattServicesAsync();
if (serviceResult.Status == GattCommunicationStatus.Success && serviceResult.Services.Count >= servicesCount)
{
connected = true;
Debug.WriteLine("Connected in " + tryCount + " tries");
}
if (tryCount > 5)//make this larger if faild
{
Debug.WriteLine("Failed to connect to device ");
return;
}
}
}
}
}
}
I want to play one video in different bitrates. Like i uploaded one video in 1080P resolution i want play that video in 720P, 480P, 360P, 240P, 144P etc.
I want this solution in asp.net using C#.
Like youtube provide the facility to watch video in different resolutions.
Please help me regarding this.
I tried the following code but not working:
using Softpae.Media;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
Job2Convert myJob = new Job2Convert();
MediaServer ms = new MediaServer();
myJob.pszSrcFile = "E:\\EhabVideoLibrary\\videos\\sinbad.mkv";
myJob.pszDstFile = "E:\\EhabVideoLibrary\\videos\\sinbad.mp4";
myJob.pszDstFormat = "mp4";
myJob.pszAudioCodec = "aac";
myJob.nAudioChannels = 2;
myJob.nAudioBitrate = -1;
myJob.nAudioRate = -1;
myJob.pszVideoCodec = "h264";
myJob.nVideoBitrate = -1;
myJob.nVideoFrameRate = -1;
myJob.nVideoFrameWidth = -1;
myJob.nVideoFrameHeight = -1;
bool ret = ms.ConvertFile(myJob);
}
}
}
You can use FFplay of the FFmpeg project. (ffmpeg.org) With FFmpeg it's possible to encode and transcode almost every codec in the resolution you want. In this thread is the use of a command line application using C# described.
I've never tried it, but there are also libraries provided for .NET using FFmpeg like this:
ffmpegdotnet.codeplex.com
intuitive.sk/fflib
Success with it!
Here is an example code using ffmpeg (I tested it under Win7 VM):
using System;
namespace ConsoleApplication_FFmpegDemo
{
class Program
{
static void Main(string[] args)
{
string inputVideo = #"C:\Users\Public\Videos\Sample Videos\Wildlife.wmv";
string outputVideo = #"C:\Users\Public\Videos\Sample Videos\Wildlife.mp4";
string ffmpegArg = string.Format("-i \"{0}\" -vf scale=320:240 \"{1}\"", inputVideo, outputVideo);
string ffmpegPath = #"C:\Portable\ffmpeg-win32-static\bin\ffmpeg.exe";
FFmpegTask ffmpegTask = new FFmpegTask(ffmpegPath, ffmpegArg);
ffmpegTask.Start();
Console.ReadLine();
}
}
}
And the FFmpegTask.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
namespace ConsoleApplication_FFmpegDemo
{
public class FFmpegTask
{
public Process process = new Process();
public FFmpegTask(string ffmpegPath, string arguments)
{
process.StartInfo.FileName = ffmpegPath;
process.StartInfo.Arguments = arguments;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = false;
process.StartInfo.UseShellExecute = false;
}
public bool Start()
{
return process.Start();
}
}
}
NEED A SOLUTION
Background agent is working only once. After There is no occurrence of a background agent. It works at the first time and it works perfectly as soon as the page opens. however, after that it takes forever and ever to do that again. sometimes page close and open doesn't work. that would probably because of not removing the agenet
My background Agent Code:
#define DEBUG_AGENT
using System;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Info;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Threading;
using Microsoft.Xna.Framework.Media;
using System.Windows.Input;
using Microsoft.Devices;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.Net.Sockets;
using System.Text;
using System.Net;
namespace ScheduledTaskAgent1
{
public class ScheduledAgent : ScheduledTaskAgent
{
private static volatile bool _classInitialized;
//private DispatcherTimer s;
Socket _socket = null;
ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;
double lat = 7.16126666666667;
static ScheduledAgent()
{
// Subscribe to the managed exception handler
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Application.Current.UnhandledException += UnhandledException;
});
}
/// Code to execute on Unhandled Exceptions
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
protected override void OnInvoke(ScheduledTask task)
{
//TODO: Add code to perform your task in background
string toastTitle = "";
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
lat += 0.001;
string snmea = DD2NMEA(lat, 80.44506);
string dates = DateTime.UtcNow.ToString("ddMMyy");
string UTCTime = DateTime.UtcNow.ToString("hhmmss") + ".000";
string s1 = Checksum("$FRCMD,869444005499999,_SendMessage,,0809.67600,N,8050.70360,E,1.0,1.08,3.0,141013,055642.000,1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
string s = Send("$FRCMD,869444005499999,_SendMessage,," + snmea + ",1.0,1.08,3.0," + dates + "," + UTCTime + ",1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
startToastTask(task, toastTitle);
}
private void startToastTask(ScheduledTask task, string toastTitle)
{
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
#endif
// Call NotifyComplete to let the system know the agent is done working.
NotifyComplete();
}
}
}
My Page from app which calls the agent
PeriodicTask toastPeriodicTask;
const string toastTaskName = "ToastPeriodicAgent";
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
toastPeriodicTask = ScheduledActionService.Find(toastTaskName) as PeriodicTask;
StartPeriodicAgent(toastTaskName);
}
private void StartPeriodicAgent(string taskName)
{
toastPeriodicTask = ScheduledActionService.Find(taskName) as PeriodicTask;
if (toastPeriodicTask != null)
{
RemoveAgent(taskName);
}
toastPeriodicTask = new PeriodicTask(taskName);
toastPeriodicTask.Description = periodicTaskDesc;
try
{
ScheduledActionService.Add(toastPeriodicTask);
#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(2));
#endif
}
catch (InvalidOperationException exception)
{
if (exception.Message.Contains("BNS Error: The action is disabled"))
{
MessageBox.Show("Background agents for this application have been disabled by the user.");
}
else if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
{
MessageBox.Show("BNS Error: The maximum number of ScheduledActions of this type have already been added.");
}
else
{
MessageBox.Show("An InvalidOperationException occurred.");
}
}
catch (SchedulerServiceException)
{
}
}
Ensure that your project has DEBUG_AGENT defined. This is a setting within your project properties. To set this flag, follow these steps
Right click the project within VS and select Properties
Select the Build tab
Add DEBUG_AGENT to the "Conditional compilation symbols" field.
If that is set, I've found it's best to give at least 30 seconds in the LaunchForTest. Sometimes it doesn't quite schedule it when you tell it to.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Security;
namespace SampleProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String input = textBox1.Text;
try
{
Process ps = new Process();
ps.StartInfo.FileName = #"\\199.63.55.163\d$\hello.bat";
ps.StartInfo.Arguments = input;
ps.StartInfo.CreateNoWindow = false;
String domain = ps.StartInfo.Domain;
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
ps.StartInfo.WorkingDirectory = #"d:\praveen";
ps.StartInfo.UserName = "Raj";
ps.StartInfo.Domain = "domain";
ps.StartInfo.Password = Encrypt("Hello123");
ps.StartInfo.UseShellExecute = false;
ps.Start();
ps.WaitForExit();
MessageBox.Show(ps.StandardOutput.ReadToEnd());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void label1_Click(object sender, EventArgs e)
{
}
public static SecureString Encrypt(String pwd)
{
SecureString ss = new SecureString();
for (int i = 0; i < pwd.Length; i++)
{
ss.AppendChar(pwd[i]);
}
return ss;
}
}
}
It's a shot in the dark, but I think that you can't read the processes standard output once it has exited.
Also you have to redirect it - take a look at this documentation: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
Duplicate of .NET Process Start Process Error using credentials (The handle is invalid) ? You need to assign RedirectStandardInput, RedirectStandardOutput, RedirectStandardError