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>
}
}
Related
I am getting an error on my code that says "Error CS5001
Program does not contain a static 'Main' method suitable for an entry point"
I am coding in C# using Microsoft Visual Studio and .NET. This is my code.
using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using System;
class projectsummer
{
[CommandMethod("OpenDrawing", CommandFlags.Session)]
public static void OpenDrawing()
{
string strFileName = "C:\\DRAFT.dwg";
DocumentCollection acDocMgr = Application.DocumentManager;
if (File.Exists(strFileName))
{
acDocMgr.Open(strFileName, false);
}
else
{
acDocMgr.MdiActiveDocument.Editor.WriteMessage("File " + strFileName +
" does not exist.");
}
}
}
I am not sure how to go about this error. Thank you!
Looking at this post and your previous question, let's try and break down what's going on.
You created a new Console application in Visual Studio. You did not tick "Do not use top level statements". This gave you a Program.cs file that was essentially empty (there was no "Main" method visible).
You erased the Hello World code given to you, and went to make a static method - the code from your previous question.
Damien_The_Unbeliever commented that based on the error, you put your method inside a "top level statement" file, and to put your method inside a class.
You wrap your method (which is still inside Program.cs) in a class, and now suddenly you get a Can't Find Entry Point error.
User Ryan Pattillo posted a great explanation of the original issue - where your method was "by itself" in the Program.cs file. You should follow their advice, but you should also ensure that this class is in its own file.
You should end up with this:
Program.cs
// this is the entire contents of the file
using ConsoleApp1;
ProjectSummer.OpenDrawing();
ProjectSummer.cs
using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using System;
namespace ConsoleApp1
{
public class ProjectSummer
{
[CommandMethod("OpenDrawing", CommandFlags.Session)]
public static void OpenDrawing()
{
// ...
}
}
}
Change ConsoleApp1 to the name of your project.
The entry point of your application, which right now is the only file that has "top level statements", remains Program.cs, thus you fix the Can't Find Entry Point error.
Another adjustment you can make, which seeing you're new to C# might be useful, is to not use top level statements at all. Modify your Program.cs to this:
namespace ConsoleApp1
{
internal static class Program
{
// this is your program's entry point
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
ProjectSummer.OpenDrawing();
}
}
}
Change ConsoleApp1 to the name of your project.
You cannot use the AutoCAD .NET API out of process. To be able to use the AutoCAD .NET libraries, you have to build a "class library" project (DLL) and NETLOAD this DLL from a running AutoCAD process. See this topic about in-process vs out-of-process and you can start from this other one to see how to create an AutoCAD .NET project.
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");
}
}
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.
I have a C# program running under Visual Studio 15 .NET Framework 4.5.2. It uses AutoMapper 4.1.1. It's been running fine for years. (I inherited it from someone else.) Just lately, it started erroring out at the line "AutoMappings.AutoMappings.CreateMaps();" Here's the relevant code:
using System;
using System.Windows.Forms;
using IVGOffice.UserInterface;
using System.Net;
using System.Net.Security;
namespace IVGOffice
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// Assign certification callback to allow for self-signed certs on the services
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IVG.Common.Certificate.ValidateRemoteCertificate);
AutoMappings.AutoMappings.CreateMaps(); // <----- Errors out here
It throws a System.TypeInitiializationException with inner error "Configuration system failed to initialize". It never actually enters into the AutoMappings class, so I don't think the problem is related to the class, but here's the beginning of it anyway:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IVG.Common;
using IVG;
namespace IVGOffice.AutoMappings
{
public static class AutoMappings
{
private static bool mapsCreated = false;
private static Utilities2.Services services = new Utilities2.Services();
public static void CreateMaps()
{
// AutoMapper CreateMap should only be called once in an application domain. If we call this twice, check and just leave the second time
if (mapsCreated)
return;
// For every IAutomappedObject
System.Reflection.Assembly assm = System.Reflection.Assembly.GetCallingAssembly();
var interfaceTypes = assm.GetTypes();
var automappedTypes = interfaceTypes.Where(type => typeof(IAutomappedObject).IsAssignableFrom(type)
&& !type.IsAbstract
&& !type.IsInterface);
foreach (var type in automappedTypes)
...
My coworker tried running the same code on his laptop and it worked fine, so there must be something going on with my copy of Visual Studio or my computer settings. I've tried running different versions of the program, rebooting, restoring the program from backup, etc. to no avail.
Anybody have any ideas? Thanks.
I hit this today because I stupidly placed appSettings before the configSections in my app.config file.
The error possibly indicates that your config file contains illegal syntax/layout. I'd start your investigation there.
The problem was in the configuration, but not in app.config. I had added code to save and restore the window status, location, and size. These settings were saved into a new user.config file. The problem was that I had added this code to a new git repo. My boss had to approve the changes before merging them into the master repo. In the meantime, I had gone back to the master to start a new project. The master didn't have the new code, but the new user.config file was still there. For some reason, that seems to have confused the program. When my boss finally merged the new code and I updated my copy of the master, the problem went away. Thanks for your feedback.
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" %>