How to create a NativeView in Nativescript-Angular? - nativescript

I'm developing a mobile App with Nativescript and Angular, but I've a problem to create an headerView to add inside the CFAlertDialog (I'm using the plugin nativescript-cfalert-dialog).
I created a service to inject to several components in my app, which is something like this
import * as application from 'tns-core-modules/application'
#Injectable()
export class PlayerDialogService {
...
constructor() {
const context = application.android.context as android.content.Context;
this.generateAndroidNativeView(context)
}
private generateAndroidNativeView(context: android.content.Context) {
this.usernameLabel = new android.widget.TextView(context)
this.usernameLabel.setTextSize(20)
this.fullNameLabel = new android.widget.TextView(context)
this.fullNameLabel.setTextSize(16)
this.playerImage = new android.widget.ImageView(context)
this.playerImage.setMaxWidth(48)
this.playerImage.setMaxHeight(48)
this.textStackLayout = new android.widget.LinearLayout(context)
this.textStackLayout.addView(this.usernameLabel)
this.textStackLayout.addView(this.fullNameLabel)
this.stackLayout = new android.widget.LinearLayout(context)
this.stackLayout.addView(this.playerImage)
this.stackLayout.addView(this.textStackLayout)
}
}
Fact is that everytime the dialog is loaded (I open a component/view that has the PlayerDialogService injected), I get this error:
JS: ERROR TypeError: Cannot read property 'usernameLabel' of undefined
I'm afraid I'm not passing the correct Context (despite it's not an empty object, nor an undefined one), but has a constructor included. So... what am I missing?

Related

How to add custom Java script code to ElectronHostHook in electronnet asp.net mvc

I am trying to add this code snippet to the wed apis demo project but I tried and failed and there isnt much documentation on how to do it.
var os = require("os");
var bytesAvailable = os.totalmem(); // returns number in bytes
// 1 mb = 1048576 bytes
console.log("Total memory available MB :" + (bytesAvailable/1048576) );
it needs to have a type script file and a javascript file according to the implamentation with the create excel.js demo but im not sure how to go about that process.
FYI everyone looking at this, the developer made a decent tutorial for this but lets just go with im the type of developer who is kinda dumb but competent.
So Basically your gonna want to create a type script file using the index.ts file as a template
once you have a type script file place your custom JS in the onHostRead() part of the script
build it
this will create the js file and make it look similar to the other example files.
create a controller for your custom js like hosthook.cs, this is called the mainfunction in the api demo
add front facing logic to your software. ....so still testing idk If i got it right just yet
This did not work in visual studio code , I used visual studio 2022
dont install the type script nuget package visual studio recommends , its not in the documentation, will break build.
sometimes the people capable are too busy to help so dive deep in the code and get good (talking to myself here)
ipController.cs
using ElectronNET.API;
using ElectronNET.API.Entities;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
namespace ElectronNET_API_Demos.Controllers
{
public class IPController : Controller
{
public IActionResult Index()
{
if (HybridSupport.IsElectronActive)
{
Electron.IpcMain.On("start-hoosthook", async (args) =>
{
var mainWindow = Electron.WindowManager.BrowserWindows.First();
var options = new OpenDialogOptions
{
Properties = new OpenDialogProperty[]
{
OpenDialogProperty.openDirectory
}
};
var folderPath = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);
var resultFromTypeScript = await Electron.HostHook.CallAsync<string>("get-ip-address", folderPath);
Electron.IpcMain.Send(mainWindow, "ip-address-found", resultFromTypeScript);
});
}
return View();
}
}
}
ipAddress.ts
// #ts-ignore
import * as Electron from "electron";
import { Connector } from "./connector";
import { IPAddress } from "./ipAddress";
export class HookService extends Connector {
constructor(socket: SocketIO.Socket, public app: Electron.App) {
super(socket, app);
}
onHostReady(): void {
// execute your own JavaScript Host logic here
var os = require("os");
var result = console.log(os.networkInterfaces);
return result;
}
}
ipAddress.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HookService = void 0;
const connector_1 = require("./connector");
class HookService extends connector_1.Connector {
constructor(socket, app) {
super(socket, app);
this.app = app;
}
onHostReady() {
// execute your own JavaScript Host logic here
var os = require("os");
var result = console.log(os.networkInterfaces);
return result;
}
}
exports.HookService = HookService;
//# sourceMappingURL=ipAddress.js.map

prisma-select issue for custom output path

I am getting the below error when I try to use
const select = new PrismaSelect(info).value;
[Nest] 65877 - 17/05/2021, 16:45:13 [ExceptionsHandler] Cannot find module '.prisma/client'
My PrismaClient is in a custom path rather than the default, as I am using a monorepo for multiple microservices.
generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "darwin"]
output = "../src/.generated/prisma/client"
}
Is there a way to point PrismaSelect to the correct Client?
The solution was shared by the author of the package
Import custom instance of Prisma Client
import { Prisma } from '../../.generated/prisma/client';
Pass dmmf object to PrismaSelect constructor
const select = new PrismaSelect(info, { dmmf: [Prisma.dmmf] }).value;

