MonoTouch, NSLog, and TestFlightSdk - xamarin.ios

I am trying to integrate the TestFlightSdk into an app I've made using MonoTouch.
I am trying to implement logging in my app in such a way that it is picked up by the TestFlightSdk. It supposedly picks up NSLogged text automatically, but I can't seem to find the right combination of code to add to my own app, written in C#/MonoTouch, that does the same.
What I've tried:
Console.WriteLine("...");
Debug.WriteLine("..."); (but I think this just calls Console.WriteLine)
Implementing support for NSlog, but this crashed my app so apparently I did something wrong (I'll ask a new question if this is the way to go forward.)
Is there anything built into MonoTouch that will write log messages through NSLog, so that I can use it with TestFlightSdk? Or do I have to roll my own wrapper for NSLog?
In order to implement NSLog myself, I added this:
public static class Logger
{
[DllImport("/System/Library/Frameworks/Foundation.framework/Foundation")]
private extern static void NSLog(string format, string arg1);
public static void Log(string message)
{
NSLog("%s", message);
}
}
(I got pieces of the code above from this other SO question: How to I bind to the iOS Foundations function NSLog.)
But this crashes my app with a SIGSEGV fault.

using System;
using System.Runtime.InteropServices;
using Foundation;
public class Logger
{
[DllImport(ObjCRuntime.Constants.FoundationLibrary)]
private extern static void NSLog(IntPtr message);
public static void Log(string msg, params object[] args)
{
using (var nss = new NSString (string.Format (msg, args))) {
NSLog(nss.Handle);
}
}
}

Anuj pointed the way, and this is what I ended up with:
[DllImport(MonoTouch.Constants.FoundationLibrary)]
private extern static void NSLog(IntPtr format, IntPtr arg1);
and calling it:
using (var format = new NSString("%#"))
using (var arg1 = new NSString(message))
NSLog(format.Handle, arg1.Handle);
When I tried just the single parameter, if I had percentage characters in the string, it was interpreted as an attempt to format the string, but since there was no arguments, it crashed.

Console.WriteLine() works as expected (it redirects to NSLog) on current xamarin.ios versions. Even on release builds (used by hockeyapp, etc). No need to use DllImport anymore.

Related

How to wrap a Hangfire cancellation token?

I'm building up a .net core web app that requires background tasks to be run. To avoid using an external cron triggers we've decided to go with Hangfire; which is a beautiful package to use, does exactly whats needed then gets out of the way ;-)
To keep things clean I'm trying to stick to Uncle Bob's Clean architecture principles and seperate my ApplicationCore from the Infrastructure as much as possible. As Hangfire is an implementation detail it should ideally sit in the Infrastructure project, alongside database access, message queues, etc. with an Interface in the ApplicationCore, that my domain can use.
For the basic client running recurring and background jobs this has been fairly simple to do, and I've ended up with this as my Interface
namespace ApplicationCore.Interfaces
{
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
public interface IBackgroundJobClient
{
void AddOrUpdate<T>(
string recurringJobId,
Expression<Func<T, Task>> methodCall,
string cronExpression);
void RemoveIfExists(string recurringJobId);
}
}
Implementation is a simple wrapper for these methods which uses RecurringJob
namespace Infrastructure.BackgroundJobs
{
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Hangfire;
using IBackgroundJobClient = ApplicationCore.Interfaces.IBackgroundJobClient;
public class HangfireBackgroundJobClient : IBackgroundJobClient
{
public void AddOrUpdate<T>(
string recurringJobId,
Expression<Func<T, Task>> methodCall,
string cronExpression)
{
RecurringJob.AddOrUpdate<T>(recurringJobId, methodCall, cronExpression);
}
public void RemoveIfExists(string recurringJobId)
{
RecurringJob.RemoveIfExists(recurringJobId);
}
}
The issue that I have is needing to setup a RecurringJob with a supplied cancellationToken. However, I can't see an easy way to do this without exposing the underlying IJobCancellationToken and JobCancellationToken objects in my ApplicationCore code...?
What I've got at present is a wrapper for the JobCancellationToken in my Infrastructure.
namespace Infrastructure.BackgroundJobs
{
public class BackgroundJobCancellationToken : JobCancellationToken
{
public BackgroundJobCancellationToken(bool canceled): base(canceled)
{
}
}
}
An Interface in my ApplicationCore, which replicates the Hangfire one.
namespace ApplicationCore.Interfaces
{
using System.Threading;
public interface IJobCancellationToken
{
CancellationToken ShutdownToken { get; }
void ThrowIfCancellationRequested();
}
}
This is then used by the Method I want to execute as job, making use of the cancellationToken.ShutdownToken to pass into other methods requiring a cancellationToken.
public async Task GenerateSubmission(Guid SetupGuidId, IJobCancellationToken cancellationToken)
{
try
{
// Sort out the entities that we'll need
var setup = await this.SetupRepository.GetByGuidIdAsync(SetupGuidId);
var forecast = await this.GetCurrentForecastForSetup(setup, DateTime.UtcNow, cancellationToken.ShutdownToken);
// Other Code
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Which in turn is enabled elsewhere by calling
public async Task<Setup> EnableSetup(Setup setup)
{
setup.Enable();
this.jobClient
.AddOrUpdate<IForecastService>(
setup.GuidId.ToString(),
f => f.GenerateSubmission(setup.GuidId, null),
"45 */2 * * *");
await this.setupRepository.UpdateAsync(setup);
return setup;
}
This should be done with DomainEvents and Handlers, but one step at a time :-)
Is there a cleaner, better, easier way of doing this without taken a direct dependency on Hangfire in my ApplicationCore?
If the above setup works, I'll leave a comment on this question.
Since Hangfire 1.7 you no longer have to rely on IJobCancellationToken. You can simply use the standard .NET CancellationToken instead.

'System.NullReferenceException' while defining an object XNA C#

I've recently been trying to make a game, and decided to start from scratch. However, I quickly encountered an error that wasn't a problem in the previous session of my game.
Me and my friend ran through several ideas of what might cause the error however we haven't been able to find.
Apparently it somehow creates an error when I'm trying to load an object using a different class(UI.UILoader) The main class is as followed:
namespace WindowsGame1.Classes
{
public static Game1 instance;
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public MouseState mouseState;
public KeyboardState keyState;
public SpriteFont debugFont;
Instance inst;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
debugFont = Content.Load<SpriteFont>("debugFont");
inst.Load();
UI.UILoader.Load();
// TODO: use this.Content to load your game content here
}
The Class UILoader can be seen beneath where it tries to load two textures using Texture2D. However when it tries to load the first texture I recieve a 'System.NullReferenceException' error.
namespace WindowsGame1.Classes.UI
{
public static class UILoader
{
public static Texture2D cursorTexture;
public static Texture2D buttonTexture;
public static void Load()
{
cursorTexture = Game1.instance.Content.Load<Texture2D>("Interface/Cursor");
buttonTexture = Game1.instance.Content.Load<Texture2D>("Interface/Cursor");
}
}
}
I thought it might have something to do me using a different class to load(which I found odd) so I tried moving it all to the load content class in the main class, however, it didn't remove the error but instead of triggering during the loading session it now triggered when I tried to put the object to use(after the object should have been given a value and thus not be null)
I don't believe that the problem is with the picture I try to use since I already added it to the folder I'm using (I would post a picture but i don't have enough reputation)
If anyone have any idea what might be the cause of this error I would be happy to here your thoughts.

Expose webjobs functions to dashboard without azure storage

In this question there's an example on how to use a webjob that can perform some background operations without interacting with azure table storage.
I tried to replicate the code in the answer but it's throwing the following error:
' 'Void ScheduleNotifications()' can't be invoked from Azure WebJobs SDK. Is it missing Azure WebJobs SDK attributes? '
In this link they have a similar error and in one of the answers it says that this was fixed in the 0.4.1-beta release. I'm running the 0.5.0-beta release and I'm experiencing the error.
Here's a copy of my code:
class Program
{
static void Main()
{
var config = new JobHostConfiguration(AzureStorageAccount.ConnectionString);
var host = new JobHost(config);
host.Call(typeof(Program).GetMethod("ScheduleNotifications"));
host.RunAndBlock();
}
[NoAutomaticTrigger]
public static void ScheduleNotifications()
{
//Do work
}
}
I want to know if I'm missing something or is this still a bug in the Webjobs SDK.
Update: Per Victor's answer, the Program class has to be public.
Working code:
public class Program
{
static void Main()
{
var config = new JobHostConfiguration(AzureStorageAccount.ConnectionString);
var host = new JobHost(config);
host.Call(typeof(Program).GetMethod("ScheduleNotifications"));
host.RunAndBlock();
}
[NoAutomaticTrigger]
public static void ScheduleNotifications()
{
//Do work
}
}
Unless you use a custom type locator, a function has to satisfy all conditions below:
it has to be public
it has to be static
it has to be non abstract
it has to be in a non abstract class
it has to be in a public class
Your function doesn't meet the last condition. If you make the class public it will work.
Also, if you use webjobs sdk 0.5.0-beta and you run a program with only the code in your example, you will see a message saying that no functions were found.
Came looking for an answer here, but didn't quite find it in the answer above, though everything he said is true. My problem was that I accidentally changed the inbound property names of a Azure web job so that they DIDN'T match the attributes of the object the function was supposed to catch. Duh!
For the concrete example:
my web job was listening for a queue message based on this class:
public class ProcessFileArgs
{
public ProcessFileArgs();
public string DealId { get; set; }
public ProcessFileType DmsFileType { get; set; }
public string Email { get; set; }
public string Filename { get; set; }
}
But my public static async class in the Functions.cs file contained this as a function definition, where the declared parameters didn't match the names within the queue message class for which it was waiting:
public static async Task LogAndLoadFile(
[QueueTrigger(Queues.SomeQueueName)] ProcessFileArgs processFileArgs,
string dealid,
string emailaddress,
string file,
[Blob("{fileFolder}/{Filename}", FileAccess.Read)] Stream input,
TextWriter log,
CancellationToken cancellationToke)
{
So if you run into this problem, check to make sure the parameter and attribute names match.

BeforeFeature/AfterFeature does not work using SpecFlow and Coded UI

I am not able to define a [BeforeFeature]/[AfterFeature] hook for my feature file. The application under test is WPF standalone desktop applications.
If I use [BeforeScenario]/[AfterScenario] everything works fine, the application starts without any problem, the designed steps are performed correctly and the app is closed.
Once I use the same steps with [BeforeFeature]/[AfterFeature] tags the application starts and the test fails with:
The following error occurred when this process was started: Object reference not set to an instance of an object.
Here is an example:
[Binding]
public class Setup
{
[BeforeScenario("setup_scenario")]
public static void BeforeAppScenario()
{
UILoader.General.StartApplication();
}
[AfterScenario("setup_scenario")]
public static void AfterAppScenario()
{
UILoader.General.CloseApplication();
}
[BeforeFeature("setup_feature")]
public static void BeforeAppFeature()
{
UILoader.General.StartApplication();
}
[AfterFeature("setup_feature")]
public static void AfterAppFeature()
{
UILoader.General.CloseApplication();
}
}
StartApplication/CloseApplication were recorded and auto-generated with Coded UI Test Builder:
public void StartApplication()
{
// Launch '%ProgramFiles%\...
ApplicationUnderTest Application = ApplicationUnderTest.Launch(this.StartApplicationParams.ExePath, this.StartApplicationParams.AlternateExePath);
}
public class StartApplicationParams
{
public string ExePath = "C:\\Program Files..."
public string AlternateExePath = "%ProgramFiles%\\..."
}
Noteworthy: I'm quite new with SpecFlow.
I can't figure it out why my test fails with [BeforeFeature] and works fine with [BeforeScenario].
It would be great if somebody could help me with this issue. Thanks!
I ran into a similar problem recently. Not sure if this can still help you, but it may be of use for people who stumble upon this question.
For BeforeFeature\AfterFeature to work, the feature itself needs to be tagged, tagging just specific scenarios will not work.
Your feature files should start like this:
#setup_feature
Feature: Name Of Your Feature
#setup_scenario
Scenario: ...

Spec fails when run by mspec.exe, but passes when run by TD.NET

I wrote about this topic in another question.
However, I've since refactored my code to get rid of configuration access, thus allowing the specs to pass. Or so I thought. They run fine from within Visual Studio using TestDriven.Net. However, when I run them during rake using the mspec.exe tool, they still fail with a serialization exception. So I've created a completely self-contained example that does basically nothing except setup fake security credentials on the thread. This test passes just fine in TD.Net, but blows up in mspec.exe. Does anybody have any suggestions?
Update: I've discovered a work-around. After researching the issue, it seems the cause is that the assembly containing my principal object is not in the same folder as the mspec.exe. When mspec creates a new AppDomain to run my specs, that new AppDomain has to load the assembly with the principal object in order to deserialize it. That assembly is not in the same folder as the mspec EXE, so it fails. If I copied my assembly into the same folder as mspec, it works fine.
What I still don't understand is why ReSharper and TD.Net can run the test just fine? Do they not use mspec.exe to actually run the tests?
using System;
using System.Security.Principal;
using System.Threading;
using Machine.Specifications;
namespace MSpecTest
{
[Subject(typeof(MyViewModel))]
public class When_security_credentials_are_faked
{
static MyViewModel SUT;
Establish context = SetupFakeSecurityCredentials;
Because of = () =>
SUT = new MyViewModel();
It should_be_initialized = () =>
SUT.Initialized.ShouldBeTrue();
static void SetupFakeSecurityCredentials()
{
Thread.CurrentPrincipal = CreatePrincipal(CreateIdentity());
}
static MyIdentity CreateIdentity()
{
return new MyIdentity(Environment.UserName, "None", true);
}
static MyPrincipal CreatePrincipal(MyIdentity identity)
{
return new MyPrincipal(identity);
}
}
public class MyViewModel
{
public MyViewModel()
{
Initialized = true;
}
public bool Initialized { get; set; }
}
[Serializable]
public class MyPrincipal : IPrincipal
{
private readonly MyIdentity _identity;
public MyPrincipal(MyIdentity identity)
{
_identity = identity;
}
public bool IsInRole(string role)
{
return true;
}
public IIdentity Identity
{
get { return _identity; }
}
}
[Serializable]
public class MyIdentity : IIdentity
{
private readonly string _name;
private readonly string _authenticationType;
private readonly bool _isAuthenticated;
public MyIdentity(string name, string authenticationType, bool isAuthenticated)
{
_name = name;
_isAuthenticated = isAuthenticated;
_authenticationType = authenticationType;
}
public string Name
{
get { return _name; }
}
public string AuthenticationType
{
get { return _authenticationType; }
}
public bool IsAuthenticated
{
get { return _isAuthenticated; }
}
}
}
Dan,
thank you for providing a reproduction.
First off, the console runner works differently than the TestDriven.NET and ReSharper runners. Basically, the console runner has to perform a lot more setup work in that it creates a new AppDomain (plus configuration) for every assembly that is run. This is required to load the .dll.config file for your spec assembly.
Per spec assembly, two AppDomains are created:
The first AppDomain (Console) is created
implicitly when mspec.exe is
executed,
a second AppDomain is created by mspec.exe for the assembly containing the specs (Spec).
Both AppDomains communicate with each other through .NET Remoting: For example, when a spec is executed in the Spec AppDomain, it notifies the Console AppDomain of that fact. When Console receives the notification it acts accordingly by writing the spec information to the console.
This communiciation between Spec and Console is realized transparently through .NET Remoting. One property of .NET Remoting is that some properties of the calling AppDomain (Spec) are automatically included when sending notifications to the target AppDomain (Console). Thread.CurrentPrincipal is such a property. You can read more about that here: http://sontek.vox.com/library/post/re-iprincipal-iidentity-ihttpmodule-serializable.html
The context you provide will run in the Spec AppDomain. You set Thread.CurrentPrincipal in the Because. After Because ran, a notification will be issued to the Console AppDomain. The notification will include your custom MyPrincipal that the receiving Console AppDomain tries to deserialize. It cannot do that since it doesn't know about your spec assembly (as it is not included in its private bin path).
This is why you had to put your spec assembly in the same folder as mspec.exe.
There are two possible workarounds:
Derive MyPrincipal and MyIdentity from MarshalByRefObject so that they can take part in cross-AppDomain communication through a proxy (instead of being serialized)
Set Thread.CurrentPrincipal transiently in the Because
(Text is required for formatting to work -- please ignore)
Because of = () =>
{
var previousPrincipal = Thread.CurrentPrincipal;
try
{
Thread.CurrentPrincipal = new MyPrincipal(...);
SUT = new MyViewModel();
}
finally
{
Thread.CurrentPrincipal = previousPrincipal;
}
}
ReSharper, for example, handles all the communication work for us. MSpec's ReSharper Runner can hook into the existing infrastructure (that, AFAIK, does not use .NET Remoting).

Resources