how to use static object in another project using api function - c#

there are similar questions here but this one is specific. I have a solution and in it two projects. Main project and run time project, in order to use run time project i need to add reference to it in main project. In run time project i need to use static object from main project, in order to do that i need to add reference which i cant to because there would be circular dependence. I read that i could use API function how can I implement that?
Thanks.
namspace mainProject
{
public static MyClass Object;
}
public sealed class RuntimeComponentClass : IBackgroundTask
{
BackgroundTaskDeferral _deferral;
public void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
//here i need to access static object from main project
_deferral.Complete();
}
}

First thing is that you cannot declare a static object just inside the namespace. I am assuming you have a class declared inside the namespace and static object is a member of that class
if you have following
namspace mainProject
{
public class AStaticClass{
public static MyClass Object;
}
}
you can definitely access the public static member from other classes.
public sealed class RuntimeComponentClass : IBackgroundTask
{
BackgroundTaskDeferral _deferral;
public void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
AStaticClass.Object is accessible
//here i need to access static object from main project
_deferral.Complete();
}
}
However this is not a good idea to have static public member if you have any multi threading scenario.

This is in support of my comment on the original post.

I we solved the problem by moving all the classes in run time component project, in this way that one reference that exists is enough. Thanks everybody!

Related

Making a moddingAPI for my Unity game and call functions without direct references

I'm trying to make a moddingAPI for my Unity game, and I stumbled upon a question I can't really find an answer to. Let me explain:
I have a specific function in my Unity project, let's name it exampleFunction()
using moddingAPI;
public class exampleClass : MonoBehaviour
{
public static void exampleFunction()
{
//stuff
}
}
How can I call this function with my moddingAPI, if modders want to call it?
I know that the modder would have to write something like:
using moddingAPI;
public void callModdingAPI()
{
moddingAPI.moddingClass.callExampleFunction();
}
And the moddingAPI class library would include this:
using ???????;
public class moddingClass : MonoBehaviour
{
public static void callExampleFunction()
{
//how do I get the reference to "exampleClass"?
exampleClass.exampleFunction();
}
}
⬆ And this part is where my question is.
I'm currently creating the moddingAPI with a brand new class library with nothing imported (.NET Framework if it is important).
I don't have a direct reference to the exampleClass that is in my Unity game, so this code wouldn't work, and I don't know how to get this reference. Do I have to import something? Do I have to build something? What do I have to do? Thanks in advance.
What you'd need to do is build-release this library as a .DLL file.
Let's assume you released this as 'ModdingApiLib.dll'.
In your unity code, you will have to import this .DLL, and then reference it in your code as:
public static void main()
{
new ModdingApiLib.ExampleFunction();
}

System.InvalidCastException when calling a class which extends application

I am working on an Android c# app where I have an class extends from Application called MyApplication. Inside MyApplication file, I have this method called getDataFromDB(). I am trying to call this method from my Activity but I am getting this exception during runtime:
System.InvalidCastException:
MyApplication.cs
public class MyApplication : Application
{
public MyApplication(IntPtr handle, JniHandleOwnership ownerShip) : base(handle, ownerShip)
{
}
public override void OnCreate()
{
base.OnCreate();
getDataFromDB();
}
public void getDataFromDB()
{ // code
}
}
Activity.cs
MyApplication application = ((MyApplication)this.ApplicationContext); //here's the location of the exception
application.getDataFromDB();
I don't have a clue why this exception is thrown. It doesn't seems to me that my casting is wrong. Would you please help me ?
The ApplicationContext is not necessarily the same object as the Application instance. I've seen this most often in emulators, but it can also be device specific.
In a Java app, you could cast the object returned by Activity#getApplication(). But according to a post on the Xamarin forum, an equivalent method does not exist in Xamarin. Instead, you can cast the Application property:
MyApplication app = (MyApplication) Application;
I'm not sure when the property is set, so this may not work in a field initializer.
Another option is to have MyApplication save a static reference to itself in OnCreate(), and provide a static getter. Although static fields are usually evil, this works because the Application instance is effectively a singleton, and its OnCreate will be called before any other component is created. The static reference can't leak the application because the application already has the same lifetime as the process.
Well, I solved it out by removing the Arguments of the contructor of MyApplication like that:
public class MyApplication : Application
{
public MyApplication() : base(handle, ownerShip) //here's the editing location
{
}
public override void OnCreate()
{
base.OnCreate();
getDataFromDB();
}
public void getDataFromDB()
{ // code
}
}
Then I called the Application:
MyApplication application = new MyApplication();

How can I access to an internal static class from another assembly?

I've the following situation:
1) I have an internal static class where my software initialize a form
2) I would like to get the instance of this form to use for other reasons.
Example of code:
Class1:
namespace x {
internal static class Program {
private static Form mainx;
private static void Main() {
.....
.....
mainx=new Form(.....);
Application.run(mainx);
}
}
}
Class2:
I want to use one thing like this:
Form1 try=Program.mainx;
How can i do it?
If both assemblies are signed, you can use the InternalsVisibleToAttribute to expose internal members of an assembly to another.
I often use this to enable unit testing of internal classes without having to expose them as public.
You could mark the assembly with the internal class as a friend assembly on the other assembly, with the attribute InternalsVisibleTo. You will find more informations about this on the MSDN.
You need to add this line to your AssemblyInfo class (in the Properties folder), i.e. on the last line. This must be added in the project where you have declared the internal class.
[assembly:InternalsVisibleTo("NameOfOtherAssembly")]
If you with to retrieve the mainx property of your Program class, you need to make a visible (public or internal) getter on your class:
internal static class Program
{
private static Form mainx;
...
public static Form GetForm()
{
return mainx;
}
}
In your second class, you should then be able to get the form by calling GetForm():
Form1 try=Program.GetForm();

