Media capture initializing error - c#

I have a problem with UWP media capture initilization. My code is below,
private async Task StartPreviewAsync()
{
try
{
//set initilize settings
Settings oneSetting = null;
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), sqlpath))
{
oneSetting = (from p in conn.Table<Settings>()
where p.id == 0
select p).FirstOrDefault();
}
if (oneSetting.camera != null)
{
var settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Video;
settings.PhotoCaptureSource = PhotoCaptureSource.VideoPreview;
var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(Windows.Devices.Enumeration.DeviceClass.VideoCapture);
foreach (var device in devices)
{
if ((device.Id).Equals(oneSetting.cameraId))
{
settings.VideoDeviceId = device.Id;
break;
}
}
_mediaCapture = new MediaCapture();
await _mediaCapture.InitializeAsync(settings);
//MediaCapture m = new MediaCapture();
//await m.InitializeAsync();
var focusSettings = new FocusSettings();
focusSettings.AutoFocusRange = AutoFocusRange.FullRange;
focusSettings.Mode = FocusMode.Auto;
focusSettings.WaitForFocus = true;
focusSettings.DisableDriverFallback = false;
_mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
await _mediaCapture.VideoDeviceController.ExposureControl.SetAutoAsync(true);
_mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
_mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);
capturePreview.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();
_isPreviewing = true;
_displayRequest.RequestActive();
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
}
}
catch (UnauthorizedAccessException)
{
// This will be thrown if the user denied access to the camera in privacy settings
System.Diagnostics.Debug.WriteLine("The app was denied access to the camera");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("MediaCapture initialization failed. {0}", ex.Message);
}
}
It returns MediaCapture initialization failed. {0} error. Recently, it runs well. But since this morning it gives the error. Is there anybody who takes the same error?
The full error message is that;
The specified device interface level or feature is not supported on this system.
: Media Capture initialization failed. {0}
The thread 0x1924 has exited with code 0 (0x0).

Same issue here.
After many hours of retries and googling i realize that it was related to the windows 10 anniversary update.
I found the solution here:
https://www.macecraft.com/fix-webcam-issues-windows-10-anniversary-update/
I added the EnableFrameServerMode key in the registry and magically the webcam came back working.

But since this morning it gives the error.
Did you recently update your device OS? On which device did you meet this problem and what is the OS version?
I personally think this is more like a device problem or drive issue. You can try to restart your device and see if this helps. Or you can start the built-in camera app and check if this official app runs well.
I'm writing this answer here because there are too many details need to be confirmed, please leave a comment here to tell us the detail information about your device and your test result based on my suggestion, so can we keep look into this issue.

Related

C# Windows 10 Bluetooth LE can't connect to server

