Azure MobileService in BackgroundTask - xaml

My question is pretty simple : Can we use MobileServices in BackgroundTasks? (WP 8.1 XAML)
I have an universal app connected to a MobileService from Azure and I wanted to let the BackgroundTask synchronize the data of my remote database.
So, is this possible?
public sealed class BackgroundTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
//Connect to mobile service and add data
deferral.Complete();
}
}
I can't add a reference to my WP project, so how can I get the App.MobileServiceClient?
My BackgroundTask project is a Windows runtime component.
EDIT:
I've added the reference to Windows Azure Mobile Service by managing nuGet Packages and I can now declare a mobileService but when I want to instanciate it I've got the following error :
BACKGROUNDTASKHOST.EXE' has exited with code 1 (0x1).
So this is what my code looks like now :
public sealed class BackgroundTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
Microsoft.WindowsAzure.MobileServices.MobileServiceClient lolServiceMobileClient =
new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
"https://myservicemobile.azure-mobile.net/",
"myKey");
deferral.Complete();
}
}
And this is the reference I've added :
Edit 2
I'm stills searching for solution and I'm now wondering, could it be because I exceed the amount of memory the background task is allowed to use?

I'm not an expert on background tasks, but you can indeed use the Mobile Services SDK there. Just make sure that the background task doesn't interfere with the app, by using an app setting to lock between the two processes.

Related

I would like to intercept the MS Teams notifications about poor network quality, during calls

