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);
Related
Sometimes it is required to turn off sleep mode in the application while a lengthy process is running. When the process has done, sleep mode can be turned on again.
How to do that in Xamarin, for Android and iOS projects?
We'll make an interface and use DependencyService to run platform-specific implementation in the platform-agnostic project.
In the platform agnostic project create an interface:
namespace MyCompany.Services {
public interface ISleepModeHandler
{
public void BlockSleepMode(bool blockSleepMode);
}
}
In the Android project:
In the AndroidManifest.xml file, add this permission:
<uses-permission android:name="android.permission.WAKE_LOCK" />
Add Xamarin.Essentials dependency to the platform-agnostic and to the android project. And don't forget to initialize Xamarin.Essentials in the android project.
Create the class:
using Android.Views;
using MyCompany.Android.Services;
using MyCompany.Services
using Xamarin.Essentials;
using Xamarin.Forms;
[assembly: Dependency(typeof(SleepModeHandlerForDroid))]
namespace MyCompany.Android.Services
{
public class SleepModeHandlerForDroid : ISleepModeHandler
{
public void BlockSleepMode(bool blockSleepMode)
{
Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
{
MainActivity activity = (MainActivity)Platform.CurrentActivity;
if (blockSleepMode)
{
activity.Window.AddFlags(WindowManagerFlags.KeepScreenOn);
}
else
{
activity.Window.ClearFlags(WindowManagerFlags.KeepScreenOn);
}
});
}
}
}
In iOS project create the class:
using MyCompany.Services;
using MyCompany.iOS.Services;
using UIKit;
using Xamarin.Forms;
[assembly: Dependency(typeof(SleepModeHandlerForiOS))]
namespace MyCompany.iOS.Services
{
[Foundation.Preserve(AllMembers = true)]
public class SleepModeHandlerForiOS : ISleepModeHandler
{
public void BlockSleepMode(bool blockSleepMode)
{
Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
{
UIApplication.SharedApplication.IdleTimerDisabled = blockSleepMode;
});
}
}
}
That's it. Now, in platform agnostic module, when you want to block sleep mode while processing, and turn it on afterwards use the following approach:
ISleepModeHandler sleepModeHandler = DependencyService.Get<ISleepModeHandler>();
sleepModeHandler.BlockSleepMode(true); // blocking the sleep mode
// your process goes here
sleepModeHandler.BlockSleepMode(false); // allowing the sleep mode again
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
I'm beginner in Xamarin Test Cloud and I want to write tests for Xamarin Test Cloud.
I have Xamarin UITests in my solution and I tried to launch REPL, but UITest REPL window didn't open.
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Android;
using Xamarin.UITest.Queries;
namespace MurakamiKiev.UITests
{
[TestFixture]
public class Tests
{
AndroidApp app;
[SetUp]
public void BeforeEachTest ()
{
app = ConfigureApp.Android.StartApp ();
}
[Test]
public void TestLaunch ()
{
app.Repl();
}
}
}
Where is the error?
Also, what I need to write to launch specified activity?
If you don't have the application source code in the same solution then you'll need to specify the prebuilt app by pointing to it via a full path.
[SetUp]
public void BeforeEachTest ()
{
app = ConfigureApp.Android.ApkFile("<path-as-string>").StartApp ();
}
I have a timed quartz.net job working fine on my dev machine, but once deployed to a remote server it is not triggering. I believe the job is scheduled ok, because if I postback, it tells me the job already exists (I normally check for postback however). The email code definitely works, as the 'button1_click' event sends emails successfully.
I understand I have full or medium trust on the remove server. My host says they don't apply restrictions that they know of which would affect it. Any other things I need to do to get it running?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Quartz;
using Quartz.Impl;
using Quartz.Core;
using Aspose.Network.Mail;
using Aspose.Network;
using Aspose.Network.Mime;
using System.Text;
namespace QuartzTestASP
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ISchedulerFactory schedFact = new StdSchedulerFactory();
IScheduler sched = schedFact.GetScheduler();
JobDetail jobDetail = new JobDetail("testJob2", null, typeof(testJob));
//Trigger trigger = TriggerUtils.MakeMinutelyTrigger(1, 3);
Trigger trigger = TriggerUtils.MakeSecondlyTrigger(10, 5);
trigger.StartTimeUtc = DateTime.UtcNow;
trigger.Name = "TriggertheTest";
sched.Start();
sched.ScheduleJob(jobDetail, trigger);
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
myutil.sendEmail();
}
}
class testJob : IStatefulJob
{
public testJob() { }
public void Execute(JobExecutionContext context)
{
myutil.sendEmail();
}
}
public static class myutil
{
public static void sendEmail()
{
// tested code lives here and works fine when called from elsewhere
}
}
}
The scheduler factory should be global to your application. In other words, declare it in Global.asax or similar that effectively gives you a global instance to operate with. You should start the scheduler in your application start if running ASP.NET.
Beware thought. ASP.NET recycles its processes which effective causes shutdown of scheduler (no jobs will run) until next next request comes in to web server to start the scheduler again. The recommended way is to have a windows service for running Quartz.NET jobs.
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.