I'm developing a c# desktop api with forms where I want to receive ACC data from a BLE server und display them in a chart.
So I'm running in a connection problem and I can't find any solution.
I can find my LE server Device with the watcher.
DevicePairingResult dpr = await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.Encryption);
returns me "AlreadyPaired"
But when I do
device = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress: eventArgs.BluetoothAddress);
mGattService = device.GetGattService(MotionService_GUID);
mCharacteristic = mGattService.GetCharacteristics(ACC_Characteristic_GUID)[0];
and then
var con = device.ConnectionStatus;
I receive "Disconnected" in con.
I am bound with de device on windows( I searched for it in Windows and entered the Code) but I am not connected(based on the Status in the windows info center).
I've read in another Thread in the windows c# developer page that it should not be necessary anymore to pair the device manually.
I'm pretty shure that the rest of my code works because sometimes I can get a connection( pretty confusing for me) and see the right Data in my chart.
Right now I just want to reach a stable connection before changing other part of my code.
Anyone any idea how to solve this?
Thx medTech
Edit:
Here is part of the Code:
Scanning for BLE
private void button1_Click(object sender, EventArgs e)
{
// Create Bluetooth Listener
var watcher = new BluetoothLEAdvertisementWatcher();
watcher.ScanningMode = BluetoothLEScanningMode.Active;
// Register callback for when we see an advertisements
watcher.Received += OnAdvertisementReceivedAsync;
// Wait 5 seconds to make sure the device is really out of range
watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(5000);
watcher.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(2000);
// Starting watching for advertisements
watcher.Start();
}
Connect to Server:
private async void OnAdvertisementReceivedAsync(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
// Filter for specific Device
if (eventArgs.Advertisement.LocalName == "MYDEVICE")
{
watcher.Stop();
var MotionService_GUID = new Guid("00002000-0000-1000-8000-00805F9B34FB");
var ACC_Characteristic_GUID = new Guid("00002001-0000-1000-8000-00805F9B34FB");
device = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress: eventArgs.BluetoothAddress);
DevicePairingResult dpr = await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.Encryption);
mGattService = device.GetGattService(MotionService_GUID);
mCharacteristic = mGattService.GetCharacteristics(ACC_Characteristic_GUID)[0];
GattDeviceServicesResult result = await device.GetGattServicesAsync();
GattCommunicationStatus status1 = await ReadFromCharacteristicAsync(mCharacteristic);
var con = device.ConnectionStatus;
while (status1 == GattCommunicationStatus.Success)
{
try
{
status1 = await ReadFromCharacteristicAsync(mCharacteristic);
}
catch
{
Console.WriteLine("ERROR");
status1 = GattCommunicationStatus.Unreachable;
}
}
}
}
Read from Characteristic:
async Task ReadFromCharacteristicAsync(GattCharacteristic mCharacteristic)
{
GattReadResult readResult = await mCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached);
if (readResult.Status == GattCommunicationStatus.Success)
{
byte[] data = new byte[readResult.Value.Length];
DataReader.FromBuffer(readResult.Value).ReadBytes(data);
if (chart1.IsHandleCreated)
{
this.Invoke((MethodInvoker)delegate { updateChart(data); });
}
return readResult.Status;
}
return readResult.Status;
}
Terminate Connection
private async Task<bool> ClearBluetoothLEDeviceAsync()
{
mCharacteristic.Service.Dispose();
mGattService.Dispose();
await device.DeviceInformation.Pairing.UnpairAsync();
device?.Dispose();
device = null;
GC.Collect();
return true;
}
SO now when I connect the first time to the Server, I only receive zeros which shows me that the there might be a authentication Error.
After that I always receive this Error:
"System.ArgumentException" in mscorlib.dll with a notification that there is noch executable Code left because all Threads are doing some asynchronous stuff.
This Error gets thrown when I try to read from the Characteristic.
I never coded in c# before so I am not shure if there is an error in my asynchronous part oder the communication part.
Thanks you
Pairing is not the same as connecting!
I really advise using the BLE-advertisementWatcher to select and connect to your device.
The reason is that many BLE-devices don't save their pairing status.
In windows device-watcher once paired, the device stays paired even if it is switched off or out of reach.
Also many times the connection status is kept, unless the device is unpaired and disposed in code or removed in windows settings.
All BLE-devices that I know of start advertising as soon as there is no connection for some time.
This time depends on the device, but most of the time within seconds.
So don't pair but just connect if the device is advertising.

TLSharp Data center (dc) Exception

I am using TLSharp library for implementing a custom Telegram client. when I run the code below:
public async Task<string> SendCodeRequest(string phoneNumber)
{
var completed = false;
TL.AuthSendCodeRequest request = null;
while (!completed)
{
request = new TL.AuthSendCodeRequest(phoneNumber, 5, _apiId, _apiHash, "en");
await _sender.Send(request);
await _sender.Receive(request);
completed = true;
}
// TODO handle other types (such as SMS)
if (request.Result is TL.AuthSentCodeType)
{
var result = (TL.AuthSentCodeType)request.Result;
return result.PhoneCodeHash;
}
else
{
var result = (TL.AuthSentAppCodeType)request.Result;
return result.PhoneCodeHash;
}
}
I gives me the following exception :
Your phone number registered to {dcIdx} dc. Please update settings.
See https://github.com/sochix/TLSharp#i-get-an-error-migrate_x for
details.
The mentioned github page says that TLSharp Handles these exceptions by itself. So I guess something is wrong with the library core because the code should resolve data center IPs by itself not generating an exception.
Any help would be appreciated.
TlSharp Currently doesn't handle this exception you have to catch the exception and get the data center number then Try to reconnect to the Data Center using the ReconnectToDc() Function.
In the MtProtoSender.cs file you can find the following line of code that generates the exception:
throw new InvalidOperationException($"Your phone number registered to {dcIdx} dc. Please update settings. See https://github.com/sochix/TLSharp#i-get-an-error-migrate_x for details.");
Replace it with the following code so that the Exception that is generated has the required Data Center number for connecting to it.
InvalidOperationException exception = new InvalidOperationException($"Your phone number registered to {dcIdx} dc. Please update settings. See https://github.com/sochix/TLSharp#i-get-an-error-migrate_x for details.");
exception.Data.Add("dcId", dcIdx);
throw exception;
Change your code like this:
while (!completed)
{
request = new TL.AuthSendCodeRequest(phoneNumber, 5, _apiId, _apiHash, "en");
try
{
await _sender.Send(request);
await _sender.Receive(request);
completed = true;
}
catch (InvalidOperationException ex)
{
if (ex.Message.StartsWith("Your phone number registered to") && ex.Data["dcId"] != null)
{
await ReconnectToDc((int)ex.Data["dcId"]);
}
else
{
throw;
}
}
}
In the Code above the Data Center number that was attached to the Exception is used for reconnecting to the Data center.
Probably your phone number is not in the format accepted by Telegram.
Phone number must start with plus sign, use country code and phone number without gap, for example: +989333333333

