The type or namespace platform does not exist in the name space MvvmCross.Forms - mvvm

I followed the TipCalc tutorial as recommended in the mvvmcross documentation
Here, The Core project and UI project works perfectly. But the android MainActivity has errors as it cannot find the namespace
MvvmCross.Forms.Platforms.Android.Core
MvvmCross.Forms.Platforms.Android.Views
Everything appears right but i am unable to figure out what i am doing wrong.
I have installed:
MvvmCross 6.1.2
MvvmCross.Forms 6.0.1.0
Xamarin.Forms 3.1.0.583944
I use TargetFrameWork 8.1 (Oreo)and .net Standard 2.0
I also confirmed in the MvvmCross GitHub repository that the namespace exists.
Here is a peek at
using Android.App;
using Android.Content.PM;
using Android.OS;
using TipCalc.Core;
using TipCalc.Forms.UI;
using MvvmCross.Forms.Platforms.Android.Core;
using MvvmCross.Forms.Platforms.Android.Views;
namespace TipCalc.Forms.Droid
{
[Activity(
Label = "TipCalc.Forms.Droid",
Icon = "#drawable/icon",
Theme = "#style/MyTheme",
MainLauncher = true,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation,
LaunchMode = LaunchMode.SingleTask)]
public class MainActivity : MvxFormsAppCompatActivity<MvxFormsAndroidSetup<App, FormsApp>, App, FormsApp>
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
}
}
}
Screenshot of the error

Your MvvmCross and MvvmCross.Forms packages are not in sync. They need to be the same version.
Easiest way is to go to the NuGet Package Manager for the solution in VS for Windows and consolidate the packages through the consolidate tab.
If you can't do that you can uninstall the packages, then re-install them.

Related

Blazor component - Failed to fetch dynamically imported module when packed in nuget

I created a blazor component that loads an isolated js interop file (target framework .Net 7)
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
var dotNetObjRef = DotNetObjectReference.Create(this);
_routeMapModule = await JsRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/MyComp/MyJs.js");
await _routeMapModule.InvokeVoidAsync("CompInit", _elRef, dotNetObjRef);
}
}
MyComp is the ProjectName so the path to get the file is "./_content/MyComp/MyJs.js".
As long as I use this component as a project reference (blazor server), everything works fine.
But as soon as I package this component in a Nuget (azure pipeline), and reference it in the project (instead of a project reference), I get "Failed to load resource: the server responded with a status of 404 () / Failed to fetch dynamically imported module when packed in nuget".
When I check the nuget in my local nuget storage (unziping it), I find the js file in the root but if I search it in the main app generated bin, it is not there.
Is there a specific parameter for the Nuget deployment ?
I tried to create the nuget directly from visual studio and/or to modify the generation parameters on Azure.
The final nuget contains the js resource file but it does not seem to be published in the main project (the one that references the nuget).
Also tried to move the file referenced in wwwroot but same problem.
What's weird is that everything works fine as long as I'm in "project reference" mode but the path "./_content/MyComp/MyJs.js" doesn't seem to follow when it's packaged in a nuget.
Any idea ?
Main Blazor App: https://jmpnet.visualstudio.com/JmpNetPublic/_git/MainBlazorApp
Blazor component App: https://jmpnet.visualstudio.com/JmpNetPublic/_git/MyComp
Nuget Feed for Blazor component App:
Name: JmpNetPublic
Source: https://jmpnet.pkgs.visualstudio.com/JmpNetPublic/_packaging/JmpNetPublic/nuget/v3/index.json
Update (29.12.2022):
I have no problem to load the module as long as I stay in project reference (with or without lazy loading).
The problem happens only when the component is packaged in Nuget.
When deploying the Nuget, the js file does not follow.
It seems to be mostly a Nuget packaging issue (via Azure) but I can't find the settings that force the deployment of the js file.
OK. The problem was with the Azure Pipeline configuration.
if I generate the nuget directly on my workstation and push it, everything works fine.
But as soon as I did the generation using an Azure pipeline, the js file was no longer deployed.
I was actually using YAML Nuget commands (targeting .net framework) with a .Net Core project.
Now that I use ".Net Core" YAML , everything works correctly.
Lazy load the module:
public partial class TestComp : ComponentBase, IAsyncDisposable
{
[Inject]
private IJSRuntime JsRuntime { get; set; }
private readonly Lazy<Task<IJSObjectReference>> moduleTask;
[Parameter]
public string? Message { get; set; }
public TestComp()
{
moduleTask = new(() => JsRuntime!.InvokeAsync<IJSObjectReference>(
identifier: "import",
args: "./_content/MyComp/MyScript.js")
.AsTask());
}
private async Task Click()
{
var module = await moduleTask.Value;
Message += "...click";
await module.InvokeAsync<string>("popup", Message);
}
public async ValueTask DisposeAsync()
{
if (moduleTask.IsValueCreated)
{
var module = await moduleTask.Value;
await module.DisposeAsync();
}
}
}
Note: I am assuming MyScript.js is in the wwwroot folder of the MyComp project which is the NuGet package.

