How to include one c# file into another c# file? - c#

How to include one c# file into another c# file?
I have two c# file like one is test.cs and another one is main.cs. I want to include test.cs into main.cs.
test.cs file code
// you can use Console.WriteLine for debugging
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Solution
{
public bool solution(long number1, int[,] arr1,int dim_2,int dim_3)
{
//some code here
}
}
main.cs code
using System;
include test.cs;
class Group
{
public static void Main(String[] args)
{
long number1 = 5;
int [,] arr1 = new int[,] {{0, 0},{1, 1},{2, 2},{3, 3},{4, 4}};
int dim_2 = 5;
int dim_3 = 2;
Solution object_class = new Solution();
bool result = object_class.solution ( number1, arr1, dim_2, dim_3 );
Console.WriteLine("Return :");
Console.WriteLine( result );
}
}
what i am doing wrong here?? Please Help me.
Thank you in Advance

I guess your problem is because both files are not added in the same project.
If you are using Visual Studio.
To add test.cs in the Group class project.
Go to Solution Explorer -> Add Existing item -> Browse your file i.e.
test.cs -> OK
If you are using DOS mode.
Make sure that both files must be in same folder.
And in either case. first delete include test.cs; from Main file. then Compile & RUN

We create object of classes declared in other source code files with the way you have already followed:
Solution object_class = new Solution();
Provided that the Solution class is declared in a source code file in the same project (console application as I can infer from your post), you don't have to mark the Solution class as a public. Otherwise, you should mark it as a public. Actually, you have to do so in case of this class is going to be used outside of your current project.
Your problem, I think is about namespaces. You might have declared this class inside a folder. Anyways, the way to solve this is to right click on the name of the Solution and then click resolve references.

ASP.NET C# Classes
this solution was helpfull for class files outside the App_Code
you need add follow line in every page(aspx) or usercontrol(asc)
<%# Assembly Src="~/App_Ctrl/PraxisPdfs/class_pdf.cs" %>

Related

Use dependency from one project to another in the same solution

Is it a way of using a dependency from a project to another while they are in the same solution? For example:
ComputerVisionProject (solution):
1. ComputerVision.FaceRecognition
2. ComputerVision.Core
3 .ComputerVision.UI
In the first project: ComputerVision.FaceRecognition, I install a nugget, for example, "OpenCV" and I can use all the functions from it with "using OpenCV", but only in the ComputerVision.FaceRecognition project.
What I want is to use the same functions in the second project, ComputerVision.Core. but I don't want to install again the nugget, and seems that only "using OpenCV" doesn't work (even if I add the entire project as a reference to the second one) Is it possible to make another type of reference or something like: "using ComputerVision.FaceRecognition.OpenCV" ?
Use a project reference.
https://learn.microsoft.com/en-us/visualstudio/ide/managing-references-in-a-project?view=vs-2019
To test; create a new solution with two projects within it.
Within one project, add a nuget package. Say, Newtonsoft.Json
Add a project reference from your second project to the first
Dependencies should now look like so;
Now within TestConsoleApp, you can add using statements to access the nuget package used in TestConsoleApp2.
eg;
using System;
using Newtonsoft.Json;
namespace TestConsoleApp
{
class Program
{
static void Main(string[] args)
{
var output = JsonConvert.SerializeObject(new ExampleObject() { field = "value" });
Console.WriteLine(output);
}
}
public class ExampleObject
{
public string field;
}
}
When run outputs {"field":"value"}

Add XML reference to a single c# script in visual studio

This may be a stupid question but how can I add XML references in Visual Studio to a single c# file?
I want to use using System.xml;, but Visual Studio is not able to find it. After a little research, I found out that I have to reference the DLL. But I only created a single C# script and no project: the project window on the right side is empty (shows 0 projects) and, when I right-click on it, there is no option for adding a reference.
The script should provide a few functions for reading specific XML files and basically should be a plug-in which can be implemented in any C# program if needed - so I think I don't really want to make an application out of it.
You can use the following code to add xml reference to c# script and call the script successfully.
static void Main(string[] args)
{
string code = File.ReadAllText("D:\\Code.cs");
CSScript.Evaluator.ReferenceAssembliesFromCode(code);
dynamic block = CSScript.Evaluator.LoadCode(code);
block.ExecuteAFunction();
Console.ReadKey();
}
Code.cs
using System;
using System.Xml;
class MyScript
{
public void ExecuteAFunction()
{
string path = "D:\\t.xml";
XmlDocument document = new XmlDocument();
document.Load(path);
Console.WriteLine(document.LastChild.InnerXml);
Console.ReadKey();
}
}
Besides, you also look at How to Add a Reference to a C# Script.

C# - How do I build/debug this code in VS2015?

