- Notifications
You must be signed in to change notification settings - Fork141
Makes things cross-platform
License
reactiveui/splat
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Certain types of things are basically impossible to do in cross-platformmobile code today, yet there's no reason why. Writing a ViewModel that handlesloading a gallery of pictures from disk will be completely riddled with#ifdefs
and basically unreadable.
Splat aims to fix that, by providing a usable leaky abstraction above platformcode. It is leaky, because it always provides an extension methodToNative()
andFromNative()
, which converts the abstraction to the platform-specificversion. Load the image in the cross-platform code, then callToNative()
inyour view to actually display it.
Splat currently supports:
- Cross-platform image loading/saving
- A port of System.Drawing.Color for portable libraries
- Cross-platform geometry primitives (PointF, SizeF, RectangleF), as well as a bunch ofadditional extension methods to make using them easier.
- A way to detect whether you're in a Unit Test runner / Design Mode
- A cross-platform logging framework
- Simple yet flexible Service Location
![]() Glenn Watson Melbourne, Australia | ![]() Rodney Littles II Texas, USA |
![]() David Vreony UK | ![]() Chris Pulman UK |
Always Be NuGetting. Package contains binaries for:
- .NET Framework 4.6.2, .NET Framework 4.7.2, .NET Standard 2.0, .NET 6.0, and .NET 8.0
- Works with:
- WPF
- Windows Forms
- WinUI 3
- Maui (WinUI, Android, iOS and Mac)
- Avalonia
// If true, we are running unit testsModeDetector.InUnitTestRunner();
Splat provides a simple service location implementation that is optimized forDesktop and Mobile applications, while still remaining reasonably flexible.
There are 2 parts to the locator design:
- Locator.Current The property to use toretrieve services. Locator.Current is a static variable that can be set on startup, to adapt Splat to other DI/IoC frameworks. We're currently working from v7 onward to make it easier to use your DI/IoC framework of choice. (see below)
- Locator.CurrentMutable The property to use toregister services
To get a service:
// To get a single service registrationvartoaster=Locator.Current.GetService<IToaster>();// To get all service registrationsvarallToasterImpls=Locator.Current.GetServices<IToaster>();
Locator.Current is a static variable that can be set on startup, to adapt Splatto other DI/IoC frameworks. We're currently working from v7 onward to make it easier to use your DI/IoC framework of choice.
The default implementation of Service Location also allows new types to beregistered at runtime.
// Create a new Toaster any time someone asksLocator.CurrentMutable.Register(()=>newToaster(),typeof(IToaster));// Register a singleton instanceLocator.CurrentMutable.RegisterConstant(newExtraGoodToaster(),typeof(IToaster));// Register a singleton which won't get created until the first user accesses itLocator.CurrentMutable.RegisterLazySingleton(()=>newLazyToaster(),typeof(IToaster));
There is a source generator that will inject constructor and properties. Seehere for instructions.
For each of the provided dependency resolver adapters, there is a specific package that allows the service locator to be implemented by another ioc container.
Note: When using ReactiveUI and overriding Splat's default behavior, you have to be sure toinitialize ReactiveUI before your container finalizes.
Please note: If you are adjusting behaviours of Splat by working with your custom container directly. Please read the relevant projects documentation onREPLACING the registration. If the container supports appending\ multiple registrations you may get undesired behaviours, such as the wrong logger factorybeing used.
Splat provides a simple logging proxy for libraries and applications to set up.By default, this logging isn't configured (i.e. it logs to the Null Logger). Toset up logging:
- Register an implementation of
ILogger
using Service Location. - In the class in which you want to log stuff, "implement" the
IEnableLogger
interface (this is a tag interface, no implementation actually needed). - Call the
Log
method to write log entries:
this.Log().Warn("Something bad happened: {0}",errorMessage);this.Log().ErrorException("Tried to do a thing and failed",exception);
For static methods,LogHost.Default
can be used as the object to write a logentry for. The Static logger uses a different interface from the main logger to allow capture of additionalcaller context as it doesn't have the details of the class instance etc. when compared to the normal logger.To get the benefit of these you don't need to do much as they are optional parameters at the end of the methodsthat are utilised by the compiler\framework. Currently we only captureCallerMemberName.
Splat has support for the following logging frameworks
Target | Package | NuGet |
---|---|---|
Console | Splat | |
Debug | Splat | |
Log4Net | Splat.Log4Net | |
Microsoft Extensions Logging | Splat.Microsoft.Extensions.Logging | |
NLog | Splat.NLog | |
Serilog | Splat.Serilog |
First configure Log4Net. For guidance seehttps://logging.apache.org/log4net/release/manual/configuration.html
usingSplat.Log4Net;// then in your service locator initialisationLocator.CurrentMutable.UseLog4NetWithWrappingFullLogger();
Thanks to @dpvreony for first creating this logger.
First configure Microsoft.Extensions.Logging. For guidance seehttps://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/
usingSplat.Microsoft.Extensions.Logging;// note: this is different from the other adapter extension methods// as it needs knowledge of the logger factory// also the "container" is how you configured the Microsoft.Logging.ExtensionsvarloggerFactory=container.Resolve<ILoggerFactory>();// in theory it could also be// var loggerFactory = new LoggerFactory();/// then in your service locator initialisationLocator.CurrentMutable.UseMicrosoftExtensionsLoggingWithWrappingFullLogger(loggerFactory);
Thanks to @dpvreony for first creating this logger.
First configure NLog. For guidance seehttps://github.com/nlog/nlog/wiki/Tutorial andhttps://github.com/nlog/nlog/wiki/Configuration-file
usingSplat.NLog;// then in your service locator initialisationLocator.CurrentMutable.UseNLogWithWrappingFullLogger();
Thanks to @dpvreony for first creating this logger.
First configure Serilog. For guidance seehttps://github.com/serilog/serilog/wiki/Configuration-Basics
usingSplat.Serilog;// Then in your service locator initialisationLocator.CurrentMutable.UseSerilogFullLogger()
Thanks to @joelweiss for first creating this logger.
Target | Package | NuGet |
---|---|---|
Splat.Drawing | Splat.Drawing |
// This System.Drawing class works, even on WinRT where it's not supposed to exist// Also, this works in a Portable Library, in your ViewModelProfileBackgroundAccentColor=Color.FromArgb(255,255,255,255);
Later, in the view, we can use it:
ImageView.Background = ViewModel.ProfileBackgroundAccentColor.ToNativeBrush();
If targeting iOS or Mac in a cross-platform solution (e.g. iOS & Android), usethe SplatColor class to define colors in your netstandard library(since Cocoa doesn't include System.Drawing.Color).
// In a netstandard librarySplatColorBackgroundColor=SplatColor.Red;
// From an iOS projectUIColor bgColor = ViewModel.BackgroundColor.ToNative();
// From an Android projectAndroid.Graphics.Color bgColor = ViewModel.BackgroundColor.ToNative();
You can register with the Splat locators.
Locator.CurrentMutable.RegisterPlatformBitmapLoader();
You can then load your images in a cross platform way:
//// Load an Image// This code even works in a Portable Library//varwc=newWebClient();StreamimageStream=wc.OpenRead("http://octodex.github.com/images/Professortocat_v2.png");// IBitmap is a type that provides basic image information such as dimensionsIBitmapprofileImage=awaitBitmapLoader.Current.Load(imageStream,null/* Use original width */,null/* Use original height */);
Then later, in your View:
// ToNative always converts an IBitmap into the type that the platform// uses, such as UIBitmap on iOS or BitmapSource in WPFImageView.Source=ViewModel.ProfileImage.ToNative();
Images can also be loaded from a Resource. On Android, this can either be aResource ID casted to a string, or the name of the resourceas as string(optionally including the extension).
varprofileImage=awaitBitmapLoader.Current.LoadFromResource("DefaultAvatar.png",null,null);
Bitmaps can also be created and saved - actuallydrawing on the image isbeyond the scope of this library, you should do this in your view-specificcode.
varblankImage=BitmapLoader.Current.Create(512.0f,512.0f);awaitblankImage.Save(CompressedBitmapFormat.Png,0.0,File.Open("ItsBlank.png"));
// If true, we are running inside Blend, so don't do anythingPlatformModeDetector.InDesignMode();
Application Performance Monitoring is split into the follow sections
- Error Reporting
- Feature Usage Tracking
- View Tracking
The table below shows the support across various APM packages
Product | Package | NuGet | Maturity Level | Error Reporting | Feature Usage Tracking | View Tracking |
---|---|---|---|---|---|---|
Appcenter | Splat.AppCenter | Alpha | TODO | Native | Native | |
Application Insights | Splat.ApplicationInsights | Alpha | TODO | Native | Native | |
Exceptionless | Splat.Exceptionless | Alpha | TODO | Native | By Convention | |
New Relic | N\A | N\A | Not Started | TODO | TODO | TODO |
OpenTrace | N\A | N\A | Not Started | TODO | TODO | TODO |
Raygun | Splat.Raygun | Prototype | TODO | By Convention | By Convention |
- To sit on top of existing APM libaries using native features where possible, or by using a common convention that gives parity in behaviour.** Where there is a convention behaviour it will be detailed under the relevant frameworks documentation.
- To define basic behaviours that are dropped into consuming libraries, for example with ReactiveUI** Commands** ViewModels** Views
Splat comes with a default implementation that pushes events into your active Splat logging framework. This allows for design and testing prior to hooking up a full APM offering.
TODO
The most basic ability for feature usage tracking is to implement the Splat.ApplicationPerformanceMonitoring.IEnableFeatureUsageTracking interface. This has the same behaviour as the logging interface and allows Splat to inject whicheverAPM platform is registered with the ServiceLocator at initialization.
/// <summary>/// Dummy object for testing IEnableFeatureUsageTracking./// </summary>publicsealedclassTestObjectThatSupportsFeatureUsageTracking:IEnableFeatureUsageTracking{publicasyncTaskSomeFeatureIWantToTrack(){using(vartrackingSession=this.FeatureUsageTrackingSession("featureName")){try{// do some work here.}catch(Exceptionexception){trackingSession.OnException(exception);}}}}
Splat also has the notion of subfeatures, some APM platforms support this natively, others have been done by convention, which will be explained in the relevant library.Splat itself does not dictate when these should be used. It's up to you. You may have a primary feature (such as a search view) and then track buttons, etc. on that viewas subfeatures.
/// <summary>/// Dummy object for testing IEnableFeatureUsageTracking./// </summary>publicsealedclassTestObjectThatSupportsFeatureUsageTracking:IEnableFeatureUsageTracking{publicasyncTaskSomeFeatureIWantToTrack(){using(varmainFeature=this.FeatureUsageTrackingSession("featureName")){try{awaitDoSubFeature(mainFeature).ConfigureAwait(false);}catch(Exceptionexception){mainFeature.OnException(exception);}}}publicasyncTaskSomeFeatureIWantToTrack(IFeatureUsageTrackingSessionparentFeature){using(varsubFeature=parentFeature.SubFeature("subFeatureName")){try{// do some work here.}catch(Exceptionexception){subFeature.OnException(exception);}}}}
TODO
First configure Appcenter. For guidance seehttps://docs.microsoft.com/en-us/appcenter/diagnostics/enabling-diagnostics
usingSplat.AppCenter;// then in your service locator initialisationLocator.CurrentMutable.UseAppcenterApm();
First configure Application Insights. For guidance seehttps://docs.microsoft.com/en-us/azure/azure-monitor/app/worker-service
usingSplat.ApplicationInsights;// then in your service locator initialisationLocator.CurrentMutable.UseApplicationInsightsApm();
First configure Exceptionless. For guidance seehttps://github.com/exceptionless/Exceptionless/wiki/Getting-Started
usingSplat.Exceptionless;// then in your service locator initialisationLocator.CurrentMutable.UseExceptionlessApm();
New Relic support isn't currently available.
OpenTrace support isn't currently available.
First configure Raygun. For guidance see TODO
usingSplat.Raygun;// then in your service locator initialisationLocator.CurrentMutable.UseRaygunApm();
The unit tests for this functionality do not generate activity to the relevant platform.The integration tests DO SEND TEST DATA to the relevant platforms, so they need to havethe user-secrets configured. There is a script in the \scripts\inttestusersecrets.cmdthat shows how to set the relevant secrets up.
Splat is developed under an OSI-approved open source license, making it freely usable and distributable, even for commercial use. We ❤ the people who are involved in this project, and we’d love to have you on board, especially if you are just getting started or have never contributed to open-source before.
So here's to you, lovely person who wants to join us — this is how you can support us:
- Responding to questions on StackOverflow
- Passing on knowledge and teaching the next generation of developers
- Submitting documentation updates where you see fit or lacking.
- Making contributions to the code base.
About
Makes things cross-platform