using Unity.Plastic.Newtonsoft.Json not found in Rider

I'm trying to use:
using Unity.Plastic.Newtonsoft.Json
public static List<Level> GetLevels()
{
var asset = Resources.Load<TextAsset>("levels.json".Replace(".json", ""));
return JsonConvert.DeserializeObject<List<Level>>(asset.text);
}
and JsonConvert is in red.
and Plastic is showing in red. It says cannot resolve symbol Plastic.
Any ideas?
EDIT: I did install Newtonsoft.Json version 13 as assembly. No luck.
EDIT: using Newtonsoft.Json; also red.
Ok after some digging:
Apparently updated unity project which wiped out the dependency that was added via package manager > add package from git URL
Unity forgot a documented change for this. So, the answer:
Package Manager Window > Add Package from GIT URL > com.unity.nuget.newtonsoft-json
And instead of using using Unity.Plastic.Newtonsoft.Json
use using Newtonsoft.Json;
NOTE: On an older project where this was added manually, Newtonsoft Json wasn't showing up in the package manager > Packages: In Project until I went to the Cog Wheel > Checked Show Dependencies.

dagger android support to androidx.fragment

How to inject a fragment from the package androidx.fragment.app.Fragment ?
I'm using the dagger-android framework to inject my dependencies in my code.
As the documentation says I do this to inject my fragment
#Override
public void onAttach(Activity activity) {
AndroidInjection.inject(this);
super.onAttach(activity);
// ...
}
the problem is that AndroidSupportInjection class accept only fragments of the package android.support.v4.app.Fragment or if I use AndroidInjection class only accept fragments of the package android.app.Fragment and I want to use fragments of the androidx.fragment.app.Fragment package.
Also DaggerFrament extend from android.support.v4.app.Fragment and want to use a fragment from androidx
And If I try to implement HasSupportFragmentInjector also this interface use a fragment from android.support
add the below code to your gradle.properties
android.useAndroidX=true
android.enableJetifier=true
And if you are trying to inject into a Fragment you have to replace AndroidInjection.inject(this) with AndroidSupportInjection.inject(this)
I had the same problem in case of HasFragmentInjector. You need to use HasSupportFragmentInjector for fragment injection. This is because, HasFragmentInjector uses android.app.Fragment which is not effected by jetifier. You need to add android-dagger-support library, jetifier converts all the support packages to androidx in Studio 3.3 (if jetifier is enabled).
If jetifier does not change support packages to androidx packages. You can download jetifier tool from here and convert the android-dagger-support.aar file manually by using the following command.
./jetifier-standalone -i dagger-android-support-<version>.aar -o <output-name>
Then add the library to your project. This is the HasSupportFragment class after conversion
import androidx.fragment.app.Fragment;
import dagger.android.AndroidInjector;
public interface HasSupportFragmentInjector {
AndroidInjector<Fragment> supportFragmentInjector();
}
Somehow, jetifier tool was not converting libraries in AndroidStudio.
I had to do it manually.
I had a similar error and it was due to the Dagger version. On version 2.17 there is an strange issue, but if you roll back to version 2.16 it compiles perfectly (apart from the flags on gradle.properties that Paul posted).
From there using the tutorials you won't have trouble. Forgot to mention that on my project I had the non-androidX version of everything, then I ran the androidX migration that android studio offers, and after that I had to switch the Dagger version, but I suppose that if you do it from the start it's the same.
Hope this helps, if you switch and it doesn't work, post a little bit of your dagger implementation and plugins versions and I will try to help more!
Add the following to your gradle.properties file
android.useAndroidX = true
android.enableJetifier = true
Just for reference. i had the same problem. It was Jetifier issue. please upgrade your gradle build tools plugin to 3.3.0
classpath 'com.android.tools.build:gradle:3.3.0'
Sample code: https://github.com/jega-ms/android-dagger2-mvp-rx
This is what I did to work with androidx namespace for Dagger 2.21
Downloaded the jetifier tool from here: https://developer.android.com/studio/command-line/jetifier
Unzip into a folder and open a terminal pointing into the extracted bin folder
From Android Studio, open a class like DaggerFragment to check the path where the file is stored, for me (in MacOS) is something like this:
From terminal execute this command (replacing with the correct variables and path)
./jetifier-standalone -i /Users/{YOUR_USER}/.gradle/caches/{PATH_TO_DAGGER_ANDROID_SUPPORT_FOLDER}/dagger-android-support-2.21.aar -o dagger-android-support-2.21.aar
The converted dagger-android-support-2.21.aar will appear in your bin folder
Now open your app build.gradle file and change this line
implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
adding the , '*.aar' part in the include array
Move the generated dagger-android-support-2.21.aar from bin to libs folder inside your project.
Remove (or comment) this line from the dependencies
implementation "com.google.dagger:dagger-android-support:2.21
Now you can proceed invalidating the cache and rebuild the project and now DaggerFragment will point to your converted version which uses androidx.fragment.app.Fragment
NOTE: Obviously this is a temporary workaround and you should move to the official version as soon this is fixed in Dagger
The solution to my particular problem was to use android dagger classes as interfaces instead of extend of them:
class MyFragment() : HasSupportFragmentInjector {
#Inject
lateinit var childFragmentInjector: DispatchingAndroidInjector<Fragment>
override fun onAttach(context: Context?) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> {
return childFragmentInjector
}
........
}
To my Activities
class MyActivity : HasSupportFragmentInjector {
#Inject
internal lateinit var fragmentInjector: DispatchingAndroidInjector<Fragment>
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> = fragmentInjector
......
}
and also I have this in my gradle.properties file:
android.useAndroidX = true
android.enableJetifier = true

