How can I use INetwork in Xamarin Forms XLabs? - networking

I am having a problem using INetwork from XLabs.Platform. I am getting System.NullReferenceException. I am not sure if the problem is similar to this where I need to initialize INetwork. However, because I am very new to Xamarin I have no idea how to set up the IOC container. I'd like to this in a completely cross-platform way (I'd like to avoid putting platform specific code if I can avoid it). Thanks!!
Code:
using XLabs.Ioc;
using XLabs.Platform;
...
namespace XXX
{
class XXX
{
public static bool isOnline()
{
var networkservice = DependencyService.Get<XLabs.Platform.Services.INetwork>();
var status = networkservice.InternetConnectionStatus();
return (
(status.Equals(XLabs.Platform.Services.NetworkStatus.ReachableViaCarrierDataNetwork))
|| (status.Equals(XLabs.Platform.Services.NetworkStatus.ReachableViaWiFiNetwork))
|| (status.Equals(XLabs.Platform.Services.NetworkStatus.ReachableViaUnknownNetwork)));
}
}
}
PS The documentation for using XLabs.Platform is out of date. The (apparently) previously functioning Reachability interface doesn't work anymore. Thinking about using this instead. This is an approach that requires cross platform code. Not going to use this as the author himself disses the approach.

If you want to check if there is any Internet Connection, I would suggest to use Connectivity Plugin (Xamarin Component). After adding the Xaamrin Component you can check if an internet connection is avaliable from PCL/Shared project like below
if (CrossConnectivity.Current.IsConnected)
{ // Make API call here
}
else
DisplayAlert("Connectivity Issue", "Please Connect to a Network", "OK") ;

You fill the ioc by adding this attribute:
[assembly: Xamarin.Forms.Dependency(typeof(NameOfClassImplementingAnInterface))]

Related

How to turn off Motion Controller line pointer

That's it, I'll step on my pride!
I'm using MRTK v2 and working fine except that at some point I want to turn off the line extending from the Motion Controller to the object and that provides input. After looking around and trying to find it in the MRTK documentation (it's gotta be easy, right?), I'm still banging my head on the wall and it's starting to hurt....
The MRTK documentation explains quite well how to configure it here:
https://github.com/microsoft/MixedRealityToolkit-Unity/blob/mrtk_release/Documentation/Input/Pointers.md
But I'm looking to do this in script, enabling and disabling it as I need it in my application.
Any clue how to do this?
Many thanks!
Answered my own question. Simple:
PointerUtils.SetMotionControllerRayPointerBehavior(PointerBehavior.AlwaysOff);
See documentation here: https://github.com/microsoft/MixedRealityToolkit-Unity/blob/mrtk_release/Documentation/Input/Pointers.md
Great question! Here's one way to do this that has worked for me. You can see my solution at this repository: https://github.com/julenka/MixedRealityToolkit-Unity/tree/so/linepointer_off. Open the scene Assets/TurnOffLinePointerTest.unity and then use hand simulation to press the buttons. The code to turn the pointers on/off is in Assets/PointerConfigurationExample.cs.
Note: the reason you need to use this approach of modifying the mediator instead of directly setting myPointer.IsActive = false is because the default mediator overwrites these values every frame. Luckily, you can customize this behavior.
Step 1: Update MRTK a bit so that PointerMediator can be accessed
Apply the changes from this commit to your MRTK clone. This change updates the FocusProvider in MRTK to make the PointerMediator publicly accessible, and makes the DefaultPointerMediator extensible by updating fields to be protected instead of private, and making methods virtual. See this pull request that implements this change directly into MRTK.
Step 2: Create a custom PointerMediator that will turn off far pointers
Create a custom Pointer Mediator like the one from this commit.
using System.Collections.Generic;
using Microsoft.MixedReality.Toolkit.Input;
public class CustomPointerMediator : DefaultPointerMediator
{
public bool FarPointersDisabled {get; set;}
public override void UpdatePointers()
{
base.UpdatePointers();
if (FarPointersDisabled)
{
foreach(var pointer in farInteractPointers)
{
pointer.IsActive = false;
}
}
}
}
Note that this mediator extends DefaultPointerMediator so it adapts almost all the default mediator logic. Make sure you have fully applied the changes from the first commit otherwise you will not be able to extend DefaultPointerMediator.
Step 3: Tell MRTK to use your custom pointer mediator
In your pointer profile, configure MRTK to use the custom pointer mediator instead of the default pointer mediator. Notice in the picture that I've created a custom pointer profile as part of a custom input system (don't modify the default profile otherwise your changes might get overwritten when you update MRTK).
Step 4: Component that uses custom mediator to turn line pointers on / off
You can now write your component which will use your custom mediator to turn the line pointers on and off.
public class PointerConfigurationExample : MonoBehaviour
{
/* Turns off all far interaction pointers */
public void TurnOffFarPointers()
{
Debug.Log("Line pointers off");
SetFarPointersDisabled(true);
}
public void TurnOnFarPointers()
{
Debug.Log("Line pointers on");
SetFarPointersDisabled(false);
}
private void SetFarPointersDisabled(bool isDisabled)
{
FocusProvider focusProvider = (FocusProvider) MixedRealityToolkit.InputSystem.FocusProvider;
if (focusProvider != null)
{
foreach(var mediator in focusProvider.PointerMediators)
{
// Note: you could check here to make sure you only disable pointers for hands
CustomPointerMediator myMediator = (CustomPointerMediator) (mediator.Value);
if (myMediator != null)
{
myMediator.FarPointersDisabled = isDisabled;
}
}
}
}
}

