Define Entry Point of a BackgroundTask for UWP - c#

I want to know how can I declarate in the EntryPoint of a Declaration in the manifest file the location of the code to execute as a background task.
I have my code set in a folder called "Models" inside the project, But I don't know how to reffer to this code.
Here you have a picture of it:
Just in case, here is my code inside the cs:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.UI.Popups;
namespace Universal_in_C.Models
{
public sealed class ExampleBackgroundTask : IBackgroundTask
{
public async Task ExampleMethodAsync()
{
Debug.WriteLine("Done Exe");
var dialog = new MessageDialog("TESTING, TESTING LIKE THERE IS NO TOMORROW.");
await dialog.ShowAsync();
}
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
await ExampleMethodAsync();
_deferral.Complete();
}
}
}
And how I call it(I know that I need to change the entry here too);
private void button6_Click(object sender, RoutedEventArgs e)
{
var taskRegistered = false;
var exampleTaskName = "BackgroundTask";
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == exampleTaskName)
{
taskRegistered = true;
break;
}
}
if (taskRegistered)
{
Debug.WriteLine("Already Exist");
}
else
{
var builder = new BackgroundTaskBuilder();
Debug.WriteLine("Started to Exist");
builder.Name = exampleTaskName;
builder.TaskEntryPoint = "exampleTaskName";
builder.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable, true));
builder.AddCondition(new SystemCondition(SystemConditionType.UserPresent));
builder.Register();
}
}
Thanks!

From what I understand, you are having problems declaring the background task on the manifest file. Based on this, my answer.
You need to create a new project that will contain your background tasks. This is necessary in order to correctly debug them later on.
Reference the project on your application.
Create the task by implementing the IBackgroundTask interface.
Register it via code.
Register it on the manifest.
At step number 5, the entry point is always the {project namespace}.{background task name}, so for example if you created a project names BackgroundTasks with a task ExampleTask, the entry point will be: BackgroundTasks.ExampleTask
I'll leave for future references a link to the guidelines and tutorial on how to implement them.

Related

CefSharp how to rename and embed BrowserSubProcess.exe

