9

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.

leppie
  • 115,091
  • 17
  • 196
  • 297
MonkeyMagix
  • 677
  • 2
  • 10
  • 30
  • Select the project in solution explorer... right click and select properties... select the application tab.... what is listed in the Output type drop down list? is it even enabled? – Paul Zahra Jul 19 '14 at 11:04
  • Hi, Yes Console Application is listed. Also Windows Application and Class Library. If I just changed it to Class Library would that do the job. Then I would just need to remove the Program class with main(string[] args) etc and it would be a DLL when compiled as an EXE? – MonkeyMagix Jul 19 '14 at 11:47
  • Not sure what VS2012 will do... take a back up and give it a whirl... afaik it only changes the output type definition (stored in .csproj XML file as GUID) and some template basics... as a class library it should compile to a dll.. not an exe eh? – Paul Zahra Jul 19 '14 at 12:23
  • LOL yeah sorry. Just used to windows apps and console apps. If that doesn't work is the only way to create a new project and then copy class after class by hand or is there a way to automate it? Tools etc – MonkeyMagix Jul 19 '14 at 12:31
  • 1
    I think you can just change the output type, but even if you can't, if your console app was written with internal business classes you can just drag/drop the files in solution explorer and fix the namespaces. – Michael Edenfield Jul 19 '14 at 14:15
  • You can reference EXE from other projects just like as DLL. Anyway you want not EXE but DLL? – Ripple Jul 19 '14 at 14:58
  • Neither the CLR nor the C# compiler actually care about your original project being a console mode app. Or its filename extension. You can simply add a reference to the EXE in another project. You may have to declare some classes *public*. – Hans Passant Jul 19 '14 at 16:56
  • Does this answer your question? [C# console application to dll file](https://stackoverflow.com/questions/28937425/c-sharp-console-application-to-dll-file) – Jim G. Jul 28 '21 at 13:50

1 Answers1

12

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

Creating C# Class Library (DLL) Using Visual Studio .NET

After Clicking on button ‘OK’, solution explorer adds one C# class ‘Class1.cs’. In this class we can write our code.

Creating C# Class Library (DLL) Using Visual Studio .NET

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.

Creating C# Class Library (DLL) Using Visual Studio .NET

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.

Creating C# Class Library (DLL) Using Visual Studio .NET

Step 6:- Add reference of DLL (CreatingDLL) which we created before few minutes.

Creating C# Class Library (DLL) Using Visual Studio .NET

Creating C# Class Library (DLL) Using Visual Studio .NET

After adding reference of DLL, following windows will appear.

Creating C# Class Library (DLL) Using Visual Studio .NET

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.

Creating C# Class Library (DLL) Using Visual Studio .NET

Edit: To change an application into a library do these steps

First, double click on Properties inside Solution Explorer window.

Double Click

Then, On the openned page, change the Output Type from Console Application to Class Library

Change output type

Matin Lotfaliee
  • 1,745
  • 2
  • 21
  • 43
  • Hi Scott, I will try this out tomorrow when I have some time. Looks good though and cheers for all the screenshots. Thanks – MonkeyMagix Jul 20 '14 at 00:20
  • By the way you never told me of how I can copy 200+ classes over to this new project without a copy and paste job? I don't really want to do it by hand. Can I copy the whole project into the new class project – MonkeyMagix Jul 21 '14 at 05:35
  • @MonkeyMagix I edited my answer to show you how to change an application into a library. – Matin Lotfaliee Jul 21 '14 at 06:16
  • So just doing that one change will copy all the files (or re-assign them) to the new app - cool. Thanks – MonkeyMagix Jul 21 '14 at 09:45
  • @MonkeyMagix if the answer was useful for you, please click on the check mark next to the answer. – Matin Lotfaliee Jul 21 '14 at 12:05
  • dont worry I will, I have been laid up in bed with a swollen leg and Cellulitis for last week so haven't had a chance to do this. Going to try now. – MonkeyMagix Jul 23 '14 at 19:37
  • Hi everything seemed to work in converting the code to DLL and I made a new console app with the DLL as a reference. However when I implement it and call one of the methods I get an error related to a DB connection string in that DLL project. Line is private string Connectionstring = ConfigurationManager.ConnectionStrings["Brainiac"].ToString(); the error is Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at NewBOT.BetfairBOT..ctor() in c:\...\BetfairBOT2\BetfairBOT.cs:line 31 (the line of the connection string) – MonkeyMagix Jul 23 '14 at 21:22
  • the code that is erroring is the init of the DLL class I am trying to use from my console app e.g public Control(int systemPK) { this.BetfairBOT = new BetfairBOT(); //errors inside on connection string line this.HelperLib = new HelperLib(); } and the code I am using in my new console app to call this code is static void Main(string[] args) { Console.WriteLine("IN MAIN"); // works Control control = new Control(3); // this fails } – MonkeyMagix Jul 23 '14 at 21:27
  • I am trying to debug between the tow and I have a break point on the Console app init of the new DLL class and it fails on the line private string Connectionstring = ConfigurationManager.ConnectionStrings["DefaultDatabase"].ToString(); with a null exception. Object not set to a reference. I am wondering now its in a DLL whether I should move this INTO the Class init for that Class as it sits outside at the moment. – MonkeyMagix Jul 23 '14 at 21:38
  • Seems to be anything to do with the ConfigurationManager object as I moved the connection string below another init in the DLL and that just got a string value from the App.Config in the DLL (do I need to rename this from App.Config to something else for DLLs?) but on this line this.logfilename = System.Configuration.ConfigurationManager.AppSettings["Logfile"].ToString(); it errored as well. So anything that gets to the ConfigurationManager manager seems to error - do I need to add this as a reference to my console app? Just as I did to the DLL app? Or something else> – MonkeyMagix Jul 23 '14 at 21:46
  • I think the solution of your problem is here:http://stackoverflow.com/questions/5190539/equivalent-of-app-config-for-library-dll – Matin Lotfaliee Jul 24 '14 at 09:30
  • Hi thanks for that so I need to move all my app.config rules for connection strings, paths to the app storage folder and so on to my consumer app. Then pass them into the DLL as parameters? This might be a bit of work re-writing everthing about like this as I have a static Helper class that takes params for the places to log, whether to log and so on that is init in almost most classes in my new DLL App. Dont want to be passing them across lots. might have to rejig it – MonkeyMagix Jul 24 '14 at 12:54
  • also does that mean I need to remove the app.config file FROM my DLL class project? – MonkeyMagix Jul 24 '14 at 13:35
  • No you don't need to pass them into the DLL as parameters. the other answers on that link have good solutions for that: some say you could use: ConfigurationSettings.AppSettings["MyClasses.ConnectionString"]; some say an xml file is best equivalent for app.config. and some say you could use DeploymentItem. I myself prefer xml files. – Matin Lotfaliee Jul 24 '14 at 14:09
  • right so your saying instead of rewrting all my DLL code I just create an XML file (any special format?) and then access all my config vars with an XML getNode type function. Also when it says ConfigurationSettings.AppSettings["MyClasses.ConnectionString"]; what do I put in for MyClasses? The Name of my DLL? Or something else? – MonkeyMagix Jul 25 '14 at 12:00
  • and by the way I am in no way a .NET expert so sorry if some of my questions seem newbie'ish – MonkeyMagix Jul 25 '14 at 12:01
  • Well, I am no expert in configurations. I think it is better to ask new question in stackoverflow for others to come and answer. – Matin Lotfaliee Jul 25 '14 at 13:54
  • I'm having problems with the function they are telling me to use the one that is an xml file and is named after the DLL with .config on the end e.g string exeConfigPath = this.GetType().Assembly.Location; I don't get any errors in the Try/Catch so the configurationManager.OpenExeConfiguration(exeConfigPath); line works but everything I return from the GetAppSetting(Configuration conf,string key) function is a String.Empty. I tried adding .config to the path but that didn't help at all. Any reason for this? – MonkeyMagix Aug 04 '14 at 15:55