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

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.

Related

Specifying cs file to build with dotnet CLI

Suppose I have two files in my current working directory:
// file1.cs
Console.WriteLine("file1");
//file 2.cs
Console.WriteLine("file2");
In powershell, I do a dotnet new and delete the automatically generated Program.cs file. Then I do a dotnet build and get an error:
Only one compilation unit can have top level statements
I understand why this occurs, but I would like to be able to have full control of which .cs file is being targetted, while the other ones get ignored.
Is there any way to achieve this without having to create a whole new project for every file?
Doing this with .NET doesn't seem to be possible as of now. An issue on the dotnet/sdk GitHub has requested for this feature to be implemented.
However, you can use the C Sharp Compiler to compile a Windows executable and specify a .cs file with csc file1.cs
file1.cs:
using System;
Console.WriteLine("File 1");
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements
These files both use top-level statements. It implies that they both contain the Main method where program execution starts. You can only have one entry point. Generally, C# code is going to be contained within classes. Define a class in one (or both) files and put your methods within.
// Program.cs
public class Program
{
static void Main()
{
Console.WriteLine("Program.cs");
}
}
// Util.cs
public class Util
{
public static void Display()
{
Console.WriteLine("Util.cs");
}
}

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"}

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>
}
}

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

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" %>

Why do 'requires' statements fail when loading (iron)ruby script via a C# program?

IronRuby and VS2010 noob question:
I'm trying to do a spike to test the feasibility of interop between a C# project and an existing RubyGem rather than re-invent that particular wheel in .net. I've downloaded and installed IronRuby and the RubyGems package, as well as the gem I'd ultimately like to use.
Running .rb files or working in the iirb Ruby console is without problems. I can load the both the RubyGems package, and the gem itself and use it, so, at least for that use case, my environment is set up correctly.
However, when I try to do the same sort of thing from within a C# (4.0) console app, it complains about the very first line:
require 'RubyGems'
With the error:
no such file to load -- rubygems
My Console app looks like this:
using System;
using IronRuby;
namespace RubyInteropSpike
{
class Program
{
static void Main(string[] args)
{
var runtime = Ruby.CreateRuntime();
var scope = runtime.ExecuteFile("test.rb");
Console.ReadKey();
}
}
}
Removing the dependencies and just doing some basic self-contained Ruby stuff works fine, but including any kind of 'requires' statement seems to cause it to fail.
I'm hoping that I just need to pass some additional information (paths, etc) to the ruby runtime when I create it, and really hoping that this isn't some kind of limitation, because that would make me sad.
Short answer: Yes, this will work how you want it to.You need to use the engine's SetSearchPaths method to do what you wish.
A more complete example
(Assumes you loaded your IronRuby to C:\IronRubyRC2 as the root install dir)
var engine = IronRuby.Ruby.CreateEngine();
engine.SetSearchPaths(new[] {
#"C:\IronRubyRC2\Lib\ironruby",
#"C:\IronRubyRC2\Lib\ruby\1.8",
#"C:\IronRubyRC2\Lib\ruby\site_ruby\1.8"
});
engine.Execute("require 'rubygems'"); // without SetSearchPaths, you get a LoadError
/*
engine.Execute("require 'restclient'"); // install through igem, then check with igem list
engine.Execute("puts RestClient.get('http://localhost/').body");
*/
Console.ReadKey();

Categories