iam quite desperate here. I couldn't find any example code for this in C#.
I want to rename BrowserSubProcess.exe and i want it to embed my main exe, if possible.
I am aware of this solution;
https://github.com/cefsharp/CefSharp/issues/1149#issuecomment-225547869
Rename CefSharp.BrowserSubprocess winforms
but i couldn't implemented it. I need sample program or code to understand. I hope #amaitland will see this and helps me.
I embed the BrowserSubProcess Program.cs to my Program.cs so it is embedded now.
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
if (args.Count() < 5)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new LoginForm());
}
else
{
MyBrowserSubProcess(args);
}
}
static int MyBrowserSubProcess(string[] args)
{
Debug.WriteLine("BrowserSubprocess starting up with command line: " + String.Join("\n", args));
SubProcess.EnableHighDPISupport();
int result;
var type = args.GetArgumentValue(CefSharpArguments.SubProcessTypeArgument);
var parentProcessId = -1;
// The Crashpad Handler doesn't have any HostProcessIdArgument, so we must not try to
// parse it lest we want an ArgumentNullException.
if (type != "crashpad-handler")
{
parentProcessId = int.Parse(args.GetArgumentValue(CefSharpArguments.HostProcessIdArgument));
if (args.HasArgument(CefSharpArguments.ExitIfParentProcessClosed))
{
Task.Factory.StartNew(() => AwaitParentProcessExit(parentProcessId), TaskCreationOptions.LongRunning);
}
}
// Use our custom subProcess provides features like EvaluateJavascript
if (type == "renderer")
{
var wcfEnabled = args.HasArgument(CefSharpArguments.WcfEnabledArgument);
var subProcess = wcfEnabled ? new WcfEnabledSubProcess(parentProcessId, args) : new SubProcess(args);
using (subProcess)
{
result = subProcess.Run();
}
}
else
{
result = SubProcess.ExecuteProcess();
}
Debug.WriteLine("BrowserSubprocess shutting down.");
return result;
}
private static async void AwaitParentProcessExit(int parentProcessId)
{
try
{
var parentProcess = Process.GetProcessById(parentProcessId);
parentProcess.WaitForExit();
}
catch (Exception e)
{
//main process probably died already
Debug.WriteLine(e);
}
await Task.Delay(1000); //wait a bit before exiting
Debug.WriteLine("BrowserSubprocess shutting down forcibly.");
Environment.Exit(0);
}
}
And my BrowserSubprocessPath is my main exe.
settings.BrowserSubprocessPath = System.AppDomain.CurrentDomain.FriendlyName;
I finally managed to rename this sub process! Haven't found any solution how to do it through the CefSharp API, but found my own worked solution.
So, In your code that uses CefSharp add one setting to the Cef Settings, before Cef.Initialize()
using CefSharp;
using CefSharp.Wpf;
using System.IO;
using System.Reflection;
using System.Windows;
public App()
{
var settings = new CefSettings
{
BrowserSubprocessPath = Path.Combine(GetAppPath(), $#"runtimes\win-x64\native{ GetAppName() }.exe")
};
Cef.InitializeAsync(settings);
}
private static string GetAppPath()
{
return new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;
}
private static string GetAppName()
{
return Assembly.GetExecutingAssembly().GetName().Name;
}
After this go to the bin\Debug\net6.0-windows\runtimes\win-x64\native\ and rename CefSharp.BrowserSubprocess.exe to Name you want to use.
Done. Now it will use this file with custom name you need.
P.S. For the auto name set you can always use Post-Build event with command to rename the file after project built and set the name same as your assembly name. I use this approach for my needs.

Tring to get GitHub repo via Octokit

I'm building simple tool for downloading .lua files from online public GitHub repos via link given by user. I started learning async methods so I wanted to test myself.
It's a console application (for now). The ultimate goal is to get .lua files in a repo and ask the user which ones he wants downloaded, but I'll be happy if I connect to GH for now.
I'm using Octokit (https://github.com/octokit/octokit.net) GitHub API integration to .NET.
This is the reduced code; I removed some of unimportant stuff:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Octokit;
namespace GetThemLuas
{
class Program
{
static readonly GitHubClient Github = new GitHubClient(new ProductHeaderValue ("Testing123"), new Uri("https://www.github.com/"));
static void Main(string[] args)
{
Console.WriteLine("Welcome to GitHub repo downloader");
GetRepoTry4();
}
private static async void GetRepoTry4()
{
try
{
Console.WriteLine("Searching for data"); //returns here... code below is never ran
var searchResults = await Github.Search.SearchRepo(new SearchRepositoriesRequest("octokit"));
if (searchResults != null)
foreach (var result in searchResults.Items)
Console.WriteLine(result.FullName);
Console.WriteLine("Fetching data...."); //testing search
var myrepo = await Github.Repository.Get("Haacked", "octokit.net");
Console.WriteLine("Done! :)");
Console.WriteLine("Repo loaded successfully!");
Console.WriteLine("Repo owner: " + myrepo.Owner);
Console.WriteLine("Repo ID: " + myrepo.Id);
Console.WriteLine("Repo Date: " + myrepo.CreatedAt);
}
catch (Exception e)
{
Console.WriteLine("Ayyyy... troubles"); //never trigged
Console.WriteLine(e.Message);
}
}
}
}
The problem is the await` keyword as it terminates the method and returns.
I'm still learning async methods so it's possible I messed something up, but even my ReSharper says it fine.
I used var to replace task<T> stuff. It seams OK to me plus no warnings nor errors.
I fixed the await issue. Now when I finally connected to GH and tried to get the repo it threw an exeption at both calls to GH (tested with commenting first then second call). e.message was some huge stuff.
I logged it into a file and it looks like an HTML document. Here it is (http://pastebin.com/fxJD1dUb)
Change GetRepoTry4(); to Task.Run(async () => { await GetRepoTry4(); }).Wait(); and private static async void GetRepoTry4() to private static async Task GetRepoTry4().
This should get you at least wired up correctly enough to start debugging the real issue.
Generally speaking all async methods need to return a Task or Task<T> and all methods that return a Task or Task<T> should be async. Additionally, you should get your code into the dispatcher as quickly as possible and start using await.
The constructor with the Uri overload is intended for use with GitHub Enterprise installations, e.g:
static readonly GitHubClient Github = new GitHubClient(new ProductHeaderValue ("Testing123"), new Uri("https://github.enterprise.com/"));
If you're just using it to connect to GitHub, you don't need to specify this:
static readonly GitHubClient Github = new GitHubClient(new ProductHeaderValue ("Testing123"));
You're seeing a HTML page because the base address is incorrect - all of the API-related operations use api.github.com, which is the default.
Install Octokit Nuget Package for Github.Then add below function
public JsonResult GetRepositoryDeatil(long id)
{
var client = new GitHubClient(new ProductHeaderValue("demo"));
var tokenAuth = new Credentials("xxxxxxx"); // NOTE: not real token
client.Credentials = tokenAuth;
var content = client.Repository.Content.GetAllContents(id).Result;
List<RepositoryContent> objRepositoryContentList = content.ToList();
return Json(objRepositoryContentList, JsonRequestBehavior.AllowGet);
}
Due to the use of the async/await you should change the definition of the method GetRepoTry4 to the following:
private static async Task GetRepoTry4()
EDIT:
Then in the Main method call it like so GetRepoTry4().Wait();. This will enable the method GetRepoTry4() to be awaited.

Await in Windows Phone 7?

I am trying to go through the Windows Phone Live tutorial but I get stuck when trying to implement the code example as it seems to be missing information.
using System;
using System.Windows;
using System.Collections.Generic;
using Microsoft.Phone.Controls;
using Microsoft.Live;
using Microsoft.Live.Controls;
namespace WindowsPhoneCodeSample
{
public partial class MainPage : PhoneApplicationPage
{
private LiveConnectClient client;
public MainPage()
{
InitializeComponent();
}
private async void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
LiveOperationResult operationResult = await client.GetAsync("me");
try
{
dynamic meResult = operationResult.Result;
if (meResult.first_name != null &&
meResult.last_name != null)
{
infoTextBlock.Text = "Hello " +
meResult.first_name + " " +
meResult.last_name + "!";
}
else
{
infoTextBlock.Text = "Hello, signed-in user!";
}
}
catch (LiveConnectException exception)
{
this.infoTextBlock.Text = "Error calling API: " +
exception.Message;
}
}
else
{
infoTextBlock.Text = "Not signed in.";
}
}
}
}
I get
Error 2 The name 'await' does not exist in the current context
Error 3 One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?
Am I missing some reference or something?
Edit
the tutorial seems to be poorly done or very out of date. I made a windows phone 8 application and it still does not build because of the "awai"t keyword.
The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
client.GetAsync is also a void method. So not sure how it returns something as well.
await works only with awaitables - see ยง7.7.7.1 on the C# Language Specification.
Since client.GetAsync is a void returning method, it can never be an awaitable.
You need to install NuGet Package Microsoft.Bcl.Async (you can find it in NuGet Manager) so compiler recognize words await and async.
more info http://www.nuget.org/packages/Microsoft.Bcl.Async/

update task using Task Scheduler Managed Wrapper?

Here's the library I'm using:
http://taskscheduler.codeplex.com/wikipage?title=Install&referringTitle=Documentation
Here's the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.TaskScheduler;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
var p = new Program();
p.EnumAllTasks();
}
void EnumAllTasks() {
using (TaskService ts = new TaskService())
EnumFolderTasks(ts,ts.RootFolder);
}
void EnumFolderTasks(TaskService ts, TaskFolder fld) {
var tasks = fld.Tasks.Where(t => t.Name.Equals("test-task", StringComparison.OrdinalIgnoreCase));
foreach (Task task in tasks)
ActOnTask(ts, task);
}
void ActOnTask(TaskService ts, Task t) {
//ea.Path
Console.WriteLine(t.Name);
Console.WriteLine(t.Path);
Console.WriteLine(((ExecAction)t.Definition.Actions.First()).Path);
var ea = (ExecAction)t.Definition.Actions.First();
ea.Path = ea.Path + ".coolio/test.exe";
UpdateFirstAction(t, new ExecAction(ea.Path+".coolio/test.exe",ea.Arguments,ea.WorkingDirectory));
//ts.s
// Do something interesting here
}
void UpdateFirstAction(Task t, Microsoft.Win32.TaskScheduler.Action action) {
if (t.TaskService.HighestSupportedVersion >= new Version(1, 2)) {
Console.WriteLine("HERE");
t.Definition.Actions.RemoveAt(0);
}
t.Definition.Actions.Add(action);
}
}
}
I added the 'UpdateFirstAction' method based upon the following: https://taskscheduler.codeplex.com/discussions/203704
I want to be able to update the path that's getting executed, and the above link seems to imply that updating the collection is enough.
How do I actually save the changes? All of the documentation I've read seems to describe how to read things only.
You can omit the UpdateFirstAction method. The library since version 1.6.1 has fixed the bug from that discussion item. The code is correct on how to edit the Path property. To update the task with the changed Path, you only need to call t.RegisterChanges() at the point you are calling UpdateFirstAction.

Trying to learn about the new async features in c#

I copied this example from here
I have seen many similar examples. Most of them say they're using the Async CTP. I'm using Visual Studio 11 on Windows 8 though so that does not apply. As shown, the error says TaskEx doesn't exist. I assume I'm missing a reference but don't know which one.
This page is http://users.zoominternet.net/~charleswatson/pic.png.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static Random rnd = new Random();
static void Main(string[] args)
{
//Do some other heavy duty background task in this thread
StartHotel();
Console.WriteLine("StartHotel called..");
Console.ReadLine();
}
static void StartHotel()
{
Console.WriteLine("Starting Hotel..");
for (int i = 0; i < 10; i++)
{
string name = "Chef" + i;
CookDish(name, "Dish" + i);
Console.WriteLine("Asked {0} to start cooking at {1}", name, DateTime.Now.ToString());
}
}
static async void CookDish(string chefName, string dish)
{
//Induce a random delay
int delay = rnd.Next(1000, 4000);
//Cook is cooking - Task
await TaskEx.Delay(delay);
//Write the result - StuffAfterAwait
Console.WriteLine("Chef {0} Finished at {1}", chefName, DateTime.Now.ToString());
}
}
}
In the CTP we were unable to add new features to the Task type so we did the pragmatic thing and just made a new TaskEx type. In the final release there will be no such type; those methods will just be on Task like you'd expect.
Replace TaskEx with Task. At the top of the .cs file, you'll need:
using System.Threading.Tasks;
Much of the sample code I've seen refers to TaskEx, and the estimable Mr. Lippert seems to be indicating that's an artifact of their development process. If you're using the Developer Preview, calls like Run, WhenAll, and Delay are already methods of the class Task rather than of TaskEx. The release tools should be the same.

Categories