MvvmCross + Xamarin.Forms "There is no implicit reference conversion..." - c#

I am following the official MvvmCross Xamarin.Forms tutorial (link), and have the following error in Visual Studio:
The type 'PriceWatch.Forms.UWP.App' cannot be used as type parameter
'TApplication' in the generic type or method
'MvxWindowsApplication'. There is no implicit reference conversion from
'PriceWatch.Forms.UWP.App' to 'MvvmCross.ViewModels.IMvxApplication'.
The line of code that is highlighted is the following:
public abstract class PriceWatchApp : MvxWindowsApplication<MvxFormsWindowsSetup<App, FormsApp>, App, FormsApp>
{
}
I've double checked my code and the code from their official tutorial, and I can't spot any inconsistencies besides using "PriceWatch" namespace instead of "TipCalc"
Here is a screenshot of my Core, UI, and Xamarin.Forms UWP projects.
And here are some of the relevant code, if any of the other files in the solution need to be seen, just ask.
PriceWatch.Core.App.cs
namespace PriceWatch.Core
{
public class App : MvxApplication
{
public override void Initialize()
{
Mvx.IoCProvider.RegisterType<IDatabaseService, DatabaseService>();
RegisterAppStart<ProductsViewModel>();
}
}
}
PriceWatch.Forms.UI.FormsApp.xaml.cs
using Xamarin.Forms;
namespace PriceWatch.Forms.UI
{
public partial class FormsApp : Application
{
public FormsApp()
{
InitializeComponent();
}
}
}
PriceWatch.Forms.UWP.App.xaml.cs
using MvvmCross.Forms.Platforms.Uap.Core;
using MvvmCross.Forms.Platforms.Uap.Views;
using PriceWatch.Forms.UI;
using Xamarin.Forms;
namespace PriceWatch.Forms.UWP
{
public sealed partial class App
{
public App()
{
InitializeComponent();
}
}
public abstract class PriceWatchApp : MvxWindowsApplication<MvxFormsWindowsSetup<App, FormsApp>, App, FormsApp>
{
}
}

Related

IPayIssueService' does not contain a definition for 'IssueVoucher'