In order to diagnose a network condition I am trying to intercept (at least on Windows) the notifications about poor network quality that Teams pops-up sometimes, during a call.
For testing, I am using "clumsy", in order to generate iffiness in the network, while in a teams audiovideo call to my phone.
I was wondering if an API would provide a local interface to teams an allow me to subscribe to those events.
So far if found a type library in C:\Users\xxx\AppData\Local\Microsoft\TeamsPresenceAddin\Uc.tlb that looks promising because of the idl file that the oleviewer generates from it:
ModalityProperty in uc.tlb is an enum and contains these two values:
ucAVModalityAudioNetworkQuality = 0x300b001d,
ucAVModalityVideoNetworkQuality = 0x300b0021,
That enum is used by the interface _IAVModalityEvents and that looks to be fired by the coclass AVModality:
[
uuid(BA2BD6F3-7676-42E3-89C6-10CEB3F7E106),
helpstring("AVModality class defines the audio video modality.This class handles the events defined in the interface IAVModalityEvents."),
noncreatable,
custom(5047D0E3-86FD-4EB4-A500-AC4F5B4E17E1, "relns=Conversation.AudioVideo")
]
coclass AVModality {
[default] interface IAVModality;
interface IAVModality2;
**[default, source] dispinterface _IAVModalityEvents;**
};
Does anyone have an idea on how to connect to the running Teams instance (tried ROT but it doesn't seem to be registered) and how to enum modalities in order to get to the AVModality and subscribe to its events ?
Update 1:
I actually got some partial results with the Uc.tlb.
First I ran: TlbImp.exe Uc.tlb to create a C# assembly from it.
I then built the following C# app to intercept conversation changes:
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Xml;
using UCCollaborationLib;
class Program
{
//Teams CLSID harvested from registry
// Take a looksie at: https://stackoverflow.com/questions/56865704/com-object-for-teams-client-microsoft-office-uc
[ComImport, Guid("00425F68-FFC1-445F-8EDF-EF78B84BA1C7")]
public class TeamsOfficeIntegration
{
}
static void Main(string[] args)
{
var version = "15.0.0.0";
IUCOfficeIntegration teamsOfficeIntegration = (IUCOfficeIntegration) new TeamsOfficeIntegration();
if (teamsOfficeIntegration == null) {
Console.WriteLine("Cannot instantiate UCOfficeIntegration for Teams");
return;
}
IClient teamsClient = (IClient) teamsOfficeIntegration.GetInterface(version, OIInterface.oiInterfaceILyncClient);
if (teamsClient == null) {
Console.WriteLine("Cannot retrieve Teams Client interface");
return;
}
var teamsConversationManager = teamsClient.ConversationManager;
if (teamsConversationManager == null) {
Console.WriteLine("Cannot retrieve Teams ConversationManager interface");
return;
}
// Handle Teams Conversation Collection events
teamsConversationManager.OnConversationAdded += (ConversationManager _eventSource, ConversationManagerEventData _eventData) => { Console.WriteLine("Conversation added");};
teamsConversationManager.OnConversationRemoved += (ConversationManager _eventSource, ConversationManagerEventData _eventData) => { Console.WriteLine("Conversation removed");};
//iterate SelfParticipant or Modalities -> iterate IAVModality -> IConnectionPoint
}
}
The good news is that, when Teams is stopped it tries to start it so it does CoCreateInstance on the Teams LocalServer so it should be able to interact with it. The bad news is that even if the Teams app starts or is being attached to the creation fails with the following entry in the EventViewer/AdministrativeEvents:
"The server {00425F68-FFC1-445F-8EDF-EF78B84BA1C7} did not register with DCOM within the required timeout."

ABP IO Code sample for run multiple databases for multi-tenancy

Please notice that I am talking about ABP.io, not the Boilerplate framework.
The in-build free module Tenant-Management is developed to work with multiple tenants and a unique database. however, the documentation says that the framework has a built-in friendly way to use the multiple database approach, including:
new dbContext
database migration and seeding
Connection String service
I am new in ABP IO, and I want a sample that employs the framework elements to implement a single database for every tenant.
I get started by overriding the tenant create sync method of the tenant management module as follows.
[Dependency(ReplaceServices = true)]
[ExposeServices(typeof(ITenantAppService), typeof(TenantAppService), typeof(ExtendedTenantManagementAppService))]
public class ExtendedTenantManagementAppService : TenantAppService
{
public ExtendedTenantManagementAppService(ITenantRepository tenantRepository,
ITenantManager tenantManager,
IDataSeeder dataSeeder) : base(tenantRepository, tenantManager, dataSeeder)
{
LocalizationResource = typeof(WorkspacesManagerResource);
ObjectMapperContext = typeof(WorkspacesManagerApplicationModule);
}
public override async Task<TenantDto> CreateAsync(TenantCreateDto input)
{
var tenant = await TenantManager.CreateAsync(input.Name);
input.MapExtraPropertiesTo(tenant);
await TenantRepository.InsertAsync(tenant);
await CurrentUnitOfWork.SaveChangesAsync();
using (CurrentTenant.Change(tenant.Id, tenant.Name))
{
//TODO: Handle database creation?
// create database
// migrate
// seed with essential data
await DataSeeder.SeedAsync(
new DataSeedContext(tenant.Id)
.WithProperty("AdminEmail", input.AdminEmailAddress)
.WithProperty("AdminPassword", input.AdminPassword)
);
}
return ObjectMapper.Map<Tenant, TenantDto>(tenant);
}
}
Any code sample?

C# XAML page dependency injection on the fly with MVVM Light

I would like some feedback to see if I'm using SimpleIoc in the correct way.
The code below works, but I'm not sure if it's best practice.
I have an UWP XAML DocumentPage class on which I want to show an IRpcDocument.
I want to use the DocumentPage for both RpcDocumentA and RpcDocumentB. The user can navigate to both types of IRpcDocument. So the application should be able to switch between the two 'on the fly'.
So I wrote my DocumentPageViewModel
public class DocumentPageViewModel : ViewModelBase
{
public IRpcDocument RpcDocument;
public DocumentPageViewModel(IRpcDocument rpcDocument)
{
RpcDocument = rpcDocument;
}
}
And my ViewModelLocator
class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<DocumentPageViewModel>();
}
public DocumentPageViewModel SimpleIoc.Default.Register<DocumentPageViewModel>
{
get
{
return ServiceLocator.Current.GetInstance<SimpleIoc.Default.Register<DocumentPageViewModel>>(Guid.NewGuid().ToString());
}
}
}
When I'm navigating to the DocumentPage I call:
SimpleIoc.Default.Register<IRpcDocument , RpcDocumentA>();
await NavigationService.NavigateAsync(typeof(DocumentPage), DocumentIdParameter);
The app then navigates to the DocumentPage, constructs the RpcDocumentA, makes the necessary RPC calls to fetch the data and shows the document.
The first line tells the IoC framework it should expect an RpcDocumentA in its constructor, the second one triggers navigation. So in this case, im not registering the interface in the static ViewModelLocator().
So for each time I navigate I call SimpleIoc.Default.Register<IRpcDocument , RpcDocumentA> or SimpleIoc.Default.Register<IRpcDocument , RpcDocumentB>
This works, but is this the right way to do this? I suspect it's not.