Issue with FCM Push Notification Android

I was able to receive push notifications some months ago, a day ago i started to work again on the app now the issue is it's not able to receive push notification. It does provide FCM token but onMessageReceived never gets called also if i try with Postman it gives an error of Mismatchsender ID, but the scenario here is a bit confusing. If i change the package name (after creating new project on console and added new goole-service.json file) it doesn't let me register for FCM token. i've stuck in this situation from last day. can anybody please help? what i'm doing wrong.
Here is implementaion of FCMToken
[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class MyFirebaseIIDService : FirebaseInstanceIdService
{
const string TAG = "MyFirebaseIIDService";
public override void OnTokenRefresh()
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
Log.Debug(TAG, "Refreshed token: " + refreshedToken);
SendRegistrationToServer(refreshedToken);
}
void SendRegistrationToServer(string token)
{
// Add custom implementation, as needed.
}
}
Here it gives me error if i change my package name to any other,
Error: Java.Lang.IllegalStateException: Default FirebaseApp is not
initialized in this process
try
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
// PushNotificationManager.Initialize(this, false);
} catch(Exception ee)
{
}
I've solved my issue with with customization of FirebaseInitialize after creating new project on Firebase here is my code. But one bad thing is here that when new token gets initialized it never gets called on FirebaseInstanceIdReceiver.
var options = new FirebaseOptions.Builder()
.SetApplicationId("<AppID>")
.SetApiKey("<ApiKey>")
.SetDatabaseUrl("<DBURl>")
.SetStorageBucket("<StorageBucket>")
.SetGcmSenderId("<SenderID>").Build();
var fapp = FirebaseApp.InitializeApp(this, options);

Xamarin.Forms App return data to calling App