BackgroundTask geofence triggering

I am trying to showToast when the phone leaves or enter the geofenced location (which is set elsewhere and passed in). The issue is that when the app is in the background the trigger does not occur and I don't see the showToast message. I am changing the location manually using an emulator on my PC.
Background Tasks> Location is set under the app manifest.
This is the code I am using to build the Geofence and backgroundtask
//Creates Geofence and names it "PetsnikkerVacationFence"
public static async Task SetupGeofence(double lat, double lon)
{
await RegisterBackgroundTasks();
if (IsTaskRegistered())
{
BasicGeoposition position = new BasicGeoposition();
position.Latitude = lat;
position.Longitude = lon;
double radius = 8046.72; //5 miles in meters
Geocircle geocircle = new Geocircle(position, radius);
MonitoredGeofenceStates monitoredStates = MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited;
Geofence geofence = new Geofence("PetsnikkerVacationFence", geocircle, monitoredStates, false);
GeofenceMonitor monitor = GeofenceMonitor.Current;
var existingFence = monitor.Geofences.SingleOrDefault(f => f.Id == "PetsnikkerVacationFence");
if (existingFence != null)
monitor.Geofences.Remove(existingFence);
monitor.Geofences.Add(geofence);
}
}
//Registers the background task with a LocationTrigger
static async Task RegisterBackgroundTasks()
{
var access = await BackgroundExecutionManager.RequestAccessAsync();
if (access == BackgroundAccessStatus.Denied)
{
}
else
{
var taskBuilder = new BackgroundTaskBuilder();
taskBuilder.Name = "PetsnikkerVacationFence";
taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
taskBuilder.SetTrigger(new LocationTrigger(LocationTriggerType.Geofence));
taskBuilder.TaskEntryPoint = typeof(Petsnikker.Windows.Background.GeofenceTask).FullName;
var registration = taskBuilder.Register();
registration.Completed += (sender, e) =>
{
try
{
e.CheckResult();
}
catch (Exception error)
{
Debug.WriteLine(error);
}
};
}
}
static bool IsTaskRegistered()
{
var Registered = false;
var entry = BackgroundTaskRegistration.AllTasks.FirstOrDefault(keyval => keyval.Value.Name == "PetsnikkerVacationFence");
if (entry.Value != null)
Registered = true;
return Registered;
}
}
}
This code is where I monitor the state of the geofence.
This is where the Entry point in the appxmanifest is pointing
public sealed class GeofenceTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
var monitor = GeofenceMonitor.Current;
if (monitor.Geofences.Any())
{
var reports = monitor.ReadReports();
foreach (var report in reports)
{
switch (report.NewState)
{
case GeofenceState.Entered:
{
ShowToast("Approaching Home",":-)");
break;
}
case GeofenceState.Exited:
{
ShowToast("Leaving Home", ":-)");
break;
}
}
}
}
//deferral.Complete();
}
private static void ShowToast(string firstLine, string secondLine)
{
var toastXmlContent =
ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
var txtNodes = toastXmlContent.GetElementsByTagName("text");
txtNodes[0].AppendChild(toastXmlContent.CreateTextNode(firstLine));
txtNodes[1].AppendChild(toastXmlContent.CreateTextNode(secondLine));
var toast = new ToastNotification(toastXmlContent);
var toastNotifier = ToastNotificationManager.CreateToastNotifier();
toastNotifier.Show(toast);
Debug.WriteLine("Toast: {0} {1}", firstLine, secondLine);
}
}
After looking at your code, it seems that your code is correct.
In order to fire the Geofence Backgroundtask to show the toast information, please make sure the following things:
1) Please make sure that you have done all the necessary configuration in the Package.appxmanifest for registering the BackgroundTask, for example you have set the correct EntryPoint and added the “Location” capabilities.
For the detailed information, you can try to compare your Package.appxmanifest with the official sample Geolocation’s Package.appxmanifest.
Please also check: Create and register a background task and Declare background tasks in the application manifest.
2) Please make sure that you know how to set the location in the Emulator manually for simulating the phone leave or enter the geofenced location. For more information about how to set location in the emulator, please check the following article:
https://msdn.microsoft.com/library/windows/apps/dn629629.aspx#location_and_driving .
3) Please make sure that your second position in your emulator is not really far away from the geofences that you have defined in the first time, because the emulator behaves like a real device, and the device doesn’t expect to suddenly move from New York to Seattle. Or the BackgroundTask will not be fire immediately.
4) Background tasks for geofencing cannot launch more frequently than every 2 minutes. If you test geofences in the background, the emulator is capable of automatically starting background tasks. But for the next subsequent background tasks, you need to wait for more than 2 minutes.
Besides, I will recommend you refer to the following article about how to use the Windows Phone Emulator for testing apps with geofencing:
https://blogs.windows.com/buildingapps/2014/05/28/using-the-windows-phone-emulator-for-testing-apps-with-geofencing/ .
Thanks.