In the project I'm working on it, there is structure between Interface and Class as bellow:
Business.Treasury's ClassLibrary contains:
// namespace Business.Treasury.FiscalTransaction.Services
internal class PayIssueService
: FiscalTransactionIssueService<PayModel, PY_Pay_c, v_PY_Pay_c,
PaySubModel, TransactionDistributionModel>
, IPayIssueService
{
}
// namespace Business.Treasury.FiscalTransaction.Services
internal class FiscalTransactionIssueService<TMasterModel,
TMasterEntity, TMasterVwEntity, TMajorDetailModel,
TMinorDetailModel>
: IssueVoucherService, IFiscalTransactionIssueService<TMasterModel>
{
}
Business.Treasury.Public's ClassLibrary contains:
// ns: Business.Treasury.Public.FiscalTransaction.Interfaces.Services
public interface IFiscalTransactionIssueService<TMasterModel>
: IIssueVoucherService
{
}
// ns: Business.Treasury.Public.FiscalTransaction.Interfaces.Services
public interface IPayIssueService
: IFiscalTransactionIssueService<PayModel>
{
}
Business.Accounting.Public's ClassLibrary contains:
// namespace Business.Accounting.Public.IssueVouchers.Services
public abstract class IssueVoucherService : IIssueVoucherService
{
public IssueVoucherModel IssueVoucher(
PrimaryFiltersModel filtersModel,
IssueVoucherModel issuevoucher,
List<IssueVoucherSubModel> details)
{
//implementation
}
}
// namespace Business.Accounting.Public.IssueVouchers.Interfaces
public interface IIssueVoucherService
{
IssueVoucherModel IssueVoucher(
PrimaryFiltersModel filtersModel,
IssueVoucherModel issuevoucher,
List<IssueVoucherSubModel> details);
}
In addition Business.Treasury has reference from both Business.Accounting.Public and Business.Treasury.Public. Also Business.Treasury.Public has reference from Business.Accounting.Public. As it clear because of inheritance, PayIssueService inherits IssueVoucher method. And the whole project use IOCContainer for DependencyInjection Finally, in another ClassLibrary I'm implementing API and using IPayIssueService:
// namespace WebApi.Treasury.Controllers.V01.Voucher
public class PayIssueVoucherController : ApiControllerBase
{
IPayIssueService _payIssueService;
PayIssueVoucherController()
{
_payIssueService = MyResolver.Container
.Resolve<IPayIssueService>(mvcValidationDictionary);
}
public async Task<IHttpActionResult> InsertAsync(
[FromBody] InsertPayIssueVoucherDto insertPayIssueVoucherDto)
{
//...
var res = _payIssueService.IssueVoucher(
new PrimaryFilterModel(),
issueVoucherModel,
lstIssueVoucherSubModel);
//...
}
}
When I want to call IssueVoucher it throws an exception: IPayIssueService does not contain a definition for IssueVoucher. Why code throws this exception when my Class inherits IssueVoucher method?
When I see Stack Trace of the exception it had this message: Anonymously Hosted DynamicMethods Assembly. In one part of my code, In PayIssueVoucherController I have used method which returns dynamic value:
private dynamic OtherParam()
{
return new AccountingVoucherIssuanceModel
{
CompanyID = Common.Security.Authorization.Authorization.CurrentCompanyId,
FiscalYearID = Common.Security.Authorization.Authorization.CurrentYearId,
AccVchIssMergeDebitArticles = false,
AccVchIssMergeCreditArticles = false,
};
}
And I used it in InsertAsync:
///...
var otherParam = OtherParam();
var lstIssueVoucherSubModel = GetIssueSubListModel(insertPayIssueVoucherDto, otherParam);
///...
I don't know why it's related to another method in PayIssueVoucherController, But change the OtherParam's output type to Class solved my problem! If anyone know the reason, It will help me to understand why it caused error!

Referencing of classes and namespaces Visual Studio 2017

I noticed for my little project that when importing classes some use full folder reference while otheres don't.
Here is code from project Mini that i am working on.
Models folder
Contains two entities, Auto and Airplane
namespace Mini.Models {
public class Auto {
// code and stuff
}
}
namespace Mini.Models {
public class Airplane {
// code and stuff
}
}
Services folder Contains single service class
namespace Mini.Services
{
public class AutoService : IAutoService {
public bool Get() {
var autoObject = new Models.Auto(); // notice how it references Models folder
var planeObject = new Airplane(); // Same folder but not referencing Models in front of it
// other code
}
}
public interface IAutoService {
bool Get();
// others
}
}
While not a major bugbear, it is still annoying that two classes in same folder get referenced differently, and i cannot figure out why.
Any advice would be appreciated.
Error Message when removing Models folder
Error CS0118: 'Auto' is a namespace but is used like a type (34, 27)
Based on the error message you have provided:
Error CS0118: 'Auto' is a namespace but is used like a type (34, 27)
It would appear that you have a namespace called Auto. Imagine the following example:
namespace MyApp.Auto
{
class Test
{
}
}
namespace MyApp
{
class Auto
{
}
class MyTest
{
private Auto test;
}
}
Because you can see, from the MyApp namespace, both a class called Auto and a namespace called Auto (either namespace MyApp.Auto or simply namespace Auto), C# isn't sure which one you want. As such, it's forcing you to be specific in choosing one or the other.
The easiest solution is to change the MyApp.Auto namespace to something else.
This is not fix but explaining with proper code sample (and why ).
namespace Mini.Models
{
public class Auto
{
// code and stuff
}
}
namespace Mini.Models
{
public class Airplane
{
// code and stuff
}
}
namespace Mini.Auto
{
public class OtherAirplane
{
// code and stuff
}
}
namespace Mini
{
using Mini.Models;
using namespaceAuto = Auto ; /// this also not fix the issue.
class NamespaceIssue
{
void execute()
{
var autoObject = new Auto(); // Error
var planeObject = new Airplane(); // Same folder but not referencing Models in front of it
// other code
}
}
}
now you can see some were in code you have "Mini.Auto" namespace , and it is couching issue.
i tested for VS 2015 have same issue. maybe we have to report to VS team or it is by design .
The issue seemed to be with VS2017 or the way it created the project first time around.
Upon starting brand new project (ASP Core 2.2, Web API, with https enabled and docker disabled), and using same classes the issue was non-existant.