"Multiple assemblies with equivalent identity have been imported" in VS2015 with a Unity generated csproj

I've started a new .NET 4.6 project in Unity 2018.1, and when I try to build it in Visual Studio 2015, I get "CS1703: Multiple assemblies with equivalent identity have been imported" for loads and loads of .NET assemblies, all of which are part of the BCL. The only code in the project is an empty class. There are no errors in the Unity console.
Easy repro steps (see version info at the end):
Create a new Unity project
Set the scripting runtime level to .NET 4.x in the player settings
Add a new C# script
Open the project in VS
Try to build it
If this was a normal project I would just remove the duplicated references but this .csproj is continually regenerated by Unity.
Version information:
Unity: 2018.1.0f2
Visual Studio 2015: Update 3 (14.0.25431.01)
Visual Studio Tools for Unity: 3.7.0.1
This appears to be a known issue in Unity 2018 with how it generates the Visual Studio project files. I just observed the same problem with Unity 2018.1.2f1 and Visual Studio 2015 Update 3 (14.0.25431.01).
Someone posted what appears to be the same problem on the Unity forum here. Sebastien Lebreton of Microsoft responded with a workaround until Unity fixes the problem. Add the below script into a folder named "Editor" in your project.
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using UnityEditor;
#if ENABLE_VSTU
using SyntaxTree.VisualStudio.Unity.Bridge;
[InitializeOnLoad]
public class ProjectFileHook
{
// necessary for XLinq to save the xml project file in utf8
class Utf8StringWriter : StringWriter
{
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
static ProjectFileHook()
{
ProjectFilesGenerator.ProjectFileGeneration += (string name, string content) =>
{
// parse the document and make some changes
var document = XDocument.Parse(content);
var ns = document.Root.Name.Namespace;
document.Root
.Descendants()
.First(x => x.Name.LocalName == "PropertyGroup")
.Add(new XElement(ns + "ImplicitlyExpandNETStandardFacades", "false"),
new XElement(ns + "ImplicitlyExpandDesignTimeFacades", "false"));
// save the changes using the Utf8StringWriter
var str = new Utf8StringWriter();
document.Save(str);
return str.ToString();
};
}
}
#endif

Importing greenDAO from eclipse to Android studio 1.0 RC 2 [duplicate]

I'm looking for a clear step-by-step explanation on how to import GreenDao in Android Studio.
I've used it before in AS, but failed to get it to work again.
There are some tutorials out there, but they don't seem to apply to the latest version of AS.
When I clone from github, I get a example project stuff etc.
Is there a way to install GreenDaoGenerator without these extras?
Just looking for an up-to-date step-by-step explanation.
Update: I suggest using Realm.io now! Check it out! :-)
Any help would be appreciated!
Tested on Android Studio 2.0
With Android Studio 0.6.1+ (and possibly earlier) you can easily add non android project to your android project as a module.
Using below method you can have Java modules(greenDaoGenerator) and Android modules in the same project and also have the ability to compile and run Java modules as stand alone Java projects.
Open your Android project in Android Studio. If you do not have one,
create one.
Click File > New Module. Select Java Library and click Next.
Fill in the package name, etc and click Finish. You should now see a
Java module inside your Android project.
Open the build.gradle file of the java project and add the following dependency
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile('de.greenrobot:DaoGenerator:1.3.0')
}
Copy your DaoGenerator classes or create if you don't have one to your java module.For e.g. I have created ExampleDaoGenerator class in my java module.
public class ExampleDaoGenerator {
public static void main(String[] args) throws Exception {
Schema schema = new Schema(1000, "de.greenrobot.daoexample");
addNote(schema);
new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");
}
private static void addNote(Schema schema) {
Entity note = schema.addEntity("Note");
note.addIdProperty();
note.addStringProperty("text").notNull();
note.addStringProperty("comment");
note.addDateProperty("date");
}
}
Now, to generate the classes that you can use in android project follow below steps.
Click on the run menu in the top bar. Click Edit Configurations...
In the new window, click on the plus sign at the top left of the window and select Application
A new application configuration should appear, fill the following information.
Give it a name e.g. greenDao.
In main class click … button and select your generator class which have the main method.for e.g. in this case it is
com.greendao.generator.ExampleDaoGenerator
In working directory select path of your java project.
In use class of module select you java project.
click ok.
Again go to run menu and now you can see e.g. run greendao. click on it.It should compile successfully.
Its done !!! you can check your generated classes in the folder that you have specified.For e.g. in this case it is /DaoExample/src-gen
NOTE: You can run your android project again by clicking on run menu -> Edit Configuration . select your project and click ok.
Here's a step by step overview for Integrating GreenDao into your Android Project.
[ Reference How to use GeenDao with Android ? ]
[Project Link: GreenDao Example ]
PART1 : Setting Up GREENDAO
Create an android project.
Click File >New > New Module. Select Java Library and click Next.
Now we have to add the following Gradle Dependencies.
In build.gradle of Module:app, insert
compile 'de.greenrobot:greendao:2.1.0'
In the build.gradle of Module:greendao-generator, insert
compile 'de.greenrobot:greendao-generator:2.1.0'
Make sure, you sync your project.
Now in the MainGenerator.java,
we will define the database structure.
import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Schema;
public class MainGenerator {
public static void main(String[] args) throws Exception {
//place where db folder will be created inside the project folder
Schema schema = new Schema(1,"com.codekrypt.greendao.db");
//Entity i.e. Class to be stored in the database // ie table LOG
Entity word_entity= schema.addEntity("LOG");
word_entity.addIdProperty(); //It is the primary key for uniquely identifying a row
word_entity.addStringProperty("text").notNull(); //Not null is SQL constrain
// ./app/src/main/java/ ---- com/codekrypt/greendao/db is the full path
new DaoGenerator().generateAll(schema, "./app/src/main/java");
}
}
Run MainGenerator.java
After running this, you will observe a newly created folder i.e. db in the Main Project Folder.
PART2 : Integrating it with Android Project
Set the activity_main.xml layout.
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textData"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/textSave"
android:layout_below="#+id/textData"
android:layout_alignEnd="#+id/textData"
android:layout_marginTop="22dp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Top"
android:id="#+id/textTop"
android:layout_below="#+id/textSave"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
In MainActivity.java,
Add the following codes
package com.codekrypt.greendao;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.codekrypt.greendao.db.DaoMaster;
import com.codekrypt.greendao.db.DaoSession;
import com.codekrypt.greendao.db.LOG;
import com.codekrypt.greendao.db.LOGDao;
import java.util.List;
public class MainActivity extends AppCompatActivity {
//Dao --> Data Access Object
private LOGDao log_dao; // Sql access object
private LOG temp_log_object; // Used for creating a LOG Object
String log_text=""; //Entered text data is save in this variable
private final String DB_NAME ="logs-db" ; //Name of Db file in the Device
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialise DAO
log_dao=setupDb();
//Setting up form elements
Button textSave= (Button) findViewById(R.id.textSave);
Button textTop= (Button) findViewById(R.id.textTop);
final TextView textData=(TextView) findViewById(R.id.textData);
assert textSave != null;
textSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
log_text=textData.getText().toString();
temp_log_object=new LOG(null,log_text);// Class Object, Id is auto increment
SaveToSQL(temp_log_object);
}
});
assert textTop != null;
textTop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textData.setText( getFromSQL() );
}
});
}
//---------------------------------SQL QUERY Functions-----------------------------------------//
public String getFromSQL(){
List<LOG> log_list = log_dao.queryBuilder().orderDesc(LOGDao.Properties.Id).build().list();
//Get the list of all LOGS in Database in descending order
if(log_list.size()>0) { //if list is not null
return log_list.get(0).getText();
//get(0)--> 1st object
// getText() is the function in LOG class
}
return "";
}
public void SaveToSQL(LOG log_object) {
log_dao.insert(log_object);
}
//----------------------------***END SQL QUERY***---------------------------------------------//
//-------------------------------DB Setup Functions---------------------------------------------//
//Return the Configured LogDao Object
public LOGDao setupDb(){
DaoMaster.DevOpenHelper masterHelper = new DaoMaster.DevOpenHelper(this, DB_NAME, null); //create database db file if not exist
SQLiteDatabase db = masterHelper.getWritableDatabase(); //get the created database db file
DaoMaster master = new DaoMaster(db);//create masterDao
DaoSession masterSession=master.newSession(); //Creates Session session
return masterSession.getLOGDao();
}
//-------------------------***END DB setup Functions***---------------------------------------//
}
Before Running the App, Make sure you have changed your configuration.
Now Run it.
PART 3 – VIEW THE SQL DB
Open Command Prompt.
Enter the following commands.
Opening the db file in SQLite3
Using SQLite3
PART 4 – EXTRAS
Structure (Core Classes) of GREENDAO
I have used this tutorial for Android Studio 0.8.9 and everything works fine.
Works on Android 1.3 Preview
For the top answer ( Tested on Android Studio 1.0 ), you might need to include that source folder in your project. Go to app/build.gradle
add the following inside android block
sourceSets{
main{
java{
srcDir 'src-gen'
}
}
Solution: IO-Exception
Go to the build from your dao generator.
add: apply 'application'
add: mainClassName = "you.package.include.Main"
execute "run" in application task (gradle task)
I dont know why it doesnt work when you create manually a run configuration.
Basically, what you need is to add a Java library module (File > New > New module..) to your Android project (assuming you're using Android Studio), and insert the generation code inside public static void main(String[] args) {} in this module's .java class. Then Run it and the code will be generated in you main app's module.
See this blog post for a step by step tutorial with explanation.