Execute functions of another C# running program - c#

I have a litle program in c#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int count;
static void Main(string[] args)
{
for (int i = 0; i<10; i++)
{
Console.WriteLine(func_count());
Console.ReadKey();
}
}
static int func_count()
{
return count++;
}
}
}
I want to write another simple C# program that will be able JUST to execute the func_count(). The first exe will be allready running, I don't want to execute it inside the second application and reflect it's properties.
In C after getting the right to access the memory region to avoid seg fault I would have to use a pointer to a function - something like:
int (* func_ptr)(); //pointer to function
func_ptr = func_count_address
What's a simple way to do this in C# like above?
Suppose that the first program (the one given) is as is and I can't change the code.
Thank you

Why not simply call the static method: ConsoleApplication1.Program.func_count(). This of course assumes that you reference the assembly where ConsoleApplication is located within your second app and that the method you want to invoke is public (which is currently is NOT).
EDIT: If you may not change the access-modifier of the desired method you may use reflection to invoke it however.
Sth. like this:
MethodInfo m = typeof(ConsoleApplication.Program).GetMethod("func_count", BindingFlags.NonPublic);
object result = m.Invoke(null, yourParams);
Usually you´d need an instance on which that method is executed. Since your method is static it does not need it and therefor the first param to Invoke is NULL.

Related

How do I set up an environment to solve LeetCode problems in Visual Studio? C#

When making the file, I am thinking of selecting a console application. But which target framework do I choose? Is this incorrect? Also, I am having trouble figuring out how to make a method in the class Program that is able to be called in the Main method. Can someone give me some advice?
one thing you can do is using interface to keep your code clean; for example :
you create an interface like this:
public interface IQuestionSolving
{
public void Solution();
}
you create some question class :
public class Question1 : IQuestionSolving
{
public void Solution()
{
}
}
and you use it like this :
static void Main(string[] args)
{
IQuestionSolving solve = new Question1();
solve.Solution();
Console.ReadKey();
}
now each time you solve a question you need to change
IQuestionSolving solve = new Question1();
to
IQuestionSolving solve = new Question2(); // 2 3 4 .. etc
you can extract your project as template so you dont have to do this each time .
or you can just use one solution and many classes .
This will get you started with Visual Studio:
Create a new console project - use the latest version of C#, which is probably what VS will "suggest" to you. Currently that's .NET 6 or .NET 7
A modern (net 6 or later) console app lets you start writing code immediately. You could create a method and then call the method right in this little Program.cs file that you start out with. However, I would probably do the following instead:
a) Create a new class for your "problem"
b) In that class create a method that solves the problem.
c) In your Program.cs add a using statement to use the namespace that your new class uses
d) In your program.cs instantiate that class and call its method/test its method
Here is an example:
Program.cs
using LeetCodeProject;
var solver = new Problem001_CalculateSquareRoot();
var solution = solver.calculate_square_root(8);
Console.WriteLine(solution);
Console.WriteLine("Press any key...");
Console.ReadKey();
Problem001_CalculateSquareRoot.cs (solves one leetcode problem)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCodeProject
{
public class Problem001_CalculateSquareRoot
{
public double calculate_square_root(int number)
{
double root = 1;
int i = 0;
while (true)
{
i = i + 1;
root = (number / root + root) / 2;
if (i == number + 1)
{
break;
}
}
return root;
}
}
}
Now you can just add new classes for each problem, and as you work on them just edit Program.cs to create the class you are currently working with and calls its solution methods.
I can (and would - and actually have, in similar cases) implement an interface for this, but the goal here is not to get into OO design principles, but just to get you started so you can get to work on the leetcode problems...once you have a few done you can start thinking about better organization of the code.

inserting into index location of a text file if a string does exist inside the line, if the string doesn't exist, still write line as it was

The program is supposed to look for a string in a line, and if it finds the string, it will make the inserts after meeting the condition inside the textfile. Currently, when I run this program it is now simply giving me a blank console. Previously, I had it just reading all the lines properly and could make inserts only if I remove them first but it messed the indexing up and ultimately did not give me the result I wanted. The logic is fairly straightforward, if you see any problems please share your thoughts. Please and thanks. I am very confused why this is having problems and not working.
using System.IO;
using System.Globalization;
using System.Diagnostics;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
namespace Masker
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine();
string path = #"\file1.txt";
ReadLines(path)
}
public static void ReadLines(string path)
{
int counter = 0;
var text = new StringBuilder();
foreach (string s in File.ReadAllLines(path))
{
counter += 1;
if (s.Contains("000INDEX"))
{
text.AppendLine(s.Insert(60, "#"));
}
else if (s.Contains("001PRTBNR"))
{
text.AppendLine(s.Insert(60, "#").Insert(119,"#").Insert(120,"#").Insert(121, "#"));
};
text.AppendLine(s);
//Console.Write(text.ToString());
}
Console.Write(text.ToString());
}
}
}
The last two blocks of your if/else statement will never be executed.
If the execution reaches the third check
else if (s.Contains("000INDEX"))
that will always be true. Because if it wasn't, then the first check
if (!s.Contains("000INDEX"))
would have already been true.
But the biggest problem is that if the line contains "000INDEX", your while loop becomes and infinite loop. You never leave it. That is probably the reason why you end up with a blank console.

