I get a System.NotImplementedException error whenever I try to launch the page on the emulator that takes photographs. Whenever I attempt to take a photo with the emulator's camera, I get taken to the main page in the Xamarin Studio project that launches the user interface. I get the error:
System.NotImplementedException has been thrown
This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.
Here is the code:
using UIKit;
namespace Relate.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
/* if you want to use a different Application Delegate class
from "AppDelegate" you can specify it here. */
UIApplication.Main(args, null, "AppDelegate");
}
}
}
Can anyone help?
Here is the code for the camera. I added Media Plugin to my project.
using System;
using Relate.Model;
using Xamarin.Forms;
using Plugin.Media;
namespace Relate.Views
{
public partial class EditMemberPage : ContentPage
{
public EditMemberPage()
{
InitializeComponent();
saveButton.Clicked += async (sender, args) =>
{
if (CrossMedia.Current.IsCameraAvailable &&
CrossMedia.Current.IsTakePhotoSupported)
{
// Supply media options for saving our photo after
it's taken.
var mediaOptions = new
Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Receipts",
Name = $"{DateTime.UtcNow}.jpg"
};
// Take a photo of the business receipt.
var file = await
CrossMedia.Current.TakePhotoAsync(mediaOptions);
}
};
}
async void SaveButton_OnClicked(object sender, EventArgs e)
{
var famMemberItem = (FamMember)BindingContext;
await App.Database.SaveFamMemberAsync(famMemberItem);
await Navigation.PopAsync();
}
}
}
The answer here should explain why this is not working for you: https://forums.xamarin.com/discussion/93536/error-while-accessing-camera
You cannot access platform specific features using portable common libraries. If you want to access your emulators camera you'll have to use something like Media Plugin
https://github.com/jamesmontemagno/MediaPlugin
Related
First off I would just like to mention that I am by no means a C# or a windows developer expert.
The following code is kind of a mish-mash I've slap together from examples and tutorials I found on the internet.
The premise of the code is to create a webview2 component in a winform, where the winform is a DLL that gets loaded by a third-party application.
Now, the third-party application loads my DLL and calls this function:
Integrations::ShowForm("Form1");
My winform is a basic C# Windows Forms App using .Net Framework.
My Form1.cs looks as follows:
namespace GuiIntegrations
{
public partial class Form1 : Form
{
public Form1()
{
string webview2DllPath = #"C:\TestFolder\runtimes\win-x64\native";
CoreWebView2Environment.SetLoaderDllFolderPath(webview2DllPath);
Environment.SetEnvironmentVariable("WEBVIEW2_USER_DATA_FOLDER", #"C:\TestFolder\user-data");
InitializeComponent();
_ = InitializeAsync();
}
}
}
My Form1.Designer.cs file looks like:
namespace GuiIntegrations
{
public partial class Form1 : Form
{
private System.ComponentModel.IContainer components = null;
#region Windows Form Designer generated code
...
#endregion
private Microsoft.Web.WebView2.WinForms.WebView2 webView21;
async Task InitializeAsync()
{
try
{
string webview2FixedPath = #"C:\TestFolder\Microsoft.WebView2.FixedVersionRuntime.105.0.1343.33.x64";
var env = await CoreWebView2Environment.CreateAsync(browserExecutableFolder: webview2FixedPath , userDataFolder: #"C:\TestFolder\user-data");
await webView21.EnsureCoreWebView2Async(env);
webView21.Source = new Uri("https://www.google.com");
}
catch (Exception e)
{
// The exception goes into an event-list that can be processed outside the DLL
}
}
}
}
(The excluded #region is just your normal winform generated code).
Also in the DLL is a class called Integrations.cs, that looks like this:
namespace GuiIntegrations
{
public static class Integrations
{
private static Form1 form;
private static Thread formThread;
[STAThread]
public static void ShowForm(string formName)
{
try
{
Assembly assembly = Assembly.GetExecutingAssembly();
Type[] types = assembly.GetTypes();
foreach (Type type in types)
{
if (type.BaseType == typeof(Form) && type.Name == formName)
{
object obj_form = type.Assembly.CreateInstance(type.FullName);
form = (Form1)obj_form;
formThread = new Thread(() => Application.Run(form));
formThread.SetApartmentState(ApartmentState.STA);
formThread.Start();
Thread.Sleep(200);
}
}
} catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
}
Apologies that its not the most eloquent source, but I kind of did it on the fly.
FYI:
C:\TestFolder\runtimes\win-x64\native is the location for the 'WebView2Loader.dll' DLL of the webview2 component.
my winform DLL location also contains the 3 other webview2 DLLs Microsoft.Web.WebView2.Core.dll, Microsoft.Web.WebView2.WinForms.dll, Microsoft.Web.WebView2.Wpf.dll
C:\TestFolder\Microsoft.WebView2.FixedVersionRuntime.105.0.1343.33.x64 is the extracted location of the fixed runtime for webview2.
The problem occurs when 'CoreWebView2Environment.CreateAsync' is called. As soon as its executed, it throws an exception 'Exception: CoInitialize has not been called. (Exception from HRESULT: 0x800401F0 (CO_E_NOTINITIALIZED)'.
As far as I could determine from the error, its not entering the single-apartment state, which is strange considering that I am setting the thread-state that starts the form as STA.
I've also checked that my component doesn't contain a 'Source' field:
ComponentProperties
Any help would be greatly appreciate.
PS. When I compile the program as a Windows Application and run it, the component loads fine and shows the google page.
I am writing a simple Xamarin application with MvvmCross. I just tried to do some binding but compliler is giving me this error
The call is ambiguous between the following methods or properties: 'MvvmCross.Binding.BindingContext.MvxBindingContextOwnerExtensions.CreateBindingSet(TTarget)' and
'MvvmCross.Binding.BindingContext.MvxBindingContextOwnerExtensions.CreateBindingSet(TTarget)** . This error is thrown at var set =
this.CreateBindingSet<LoginViewController, LoginViewModel>();
I have added MvvmCross, MvvmCross.Binding, MvvmCross.Platform and MvvmCross.Core in my Xamarin.iOS project.
Please help to get rid of this error. Below is the code of my ViewController:
using Kinettix.Core.ViewModels;
using MvvmCross.Binding.BindingContext;
using MvvmCross.Platforms.Ios.Views;
using UIKit;
namespace Kinettix.iOS.Views
{
public partial class LoginViewController : MvxViewController<LoginViewModel>
{
public LoginViewController() : base("LoginViewController", null)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
this.NavigationController.NavigationBarHidden = true;
var set = this.CreateBindingSet<LoginViewController, LoginViewModel>();
set.Apply();
tfUsername.ShouldReturn+= (sender) =>
{
sender.ResignFirstResponder();
return false;
};
tfPassword.ShouldReturn += (sender) =>
{
sender.ResignFirstResponder();
return false;
};
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
}
}
Ok. I have found the answer to my question. I had MvvmCross.Core, MvvmCross.Platform, MvvmCross.binding and MvvmCross in my iOS project. It was complaining about ambiguous call to CreateBindingSet between MvvmCross and MvvmCross.Binding. I removed all packages and just installed MvvmCross. This way, It made call to CreateBindingSet using MvvmCross and It Worked. :)
I have been trying to write a C# application on Win10 that only runs a background task that writes into a file.
Running the code below throws UnauthorizeAccessException exception after the trigger, 'Access to the path 'C:\temp' is denied'.
The file and directory both have full access for Everyone.
Also, what can background tasks access/run? I am trying to run a background task while in modern standby and for it to read some registers and/or run another tool. Is that even possible while still in modern standby?
Here is the code of my attempt in doing so:
Background task:
using Windows.ApplicationModel.Background;
using System.IO;
namespace RuntimeComponent2
{
public sealed class Class1 : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
File.WriteAllText(#"C:\temp\test.txt", "test");
}
}
}
Main page:
using System;
using Windows.ApplicationModel.Background;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace App3
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
var exampleTaskName = "MyTask1";
foreach (var t in BackgroundTaskRegistration.AllTasks)
{
t.Value.Unregister(true);
}
await BackgroundExecutionManager.RequestAccessAsync();
var builder = new BackgroundTaskBuilder();
builder.Name = exampleTaskName;
builder.TaskEntryPoint = "RuntimeComponent2.Class1";
builder.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false));
BackgroundTaskRegistration task = builder.Register();
}
}
}
You cannot do that, and the problem is not regarding the BackgroundTask. Inside a UWP application you cannot write on your hard-disk. The only places you can read & write is accessible using ApplicationData.Current (LocalCacheFolder, LocalFolder and so on), or any folder the user choose explicitly using SaveFilePicker.
Furthermore, you need to use this syntax (Intellisense suggests you to use the class File, but in UWP isn't really available)
FileIO.ReadTextAsync(StorageFile file);
I'm trying to create a file then write to the file and read from it as well... kind of like settings for my app to load every time it loads. Why is this not working for me? I'm running visual studio 2012 and I think when I run the program there the file should be created in the project's folder... my method it's async and void... don't really know what is going on haha
StorageFile sampleFile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("config.txt", CreationCollisionOption.ReplaceExisting);
How can I create this in the local folder? so every time the program runs no matter in what computer it will create the file and load it when the user close and re-open the program?
Man, great question!
Here's the exact logic to do what you are asking:
public class MyData
{
public string Title { get; set; }
}
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
this.DataContext = await LoadData();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
SaveData(this.DataContext as MyData);
base.OnNavigatedFrom(e);
}
private async Task<MyData> LoadData()
{
var _Data = await StorageHelper.ReadFileAsync<MyData>(
this.GetType().ToString(), StorageHelper.StorageStrategies.Local);
return _Data ?? new MyData() { Title = "Welcome" };
}
private async void SaveData(MyData data)
{
await StorageHelper.WriteFileAsync(
this.GetType().ToString(), data, StorageHelper.StorageStrategies.Local);
}
}
The StorageHelper class can be found here. or on my blog http://jerrynixon.com
Best of luck!
How can I create this in the local folder?
You can't, and anyway you're not supposed to... Windows Store apps run in a sandbox, they have a very restricted access to the file system. Basically, you have access to:
your app's LocalFolder (which is not the installation folder) and RoamingFolder
documents library, pictures library, music library, etc, depending on your app's capabilities (declared in the app manifest)
files selected by the user using a file picker
And I think that's about it... You can also access the files in the installation folder (Package.Current.InstallationFolder), but only for reading.
I am trying to use ManagementEventWatcher in a service to keep track of when a computer goes in and out of sleep mode. I am new to .NET and C# so I am struggling quite a bit to come up with syntax to make this work.
I have found a blog post that details how he used ManagementEventWatcher to keep track of this status, but he did not post up his entire code. I am trying to go through and make a simple service that creates a .txt log file stating that the computer has been suspended/resumed but am running into problems with the namespaces and types.
Here is the code to the service.cs file:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Management;
namespace SleepNotifierService
{
public class WqlEventQuery : EventQuery { }
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WqlEventQuery query = new WqlEventQuery("Win32_PowerManagementEvent");
_watcher = new ManagementEventWatcher(query);
_watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
_watcher.Start();
}
protected override void OnStop()
{
_watcher.Stop();
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
try
{
int eventType = Convert.ToInt32(e.NewEvent.Properties["EventType"].Value);
switch (eventType)
{
case 4:
Sleep();
break;
case 7:
Resume();
break;
}
}
catch (Exception ex)
{
//Log(ex.Message);
}
}
public void Sleep()
{
}
public void Resume()
{
}
}
}
Again, this is the first time that I am programming with .NET and C# so I apologize for my ignorance.
I am getting namespace errors such as:
The type or namespace name
'ManagementEventWatcher' could not be
found (are you missing a using
directive or an assembly reference?)
Thanks,
Tomek
You need the System.Management namespace, which is included in the code sample provided by you. I believe you need to reference the System.Management library in your project settings. Follow the following steps to do this( I am assuming you are suing Visual Studio):
Go to the Solution Explorer, and expand your project, right click on the References folder/option and select Add References from the context menu. Now select the .Net tab and select the System.Management from the list and click OK.