I have two applications and 1 class for database process.
First Application is a Windows forms application like
public class Form1 :System.Windows.Forms.Form
{
public Form1()
{
}
}
And my second application is a Windows control library application like
public class MyControl :System.Windows.Forms.UserControl
{
public MyControl()
{
//
//Some Code
//
}
}
and my class is static class like
public static class Deneme
{
public static void Connect()
{
//
//SomeCode
//
}
public static void CreateTable(string SqlCommandP)
{
//
//Some Code
//
}
}
I compile the control library application and get a .dll file. After that, I'm adding this file to Windows application project toolbox. I can use this control.
My problem is that:
I am using static class in a Windows application and control library application maybe I will make another control libary application.
How can I use this static class from one project it have to be one in a project?
If the static class Deneme is to be shared between the 2 applications, you should place that static object in it's own library which both the WinForm project and the control project will reference.
Reference one project to the other? It seems like you're forgetting the Project Reference somewhere. Being more specific with the question might be helpful, though.
Related
We are in the beginning stages of converting a c# Winforms App from .NET Framework to .NET 6. We can get the project to build and run in .NET 6, but when it comes to a dynamically loaded assembly, we are having issues. We can get the assembly to load but attempting to access the custom class within it returns a null. I recreated this scenario in two smaller projects as an example.
Solution 1/Project 1 - The code for the assembly to be loaded into the main application. This is a class library that creates the TestAssembly.dll
namespace Custom.TestAssembly
{
public class TestClass : CallingModule
{
public override object GetValue()
{
return "Hello World";
}
}
}
Solution 2/Project 1 - This is a project and class within the main application's solution. This is a class library that creates the Custom.TestAssembly.dll
namespace Custom.TestAssembly
{
public class CallingModule
{
public virtual object? GetValue()
{
return null;
}
}
}
Solution 2/Project 2 - A button has been placed on a form. When it is clicked, the assembly should be loaded, which it is. However, attempting to extract the class from the assembly always returns a NULL.
Form1.cs
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Loader;
namespace TestCallingApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Assembly dynamicAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(#"C:\LocationOf\TestAssembly.dll");
Module customizationModule = dynamicAssembly.GetModule("TestAssembly.dll");
Type customClientModule = customizationModule.GetType("Custom.TestAssembly.TestClass"); //THIS RETURNS A NULL??
}
}
}
Just trying to understand what I am missing. Any thoughts? Or a better way to load runtime assemblies and access classes within them in .NET 6?
Did you reference Solution 2/Project 1 ?
Since they have the same assembly name Custom.TestAssembly, the runtime will not load it again if already loaded in memory.
You can, however, load it under a different AssemblyLoadContext, there's an example on MSDN as well.
Also, you may want to take a look at DotNetCorePlugins, which takes care of assembly loading, reloading, isolation, shared type, and dependency resolving.
For an assignment i had different DataStructures (in C#) that I needed to implement. That part was easy. But I am also required to make a main menu driven programme for all those projects. So i searched a bit and found out a way. For example i had a project named linkedlist with namespace as Implementing_LinkedList and another project queue and namespace as Implementing_queue. To make a menu driven programme i just created another project named Assignment with namespace assignment. Mainconsole. Then i changed the namespace of linkedlist project to Assignment.Implementing_LinkedList and similarly with queue.Also made all the methods and classes public. Then i just called the main method of linkedlist inside main method of assignment as follows
Implementing_LinkedList.Program.Main();
Main method is inside a class named program in linked list project and it worked. Now i want to know how this worked because specifically .MainConsole part and if there is any other way to acheive this.
(Also i am pretty new to Stack overflow so pardon me for the extra long question but i didn't want to skip any details)
You don't have to rename namespaces or anything. Each program's Main() function is static and it can be called from any other function using a fully qualified name.
Program1.cs
namespace Project1
{
public static class Program1
{
public static Main(string[] argc)
{
// code here
}
}
}
Program2.cs
namespace Project2
{
public static class Program2
{
public static Main(string[] argc)
{
// code here
}
}
}
MenuProgram.cs
namespace MenuProject
{
public static class MenuProgram
{
public static Main(string[] argc)
{
// call all projects in sequence
Project1.Program1.Main();
Project2.Program2.Main();
}
}
}
This assumes the menu project has all the sources of the sub projects included. If they are separate project files, then you need to Add Reference... to those projects from the project file references.
I am a total beginner in C# programming language. I am trying to use Getter and Setter in order to set the string in ProjectA and the retrieve it in Project B.
Project B uses Windows Forms, and I wasnt to set the value of TextBox
with the retrieved string.
Project A is a Console Project and it just reads out some stuff from
file and stores it in string, which I want to retrieve.
However, this is my call in Project B:
string cardOwner = Transmit.Program.CardOwner;
Debug.WriteLine("Card owner = " + cardOwner);
tb_cardholder.Text = cardOwner;
And this is my Getter / Setter in Project A:
private static string _cardOwner;
public static string CardOwner
{
get
{
return _cardOwner;
}
set
{
_cardOwner = value;
}
}
_cardOwner = System.Text.Encoding.ASCII.GetString(bCardOwner);
But in Project B I get "" empty string.
I have included Project A in Project B (added Reference and wrote "using ProjectA").
Any ideas what's going wrong?
Thanks.
Just because you include a project and use its classes in your project B, it doesn't mean that you also use the instances of these classes.
Take the following class:
public class Test
{
public string Message { get; set; }
}
You can put this class into a DLL project (Tools) and reference it from other projects, like a WinForms project ProjectA and a console project ProjectB.
In both projects, you can write something like:
Test t = new Test() { Message = "Hello" };
That creates a new instance of the Test class, but the two running applications ProjectA and ProjectB do not exchange the data! They are completely separated.
The same is true for class properties.
You can't share information between two different applications so easily. Static properties only share data within the same Application Domain, that is in most simple constellations within the same Windows process.
If you want to transfer data between two different processes, you need to use an explicit mechanism for interprocess communication.
When is this line executed?
_cardOwner = System.Text.Encoding.ASCII.GetString(bCardOwner);
You'll need to put that in a method and call that method (and knowing when the call happens will help you understand why _cardOwner is not set:
public static void Init()
{
_cardOwner = System.Text.Encoding.ASCII.GetString(bCardOwner);
}
Then call this method somewhere that you know will be executed before you need _cardOwner:
Transmit.Program.Init();
string cardOwner = Transmit.Program.CardOwner;
tb_cardholder.Text = cardOwner;
I am rewriting the Betfair API to JSON from SOAP and I have started off the way I did it before as a console APP which is then called from a task scheduler or win service.
However now I have been asked to do various different jobs with the code and I don't want to write a console app for each job (different sites want prices, bets placed etc)
The new codebase is much larger than the old one and I would have been able to copy the 4 files from the old system into a DLL app and then create various console apps/services to implement the DLL - however because it's 40+ files I don't want a copy n paste job if possible.
Is there a way I can EASILY convert an existing console project into a class / DLL project with some tool or command in VS?
I want to be able to just then create simple apps that just go
BetfairBOT myBOT = new BetfairBOT()
myBOT.RunGetPrices();
or
BetfairBOT myBOT = new BetfairBOT()
myBOT.RunPlaceBets();
e.g 2/3 lines of code to implement my DLL that is registered to my app.
So without copy and paste can I do this.
I am using VS 2012, .NET 4.5 (or 4.0 if I need to depending on server), Windows 8.1
Any help would be much appreciated.
This answer is from here. while it used winforms instead of console application, I think you will be able to use it.
Steps for creating DLL
Step 1:- File->New->Project->Visual C# Projects->Class Library. Select your project name and appropriate directory click OK
After Clicking on button ‘OK’, solution explorer adds one C# class ‘Class1.cs’. In this class we can write our code.
When we double click on Class1.cs, we see a namespace CreatingDLL. We will be use this namespace in our project to access this class library.
Step 2:- Within Class1.cs we create a method named ‘sum’ that takes two integers value and return sum to witch method passed numbers.
using System;
namespace CreatingDLL
{
public class Class1
{
/// <summary>
/// sum is method that take two integer value and return that sum
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int sum(int x, int y)
{
return x + y;
}
}
}
Step 3:- Now build the Application and see bin\debug directory of our project. ‘CreatingDLL.dll’ is created.
Now we create another application and take this DLL (CreatingDLL.dll) reference for accessing DLL’s method.
Steps for accessing created DLL
Step 4:- File->New->Project->Visual C# Projects->Windows Form Application.
Step 5:- Designed windows form as bellow figure.
Step 6:- Add reference of DLL (CreatingDLL) which we created before few minutes.
After adding reference of DLL, following windows will appear.
Step 7:- Write code on button click of Windows Form Application. Before creating object and making method of Add DLL, add namespace CreatedDLL in project as bellow code.
using System;
using System.Windows.Forms;
using CreatingDLL;
namespace AccessingDLL
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
Class1 c1 = new Class1();
try
{
txtResult.Text = Convert.ToString(c1.sum(Convert.ToInt32(txtNumber1.Text), Convert.ToInt32(txtNumber2.Text)));
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Step 8:- Now build the application and execute project and see output.
Edit: To change an application into a library do these steps
First, double click on Properties inside Solution Explorer window.
Then, On the openned page, change the Output Type from Console Application to Class Library
When I'm developing a ConsoleApp there is no problem to use classes in my Main that I've created in separated files (Project Menu --> Add Class). But later, when I try to do it in WPF that class is not recognized. I have made sure that the namespace it's the same both in my "MainWindow.xaml.cs" and my Class Canal.cs. When I define that same class but inside MainWindow.xaml.cs everything works fine, but due to the extension of the code I prefer separate it.
MainWindow.xaml.cs:
//using
namespace Tcomp
{
public partial class MainWindow : Window
{
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{ //Stuff but I can't use class created outside of MainWindow.xaml.cs
}
}
}
Canal.cs
//using
namespace TComp
{
public class Canal
{ //some propreties here
}
}
Thanks.
Create the class inside a library project not on a console app. And on your WPF project, add a project reference to the library project you have created.
#mcxiand already answered your question. I would like to add another option: you can use a
public partial class MainWindow : Window
and add it to as many files as you want containing your code, thus there will be no need to create additional class library. The key word here is partial, which allows the code encapsulated in this class to spread over multiple files (.cs).
You must either instantiate the Canal class:
var myClass = new Canal();
and then you can use the properties from it. Make myClass a private member of your MainWindow.xaml.cs and you can access it anytime. Or the second way, make Canal class static and then you can access it from everywhere. Hope this helps.