So, either I am asking incorrectly, or it isn't possible, let's see which...
If my app (Xamarin.Forms) is launched from another app, in order to get a url from my app, how do I return that data to the calling app? I wrongly assumed SetResult and Finish, I also wrongly assumed StartActivityForResult, but there has to be a way to do this. I know how to get data INTO my app from another app, but not the same in return.
POSSIBLE PARTIAL SOLUTION -- UPDATE, FAILS
So I have to setup an interface in my PCL, and call the method from the listview item selected handler, in the Android app I can then do this:
Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_url"));
setResult(Activity.RESULT_OK, result);
finish();
(source: https://developer.android.com/training/basics/intents/filters.html)
Is this looking right, and how would I implement the same thing on iOS?
END
I deleted my previous question because I couldn't explain the problem clearly, so here goes.
I have a Xamarin Forms app, I want to use a section of this app as a gallery. Currently I have images displayed in a list, and I have an Intent filter set that launches this page when you select the app as the source for an image (such as upload image on Facebook).
My issue is that I don't know how to return the data (the selected image) back to the app / webpage that made the request. In android I understand that you would use StartActivityForResult and OnActivityResult to handle this, but I am using Xamarin Forms (Android, iOS, UWP) and can't really find a solution that could be used cross-platform.
Just a link to documentation that covers this would be great, but if you have an example then even better.
Thanks
EDIT
Here is the code used to launch the app, I am interested in getting data back from the Intent.ActionPick after the user has selected an image from a ListView, which is in a ContentPage in the PCL.
[Activity(Label = "", Icon = "#drawable/icon", Theme = "#style/DefaultTheme", MainLauncher = true, LaunchMode = LaunchMode.SingleTop,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[IntentFilter(new[] { Intent.ActionSend }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = #"*/*")]
[IntentFilter(new[] { Intent.ActionView, Intent.ActionPick, Intent.ActionGetContent }, Categories = new[] { Intent.CategoryDefault, Intent.CategoryOpenable }, DataMimeType = #"*/*")]
public class MainActivity : FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
try
{
base.OnCreate(bundle);
CurrentPlatform.Init();
Xamarin.Forms.Forms.Init(this, bundle);
App _app = new App();
LoadApplication(_app);
if (Intent.Action == Intent.ActionSend)
{
var image = Intent.ClipData.GetItemAt(0);
var imageStream = ContentResolver.OpenInputStream(image.Uri);
var memOfImage = new System.IO.MemoryStream();
imageStream.CopyTo(memOfImage);
_app.UploadManager(memOfImage.ToArray()); //This allows me to upload images to my app
}
else if (Intent.Action == Intent.ActionPick)
{
_app.SelectManager(); //here is where I need help
}
else
{
_app.AuthManager(); //this is the default route
}
}
catch (Exception e)
{
}
}
It seems you cannot use remote URI to provide to calling app. Some posts I checked suggest to store the file locally and provide it's path to calling app. To avoid memory leak with many files stored I suggest to use the same file name then you will have only one file at any moment.
One more note. I tested this solution in facebook. Skype doesn't seem to accept that and, again, the posts I checked saying that Skype doesn't handle Intent properly (not sure what that means).
Now to solution. In main activity for example in OnCreate method add the follow.
ReturnImagePage is the name of my page class where I select an image
Xamarin.Forms.MessagingCenter.Subscribe<ReturnImagePage, string>(this, "imageUri", (sender, requestedUri) => {
Intent share = new Intent();
string uri = "file://" + requestedUri;
share.SetData(Android.Net.Uri.Parse(uri));
// OR
//Android.Net.Uri uri = Android.Net.Uri.Parse(requestedUri);
//Intent share = new Intent(Intent.ActionSend);
//share.PutExtra(Intent.ExtraStream, uri);
//share.SetType("image/*");
//share.AddFlags(ActivityFlags.GrantReadUriPermission);
SetResult(Result.Ok, share);
Finish();
});
Above will listen for the message when the image is selected.
Then in XFroms code when image is selected dowload it, store it, get path and send to Activity using it's path. Below is my test path
MessagingCenter.Send<ReturnImagePage, string>(this, "imageUri", "/storage/emulated/0/Android/data/ButtonRendererDemo.Droid/files/Pictures/temp/IMG_20170207_174559_21.jpg");
You can use static public class to save and access results like:
public static class StaticClass
{
public static int Result;
}

MVVMCross Manual Bind in MvxFragment with MvxViewPagerFragmentAdapter

I'm using an implementation of Cheesebaron's MvxViewPagerFragmentAdapter example that can be found here http://blog.ostebaronen.dk/2013/07/fragments-and-viewpager-with-mvx.html
var fragments = new List<MvxViewPagerFragmentAdapter.FragmentInfo>
{
new MvxViewPagerFragmentAdapter.FragmentInfo
{
FragmentType = typeof(JobDetailsView),
Title = "Detail",
ViewModel = ViewModel
},
new MvxViewPagerFragmentAdapter.FragmentInfo
{
FragmentType = typeof(JobFeaturesView),
Title = "Info",
ViewModel = ViewModel
}
}
Within my JobDetailsView's OnCreateView, I can inflate my layout specified using BindingInflate and any bindings that I have specified in the XML layout work correctly.
I now have a requirement to bind some elements programmatically, which i have tried to do using CreateBindingSet, but the bindings do not work. I've tried a simple text property and a button click. Both of these work when specified in the XML.
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Android.OS.Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
this.EnsureBindingContextIsSet(savedInstanceState);
_view = this.BindingInflate(Resource.Layout.jobview_details, null);//jobview_withtabs_details
var signatureCard = _view.FindViewById<CardFeature>(Resource.Id.signature_cardview);
signatureCard.FindViewById<TextView>(Resource.Id.tv_basecard_header_title).Text = "Signature";
var signatureButton = signatureCard.FindViewById<Button>(Resource.Id.btn_basecard_footer).Text = "Capture";
var set = this.CreateBindingSet<JobDetailsView, JobWithTabsViewModel>();
set.Bind(signatureButton).To(vm => vm.SignatureClickCommand);
set.Apply();
return _view;
}
in my output window, i can see this, but i don't know what to do to fix it:
04-16 17:40:43.721 I/mono-stdout(27727): MvxBind:Error: 23.79 Empty binding target passed to MvxTargetBindingFactoryRegistry
MvxBind:Warning: 23.80 Failed to create target binding for binding for SignatureClickCommand
[0:] MvxBind:Warning: 23.80 Failed to create target binding for binding for SignatureClickCommand
04-16 17:40:43.731 I/mono-stdout(27727): MvxBind:Warning: 23.80 Failed to create target binding for binding for SignatureClickCommand
Anyone have any ideas?
UPDATE
In typical fashion, left it for an hour and realised my mistake.
I was being lazy by typing:
var signatureButton = signatureCard.FindViewById<Button>(Resource.Id.btn_basecard_footer).Text = "Capture"
Which was confusing the binding. Switched to:
var signatureButton = signatureCard.FindViewById<Button>(Resource.Id.btn_basecard_footer);
signatureButton.Text = "Capture";
And it works perfectly
An updated example using TabView and ViewPager is available here: https://github.com/MvvmCross/MvvmCross-AndroidSupport/tree/master/Samples
It uses the latest stuff from the Android design libraries.

Resources