Windows Phone 8 (HTC 8X) Flashlight does not turn on(Without using camera) - c#-4.0

As a newbie programmer I am going to ask a silly question. I want to turn on the flashlight of windows phone 8 without blinking (continous like other flashlight apps). Now I tried to use the sample example of
Reflection failure when attempting to access Microsoft.Phone.Media.Extended
but it did not work. I created a button called 'flash' and paste the code. It compiled fine, but my device HTC 8X does not turn on the flashlight even for a second. What I should do ?
The library & code I used :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Flashlight_V_0._1.Resources;
using Microsoft.Phone.Media;
using Windows.Phone.Media.Capture;
using Microsoft.Xna.Framework.Media;
using System.IO;
namespace Flashlight_V_0._1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
try
{
// get the AudioViceoCaptureDevice
var avDevice = await AudioVideoCaptureDevice.OpenAsync(sensorLocation,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation).First());
// turn flashlight on
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
{
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
// set flash power to maxinum
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
AudioVideoCaptureDevice.GetSupportedPropertyRange(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchPower).Max);
}
else
{
//ShowWhiteScreenInsteadOfCameraTorch();
}
}
catch (Exception ex)
{
// Flashlight isn't supported on this device, instead show a White Screen as the flash light
//ShowWhiteScreenInsteadOfCameraTorch();
}
}
}
}
I also tried this:
try
{
var _device = await AudioVideoCaptureDevice.OpenAsync(CameraSensorLocation.Back, AudioVideoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).First());
_device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
}
catch (Exception ex)
{
//
}
What am I doing wrong?

Sorry for late reply, got it ago but could not post.Sorry for that.
WP7/WP7.5 gives default to access all the sensors. But in WP8, you have to manually enable the sensors capability.
Go to the solution explorer.
Select the project.
Select Properties -> WMAppManifest.xml
Double Click on 'WMAppManifest.xml'
Select 'Capabilities'
Enable proper capability for app
To resolve my problem I had to enable two capabilities.
ID_CAP_ISV_CAMERA
ID_CAP_MICROPHONE
Thank YOU

Related

Environment.userName is Unknown in Hololens2

I have an hololens2 application that I built in Unity. The Environment.Username works in the Unity editor correctly, but when I deployed to the HL2, the Environment.UserName is Unknown. Under the player settings I've applied Enterprise Application, WebCam,Microphone, HumanInterfaceDevice, UserAccountInformation, Bluetooth, SystemManagement, UserDataTasks and Contacts.
It builds just fine and deploys to HL2 without problems, but the UserName is Unknown. When I go to the HL2 start menu, it displays my name correctly.
Please Help,
Martin F.
Please try the following code, it should display the account name signed into the HoloLens2:
using System;
using System.Collections.Generic;
using System.Text;
using TMPro;
using UnityEngine;
#if WINDOWS_UWP
using Windows.System;
#endif
public class UserName : MonoBehaviour
{
[SerializeField]
private TMP_Text userNameText = null;
// Start is called before the first frame update
async void Start()
{
#if WINDOWS_UWP
IReadOnlyList<User> users = await User.FindAllAsync();
StringBuilder sb = new StringBuilder();
foreach (User u in users)
{
string name = (string)await u.GetPropertyAsync(KnownUserProperties.AccountName);
if (string.IsNullOrWhiteSpace(name))
{
name = "unknown account name";
}
sb.AppendLine(name);
}
userNameText.text = sb.ToString();
#endif
}
}

How to wrap a Hangfire cancellation token?