Error when trying to get my current location using Bing Maps in a Windows Store App

I'm developing a Windows Store App where I'm using the Bing Maps control. I created a method that use the Geolocator and GeoPosition to get the users current position.
Also, I enabled the location capability from the manifiest file.
However, everytime when I run the App, the first time I click on the button to get the position I got the following error message: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).
When I click the second time in the same button to perform the same action, now the error messages disappear and the Bing Maps work properly showing me my current position. But, I'm a little concerned why I got the error messages always the firsr time I try to get the location.
Here are the two methods I execute to get the position:
private async Task SetMyLocation()
{
var position = await GetCurrentPosition();
if (position != null)
{
this.DataContext = position;
this.myLocation = new Location(position.Latitude, position.Longitude);
this.myMap.Center = this.myLocation;
//this.myMap.ZoomLevel = 20;
this.myMap.SetView(myLocation, 12, MapAnimationDuration.Default);
this.AddMyLocationPushpin();
}
}
private async Task<Position> GetCurrentPosition()
{
try
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.MovementThreshold = 0;
Geoposition location = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromMinutes(5),
timeout: TimeSpan.FromSeconds(10)
);
var postion = new Position
{
Latitude = location.Coordinate.Latitude,
Longitude = location.Coordinate.Longitude
};
return postion;
}
catch (Exception ex)
{
. . .
return null;
}
}
Any suggestion, comment why I am getting the above error message? Any clue and/or solution would be OK?
Regards!
Ensure that you have allowed your app to access the user location. Open the Package manifest and go to the capabilities tab. Make sure the Location option is checked. Re-run your app, you will be prompted to allow the app to access your location, allow it. It should then work for you. You can find a blog post example on this here: http://www.bing.com/blogs/site_blogs/b/maps/archive/2012/11/05/getting-started-with-bing-maps-windows-store-apps-native.aspx

Mute microphone on Windows 7

I have an problem with muting the mic on an windows 7 machine. But all the code i have found dosen't run ore it's not doing anything the runned. Have is it done for an Windows 7 machine using C# code. I just need an on/off solution.
The DDL file works also with Win x64bit. But i thing that i creates an error another place.
mixers.Recording.Lines.GetMixerFirstLineByComponentType(
MIXERLINE_COMPONENTTYPE.SRC_MICROPHONE).Volume = 0;
if (!mediaElement1.CheckAccess()) mediaElement1.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate { mediaElement1.Play(); });
if (MessageBox.Show("Incoming Call from: " + string.Format(e.RemoteParticipant), "Video Chat Call", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
mixers.Recording.Lines.GetMixerFirstLineByComponentType(
MIXERLINE_COMPONENTTYPE.SRC_MICROPHONE).Volume = 1;
if (!mediaElement1.CheckAccess()) mediaElement1.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate { mediaElement1.Stop(); });
_currentConversation.StartVideo();
}'
If error occurs at if (MessageBox.Show("Incoming Call from: " + string.Format(e.RemoteParticipant), "Video Chat Call", MessageBoxButton.YesNo) == MessageBoxResult.Yes) and says {"Arithmetic operation resulted in an overflow."}
http://www.computercabal.com/2010/11/mute-microphone-from-c-on-windows.html -- this gentleman appears to have had a similar problem, and he's provided the source code for a solution.
You can use Audio Switcher Api
https://www.nuget.org/packages/AudioSwitcher.AudioApi.CoreAudio/4.0.0-alpha5
Code is quite simple:
private async void btnMute_ButtonClick(object sender, EventArgs e)
{
var audioController = new CoreAudioController();
var devices = await audioController.GetDevicesAsync(DeviceType.Capture, DeviceState.Active);
var device = devices.FirstOrDefault(x => x.IsDefaultDevice);
if(device != null) {
await device.SetMuteAsync(!device.IsMuted);
}
}
this might help: Windows Mixer Control in C#
Good luck :).
EDIT: It can also mute certain devices if I'm right.

Categories