What is the proper way of using the Windows.Media.Miracast namespace? - c#

I am looking into screen casting through Miracast in an application but am unsure of how to use the Windows.Media.Miracast namespace. Limited information exists on the internet due to the short age of the Windows 10 1903 update that the namespace comes as a part of.
The only thing I've found so far is this documentation.
My question is does anybody know what the proper way of using this namespace is? Any examples or resources found online would be a great help.
Cheers.

These three sample projects demonstrate various MiraCast source apis that can be used from UWP applications. Not sure about outside UWP.
https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BasicMediaCasting
https://github.com/microsoft/Windows-universal-samples/tree/master/Samples/AdvancedCasting
https://github.com/microsoft/Windows-universal-samples/tree/master/Samples/Projection
I'm personally using code like the following, on Windows IoT Core, to cast my whole screen
Scan for devices:
miraDeviceWatcher = DeviceInformation.CreateWatcher(CastingDevice.GetDeviceSelector(CastingPlaybackTypes.Video));
miraHandlerAdded = new TypedEventHandler<DeviceWatcher, DeviceInformation>(async (watcher, deviceInfo) =>
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
//Add each discovered device to our listbox
CastingDevice addedDevice = await CastingDevice.FromIdAsync(deviceInfo.Id);
var disp = new CastingDisplay(addedDevice); //my viewmodel
MiraDevices.Add(disp); //ObservableCollection
});
});
miraDeviceWatcher.Added += miraHandlerAdded;
Connect to selected device:
public async Task StartCasting(CastingDisplay castee)
{
//When a device is selected, first thing we do is stop the watcher so it's search doesn't conflict with streaming
if (miraDeviceWatcher.Status != DeviceWatcherStatus.Stopped)
{
miraDeviceWatcher.Stop();
}
//Create a new casting connection to the device that's been selected
connection = castee.Device.CreateCastingConnection();
//Register for events
connection.ErrorOccurred += Connection_ErrorOccurred;
connection.StateChanged += Connection_StateChangedAsync;
var image = new Windows.UI.Xaml.Controls.Image();
await connection.RequestStartCastingAsync(image.GetAsCastingSource());
}
This Image is just used as a casting source. Once the connection is made, my whole screen is broadcast. The behavior is not documented. Hopefully it won't get 'fixed' in a future update.

Related

Playing an HDHomeRun stream on a Tizen.NET Xamarin App

I'm trying to play a HDHomeRun Connect Video source from a url in the following format: http://x.x.x.x:xxxx/auto/v4.1. This video source is an MPEG2 video encoding and AC3 audio encoding.
I've tried using the Samsung Tizen.TV .NET sample with the following source but the video never plays.
_player = new Tizen.Multimedia.Player();
var mediaSource = new Multimedia.MediaUriSource(uri);
_player.SetSource(mediaSource);
var display = new Multimedia.Display(Window.Instance);
_player.Display = display;
await _player.PrepareAsync();
The player state gets stuck in preparing, and the await _player.PrepareAsync() call never finishes. It is worth noting that I'm using the Tizen Samsung TV Emulator. Do I need to transcode the stream from the HDHomeRun to be playable? Are there any other measures I might be missing for the Video to play?
Ultimately, the Display property of the player wasn't being set correctly. The property that worked for me (found from investigating the JuvoPlayer code was this:
var display = new Multimedia.Display(((FormsApplication)Forms.Context).MainWindow);
_player.Display = display;
When you are to develop a Tizen .NET application, please be aware of which UI framework your project is targetted for among 3 different types: Xamarin.Forms, (pure) ElmSharp, and Tizen.NUI.
Unless your project is based on the Tizen.NUI framework, you shouldn't use Tizen.NUI.Window.Instance and types in Tizen.NUI namespace in any case. Instead, you will have to use types of ElmSharp or Xamarin.Forms.Platform.Tizen namespace for platform-specific code in your application.
Since the internal implementation of Xamarin.Forms for Tizen is based on ElmSharp, FormsApplication.MainWindow will return a ElmSharp.Window instance which can be used to instantiate a Tizen.Multimedia.Display object. That's why the code in your answer worked.

Discord: Change region using .NET library?

