I'm having a problem compiling a cross platform MAUI library project implementing a partial class platform dependent. My project structure looks like this:
Project
Core
MyClass
Design
IMyInterface
Platform
Android
MyClass
Windows
MyClass
And my code looks like this:
Project\Design\IMyInterface.cs
namespace Core
{
puclic interface IMyInterface
{
string SomeString { get; set; }
event EventHandler<int> OnSomethingHappend;
int SomeMethod();
}
}
Project\Core\MyClass.cs
namespace Core
{
puclic partial class MyClass : IMyInterface
{
public event EventHandler<int> OnSomethingHappend;
}
}
Project\Platform\*\MyClass.cs
namespace Core
{
puclic partial class MyClass
{
string SomeString { get; set; }
int SomeMethod()
{
// Do some platform dependent stuff
}
}
}
As you can see I want my class to implement my interface, but have the relevant parts in the platform specific files in Platform\* . I made sure that they are placed in the same namespace. I also made sure to select a target platform for compilation.
At this point visual studio should build it using the partial class for the selected platform. However I get an error saying that MyClass doesn't implement my interface. If I copy the platform code into the Core folder there is no problem. I guess it's some kind of small setting that's missing here, but I can't find anything. For some reason it seems to ignore the platform folder when looking for the partial classes. All I can find is the general "partial class implementing interface" stuff. I didn't find something related to a Maui SingleProject.
Edit: As asked, here is a minimal github repo. On my pc it creates the error.
On the core partial, inform the compiler that the missing members will be provided by a partial elsewhere:
public partial class MyClass : IMyInterface
{
public event EventHandler<int> OnSomethingHappend;
public partial string SomeString { get; set; }
public partial int SomeMethod();
}
I have found the solution, and what causes the error is actually very simple.
On the side of your RUN button you can choose what framework you want to compile to. In a normal MAUI app, you would choose e.g. android or windows here to decide what platform you are working/debugging on.
As it turns out, this is not all you need to keep in mind when working with partial classes in your platform folders, there are two parts to take into account.
First part is intellisense. It does not show errors based on what platform you select using the RUN button drop-down menu. Below your open file tabs are some drop-down menus showing the structure of the file. you can use them to move to a specific element (property, method, etc) of a class/interface etc implemented in that file. The left one lets you select the target framework that intellisense will use for marking code errors (see image).
I don't remember seeing the left one before MAUI, it might have been added specifically for single project. If you open e.g. a standard net6 library it will hace nothing to chose as there are no other targets. But I can't really say because I never paid any attention to them before.
The second part is the actual compilation. The answer to that is rather simple as well. Visual Studio dowsn't build the platform you select using the RUN button drop-down menu for building, only for running. It will build all platforms it seems.
You need a partial class with a default implementation (e.g. throw new NotImplementedException(); for everything) for every platform.
My project was new, and I had just started on the windows part. I expected it to compile only that part because I chose windows as target platform. But it wants to compile for all platforms. So you have to either add that default until you get to that platform or remove it from the project target frameworks until then.
Related
I need to create code by the IIncrementalGenerator in at least two projects which are referring to the same library that references the SourceCodeGenerator project.
My solution, for further clarification:
MySolution
|->DesktopApp
| |->ref:Library
|
|->Library
| |->ref:SourceGenerator
|
|->WebApi
| |->ref:Library
|
|->SourceGenerator
In the library, I define Interfaces for all objects I use across my application, many properties I define in the interface are Ids which I mark by an attribute where I head the IType of the underlying object.
The attribute:
[System.AttributeUsage(System.AttributeTargets.Property)]
public class NavigationPropertyAttribute : System.Attribute
{
public System.Type NavigationPropertyType { get; }
public NavigationPropertyAttribute(System.Type type) => NavigationPropertyType = type;
}
This is how such an Interface looks like:
public interface IFoo
{
int Id { get; set; }
[NavigationProperty(typeof(IBar))]
int BarId { get; set; }
[NavigationProperty(typeof(IFoo))]
int ParentId { get; set; }
[NavigationProperty(typeof(IFoo))]
int ChildId { get; set; }
}
In both projects, one is a desktop application, the other is a Web API using EF Core, I have partial classes implementing these interfaces.
namespace IGTryout.Main;
public partial class Foo : IFoo
{
public int Id { get; set; }
public int BarId { get; set; }
public int ParentId { get; set; }
public int ChildId { get; set; }
}
what I need now, and where I'm struggling with, is using the IIncrementalGenerator to create a partial class with properties based on the Id, Name and the Type from the NavigationPropertyAttribute.
public partial class Foo
{
private Bar bar;
public Bar Bar => bar ??= GetValue<Bar>();
private Foo parent;
public Foo Parent => parent ??= GetValue<Foo>();
private Foo child;
public Foo Child => child ??= GetValue<Foo>();
}
(GetValue<T>() is an extension which gets the [CallerMemberName], resolves the matching Id via reflection and returns the object from cache by resolving it by the type and id)
In the Web API project, I'm also implementing the interfaces, yet, creating the NavigationProperties the common way
Foo { get; set; }
to fullfill EF Core's needs, also I'm creating the InversePropertyCollection in the related object for having the foreign keys set as needed by EF Core.
All of this is done, so I can use the interfaces as TransportObject with as little overhead as possible when sending them from the Web API to my desktop application and reverse.
Now to the problem I have:
to trigger all changes done to the interfaces, I reference my SourceCodeGenerator project from the library project, but by doing so, I can not find any opportunity to create the code inside the Web API assembly or the desktop app assembly.
I did solve this problem before by using the common SourceGenerator and referencing the SourceCodeGenerator project by both, the desktop app and the Web API, and accessing the interfaces inside my library project by calling the ReferencedAssemblySymbols of my compilations SourceModule and iterating over to the relevant project, since it is referenced by both, but this rather hacky solution is not possible, since would loose all the possibilities, which led me to switch to the IIncrementalGenerator in the first place.
Below is the answer to why this will not work with a Class Library project. however while tying up this answer I learned of the existence of Shared Projects which based on a cursory look at how they work, might enable the behavior of incremental generators on shared source code, see thoughts below.
The Problem
There are at 2 distinct reasons why what is asked in the question won't work with a Class Library project. One is to use source generator in a way they are not designed to work, and two, even if they worked as you wanted, the generated code would not behave as expected.
Source Generators hook to a compilation
By design, Source Generators hook to a compilation. The purpose of projects is to provide a distinct compilation unit. The use of solutions to group projects and order projects is a convivence, but does not cause the individual projects to merge into one compilation. Once a class library project is visible to the downstream projects, it is not longer a bunch of source code, it is just a dll.
Partial Classes in Different Projects
The example is making a partial class with the partials in three different projects, so even if you got the source generator to make the files in the correct project you would not end up with what you wanted, which is a WebApp version of Foo and and Desktop version of Foo. Instead you would end up with 3 versions of Foo the Library version with the Id Properties, the WebApp version with the auto properties for the navigations, and the Desktop version with the GetValue call. with both the desktop and webapp version missing the Id Properties. see this question/answer
Shared Projects
Can Shared Projects help here? Maybe. The intent of shared projects is to shared source code, not to be a compilation unit, so a change to the source should trigger the incremental generator in any project referencing that shared source, since that source is now part of that project's compilation.
You will want to be aware of the differences between a class library, and a shared project, and how that can impact your program, as now that code is being compiled multiple times in different contexts, so you can actually end up with completely different functionality from the same source. (i.e. features like global usings could cause namespace resolution to cause a Type to match by name to one in a completely different assembly, e.g. you have a property Document {get;set;} which in one project resolves to say AutoCAD.Document, but in another resolves to Microsoft.CodeAnalysis.Document.)
I want to add this class as setting's type:
using System.Collections.Generic;
using System.Configuration;
namespace MY_PROJECT.SUB_PROJECT
{
[SettingsSerializeAs(SettingsSerializeAs.Xml)]
public class Configs: List<ConfigData>
{
Configs(int capacity): base(capacity) { }
public string GroupName { get; set; }
}
}
So what I did:
Select Browse... in the type dropbox:
I cannot see the MY_PROJECT namespace anywhere:
So I typed the full type manually:
The result is an error:
Type 'MY_PROJECT.SUB_PROJECT.Configs' is not defined.
I also tried SUB_PROJECT.Configs and Configs alone. Nothing helped. Why does my class not show in the browser?
In order to pull something in as a reference you need to have it compiled as a dll file. In Visual Studio they refer to this as a "Library" which is really just a class without a main function. Other option is to just leave it in the same namespace and pull the class into whatever else your working on.
I just had this issue and it was due to an Inconsistent accessibility error. Make sure that any 'required' type/field is globally accessible (public?). For the OP's case, making the constructor public solves the issue:
[SettingsSerializeAs(SettingsSerializeAs.Xml)]
public class Configs: List<ConfigData>
{
public Configs(int capacity): base(capacity) { }
// ^^
public string GroupName { get; set; }
}
In my case this was the problem:
internal struct NativeType
{
//...
}
[SettingsSerializeAs(SettingsSerializeAs.Xml)]
public class NativeTypeWrapper
{
public NativeType type; // This will not work because NativeType
// is less accessible than NativeTypeWrapper...
}
I had this problem as well. I was doing exactly the same: creating a custom class to use in Application Settings. In my case, I followed the steps outlined in this very informative article:
http://www.blackwasp.co.uk/CustomAppSettings.aspx
I should note the article is written for C#, and I painstakingly converted it to VB until it worked. I had to solve the Type...is not defined error the hard way: relentlessly experimenting until I got it to work.
I will describe my first solution, one which was not mentioned in the article, probably because it's for C# instead of VB, and that is: put the custom class or classes each in their own .vb files. For instance: Employee.vb and Room.vb. This is the only way I could make it work perfectly with no errors. After doing this and rebuilding the solution, I was then able to add my custom class as an Application Setting, but of course only by manually typing the full name TestProject.Employee in the Select a Type dialog.
However, following the article I linked above, if I put all the class definitions in the Module1.vb file with Sub Main(), the Select a Type dialog cannot find them, and I receive the Type...is not defined error.
And the cause of this error seems to be shortcomings in the code & design of the Applications Settings system and Settings page of the Project Properties dialog. I say this because of the solution I found: I hacked my classes into the settings the hard way.
What I mean by that is I initially created the setting with the name DefaultEmployee and type of String. Then I used the Find In Files dialog to find all instances of DefaultEmployee and replaced the appropriate instances of String with TestProject.Employee.
The files I made replacements in are: App.config, Settings.Designer.vb, and Settings.settings.
And it worked..! Sort of. I should say the code ran fine and it did what was expected. But...the Application Settings dialog didn't like it. After I made the changes, there are various errors from the Project Properties/Settings system every time I opened it. But as I said, it still works.
Thus...my only conclusion is the coding of the Settings system is not designed to handle this situation, and if you wish to have the most reliable & error-free experience, it's best to put each of the custom classes in their own .vb class file.
On the other hand, if you wish to become very adventurous, you could create your own Applications Settings system, as the author of this article did. I have not read all of this yet, but scanning through it seems very interesting:
https://weblog.west-wind.com/posts/2012/dec/28/building-a-better-net-application-configuration-class-revisited
At first I have a Multi-platform Project where I created a Class which transfers Data and my problem is that as example if I click a Button a method in this class should be called but I cannot reach the method.
This is my project structure:
The red part is where the Data Handler is located
the green part from where I get the clicked event and call the method.
I'll hope someone can help me with this problem!
As Jason mentioned in comment, you can not reach code from platform specific just like that, because you are not referencing platform specific projects, and there is something called DependencyService (which Jason also mentioned) and that will help you to solve this "issue" that you have.
This is how you can use DependencyService, inside your shared code project, create one interface in my case that will be:
public interface IDataHandler
{
string GetSomeStringValue();
}
Go to your iOS or other platform specific project and create new class DataHandler.cs (which you already have). And it should implement this interface that we created. Something like this:
[assembly: Dependency(typeof(DataHandler))]
namespace provisioning.ios
{
public class DataHandler: IDataHandler
{
public DataHandler()
{
}
public string GetSomeStringValue()
{
return "Some string value or whatever";
}
}
}
After that when you want to reach this method you will use DepedencyService inside of your shared code project like this:
private void SomeMethod()
{
string fromSpecificProject = DependencyService.Get<IDataHandler>().GetSomeStringValue();
}
If you want or need you can use this to pass some values to platform specific project and to return the data like I did it this mini example.
Note that implementations must be provided for each platform project
in your solution. Platform projects without implementations will fail
at runtime!
Strongly recommend you to take a look at official docs here.
Also I made this mini blogpost about usage of Dependency Service in Xamarin.Forms apps you can find it here.
I have to be able to connect to two different versions of the an API (1.4 and 1.5), lets call it the Foo API. And my code that connects to the API and processes the results is substantially duplicated - the only difference is the data types returned from the two APIs. How can I refactor this to remove duplication?
In Foo14Connector.cs (my own class that calls the 1.4 API)
public class Foo14Connector
{
public void GetAllCustomers()
{
var _foo = new Foo14WebReference.FooService();
Foo14WebReference.customerEntity[] customers = _foo.getCustomerList;
foreach (Foo14WebReference.customerEntity customer in customers)
{
GetSingleCustomer(customer);
}
}
public void GetSingleCustomer(Foo14WebReference.customerEntity customer)
{
var id = customer.foo_id;
// etc
}
}
And in the almost exact duplicate class Foo15Connector.cs (my own class that calls the 1.5 API)
public class Foo15Connector
{
public void GetAllCustomers()
{
var _foo = new Foo15WebReference.FooService();
Foo15WebReference.customerEntity[] customers = _foo.getCustomerList;
foreach (Foo15WebReference.customerEntity customer in customers)
{
GetSingleCustomer(customer);
}
}
public void GetSingleCustomer(Foo15WebReference.customerEntity customer)
{
var id = customer.foo_id;
// etc
}
}
Note that I have to have two different connectors because one single method call (out of hundreds) on the API has a new parameter in 1.5.
Both classes Foo14WebReference.customerEntity and Foo15WebReference.customerEntity have identical properties.
If the connectors are in different projects, this is an easy situation to solve:
Add a new class file, call it ConnectorCommon and copy all of the common code, but with the namespaces removed. Make this class a partial class and rename the class (not the file) to something like Connector.
You will need to add a link to this to each project.
Next, remove all of the code from your current connector classes, rename the class (not necessarily the file) to the same as the partial class, and add a using statement that references the namespace.
This should get what you are looking for.
So, when you are done you will have:
File ConnectorCommon:
public partial class Connector
{
public void GetAllCustomers()
{
var _foo = new FooService();
customerEntity[] customers = _foo.getCustomerList;
foreach (customerEntity customer in customers)
{
GetSingleCustomer(customer);
}
}
public void GetSingleCustomer(customerEntity customer)
{
var id = customer.foo_id;
// etc
}
}
File Magento15Connector
using Foo15WebReference;
partial class Connector
{
}
File Magento14Connector
using Foo14WebReference;
partial class Connector
{
}
Update
This process can be a little confusing at first.
To clarify, you are sharing source code in a common file between two projects.
The actual classes are the specific classes with the namespaces in each project. You use the partial keyword to cause the common file to be combined with the actual project file (i.e. Magneto14) in each project to create the full class within that project at compile time.
The trickiest part is adding the common file to both projects.
To do this, select the Add Existing Item... menu in the second project, navigate to the common file and click the right-arrow next to the Add button.
From the dropdown menu, select Add as link. This will add a reference to the file to the second project. The source code will be included in both projects and any changes to the common file will be automatically available in both projects.
Update 2
I sometimes forget how easy VB makes tasks like this, since that is my ordinary programming environment.
In order to make this work in C#, there is one more trick that has to be employed: Conditional compilation symbols. It makes the start of the common code a little more verbose than I would like, but it still ensures that you can work with a single set of common code.
To employ this trick, add a conditional compilation symbol to each project (ensure that it is set for All Configurations). For example, in the Magento14 project, add Ver14 and in the Magento15 project add Ver15.
Then in the common file, replace the namespace with a structure similar to the following:
#if Ver14
using Magneto14;
namespace Magento14Project
#elif Ver15
using Magneto15;
namespace Magento15Project
#endif
This will ensure that the proper namespace and usings are included based on the project the common code is being compiled into.
Note that all common using statements should be retained in the common file (i.e., enough to get it to compile).
If the FooConnectors are not sealed and you are in control to create new instances, then you can derive your own connectors and implement interfaces at the same time. In c# you can implement members by simply inheriting them from a base class!
public IFooConnector {
void GetAllCustomers();
}
public MyFoo14Connector : Foo14Connector, IFooConnector
{
// No need to put any code in here!
}
and then
IFooConnector connector = new MyFoo14Connector();
connector.GetAllCustomers();
You should introduce an interface that is common to both of the implementations. If the projects are written in the same language and are in different projects, you can introduce a common project that both projects reference. You are then making a move towards having dependencies only on your interface which should allow you to swap in different implementations behind the scenes somewhere using inversion of control (google, dependency injection or service locator or factory pattern).
Difficulties for you could be:
1) Public static methods in the implementations are not able to be exposed staticly via an interface
2) Potentially have code in one implementation class ie Foo14Connector or Foo15Connector that doesnt make sense to put into a generic interface
I'm writing a simple plugin based program. I have an interface IPlugin which has some methods and functions, and a List<Plugin> in my main program. For the sake of simplicity, lets say its defined like this:
public interface IPlugin
{
public void OnKeyPressed(char key);
}
Everytime a key is pressed, I loop through the Plugin list, and call OnKeyPressed(c) on each of them.
I can create a class like so, and add it to the list...
public class PrintPlugin
{
public void OnKeyPressed(char key)
{
Console.WriteLine(c);
}
}
And then whenever you press a key, its printed out. But I want to be able to load plugins from DLL files. This link was helpful, but it doesn't explain how to have the classes in the DLL implement my IPlugin interface... How can I do that? I really don't want to have to copy the IPlugin.cs file every time I want to make a plugin...
If I am understanding you correctly...
Create 3 Projects:
Project 1: Your main program (the one with List in it)
Project 2: the project with your interface
public interface IPlugin
{
public void OnKeyPressed(char key);
}
Project 3: A sample Plugin
public class PrintPlugin : IPlugin
{
public void OnKeyPressed(char key)
{
Console.WriteLine(c);
}
}
Then Add project 2 as a reference to both project 1 and 3.
This way you share the interface with both your main project and any of your plugins.
I have used this on a couple of projects and it has served me well.
You may want to look into the Managed Extensibility Framework as well. It provide a complete API for writing plugin based programs and covers a lot of concerns such as security if you're ever going to plan to make the plugin API available to third parties.
If you need to load user defined plugins, you should search for new DLLs when the application starts (or any other action). This can be done by using:
1) AppDomain.CurrentDomain.GetAssemblies() method returns the list of loaded assemblies in the current AppDomain
2) Search all DLLs in a folder where plugins should be positioned and check if a certain assembly is in the list. If not, use the Assembly.Load method to load this assembly, find the IPlugin class in it and finally add it to the List object.