Using an android scanner device, running KitKat.
Using Xamarin in Visual Studio Enterprise 2017, 15.9.9.
I need to generate a "Success" or "Error" sound, based on the content of the scanned barcode.
I have two files: "Success.mp3" and "Error.wav", neither of which will play.
Since this should be a very simple process, I am trying to use Android's MediaPlayer class, rather than add some NuGet package.
I am using Dependency Injection to properly run the Android code, since Xamarin does not have any sort or media API.
I instantiate Android's MediaPlayer as variable "player", and it does successfully instantiate, but as soon as I attempt to do anything with it, it throws a Null Exception error and the value of "player" displays as Null.
I have been experimenting with different ways to do this and have copies of the sound files stored both in the Assets folder, and the Resources/Raw folder (see below).
Here is my method:
public void PlaySound(string soundType) {
var filename =
global::Android.App.Application.Context.Assets.OpenFd(soundType);
if (player == null) {
MediaPlayer player = new MediaPlayer();
}
//This is where the error happens
player.SetDataSource(filename);
player.Prepare();
player.Start();
}
I have also tried the last three lines as the following, with the same result:
player.Prepared += (s, e) => {
player.Start();
};
player.SetDataSource(filename.FileDescriptor, filename.StartOffset,
filename.Length);
player.Prepare();
I have also attempted to utilize what so many people demonstrate as the way to do this, but it does not work for me. This is where the file must be stored in Resources/Raw:
player = MediaPlayer.Create(global::Android.App.Application.Context,
Resource.Raw.someFileName);
Whatever value that you use for "someFileName", all Visual Studio gives you is "'Resource.Raw' does not contain a definition for 'someFileName'".
Resource.designer.CS does contain entries for both files:
public const int Error = 2131230720;
public const int Success = 2131230721;
Expected results: sound, or some meaningful error message that puts me on the right path.
I am still relatively new to Xamarin and am probably missing something that would be obvious to veteran eyes. I have tried so many other things, most of which are not mentioned here, grasping for some straw. This should be simple, but is proving otherwise. Thank you for any help that you can provide.
This question already has an answer here:
UWP app: FileOpenPicker PickSingleFileAsync() can't await
(1 answer)
Closed 5 years ago.
I am building an UWP app (C#) and on click of button, I want to verify input.
If verification fails, I want to display a message saying that there is wrong input.
this is my function which should handle this:
private async void AddContact_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
DBHelper db = new DBHelper();
if(i_name.Text != "" && i_phone.Text != "") {
db.insertPerson(new Person(i_name.Text, i_phone.Text));
Frame.Navigate(typeof(MainPage));
} else {
ContentDialog msg = new ContentDialog() {
Title = "Empty input!",
Content = "Please fill both fields!",
CloseButtonText = "OK"
};
await msg.ShowAsync();
}
}
However, when the last part (await msg.showAsync() ) is typed it stays underlined in red (in VS). The builder reads the following error:
Error CS4036 'IAsyncOperation' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'IAsyncOperation' could be found (are you missing a using directive for 'System'?) testniStudioApp d:...\SecondPage.xaml.cs 43 Active
Now i tried to assign this call to variable (as I saw that someone solved similiar problem that way), but it still didn't worked.
Then I tried clearing NuGet cache and rebuilding project as stated here, but none of those solutions worked.
I have a hard time understanding what it wants from me.
Every single tutorial on how to display message was written in more or less the same manner, so I can't understand what can be wrong.
using System; was mising.
Thanks to comments for answer
I have problem with using camera in Windows Phone Silverlight 8.1 application. I want just to initialize camera and see its preview (for now I don't need any photos or video capture). I have found nice and simple example on MSDN and
private CaptureSource captureSource;
private VideoCaptureDevice videoCaptureDevice;
private void InitializeVideoRecorder()
{
try
{
if (captureSource == null)
{
captureSource = new CaptureSource();
var a = captureSource.VideoCaptureDevice;
videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
captureSource.CaptureFailed += OnCaptureFailed;
if (videoCaptureDevice != null)
{
VideoRecorderBrush = new VideoBrush();
VideoRecorderBrush.SetSource(captureSource);
captureSource.Start();
CameraStatus = "Tap record to start recording...";
}
else
{
CameraStatus = "A camera is not supported on this phone.";
}
}
}
catch (Exception ex)
{
CameraStatus = "ERROR: " + ex.Message.ToString();
}
}
The code stops at captureSource.Start(); throwing System.UnauthorizedAccessException: Attempted to perform an unauthorized operation..
First of all I found information (on the same page) that ID_CAP_ISV_CAMERA capability is needed in `WMAppManifest.xml'. But I have problem with adding it, because:
I can't find this capability in designer
I get error when I add it manualy to .xml file
Error reproduced below:
Warning 1 The 'Name' attribute is invalid - The value 'ID_CAP_ISV_CAMERA' is invalid according to its datatype 'http://schemas.microsoft.com/appx/2010/manifest:ST_Capabilities' - The Enumeration constraint failed.
Error 3 App manifest validation failed. Value 'ID_CAP_ISV_CAMERA' of attribute '/Package/Capabilities/Capability/#Name' must be a valid capability.
I have even found the same solution on SO WP8.1 SilverLight Microsoft.Devices.PhotoCamera Access Denied
Can somebody tell me why can't I use original MSDN solution to this problem?
First, it looks like you're trying to add that capability to Package.appxmanifest instead of WMAppManifest.xml. You should be able to find WMAppManifest.xml under Solution Explorer -> <your project> -> Properties:
Opening that file should give you the option to add ID_CAP_* capabilities.
Second, you need to specify both ID_CAP_ISV_CAMERA and ID_CAP_MICROPHONE in order to use CaptureSource.Start(), even if you're only using one of the devices.
I'm try to use Vista TaskDialog Wrapper and Emulator and I'm getting the following exception:
"Unable to find an entry point named 'TaskDialogIndirect' in DLL 'ComCtl32'."
...in a simple Console application:
class Program
{
[STAThread]
static void Main(string[] args)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
PSTaskDialog.cTaskDialog.MessageBox(
"MessageBox Title",
"The main instruction text for the message box is shown here.",
"The content text for the message box is shown here and the text willautomatically wrap as needed.",
PSTaskDialog.eTaskDialogButtons.YesNo,
PSTaskDialog.eSysIcons.Information
);
}
}
What am I doing wrong?
UPDATE:
Actually, I'm working on an Excel plugin using excel-dna. How can I control what dll Excel loads?
http://exceldna.codeplex.com/discussions/286990#post728888
I haven't been at Office programming in a while, but my guess is that Excel loads both versions of comctl32, so you may need to use the Activation Context API to direct your code to the version that includes TaskDialog. Some ideas for fixing the problem (not solutions as such):
For test purposes, make a temporary enumeration of all modules in the active process - just to check if 6.10 is actually loaded (see below for a simple example of such an enumeration, albeit with a different intent).
Use the Activation Context API to get to the right version. Example of use from C# (for enabling themes by way of comctl32 6.0) here.
Alternatively (I never actually got this to work reliably in a WPF application I worked on), make a dialog abstraction class, which falls back to MessageDlg depending on the version available to you. There may be better ways of doing the check, but...:
FileVersionInfo version = ProcessUtils.GetLoadedModuleVersion("comctl32.dll");
if (version != null && version.FileMajorPart >= 6 && version.FileMinorPart >= 1)
{
// We can use TaskDialog...
}
else
{
// Use old style MessageBox
}
The enumeration of modules:
internal static FileVersionInfo GetLoadedModuleVersion(string name)
{
Process process = Process.GetCurrentProcess();
foreach (ProcessModule module in process.Modules)
{
if (module.ModuleName.ToLower() == name)
{
return module.FileVersionInfo;
}
return null;
}
}
In addition to what all the others are saying: This error will disappear if you set the ForceEmulationMode on PSTaskDialog to true.
I am trying to display a simple message, which I have done probably thousands of times in the past, and NOW... The full string of text is NOT being displayed in the MessageBox. I'm not doing anything differently, so I don't see the problem. Here's my code:
if (MessageBox.Show("The text in this file has changed. Do you want to save changes?",
"TextEditor - Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
{ //Do stuff
} else {
// Do stuff }
Now, when the messagebox is displayed, the only text that is visible is this:
The text in this file has changed.
NOTE: The Yes/No buttons are visible, and the messagebox looks normal, it doesn't look broken or anything, so I have no idea why I can't display a simple dam question in there anymore!?... Does anybody know about this? Have you experienced this before?
Thanks
OK, THIS IS WIERD... (EDITED)
I have just changed the text for the above messagebox text and now it displays the following:
The text in this file has changed. Do you wa
But the most important part of the question is still not being displayed...
Couple of things to try:
1) If running the debug version, try compiling and running the release version
2) Try creating a whole new project and copying the code to the new project and run it (could be a project setting was changed, then you could diff the files)
3) Try disabling any anti-virus software you have.
have you tried - just to be sure - to escape the whole string by prefixing it with a #-sign?
like so:
if (MessageBox.Show(#"The text in this file has changed. Do you want to save changes?",
#"TextEditor - Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
{ //Do stuff
} else {
// Do stuff }
Did you try to put your text in a variable juste to see if it work?
string message = #"The text in this file has changed. Do you want to save changes?";
string title = "TextEditor - Confirmation";
if (MessageBox.Show,(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1) == DialogResult.Yes){ //Do stuff } else { // Do stuff }
Its something odd/stupid - its time to act back by being stupid
First question - are all of your message boxes affected? If not then this case has something wrong with it. If they are all affected then ... well I don't know what to suggest really. More coffee?
Best thing to do is to reduce the problem down to the smallest possible. Create a new message box and only enter your current text (copy and paste it). Dont set any of the other parameters and take it out of the if statement
If that works, then the problem is with the parameters
- slowly add the parameters until it breaks
If it doesnt then the problem is with the text
- delete the text and retype it - there may be a strange character there - e.g. has the text been near MS Word...
- if that works, then you are golden
- otherwise, delete word by word until it starts working
I reckon you'll find out it something really stupid
The space between "changed." and "Do" wouldn't be some weird character (say NULL), would it? Try to delete the whole text and then type it again by hand.
Hmm... just remembered some weird old bug with McAffee antivirus and .NET whereupon the whole contents of messageboxes would disappear. This was however more than 5 years ago...
Maybe try updating your PC? And - you wouldn't happen to be running McAffee, would you? :)
Idea No. 3: Send us your compiled .EXE and the source files?
Idea No. 4: Compile it, then rip it open with Reflector and check how it has been compiled. Compilers have bugs too...
I've tried it too and it seems to work fine.
Maybe check the regional/language settings on the machine your running it on?
There's no set size for message boxes in the form.Designer.cs is there?
Have you tried creating another solution with 1 form and the following code - btw works form me vs2008 winXP en-gb lang
using System;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
if (MessageBox.Show("The text in this file has changed. Do you want to save changes?", "TextEditor - Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
{
MessageBox.Show("yes");
}
else
{
MessageBox.Show("no");
}
}
}
}
Could you possibly try a newline \n after "changed"?
I have just solved this problem. I am using Windows XP Home Edition and am also using Stardock's WindowBlinds to pretty-up the 500-year old WindowsXP interface. This has never caused any problems in the past, I have been using WindowBlinds for years, and also doing C# stuff for about a year and a half, and this is the first time that WindowBlinds has caused any problems what so ever.
The reason why only part of the text was showing in the MessageBox still ramins a mystery, BUT as soon as I decided to try and Close WindowBlinds and apply the standard XP theme again... All MessageBox's work properly in C#.
Thank you ALL for your good suggestions they are very much appreciated. :o)
Jason Pezzimenti