I'm currently trying to prevent lags on my Discord server using a bot checking the latency, and switching to another region if it does happen. I saw a couple of bots in js doing that, I'd like to know if there's something in Discord.NET able to do it. Of course, I've been parsing Google for hours to find a way.
Thanks
You can call ModifyAsync on an instance of your SocketGuild and set the RegionId property to your desired new region.
//I'm doing this as a command, but the logic can be implemented wherever you decide.
[Command("region")]
[Remarks("Let's pretend my module has access to a singleton instance of random")]
public async Task ChangeRegion()
{
//Get a collection of all available voice regions
//Exclude the region we are currently in
var voiceRegions = Context.Client.VoiceRegions.Where(r => !r.Id.Equals(Context.Guild.VoiceRegionId));
//Select a random new region
var newRegion = voiceRegions(random.Next(voiceRegions.Count));
//Update the RegionId property for the guild.
await Context.Guild.ModifyAsync(prop => prop.RegionId = newRegion.Id)
await ReplyAsync($"Region updated to {newRegion.Name}: {newRegion.Id}");
}

Read data via bluetooth using c#

I am using Lecia Disto e7100i which basically measures distance and area using laser. This device has bluetooth and can be paired with windows.
I am trying to develop an wpf app that reads the mesaured data using c#
There is no sdk that comes along with the device.
I have tried to use 32feet.Net but since there is no proper documentation I don't know where to start.
Is there any way that I can do to solve my problem?
This is not a full response, instead its more of a guideline on how to resolve your issue:
Pair the device with your Computer
Run the included software that displays the data somehow
Use WireShark to analyze the traffic
see if it is a standard protocol type or something custom
understand the protocol and reimplement it using c# and BluetoothSockets
To get started, you can try:
var client = new BluetoothClient();
// Select the bluetooth device
var dlg = new SelectBluetoothDeviceDialog();
DialogResult result = dlg.ShowDialog(this);
if (result != DialogResult.OK)
{
return;
}
BluetoothDeviceInfo device = dlg.SelectedDevice;
BluetoothAddress addr = device.DeviceAddress;
Console.WriteLine(device.DeviceName);
BluetoothSecurity.PairRequest(addr, "PIN"); // set the pin here or take user input
device.SetServiceState(BluetoothService.HumanInterfaceDevice, true);
Thread.Sleep(100); // Precautionary
if (device.InstalledServices.Length == 0)
{
// handle appropriately
}
client.Connect(addr, BluetoothService.HumanInterfaceDevice);
Also make sure that
Device appears in "Bluetooth devices" in the "Control panel".
Device is HID or change code accordingly.
Hope it helps. Cheers!
Try this demo project, and the following articles after that one.
Try to follow this tutorial
Here you can see a direct answer by the mantainer of 32feet, with which you can get in touch
Check also this answer

c# Bluetooth LE - write configuration error - ValueChanged never called