I was given some code for a simple text file parser that I would like to build on and modify. It was built in VS and I've installed VS2015 Community so that I can work with it, but for the life of me I can't figure out how to set it up in VS2015.
A snippet of the very beginning of the code is below. Do I build it as a class, or a console application, or something else? How can I modify it to read a local file line by line?
Any help would be tremendously appreciated!
using System;
using System.Collections.Generic;
using System.IO;
public static class Cawk
{
public static IEnumerable<Dictionary<string, object>> Execute(StreamReader input)
{
Dictionary<string, object> row = new Dictionary<string, object>();
string line;
//string[] lines = File.ReadAllLines(path);
//read all rows
while ((line = input.ReadLine()) != null)
{
The snippet you posted is a class file definition.
You will need a class called Cawk.cs with that code inside.
To run it, you will need something to invoke it, either a console app or a unit test will do.
For a console app:
create a new console application project.
add a new class named Cawk.cs with your code inside.
in the 'program.cs' class (created when you create the console project), inside the Main method, call your Execute method.
To debug it, put a breakpoint on a line and press F5.
Considering you've never build an application in visual studio, the easiest way are:
Start VS
Create new project: File -> New -> Project
Select Templates -> Visual C# -> "Console application"
Choose a folder to save the project, click OK.
That will give you a basic console application with one file Program.cs that has static method Main() inside. Now let's add the new class.
Right click the solution tree, choose Add -> New item
Choose "Class", enter name "Cawk", click OK.
You will create a new file "Cawk.cs" for Cawk class. Let's fill it up.
Copy-paste your snippet in Cawk.cs, overwriting it's contents.
Correct the namespace - it should be the same as in the Program.cs
So it will become something like:
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication1
{
public static class Cawk
{
...
Now you can call Cawk.Execute() static method from the Main() method.
The method Execute() accepts a StreamReader object. This object reads data from a byte stream - a flow of data coming from some kind of source - user input, file, another application, etc.
In order to parse a file through Cawk you need to instantiate StreamReader first with a proper constructor, and dispose it afterwards (see "using" statement in C#).
Let me provide you an example of code:
using (var sr = new StreamReader("C:\temp\file.txt"))
{
var results = Cawk.Execute(sr);
foreach (item in results)
{
// do something with item which is Dictionary<string, object>
}
}

Can someone provide an example for the ImageCompare methods?

I'm attempting to compare two images using Visual Studio 2013 Pro. The MSDN provides information (http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.uitesting.imagecomparer.compare.aspx) on ImageComparer.Compare, alas I'm failing to get it implemented in my code. On the last line of my code I'm told that "The name 'Compare' does not exist in the current context". Can someone please help? Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UITesting;
namespace Intranet.SmokeTests
{
public class Intranet_Login : Intranet_Setup
{
public List<string> IntranetLoginTest(string BrowserURL, string Host, int Port)
{
Image expected = Image.FromFile(#"\\webdriver\ImageVerification\Expected\IntranetHome.png");
Image actual = Image.FromFile(#"\\webdriver\ImageVerification\Actual\IntranetHome.png");
bool equal = Compare(actual, expected);
}
}
}
You must do it like this:
bool equal = ImageComparer.Compare(actual, expected);
When you want to use a class's static member in c# you must always qualify it with the class first. Otherwise the compiler will try to locate the member on the current class.
Another problem you might be having with your IntranetLoginTest is that it's supposed to return an instance of List<string>, but it doesn't. I must also say I find it strange that you are making an image comparison test in a method that would suggest it performs authentication mechanisms testing.
1- Using nuget Install System.Drawing.Common
2- Reference Microsoft.VisualStudio.TestTools.UITesting.dll from C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\Extensions\TestPlatform
Image expected = Image.FromFile(#"2020-09-01_15h31_24.png");
Image actual = Image.FromFile(#"2020-09-01_15h31_30.png");
Image difference = null;
var isTestPass = ImageComparer.Compare(actual, expected, out difference);
if (!isTestPass)
difference.Save("diff.png");
Console.ReadLine();
Expected
Actual
Difference
It turns out that the correct version of the referenced dll was not being added. The complete answer is here: How can I make the namespace locally match what is listed on MSDN?

"does not contain a static 'main' method suitable for an entry point"

I can't figure what's my wrong with my code below.
When I try to compile I get the message:
does not contain a static 'main' method suitable for an entry point.
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace RandomNumberGenerator
{
public partial class Form1 : Form
{
private const int rangeNumberMin = 1;
private const int rangeNumberMax = 3;
private int randomNumber;
public Form1()
{
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min,int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void Display(object sender, EventArgs e)
{
switch (randomNumber)
{
case 1:
MessageBox.Show("A");
break;
case 2:
MessageBox.Show("B");
break;
case 3:
MessageBox.Show("C");
break;
}
}
}
}
Can someone please tell me where I've gone wrong.
Every C# program needs an entry point. By default, a new c# Windows Forms project includes a Program class in a Program.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StackOverflow6
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
You are probably missing this or deleted it.
Your project must be created as an empty project. So the output type shows as Console Application. Change it to Class library, and it should work
simple change in code.
main method should be 'Main' (Capital M).
I just had this issue myself.
I created a winforms project, decided to refactor my code and the project would now not contain the UI, so I deleted the Program.cs and winforms files only to get the same error you were getting.
You either need to re add the static void main() method as Matt Houser mentioned above, or go into the project properties and change the output type in the Application tab to Class Library.
I have also experienced this wrong. I changed the dropdown situated in Project properties/Application tab (Output type:). The original selected value was "Class Library" but i changed to "Windows Application" and found same error. Now resolved.
I also faced the similar issue, and i wasted my 13 hours in finding the solution. Lastly, i got the sol...
Right click on the project --> Go to properties -->Change output type to "Class Library"
Vote me up it this helped you.
Late, but for me, it was a "Console Application" project type, but "Build Action" in the file properties was some set to "None". Changed it to "Compile" and it was fine.
Might be you deleted Program file from your project. Just add Program.cs file your problem get resolved
in the Solution Explorer: Right click on Project-->select properties-->select application tab-->select output type as Class library and save it and build it.
My case was very strange - app built fine before, but in one moment I faced with same issue.
What I had :
ConsoleApplication
public static async void Main(string[] args)
so my main is async, but return type is void, but must be Task
public static async Task Main(string[] args)
Worked brilliantly before with void, not sure what was trigger this scenario, where void is became not ok to build
¯ \ (ツ) / ¯

Categories