Linq and localhost, entity namespace is different than program namespace but still get error

I have tried to search for this but every example I find has a problem like them actually having the same namespace as their class or something.
I am simply trying to start using Linq. When I add new item Host is localhost. I have my database in Visualstudio and my project name is different than the DataContext name but I can't get it initialized. I get error:
'LinkedContext' is a namespace but is used like a type'
here is code...
namespace TryAgain
{
class Program
{
static void Main(string[] args)
{
LinkedContext db = new LinkedContext();
}
}
}
LinkedContext doesn't work? In settings of the Database Diagram it says the Entity Namespace is 'LinkedContext' So what am I missing. I thought I saw you could run that one line of code to connect your database that is already in VisualStudio due to adding a new item and then start playing with it? I just want to be able to practice with a database! Do stuff like:
var example = from x in example.Table
orderby x.field
select x;
you need using LinkedContext at the top of your file. the error you’re getting is telling you LinkedContext is a namespace but you’re treating like a type, ie a class. once you define it at the top you can then use the type that you need within that namespace.
added "using LinkedContext" to the top of code then also had to use LinkedDataContext not just LinkedContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkedContext;
namespace TryAgain
{
class Program
{
static void Main(string[] args)
{
LinkedDataContext db = new LinkedDataContext();
var example = from x in db.employees
orderby x.employee_id
select x;
foreach (var whatever in example)
{
Console.WriteLine(whatever.name);
}

Read text file into Clipboard

after along time of searching via google, I decided to poste my problem here.
First: I am total C# Noob. I am using a Macro Recorder from Jitbit and I have no choice to use a different. The Problem is in the Macro Recorder, it is missing some essential things.
Like reading a text file into a variable and paste this variable via Clipboard :-(
However the good thing is, the tool support "some" type of native C# Code
If I open the C# Command I get this:
public class Program
{
public static void Main()
{
System.Windows.Forms.MessageBox.Show("test");
}
}
And the C# program has to follow also these rules:
=> This Code MUST contain a class named "Program" with a static method "Main"
I already used google and found code that should do the job but I get errors, I guess the
code doesn`t follow the above rules.
This is what I found and tried:
using System;
using System.IO;
public class Program
{
public static void Main()
{
// Read the file as one string.
System.IO.StreamReader myFile =
new System.IO.StreamReader("Counter.txt");
string counter = myFile.ReadToEnd();
myFile.Close();
// Load string into clipboard
Clipboard.SetDataObject( counter, true );
}
}
I always get the error : "Line 15: The Name Clipboard is not existing in the context"?!?
I hope that someone can explain a noob (me) what is wrong and what is the correct code.
Thanks.
add reference to System.Windows.Forms
using System;
using System.IO;
using System.Windows.Forms;
public class Program
{
[STAThread]
public static void Main()
{
Clipboard.SetDataObject(File.ReadAllText("Counter.txt"), true);
}
}
Note that to Avoid the ThreadStateException you need to applying the STAThread attribute to your Main() function

Why can't I read a db4o file created by a Java app in a C# app?

I have a db4o database that was generate by a Java app and I'm trying to read it using a C# app.
However, when running the following line of code:
IObjectContainer db = Db4oEmbedded.OpenFile(#"..\..\..\Databases\people.db4o");
I get the following error:
Unable to cast object of type
'Db4objects.Db4o.Reflect.Generic.GenericObject' to type
'Db4objects.Db4o.Ext.Db4oDatabase'.
Any ideas? I know there are person objects that contain personId fields (along with others) in the DB. I'm using db4o version 8. I'm not sure what version was used to generate the database.
The entire program is:
using System;
using System.Collections.Generic;
using System.Linq;
using Db4objects.Db4o;
using Db4objects.Db4o.Config;
using MyCompany.Domain;
namespace MyCompany.Anonymizer
{
internal class Program
{
// Private methods.
private static IEmbeddedConfiguration ConfigureAlias()
{
IEmbeddedConfiguration configuration = Db4oEmbedded.NewConfiguration();
configuration.Common.AddAlias(new TypeAlias("com.theircompany.Person", "MyCompany.Domain.Person, MyCompany.Domain"));
configuration.Common.Add(new JavaSupport());
return configuration;
}
private static void Main(string[] args)
{
IObjectContainer db = Db4oEmbedded.OpenFile(#"..\..\..\Databases\people.db4o");
try
{
IList<Person> result = db.Query<Person>();
for (int i = 0; i < result.Count; i++)
{
Person person = result[i];
Console.WriteLine(string.Format("Person ID: {0}", person.personId));
}
}
finally
{
db.Close();
}
}
}
}
The most common scenario in which this exception is thrown is when db4o fails to resolve the type of a stored object.
In your case, db4o is failing to read one of its internal objects which makes me believe you have not passed the configuration to the OpenFile() method (surely, the code you have posted is not calling ConfigureAlias() method);
Keep in mind that as of version 8.0 no further improvement will be done regarding cross platform support (you can read more details here).

Categories

Resources