Monotouch - Use of Application class as storage of common objects - xamarin.ios

To communicate between views and objects persistant information, for example the username and choice of font size for display, is it considered good form to put these onto the Application object, or is it more efficient to put them into static singletons?
For example:
public class Application
{
static void Main (string[] args)
{
UIApplication.Main (args);
}
public static Username {get;set;}
}

I don't think there's any difference performance-wise between putting static objects into the Application vs singletons vs static classes.
For things like Colors and fonts, I usually prefer to create static classes to hold each type of object, so for example I usually write this:
public static class Colors {
public static Color ToolbarColor = Color.Black;
..
}
This makes it easier to change colors around the entire app without having to be searching around everywhere. I do the same thing for fonts, images, etc.

Related

servicestack plugin to a Windows Service that will serve static files?

I've ServiceStack (V5.1.0) as a Windows Service, serving REST APIs, no problems. I would like to create a plugin that will serve static files from a specific physical directory, for any routes that start with /GUI.
I've read "Q: ServiceStack Razor with Multiple SPAs" here ServiceStack Razor with Multiple SPAs
But this seems to only handle individual files like index.html., and I need to serve not just files in the root of the physical path, but files in the subdirs of the physical path as well. For example, the route /GUI/css/site.css should serve the site.css file found in the css subdirectory below the root.
I looked at "Mapping static file directories in ServiceStack" here
https://forums.servicestack.net/t/mapping-static-file-directories-in-servicestack/3377/1
and based on this, tried overriding GetVirtualFileSources
public class AppHost : AppSelfHostBase {
...
// override GetVirtualFileSources to support multiple FileSystemMapping.
// Allow plugins to add their own FileSystemMapping
public override List<IVirtualPathProvider> GetVirtualFileSources()
{
var existingProviders = base.GetVirtualFileSources();
// Hardcoded now, will use a IoC collection populated by plugins in the future. Paths will be either absolute, or relative to the location at which the Program assembly is located.
existingProviders.Add(new FileSystemMapping("GUI",#"C:\Obfuscated\netstandard2.0\blazor"));
return existingProviders;
}
....
}
and using a FallBackRoute in the plugins' model,
[FallbackRoute("/GUI/{PathInfo*}")]
public class FallbackForUnmatchedGUIRoutes : IReturn<IHttpResult>
{
public string PathInfo { get; set; }
}
But I can't figure out how to get the interface method to change the PathInfo into an object that implements IVirtualFile.
public HttpResult Get(FallbackForUnmatchedGUIRoutes request)
{
// If no file is requested, default to "index.html"" file name
var cleanPathInfo = request.PathInfo ?? "index.html";
// Somehow, need to convert the cleanPathInfo into an IVirtualFile, that specifies the correct VirtualPathProvider (indexed by "GUI"")
// insert here the magic code to convert cleanPathInfo into an object that implements IVirtualFile
// var cleanVirtualPathInfo = cleanPathInfo as IVirtualFile
// to make use of ServiceStack enhanced functionality, wrap the cleanVirtualPathInfo in a HttpResult,
HttpResult httpresult = new HttpResult(cleanPathInfo,false); // this doesn't compile, because no overload with 2 parameters takes a string as the first parameter, but there is an overload that will take an IVirtualFile object
return httpresult;
}
Any suggestions to make the interface code return the correct files? Or a better way to allow for multiple plugins, each to support a different SPA, based on the first portion of the route? Hints, links, explicit instructions - any and all are welcome!
You just need to register a Virtual File System, you don't need to create your own Service as ServiceStack's static file handler will automatically return the first file it finds in the list of registered Virtual File Sources.
If you want to be able to register File Mappings in a Plugin you can add it to the AppHost's AddVirtualFileSources list in the plugin constructor, e.g:
public class GuiPlugin : IPlugin, IPreInitPlugin
{
public void Configure(IAppHost appHost)
{
appHost.AddVirtualFileSources.Add(
new FileSystemMapping("GUI", appHost.MapProjectPath("~/blazor")));
}
public void Register(IAppHost appHost) {}
}
The appHost.MapProjectPath() lets you resolve a physical file from your AppHost's projects Content Path. Then you can register the Plugin in your AppHost with:
public override void Configure(Container container)
{
Plugins.Add(new GuiPlugin());
}
Where your files in /blazor should now be resolvable from your registered path mapping, e.g:
/GUI/file.html -> C:\project\path\file.html
Note you don't need any Services and ServiceStack will automatically return the static files of registered file mappings, so you'll want to remove any [FallbackRoute] you've added.

Improve my NinjectBootstrapper static class.

A NinjectBootstrapper class has been created in a Service project(responsible for getting products).
This is my code
public static class NinjectBootstrapper
{
private static readonly object _thislock = new object();
//flag to prevent bootstrap for executing multiple times
private static bool _done;
public static void Bootstrap()
{
lock(_thislock)
{
if(_done)
{
return;
}
_done = true;
// services
NinjectContainer.Kernel.Bind<IProductService>().To<ProductService>();
// repositories
NinjectContainer.Kernel.Bind<IProductRepository>().To<ProductRepository>();
}
}
}
Now, while this works, I would really like to know if there are better ways to refactor my code. For instance I've read a lot of stuff about using a singleton instead of the static class.
I'd like to really set a good base here to make it easy and flexible for future developers to extend functionality. What are some good pointers and tips I can take into consideration?
I've read a lot of stuff about using a singleton instead of the static class.
When applying DI we typically prefer instance classes over static classes, because we can't practice Constructor Injection in static classes. This doesn't mean however, that static classes are a bad practice. When classes have no dependencies and no state, static is fine.
This holds as well for code in the startup path, such as your NinjectBootstrapper. You can make it an instance class, but since this class is started directly at startup, no dependencies need to be injected (obviously, because it is the thing that wires the DI container), it would typically be useless to make this an instance class.

Adding attributes to parent class fields and properties

In my example to illustrate my use case I have a parent class that is purposely database agnostic (let's say I can't change the code of it for some reasons, because the class come from a commercial assembly or the .net framework or are auto generated by entity framework):
public class Father
{
public string Field1;
public string Field2;
}
Now I'd like to store an object derived from it into MongoDB (again, it's only for the example, there a lot of other use cases and my question has nothing to do with MongoDB):
public class Child:Father
{
public ObjectId Id;
public DateTime DateCreation;
}
But I'd like to add attributes to some elements of the father, like [BsonIgnoreIfNull], without overriding (they are not marked as virtual) or having to fully reimplement the Father in my Child class.
What would be the cleanest way to do this?
Thanks!

Displaying an interactive image in Android

In my ANDROID application, I am trying to develop an interactive image. The image is made of several interconnected nodes. I would like to tap on two different nodes to get the shortest path between them. When the nodes are tapped, I want to draw an overlay on top of the image which indicates the shortest path between the tapped nodes. In addition to this, I would want to implement the animation of the path from source node to intermediate nodes and finally to the destination node.
I was trying to implement this in Surface View.
Any suggestions on how to get started with this would be really helpful. Any tutorials, sample code which I can use as a guidance would be great.
You can start by creating your own surfaceview class that displays an image.
Make sure you implement SurfaceHolder.Callback in your surfaceview class.
public class MySurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mthread.setRunning(false);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
You can use a thread to call draw methods and render the image. Make sure to use Canvas locks while implementing Threads.

Static Class vs Private Instances - Pros/Cons - Read for more information

I'm trying to figure out which is the best way to design my game's structure.
Currently I store class instances everywhere but I would prefer to use a straight up static access.
For example I have a class called "GameSaveSystem.cs"
This class handled obtaining a StorageDevice and all storage related information for all current players.
So my current strategy is the following
----------------MainClass.cs
public static void Main(string[] args) {
new Main();
}
----------------Main.cs
public Main() {
GameSaveSystem save_system = new GameSaveSystem();
singlePlayer = new SinglePlayer(save_system);
multiPlayer = new MultiPlayer(save_system);
}
----------------SinglePlayer.cs
SinglePlayer(GameSaveSystem save_system) {
this.save_system = save_system;
}
----------------MultiPlayer.cs
MultiPlayer(GameSaveSystem save_system) {
this.save_system = save_system;
}
The reason I do it like this is because in Java i could create a new .Java file and have it call "MainClass.main(args);"
So then Inside that extra class I can gain access to any Static class members or public static instances which are stored throughout the class files.
so what i'm wondering is would it be safer to use instances or for this type of situation should i just go with static classes? I want the game to have some kind of security against this types of issues.
So below are the 3 ways I've seen for grabbing access to a class
Static access - were the person can access this class at anytime from anywhere (This is my preferred strategy for ease of use).
ClassB.DoSomething();
Instances stored everywhere - Each every class will have the created instance of a class stored so they have access to it at anytime. Classes have all the instances they will need stored and nothing else.
public class A(ClassB classB) {
this.classB = classB;
}
classB.DoSomething();
Instance stored in one class - 1 Class creates a single instance of all the classes which would normally have only 1 instance created. Then you create an instance of this class and store it into all the classes which require access to the previously created instances. Only the classes which stored the main instance will have access to the other instances.
public class A(Main main) {
this.main = main;
}
main.getInstanceB().DoSomething();
It looks to me like you would benefit from reading a little bit on this.
Essentially which one you go with is more of a personal choice. There are, of course, performance considerations for each, but semantics are also important. It's up to you, as the software engineer, to decide what's best.

Resources