I'm building up a .net core web app that requires background tasks to be run. To avoid using an external cron triggers we've decided to go with Hangfire; which is a beautiful package to use, does exactly whats needed then gets out of the way ;-)
To keep things clean I'm trying to stick to Uncle Bob's Clean architecture principles and seperate my ApplicationCore from the Infrastructure as much as possible. As Hangfire is an implementation detail it should ideally sit in the Infrastructure project, alongside database access, message queues, etc. with an Interface in the ApplicationCore, that my domain can use.
For the basic client running recurring and background jobs this has been fairly simple to do, and I've ended up with this as my Interface
namespace ApplicationCore.Interfaces
{
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
public interface IBackgroundJobClient
{
void AddOrUpdate<T>(
string recurringJobId,
Expression<Func<T, Task>> methodCall,
string cronExpression);
void RemoveIfExists(string recurringJobId);
}
}
Implementation is a simple wrapper for these methods which uses RecurringJob
namespace Infrastructure.BackgroundJobs
{
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Hangfire;
using IBackgroundJobClient = ApplicationCore.Interfaces.IBackgroundJobClient;
public class HangfireBackgroundJobClient : IBackgroundJobClient
{
public void AddOrUpdate<T>(
string recurringJobId,
Expression<Func<T, Task>> methodCall,
string cronExpression)
{
RecurringJob.AddOrUpdate<T>(recurringJobId, methodCall, cronExpression);
}
public void RemoveIfExists(string recurringJobId)
{
RecurringJob.RemoveIfExists(recurringJobId);
}
}
The issue that I have is needing to setup a RecurringJob with a supplied cancellationToken. However, I can't see an easy way to do this without exposing the underlying IJobCancellationToken and JobCancellationToken objects in my ApplicationCore code...?
What I've got at present is a wrapper for the JobCancellationToken in my Infrastructure.
namespace Infrastructure.BackgroundJobs
{
public class BackgroundJobCancellationToken : JobCancellationToken
{
public BackgroundJobCancellationToken(bool canceled): base(canceled)
{
}
}
}
An Interface in my ApplicationCore, which replicates the Hangfire one.
namespace ApplicationCore.Interfaces
{
using System.Threading;
public interface IJobCancellationToken
{
CancellationToken ShutdownToken { get; }
void ThrowIfCancellationRequested();
}
}
This is then used by the Method I want to execute as job, making use of the cancellationToken.ShutdownToken to pass into other methods requiring a cancellationToken.
public async Task GenerateSubmission(Guid SetupGuidId, IJobCancellationToken cancellationToken)
{
try
{
// Sort out the entities that we'll need
var setup = await this.SetupRepository.GetByGuidIdAsync(SetupGuidId);
var forecast = await this.GetCurrentForecastForSetup(setup, DateTime.UtcNow, cancellationToken.ShutdownToken);
// Other Code
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Which in turn is enabled elsewhere by calling
public async Task<Setup> EnableSetup(Setup setup)
{
setup.Enable();
this.jobClient
.AddOrUpdate<IForecastService>(
setup.GuidId.ToString(),
f => f.GenerateSubmission(setup.GuidId, null),
"45 */2 * * *");
await this.setupRepository.UpdateAsync(setup);
return setup;
}
This should be done with DomainEvents and Handlers, but one step at a time :-)
Is there a cleaner, better, easier way of doing this without taken a direct dependency on Hangfire in my ApplicationCore?
If the above setup works, I'll leave a comment on this question.
Since Hangfire 1.7 you no longer have to rely on IJobCancellationToken. You can simply use the standard .NET CancellationToken instead.

MvvmCross and UIButton.Selected UISegmentedControl Bindings, iOS

In a cross platform Xamarin app built with the MvvmCross framework I'm using a ToggleButton Widget in an Android .axml layout. I've bound the Checked property to a View Model property using a converter using the following binding syntax:
Checked MarketBuySellViewModel.Direction, Converter=DirectionBool, ConverterParameter='Sell'
Everything works well. On the iOS side, it appears you can use UIButton as a ToggleButton by using the Selected property. This implies that the following binding should achieve what I want on iOS:
set.Bind (SellButton).For(b => b.Selected).To (vm => vm.MarketBuySellViewModel.Direction).WithConversion("DirectionBool", "Sell");
I don't get any binding errors in the application output but the binding itself doesn't seem to work. Clicking the button doesn't set the Direction property and setting the direction to a different value does not set the Selected property on the UIButton.
Do I need to create a Custom Binding or am I simply setting up the binding incorrectly?
I also tried using a UISegmentedControl to achieve the same effect. Is binding to this control supported at all in MvvmCross? I don't see any reference to it in the source code. Does this mean I need to create custom bindings for it too?
For the UIButton, I don't believe there's any included Selected binding built into MvvmCross. Because of this - and because Selected doesn't have a simple paired event SelectedChanged, then I believe Selected binding should work one-way (from ViewModel to View) but not two-way.
There is a binding for the On of a UISwitch control and that's the control I've seen used most in these situations.
If you wanted to add a custom 2-way binding for Selected then I guess you'd have to do this using the ValueChanged event (but would need to check that is correct).
To do so, you'd just build a target binding something like:
public class MvxUIButtonSelectedTargetBinding : MvxPropertyInfoTargetBinding<UIButton>
{
public MvxUIButtonSelectedTargetBinding(object target, PropertyInfo targetPropertyInfo)
: base(target, targetPropertyInfo)
{
var view = View;
view.ValueChanged += HandleValueChanged;
}
private void HandleValueChanged(object sender, System.EventArgs e)
{
var view = View;
if (view == null)
return;
FireValueChanged(view.Selected);
}
public override MvxBindingMode DefaultMode
{
get { return MvxBindingMode.TwoWay; }
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (isDisposing)
{
var view = View;
if (view != null)
{
view.ValueChanged -= HandleValueChanged;
}
}
}
}
and this could be registered in Setup in protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry) using something like:
registry.RegisterPropertyInfoBindingFactory(typeof(MvxUIButtonSelectedTargetBinding), typeof(UIButton),
"Selected");
Similarly, I don't believe anyone has added a two way UISegmentedControl binding yet - but would happily see one added.
Building a two way UISegmentedControl binding would be quite straight-forward - you'd just have to bind to the pair SelectedSegment and ValueChanged - with code similar to above.
Alternatively, you could switch to using a custom MySegmentedControl which had a nicer Value`ValueChanged` pair which would automatically work without a custom binding - e.g.:
public class MySegmentedControl : UISegmentedControl
{
// add more constructors if required
public int Value
{
get { return base.SelectedSegment; }
set { base.SelectedSegment = value; }
}
}
If any or all of these custom bindings are needed, then the Mvx project is happy to get these bindings added as issues or pull requests along with test/demo UIs in the https://github.com/slodge/MvvmCross-Tutorials/blob/master/ApiExamples/ApiExamples.Touch/Views/FirstView.cs project
Could be helpful to someone else, so i'm sharing my experience. I needed a two way binding for UISegmentedControl.SelectedSegment property to a ViewModel. The one way biding (ViewModel => View) works by default. I couldn't able to properly utilize the solution proposed by Stuart - to subclass the UISegmentedControl. I tried to ensure that the linker does not rip off the new custom control code, but this didn't help me a bit. So a perfectly viable solution is the one with MvxPropertyInfoTargetBinding. Here is the code working ok for me:
public class MvxUISegmentedControlSelectedSegmentTargetBinding : MvxPropertyInfoTargetBinding<UISegmentedControl>
{
public MvxUISegmentedControlSelectedSegmentTargetBinding(object target, PropertyInfo targetPropertyInfo)
: base(target, targetPropertyInfo)
{
this.View.ValueChanged += HandleValueChanged;
}
private void HandleValueChanged(object sender, System.EventArgs e)
{
var view = this.View;
if (view == null)
{
return;
}
FireValueChanged(view.SelectedSegment);
}
public override MvxBindingMode DefaultMode
{
get { return MvxBindingMode.TwoWay; }
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (isDisposing)
{
var view = this.View;
if (view != null)
{
view.ValueChanged -= HandleValueChanged;
}
}
}
}
public class Setup : MvxTouchSetup
{
...
protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
registry.RegisterPropertyInfoBindingFactory(typeof(MvxUISegmentedControlSelectedSegmentTargetBinding), typeof(UISegmentedControl), "SelectedSegment");
}
}