WiX Votive Managed Custom Action cannot be referenced by other managed code in the same solution?

Question:
Is it possible to reference public static methods held within the CustomAction class, Votive generates for creating C# managed Custom Actions, from other libraries within the same solution?
I'm having trouble getting a reference to the class and method inside my C# library for the C# Custom Action when trying to create a test bed for the CA.
namespace TestInstaller.InstallCA
{
public class CustomActions
{
[CustomAction]
public static ActionResult InstallUIStart(Session session)
{
//Stuff
return Begin(<Constructed DataClass>);
}
public static ActionResult Begin(DataClass dc)
{
//Stuff I want to test
}
}
}
...
namespace TestInstaller.InstallerTest
{
static class Program
{
Static void Main()
{
//Stuff
//This line is not valid.
TestInstaller.InstallCA.CustomActions.Begin(<Constructed DataClass>);
}
}
}
Despite me adding a reference to InstallCA I cannot add a using statement for TestInstaller.InstallCA or InstallCA, and the compile time error only suggests adding a reference, which I have done.
Is this anything to do with Votive protecting its DLLs somehow?

Can there be stand alone functions in C# without a Class?

In C/C++, I have a bunch of functions that I call from main(), and I want to rewrite this in C#. Can I have stand alone functions(methods) or do I have to put them in another class? I know I can have methods within the same class, but I want to have a file for each function/method.
Like this works:
using System.IO;
using System;
class Program
{
static void Main()
{
House balls = new House();
balls.said();
}
}
public class House
{
public void said()
{
Console.Write("fatty");
Console.ReadLine();
}
}
But then I have to create an instance of House and call said(), when in C I can just call said().
For reference, I want to add the using static addition of C# 6 here.
You can now use methods of a static class without having to type the name of that class over-and-over again. An example matching the question would be:
House.cs
public static class House
{
public static void Said()
{
Console.Write("fatty");
Console.ReadLine();
}
}
Program.cs
using static House;
class Program
{
static void Main()
{
Said();
}
}
No. Make them static and put them in a static utility class if they indeed don't fit within any of your existing classes.
If using C# 9 it is now kinda possible, thanks to the top-level statements feature.
In your executable project, the following syntax is now allowed:
using SomeNamespace;
// The following statements are seemingly defined without even a method,
// but will be placed inside a "Main" static method in a "$Program" static class
SayHello();
var classFromSomeNamespace = new SomeClass(); // from SomeNamespace
classFromSomeNamespace.SomeMethod();
// This function is seemingly defined without a class,
// but on compile time it will end up inside a "$Program" static class
void SayHello()
{
Console.WriteLine("Hello!");
}
// Here the "traditional" syntax may start
namespace SomeNamespace
{
public class SomeClass
{
public void SomeMethod()
{
Console.WriteLine("SomeMethod called");
}
}
}
It should be noted, that the above syntax is valid only for a single file in a project, and the compiler actually still wraps this all inside a $Program static class with static methods. This feature was introduced specifically to avoid boilerplate code for the program entry point, and make it possible to easily write "scripts" in C#, while retaining the full .NET capabilities.
There is no concept of standalone functions in C#. Everything is an object.
You can create static methods on some utility class, and call those without creating an instance of a class eg
class Program
{
static void Main()
{
House.said();
}
}
public class House
{
public static void said()
{
Console.Write("fatty");
Console.ReadLine();
}
}
You have to put them in a class, but the class can be static as others mentioned. If you REALLY want to have a separate file for each method, you can mark the class as partial to get the following:
Program.cs
----------
class Program
{
static void Main()
{
House.said();
House.saidAgain();
}
}
House-said.cs
-------------
public static partial class House
{
public static void said()
{
Console.Write("fatty");
Console.ReadLine();
}
}
House-saidAgain.cs
------------------
public static partial class House
{
public static void saidAgain()
{
Console.Write("fattyAgain");
Console.ReadLine();
}
}
I wouldn't recommend separating each one out, however. Partial classes are mostly used so that designer-generated code won't overwrite any custom code in the same class. Otherwise you can easily end up with hundreds of files and no easy way to move from one method to another. If you think you need a partial class because the number of methods is getting unmaintainable, then you probably need to separate the logic into another class instead.
Although the concept of stand-alone functions exists in .NET, C# doesn't allow you to specify such functions. You need to stick them inside a static Utils class or similar.
If you declare your method as static (that is: public static void said()) then you can just call it with House.said(), which is as close as you'll get in C#.
You could add all your methods to the Program class, but this would quickly become an unmaintainable mess, commonly referred to as the God Class or Ball of Mud anti-pattern.
Maintaining a single file for each function would similarly become a huge mess. The questions "Where do I put my methods" and "What classes should I create" are answered by Design Patterns. Classes aggregate behavior (functions) and should do one thing (Single Reponsibility.)

Categories

Resources