ASP.NET Core Identity - UserManager and UserStore woes

I'm trying to implement the Identity system in an ASP.NET Core app (RC2 libraries) and there is a particular hangup that is driving me crazy.
First of all, I am not using EntityFramework. I'm not even using SQL. I'm backing up to RavenDB, so I need the implementation to be very specific to that; Which isn't a problem.
So I designed a RavenUserStore class, and it looks like this;
public class RavenUserStore<TUser> :
IUserStore<TUser>,
IUserLoginStore<TUser>,
IUserPasswordStore<TUser>,
IUserRoleStore<TUser>,
IUserSecurityStampStore<TUser>,
IUserClaimStore<TUser>,
IUserLockoutStore<TUser>,
IUserTwoFactorStore<TUser>,
IUserEmailStore<TUser> {
// ...
}
Works great on its own. I've implemented all the methods, etc. It's wonderful. Very clean and efficient.
Now, I go over to my web application and wire things up;
services.AddTransient<ILookupNormalizer>(s => new LowerInvariantLookupNormalizer());
services.AddTransient<IPasswordHasher<Member>>(s => new PasswordHasher<Member>());
services.AddTransient<IUserStore<Member>, RavenUserStore<Member>>();
services.AddIdentity<Member, Role>(o => {
o.Password.RequiredLength = 6;
o.Password.RequireDigit = true;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
})
.AddUserStore<RavenUserStore<Member>>()
.AddRoleStore<RavenRoleStore<Role>>();
So I go make a controller to use this, per all the samples I've seen, and the very core sample from the Identity Framework Github Repository
//... [PROPERTIES]...//
public AccountController(UserManager<Member> userManager, SignInManager<Member> signInManager) {
// ... [attach constructor parameters to properties] ...//
}
Alright, so I inspect the classes carefully.
UserManager<T> has a property Store,which is a type of IUserStore<T>.
So theoretically.. if the dependency injection resolves types of IUserStore<T> to RavenUserStore<T> when they are injected through a constructor.. shouldn't that mean that the UserManager<T> gets a RavenUserStore<T> as its Store property?
I thought it would too; But when I call methods on the UserManager, it DOES NOT call the ones on my RavenUserStore. Why is this? What can I do?
Do I really have to ALSO make a custom UserManager class and do all of those methods AGAIN?
You need to add your own custom providers before calling services.AddIdentity(). Internally, AddIdentity uses TryAddScoped() which only adds the default items if they don't already exist in the services container.
So just putting the call to AddIdentity() after you registered all your custom implementations should mean that they will take precedence as you expect.

Using environment variables in AX

Is there any possibility to make use of windows-environment-variables in AX?
Example:
Property NormalImage on a MenuItem. I'd like to use sth. like %USERNAME% instead of the explicit username. In Classes for example I can use the WINAPI macro and refer to a user-folder-variable, eg CSIDL_MYPICTURES, to access the path per user. In AOT-object-properties there's no possibility to reference to macros...
Any way to achieve this?
No, you can't do this on the AOT. You can change some properties on runtime through X++ code, but you can't dynamically change the image on a MenuItem as far as I know.
You can make visible/invisible some menuitems. May be can simulate what you are trying to do this way, although this is not quite aligned with the AX design patterns.
Yes you can use .Net framework to get environment variables or you can use built in AX functions. See this example I typed up:
static void Job85(Args _args)
{
System.String systemString;
str marshalString;
;
// Built in AX function
info(strfmt("%1, %2, %3", xUserInfo::find().networkAlias, xUserInfo::find().networkDomain, xUserInfo::find().name));
// .Net Framework
systemString = System.Environment::GetEnvironmentVariable('username');
marshalString = systemString; // Marshal it
info(strfmt("%1", marshalString));
}
See http://msdn.microsoft.com/en-us/library/system.environment.getenvironmentvariable.aspx
An example of getting the client name and machine name
static void testGetClientMachineName(Args _args)
{
str localClientname, terminalServerName;
;
localClientname = System.Environment::GetEnvironmentVariable('CLIENTNAME') ;
info(localClientname);
terminalServerName = System.Environment::get_MachineName();
info(terminalServerName);
}

How to tell if Flex is run in debug mode?