play 2.5 render view test, access to flash messages

Here the simple play render view test. In view template i trying to accesss session information throught flash.get().
But test failed with message There is no HTTP Context available from here. How add fake session data to tested application in junit test context?
public class ApplicationTest extends WithServer {
private FormFactory formFactory() {
return app.injector().instanceOf(FormFactory.class);
}
#Test
public void renderTemplate() {
Content html;
session().put("session","123");
html = index.render(formFactory().form(Auth.Login.class));
assertTrue(contentAsString(html).contains("Hello"));
}
}
Test ApplicationTest.renderTemplate failed: java.lang.RuntimeException: There is no HTTP Context available from here., took 0.544 sec
at play.mvc.Http$Context.current(Http.java:57)
at play.mvc.Http$Context$Implicit.flash(Http.java:307)
at views.html.index_Scope0$index$$anonfun$apply$1.apply(index.template.scala:39)
at views.html.index_Scope0$index$$anonfun$apply$1.apply(index.template.scala:38)
at views.html.helper.form_Scope0$form.apply(form.template.scala:35)
at views.html.index_Scope0$index.apply(index.template.scala:38)
at views.html.index_Scope0$index.render(index.template.scala:141)
at views.html.index.render(index.template.scala)
at ApplicationTest.renderTemplate(ApplicationTest.java:37)
Using WithServer starts up an application that you can make requests to. For the tests you describe here, you need to use WithApplication.
To manually set a context, you can override the startPlay method.
#Override
public void startPlay()
{
super.startPlay();
Http.Context.current.set(new Http.Context(1L,
Mockito.mock(RequestHeader.class),
Mockito.mock(Http.Request.class),
Collections.<String, String>emptyMap(),
Collections.<String, String>emptyMap(),
Collections.<String, Object>emptyMap()));
}

Xamarin Forms Sharedpreferences cross

I'd like to know what is the best solution to manipulate application settings in a cross-platform way.
In iOS we can change the settings outside the app in the settings screen, but we don't have that in windows phone and android.
So, my idea is to create a normal page/screen inside the app that shows all my application settings and have an interface with Save() and Get() methods that I can implement specific per device using DependencyServices.
Is this the right way to do it?
The Application subclass has a static Properties dictionary which can be used to store data. This can be accessed from anywhere in your Xamarin.Forms code using Application.Current.Properties.
Application.Current.Properties ["id"] = someClass.ID;
if (Application.Current.Properties.ContainsKey("id"))
{
var id = Application.Current.Properties ["id"] as int;
// do something with id
}
The Properties dictionary is saved to the device automatically. Data added to the dictionary will be available when the application returns from the background or even after it is restarted. Xamarin.Forms 1.4 introduced an additional method on the Application class - SavePropertiesAsync() - which can be called to proactively persist the Properties dictionary. This is to allow you to save properties after important updates rather than risk them not getting serialized out due to a crash or being killed by the OS.
https://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/app-lifecycle/
Xamarin.Forms plugin which uses the native settings management.
Android: SharedPreferences
iOS: NSUserDefaults
Windows Phone: IsolatedStorageSettings
Windows Store / Windows Phone RT: ApplicationDataContainer
https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/Settings
I tried using the Application.Current.Properties Dictionary and had implementation problems.
A solution that worked with very little effort was James Montemagno's Xam.Plugin.Settings NuGet. GitHub Installing the NuGet automagically creates a Helpers folder with Settings.cs. To create a persisted setting you do:
private const string QuestionTableSizeKey = "QuestionTableSizeKey";
private static readonly long QuestionTableSizeDefault = 0;
and
public static long QuestionTableSize
{
get
{
return AppSettings.GetValueOrDefault<long>(QuestionTableSizeKey, QuestionTableSizeDefault);
}
set
{
AppSettings.AddOrUpdateValue<long>(QuestionTableSizeKey, value);
}
}
Access and setting in the app then looks like:
namespace XXX
{
class XXX
{
public XXX()
{
long myLong = 495;
...
Helpers.Settings.QuestionTableSize = myLong;
...
long oldsz = Helpers.Settings.QuestionTableSize;
}
}
}