C# code fails to read serial input from Arduino

Hi I am trying to read serial input from my Arduino but I am having no luck. I believe I am opening and closing the connection correctly but do not appear to be having much success!
I'm sure the Arduino is outputting data because I can see it in the serial terminal.
The code for my C# program is below, I was wondering if anyone could spot any mistakes I may have missed.
Also this is an example of the serial data I should receive "12.2,1111,332,233"
namespace FridgeProtectionDeviceMonitor
{
public partial class Online_mode : Form
{
public Online_mode()
{
InitializeComponent();
}
private void Online_mode_Load(object sender, EventArgs e)
{
cmbPortSelection.DataSource = SerialPort.GetPortNames();
cmbChartSelection.SelectedIndex = 0;
}
string x = "";
SerialPort port;
private void btnFindPorts_Click(object sender, EventArgs e)
{
var ports = SerialPort.GetPortNames();
cmbPortSelection.DataSource = ports;
}
private void btnOpenPort_Click(object sender, EventArgs e)
{
if (cmbPortSelection.SelectedIndex > -1)
{
port = new SerialPort(cmbPortSelection.Text);
try
{
if (!port.IsOpen)
{
port.BaudRate = 9600;
port.Open();
}
}
catch (Exception)
{
MessageBox.Show("Serial connection request denied: Port is in use!");
}
}
else
{
MessageBox.Show("Serial connection request denied: No port selected!");
}
}
private void btnClosePort_Click(object sender, EventArgs ex)
{
try
{
port.Close();
}
catch (Exception)
{
MessageBox.Show("Serial close connection request denied: ", ex.ToString());
}
}
private void update(object sender, EventArgs e)
{
txtSaveLocation.Text = x;
}
private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
x = port.ReadLine().ToString();
MessageBox.Show(x);
this.Invoke(new EventHandler(update));
}
}
}
I was just working on the same thing as you, you'll have to modify it if you want to use it for your purposes, but here's the code I use that works. The only problem is that for me I need it to read very quickly because it's for a speedometer and it sort of lags (anyone know why?) but anyways here's my code that works for me.
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
try
{
if (arduinoCom.IsOpen == false)
{
arduinoCom.Open();
}
}
catch
{
MessageBox.Show("Serial Error: Is your serial plugged in?");
}
}
private void refresh_Tick(object sender, EventArgs e)
{
string speedReading = arduinoCom.ReadLine();
speed.Text = speedReading;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
arduinoCom.Close();
}
}
}
I've got a USB to serial converter linked to an XBee wireless bridge linked to PIC micro-controllers and i've found that running the serial port read functions in a separate thread increases communication speeds something chronic!
The readline blocks the code until the newline character is received, therefore blocking your main thread. Before i moved it to another thread my GUI became un-responsive etc.
By the way I'm using ReadByte().
I'm continuously reading bytes from the serial buffer in a backgroundworker and storing them in a thread safe queue. Then checking the queue for my communication start bits and analyzing the packet from there. Using manual reset events I'm syncing everything.
In my experience the port_datareceived event is a nice addition to the serialport class but unfortunately it is relatively useless for fast communications. I'm running at 12900 baud.
If you want code snippets i can provide them.
Regards,
Pete
P.S. I'm using an ATS5004D 4 channel differential oscilloscope with multichannel software. multichannel software can analyse the voltage signal into serial data through it's built in serial analyzer block. That way you can see what's actually being discussed on the serial comms lines!! cutting out all the BS other serial terminals add...
#michael b I'd start by looking at what the actual communication is doing i.e. scope the TX RX lines to see what the arduino board is putting out. I have only little experience with arduino but its predecessor the PICAXE system had a debug function which slowed everything down heaps, is something like this going on?
How many times per second do you want to update the speedo?
The SAE J1939 automotive serial communication standard says that RPM only needs to be updated once every 100ms. The human eye usually can't see/react faster than 300ms. 9600 baud gives you one 8bit byte per millisecond approx.
Personally I wouldn't use the timer to get the updates and instead do everything on a separate thread from main, and let it run as fast/slow as it wants.
this thread shows you roughly how i've set up my communications System.IO.IOException: A device attached to the system is not functioning C# .NET 4.0
hope it helps,
pete

How to get live camera preview in Windows Phone 8

I want to create an application in Windows phone8. In this application i want to show live camera preview with different effect in multiple frame using C# in Windows phone 8. please give me a solution
To use the camera in Windows phone 8 you need to use the PhotoCamera object. Best to create this object on your OnNavigatedTo like so:
protected override void OnNavigatedTo (System.Windows.Navigation.NavigationEventArgs e)
{
if (PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true)
{
cam = new PhotoCamera(CameraType.Primary);
cam.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(cam_CaptureImageAvailable);
viewfinderBrush.SetSource(cam);
}
else
{
txtMessage.Text = "A Camera is not available on this device."; }
}
}
// dispose when we leave
protected override void OnNavigatingFrom (System.Windows.Navigation.NavigatingCancelEventArgs e)
{
if (cam != null)
{
cam.Dispose();
}
}
To actually capture the image from the camera you can then call the CaptureImage method on the cam object.

Resources