Controller Service Dependency Injection Issue - Asp.net Framwork

Hello I'm trying to instantiate a class on application startup and then share that instance through dependency injection to a controller. For some reason it won't let me use a Controller Constructor with parameters. It gives the errors:
[MissingMethodException: No parameterless constructor defined for this
object.]
and
[InvalidOperationException: An error occurred when trying to create a
controller of type 'Project1.Controllers.HomeController'. Make
sure that the controller has a parameterless public constructor.]
I've found a couple of people who have had similar issues but I haven't been able to figure out what the exact problem is.
I also left out some of the extraneous code (why it doesn't look like the code actually does anything useful).
Startup.cs
using Project1.Services;
[assembly: OwinStartup(typeof(Project1.Startup))]
namespace Project1
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IPackageScraperService>(new PackageScraperService());
}
public void Configuration(IAppBuilder app)
{
}
}
}
IPackageScraperService.cs
using Project1.Services;
namespace Project1.Services
{
public interface IPackageScraperService
{
List<PackageScraperService.Script> GetLoadedScripts();
}
}
PackageScraperService.cs
namespace Project1.Services
{
public class PackageScraperService : Services.IPackageScraperService
{
public class Script
{
public FileAttributes Attibutes { get; set; }
public string Text { get; set; }
}
public List<Script> Scripts;
public List<Script> GetLoadedScripts()
{
return Scripts;
}
}
HomeController.cs
using Project1.Services;
namespace Project1.Controllers
{
public class HomeController : Controller
{
private IPackageScraperService _packageScraperService;
public HomeController(IPackageScraperService packageScraperService)
{
_packageScraperService = packageScraperService;
}
public ActionResult Index()
{
return View();
}
}
}
For anyone else looking for documentation, this tutorial worked for me.
http://scottdorman.github.io/2016/03/17/integrating-asp.net-core-dependency-injection-in-mvc-4/

Changing Entity Framework connection on the fly

At the minute I am creating my entities using unit of work principle that their is only one context per request.
But I now have a request that I must be able to change the database on the fly at runtime this would be done on the loading of application and they have allowed us to reload the application.
public void AddToAppointment(Appointment newAppointment)
{
using (var myContext = new SMBASchedulerEntities())
{
myContext.Appointments.Add(newAppointment);
myContext.SaveChanges();
}
}
The above code is in my SourceContext class and looking for some guidance on this.
My main question is thus can I change the SMBASchedulerEntities to get its connection information from a class if so what would this class look like and function as. The databases will all have the same schema.
What is the best practise for this method?
Edit 2
Sorry I should have stated my context class is like this
public class SourceContext : ContextBase
{
// public SMBASchedulerEntities _sourceEntities = new SMBASchedulerEntities();
// private SystemDa _systemDB = new SystemDa();
then my other methods
}
Which context class should I pass the connection to and how would I build that?
Edit 3
This is showing my main entity class which is autogenerated.
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Linq;
public partial class SMBASchedulerEntities : DbContext
{
public SMBASchedulerEntities()
: base("name=SMBASchedulerEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
Use DbContext overload for constructor. It can take connection string to your database.
public void AddToAppointment(Appointment newAppointment, string connectionString)
{
using (var myContext = new SMBASchedulerEntities(connectionString))
{
myContext.Appointments.Add(newAppointment);
myContext.SaveChanges();
}
}
Edit
If you look closely, your db-first generated class conviniently marked as partial, so you free to add new file called "MyPartialContext.cs" which will contain this:
public partial class SMBASchedulerEntities
{
public SMBASchedulerEntities(string connectionString) : base(connectionString) {}
}

Implement Prism in existing Xamarin.Forms Shared Application

I would like to know of there is a valid way to implement Prism in a existing Xamarin.Forms Shared project. I'm sure others would also like to know if they can profit from what Prism has to offer without having to convert their existing project to a PCL project. All existing examples I've found show a PCL project(probably for a good reason).
To try implementing Prism in my project I installed the Prims.Unity.Forms nuget to each platform project.
I tried to inherit from PrismApplication:
public partial class App : PrismApplication
{ }
But, this does not work. The app class does not allow me to inherit from a different base class.
Adding the following lines to my android project did not help:
protected override void OnCreate(Bundle bundle)
{
LoadApplication(new App(new AndroidInitializer()));
}
public class AndroidInitializer : IPlatformInitializer
{
public void RegisterTypes(IUnityContainer container)
{ }
}
Perhaps I am missing something or trying something that structurally is not possible.
Yes, it's completely possible.
First, ensure nuget packages are installed.
For example, for Prism and Unity you need:
<package id="Prism.Core" version="6.3.0" ... />
<package id="Prism.Forms" version="6.3.0" .../>
<package id="Prism.Unity.Forms" version="6.3.0" ... />
<package id="Unity" version="4.0.1" ... />
Add missing folders(just for order)
And move your existing page to the Views folder, but remember to
adjust the namespaces or your binding just won't work.
Change application base type
Remember to change application base type in code and XAML.
using Prism.Unity;
using Xamarin.Forms;
namespace XamPrismShared
{
public partial class App : PrismApplication
{
public App (IPlatformInitializer platformInitializer):base(platformInitializer)
{
}
}
}
Set the first page and its ViewModel
Implement OnInitialized and RegisterTypes. Remember that you need to register each type you want to use with Prism as a page.
using Prism.Unity;
using Xamarin.Forms;
namespace XamPrismShared
{
public partial class App : PrismApplication
{
public App (IPlatformInitializer platformInitializer):base(platformInitializer)
{
}
protected override void OnInitialized()
{
InitializeComponent();
NavigationService.NavigateAsync("MainPage");
}
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<NavigationPage>();
Container.RegisterTypeForNavigation<MainPage>();
}
}
}
If you have existing pages
Add ViewModelLocator.AutowireViewModel="True"to your existent views in order to allow Prism to automatically bind with their respective ViewModel.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
prism:ViewModelLocator.AutowireViewModel="True" x:Class="x:Class="XamPrismShared.Views.MainPage"" Title="MainPage">
<Label Text="{Binding Title}"
VerticalOptions="Center"
HorizontalOptions="Center" />
</ContentPage>
Add the missing ViewModel
using Prism.Mvvm;
namespace XamPrismShared.ViewModels
{
public class MainPageViewModel : BindableBase
{
public MainPageViewModel()
{
Title = "Hi from Prism.";
}
public string Title { get; set; }
}
}
Add Platform initializers in each platform project
Add the missing platform initializers and fix Xamarin.Forms load.
For Android,
using Android.App;
using Android.Content.PM;
using Android.OS;
using Microsoft.Practices.Unity;
using Prism.Unity;
namespace XamPrismShared.Droid
{
[Activity (Label = "XamPrismShared", Icon = "#drawable/icon", Theme="#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate (Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
LoadApplication (new XamPrismShared.App(new AndroidPlatformInitializer()));
}
}
public class AndroidPlatformInitializer : IPlatformInitializer
{
public void RegisterTypes(IUnityContainer container)
{
}
}
}
For iOS,
using Foundation;
using Microsoft.Practices.Unity;
using Prism.Unity;
using UIKit;
namespace XamPrismShared.iOS
{
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init ();
LoadApplication (new XamPrismShared.App(new iOSPlatformInitializer()));
return base.FinishedLaunching (app, options);
}
}
public class iOSPlatformInitializer : IPlatformInitializer
{
public void RegisterTypes(IUnityContainer container)
{
}
}
}
And voilĂ 
If you have any question or want to check, you can review the code in Github https://github.com/jesulink2514/Xamarin-Prism-shared-project

Categories

Resources