So I try to connect my c# WPF program to a BLE device and this is the code to connect to the device:
private async Task ConnectToWatcher(DeviceInformation deviceInfo) {
try {
// get the device
BluetoothLEDevice device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
// get the GATT service
Thread.Sleep(150);
var gattServicesResult = await device.GetGattServicesForUuidAsync(new Guid(RX_SERVICE_UUID));
service = gattServicesResult.Services[0];
// get the GATT characteristic
Thread.Sleep(150);
var gattCharacteristicsResult = await service.GetCharacteristicsForUuidAsync(new Guid(RX_CHAR_UUID));
characteristic = gattCharacteristicsResult.Characteristics[0];
// register for notifications
Thread.Sleep(150);
characteristic.ValueChanged += (sender, args) => {
Debug.WriteLine($"[{device.Name}] Received notification containing {args.CharacteristicValue.Length} bytes");
};
GattWriteResult result =
await characteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
Debug.WriteLine($"Characteristics write result: status={result.Status}, protocolError={result.ProtocolError}");
} catch (Exception ex) when ((uint)ex.HResult == 0x800710df) {
Debug.WriteLine("bluetooth error 1");
// ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on.
}
}
The line
Debug.WriteLine($"Characteristics write result: status={result.Status}, protocolError={result.ProtocolError}"
creates the output
Characteristics write result: status=protocolError, protocolError=3
I couldn't find anywhere whats that supposed to mean. The effect is the Method characteristic.ValueChanged never gets called.
Do I have to do more to have the characteristic configurated? And has anybody any idea why the method isn't called or what that error message means?
Thanks a bunch.
Apparently, some Windows 10 builds have a COM security bug.
Solution was to register for Windows-Insider-Program and update Windows.
Update:
There are two more solutions to this:
1) Calling CoInitializeSecurity from outside your c#-code (didn't bring it to work)
- or-
2) Writing two new keys into the windows registry. You cann create a file "Bluetooth.reg", which will add those two keys on a doubleklick. This answer from https://social.msdn.microsoft.com/Forums/en-US/58da3fdb-a0e1-4161-8af3-778b6839f4e1/bluetooth-bluetoothledevicefromidasync-does-not-complete-on-10015063?forum=wdk was my solution:
Hi Kamen, I have experienced exactly same issue. You can give a quick try of the following:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID{C6BFD646-3DF0-4DE5-B7AF-5FFFACB844A5}]
"AccessPermission"=hex:01,00,04,80,9c,00,00,00,ac,00,00,00,00,00,00,00,14,00,\
00,00,02,00,88,00,06,00,00,00,00,00,14,00,07,00,00,00,01,01,00,00,00,00,00,\
05,0a,00,00,00,00,00,14,00,03,00,00,00,01,01,00,00,00,00,00,05,12,00,00,00,\
00,00,18,00,07,00,00,00,01,02,00,00,00,00,00,05,20,00,00,00,20,02,00,00,00,\
00,18,00,03,00,00,00,01,02,00,00,00,00,00,0f,02,00,00,00,01,00,00,00,00,00,\
14,00,03,00,00,00,01,01,00,00,00,00,00,05,13,00,00,00,00,00,14,00,03,00,00,\
00,01,01,00,00,00,00,00,05,14,00,00,00,01,02,00,00,00,00,00,05,20,00,00,00,\
20,02,00,00,01,02,00,00,00,00,00,05,20,00,00,00,20,02,00,00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID\YOURAPP.exe]
"AppID"="{C6BFD646-3DF0-4DE5-B7AF-5FFFACB844A5}"
Copy above content to a text file.
Replace 'YOURAPP.EXE' with your executable name
Optionally replace GUIDs (I have created a new one for you)
Save text file with an extension as .reg
Double click on the file.
You would see a message 'The Keys and values contained in ..... .reg have been successfully added to the registry.'
With this, I don't need to call CoInitializeSecurity from my app.
you need to call CoInitializeSecurity before
more info here. couple of weeks I spent looking for solution :)
https://social.msdn.microsoft.com/Forums/en-US/58da3fdb-a0e1-4161-8af3-778b6839f4e1/

Xamarin says "Allow Multiple Bind To Same Port only allowed on Windows". What do I do?

I'm trying to use SocketLite.PCL with my iOS/Android solution in Xamarin,
but I get the message Allow Multiple Bind To Same Port only allowed on Windows when running it.
What does it mean and how do I fix it?
EDIT:
Example code I'm using can be found here: https://github.com/1iveowl/SocketLite.PCL
I put the following code inside rotected async override void OnStart(){} of the app:
var udpReceived = new UdpSocketReceiver();
await udpReceived.StartListeningAsync(4992, allowMultipleBindToSamePort: true);
var udpMessageSubscriber = udpReceived.ObservableMessages.Subscribe(
msg =>
{
System.Console.WriteLine($"Remote adrres: {msg.RemoteAddress}");
System.Console.WriteLine($"Remote port: {msg.RemotePort}");
var str = System.Text.Encoding.UTF8.GetString(msg.ByteData);
System.Console.WriteLine($"Messsage: {str}");
},
ex =>
{
// Exceptions received here
}
);
EDIT 2:
Ok, so setting allowMultipleBindToSamePort to false stopped that error.
Now I get the error Address already in use.
However I am still curious as to what allowMultipleBindToSamePort is used for.
As you can see in the new documentation:
IMPORTANT: Please notice that the parameter allowMultipleBindToSamePort will only work on Windows. On other platforms it should be set to false
About However I am still curious as to what allowMultipleBindToSamePort is used for.
There is a good and complete explanation on this post, you can read more in the following stackoverflow post

Categories