I want to declaratively turn on and off logger for my Flex application and it seems that my usual way of determining if it's debug mode or not works only sometimes. The code for it:
isDebugSWF = new Error().getStackTrace().search(/:[0-9]+]$/m) > -1;
Do you know a better way for it?
Edit:
I posted answer below.
The static property Capabilities.isDebugger in the flash.system.Capabilities class specifies if the Flash player installed is a debug version or not. It requires Flash Player 9 or AIR 1.0 as the minimum version.
Keep in mind though that debug Flash Player installers are publicly available, and that there is nothing stopping users from installing the debug version of Flash. If have something sensitive that you want to hide, using conditional compilation would be a better option.
The previous approach was based on great article . One of the comments suggested that in Release the stacktrace is null, so I modified it properly:
protected function configureLogger() : void
{
if(!isDebugPlayer()|| !isDebugBuild())
{
// stop logging
Logger.hide = true;
}
else
{
// resume logging
Logger.hide = false;
}
}
private function isDebugPlayer() : Boolean
{
return Capabilities.isDebugger;
}
/**
* Returns true if the swf is built in debug mode
**/
private function isDebugBuild() : Boolean
{
var stackTrace:String = new Error().getStackTrace();
if(stackTrace == null || stackTrace.length == 0)
{
//in Release the stackTrace is null
return false;
}
//The code searches for line numbers of errors in StackTrace result.
//Only StackTrace result of a debug SWF file contains line numbers.
return stackTrace.search(/:[0-9]+]$/m) > -1;
}
This way I can finally configure ThunderBoltAS3 logger depending on current build type.
Looks like you are looking for the same, as answered in another post. Look here: How can you tell programmatically if a Flex App is running in debug mode?
We are using conditional compilation at our project :
Adobe Documentation

Get instance of type inheriting from base class, implementing interface, using StructureMap

Continuing on my quest for a good plugin implementation I have been testing the StructureMap assembly scanning features.
All plugins will inherit from abstract class PluginBase. This will provide access to common application services such as logging. Depending on it's function, each plugin may then implement additional interfaces, for example, IStartUpTask.
I am initializing my plugins like so:
Scan(x => {
x.AssembliesFromPath(HttpContext.Current.Server.MapPath("~/Plugins"),
assembly => assembly.GetName().Name.Contains("Extension"));
x.AddAllTypesOf<PluginBase>();
});
The difficulty I am then having is how to work against the interface (not the PluginBase) in code. It's easy enough to work with PluginBase:
var plugins = ObjectFactory.GetAllInstances<PluginBase>();
foreach (var plugin in plugins)
{
}
But specific functionality (e.g. IStartUpTask.RunTask) is tied to the interface, not the base class.
I appreciate this may not be specific to structuremap (perhaps more a question of reflection).
Thanks,
Ben
Do you know all of the specific interfaces at registration time? If so, you can make a custom registration convention that registers each type with the plugin "family" of the interface it implements. An IRegistrationConvention gets each type, one at a time. You could do a simple check to see if the current type implements the desired interface, and if so, add it.
if (typeof(IStartUpTask).IsAssignableFrom(currentType)){
For<IStartUpTask>().Add(currentType);
}
Then later in the code, you can retrieve plugins for each specific interface individually:
var startupTasks = ObjectFactory.GetAllInstances<IStartUpTask>();
This approach has the benefit of allowing you to inject an enumerable of your custom interface plugins into a class that needs them, instead of making the service location call.
Alternatively, if you don't want to make a registration convention, you can just do the filtering at runtime using the handy OfType linq extension method:
var startupTasks = ObjectFactory.GetAllInstances<PluginBase>().OfType<IStartupTask>();
In case it helps others, I followed Joshua's advice and added my own registration convention:
public class PluginConvention : IRegistrationConvention
{
public void Process(Type type, Registry registry) {
if (type.BaseType == null) return;
if (type.BaseType.Equals(typeof(PSAdmin.Core.Domain.PluginBase))) {
if (typeof(IStartUpTask).IsAssignableFrom(type)) {
registry.For<IStartUpTask>()
.TheDefault.Is.OfConcreteType(type);
}
}
}
}
I couldn't get the .Add method to work, no matter what I tried, so had to use TheDefault.Is.OfConcreteType(type).
Then in my bootstrapper I am scanning like so:
Scan(x => {
x.AssembliesFromPath(HttpContext.Current.Server.MapPath("~/Plugins"),
assembly => assembly.GetName().Name.Contains("Extension"));
x.Convention<PluginConvention>();
});
I can then grab my IStartUp task types like so:
var plugins = ObjectFactory.GetAllInstances<IStartUpTask>();
foreach (var plugin in plugins)
{
plugin.Configure();
}
That said, after reading up on some of the new features of StructureMap, I'm not sure I need to do any of the above. For example I could just change my Scan delegate function to:
Scan(x => {
x.AssembliesFromPath(HttpContext.Current.Server.MapPath("~/Plugins"),
assembly => assembly.GetName().Name.Contains("Extension"));
x.AddAllTypesOf<PluginBase>();
});
And to use my interface concrete types (that inherit from PluginBase):
var tasks = ObjectFactory.Model.GetAllPossible<IStartUpTask>();
foreach (var task in tasks)
{
task.Configure();
}
Both methods seem to achieve the same thing.

Resources