I need to create an EXE file with my application, I can pass strings with manipulating the string format but I cannot pass the other variables that I need to ex:byte array, here is my code if this helps:
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Windows;
namespace ACompiler.CompWorker
{
class CompilerWorker
{
public static byte[] testarray = SomeClass.SomeArray;
public static string Key = "Testkey12";
public static void Compile()
{
CSharpCodeProvider CompileProvider = new CSharpCodeProvider();
CompilerParameters CompileProviderParameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, AppDomain.CurrentDomain.BaseDirectory + "Compiled.exe", true);
CompileProviderParameters.GenerateExecutable = true;
string test= #"using System;
namespace Tests
{
class Program
{
static void Main(string[] args)
{
byte[] Content = " + testarray + #";
string Key = """ + Key + #""";
Console.WriteLine(""Key: "" + EKey);
Console.WriteLine(Content);
Console.ReadLine();
}
}
}
";
var Result = CompileProvider.CompileAssemblyFromSource(CompileProviderParameters, test);
}
}
}
Basically I want to move the "testarray" into the compiled app, I hope someone can point me to the right direction!
The trick is to "serialize" the data back in to code the compiler can compile. Try this:
var arrayCode = "new byte[] { " + string.Join(", ", testarray) + " }";
string test = #"using System;
namespace Tests
{
class Program
{
static void Main(string[] args)
{
byte[] Content = " + arrayCode + #";
string Key = """ + Key + #""";
Console.WriteLine(""Key: "" + EKey);
foreach(byte b in Content)
{
Console.WriteLine(b.ToString());
}
Console.ReadLine();
}
}
}
";
Keep in mind, you can't do Console.WriteLine on a byte array object and have it spit out each item. You will have to iterate over the items to print them out. I updated your code to do it the proper way.
Related
I have a list of directories where I am supposed to copy their contents to pre-defined output locations. How do I create a function to perform this operation?
using System;
using System.IO;
namespace doos_date_change
{
class Program
{
static void Main(string[] args)
{
var doosdate = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
string Fax_Single_General_Nontask_01inputlocation = #"location_path" + doosdate + "_01" + "\\" + "General_Nontask" + "\\";
string Fax_Single_General_Nontask_01Outputlocation = #"location_path" + doosdate + "_01" + "\\" + "General_Nontask" + "\\";
if (Directory.Exists(Fax_Single_General_Nontask_01Outputlocation) == false)
{
Directory.CreateDirectory(Fax_Single_General_Nontask_01Outputlocation);
}
foreach (var srcPath in Directory.GetFiles(Fax_Single_General_Nontask_01inputlocation))
{
File.Copy(srcPath, srcPath.Replace(Fax_Single_General_Nontask_01inputlocation, Fax_Single_General_Nontask_01Outputlocation), true);
}
//the steps above are repeated for many directories.
}
}
}
Looking at the code, you're performing the same operations repeatedly:
calculate the input path
calculate the output path
create a directory if it doesn't exist
copy the contents from the input to the output.
You can write a single function that does this for you:
static readonly string rootPath = $"location_path{DateTime.Now.AddDays(-1):yyyyMMdd}";
static void CopyFiles(int number, string folder)
{
var inputPath = $"{rootPath}_{number:00}\\{folder}\\";
//your code sample generates the same input location and output location
//so you'll need to fix it appropriately.
var outputPath = $"{rootPath}_{number:00}\\{folder}\\";
//no need to check if the directory exists, CreateDirectory handles that
Directory.CreateDirectory(outputPath);
foreach (var file in Directory.GetFiles(inputPath))
{
//make a copy of the file, using the same name, but in the
//output location directory
File.Copy(file, Path.Combine(outputPath, Path.GetFileName(file)), true);
}
}
With this function, then in your main program, you can do something like this:
static void Main(string [] args)
{
var locations = new string[]
{
"General_NonTask",
"General_Task",
//...add all of your locations
};
for (int i = 1; i <= 2; i++)
{
foreach (var location in locations)
{
CopyFiles(i, location);
}
}
}
I am trying to create user defined function which uses class defined in pcapDotNet.Core.Dll file. My c# Code is as below:
using System;
using System.IO;
using System.Collections.Generic;
using PcapDotNet.Core;
using System.Linq;
using System.Runtime.InteropServices;
using RGiesecke.DllExport; //GANESH
using System.Runtime.InteropServices;//GANESH
using System.Reflection;
namespace ObtainingAdvancedInformationAboutInstalledDevices
{
class Program1
{
/*
static void Main(string[] args)
{
Program1 var1 = new Program1();
var1.checkDevice();
}*/
public Program1()
{
AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
}
static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
String dllName = new AssemblyName(args.Name).Name + ".dll";
var assem = Assembly.GetExecutingAssembly();
String resourceName = assem.GetManifestResourceNames().FirstOrDefault(rn => rn.EndsWith(dllName));
if (resourceName == null) return null; // Not found, maybe another handler will find it
using (var stream = assem.GetManifestResourceStream(resourceName))
{
Byte[] assemblyData = new Byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
}
//**************************************USER DEFINED FUNCTIONS START*********************
[DllExport("checkFunction", CallingConvention = CallingConvention.Cdecl)]//GANESH
public static int checkFunction()
{
Program1 worker1 = new Program1();
worker1.checkDevice();
return 0;
}
void checkDevice()
{
// Retrieve the interfaces list
IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;
Console.WriteLine(" inside checkDevice\n");
// Scan the list printing every entry
for (int i = 0; i != allDevices.Count(); ++i)
DevicePrint(allDevices[i]);
}
// Print all the available information on the given interface
private static void DevicePrint(IPacketDevice device)
{
// Name
Console.WriteLine(device.Name);
// Description
if (device.Description != null)
Console.WriteLine("\tDescription: " + device.Description);
// Loopback Address
Console.WriteLine("\tLoopback: " +
(((device.Attributes & DeviceAttributes.Loopback) == DeviceAttributes.Loopback)
? "yes"
: "no"));
// IP addresses
foreach (DeviceAddress address in device.Addresses)
{
Console.WriteLine("\tAddress Family: " + address.Address.Family);
if (address.Address != null)
Console.WriteLine(("\tAddress: " + address.Address));
if (address.Netmask != null)
Console.WriteLine(("\tNetmask: " + address.Netmask));
if (address.Broadcast != null)
Console.WriteLine(("\tBroadcast Address: " + address.Broadcast));
if (address.Destination != null)
Console.WriteLine(("\tDestination Address: " + address.Destination));
}
Console.WriteLine();
}
}
}
My python code is as below:
class gooseDriver():
"""A class that creates windows form by importing IED.MainWindow()"""
def __init__(self, ipAddress, port):
self.hllDll = WinDLL (r"C:\WORK\IEC61850\gooseThread1\gooseThread1\bin\x64\Debug\gooseThread1.dll")
self.hllDll.checkFunction()
print("Goose Message Started\n")
def main():
IED = gooseDriver("192.168.0.20", 102)
print("GooseDriver is called\n")
if __name__ == '__main__':
main()
when I tried to call checkFunction from python giving error as "OSError: [WinError -532462766] Windows Error 0xe0434352". This is because function is using LivePacketsDevice class from pcap files. I have embedded pcapDotNet.Core.Dll file while generating DLL as reference. Can anybody suggest what is solution for this issue please.
After lot of trial, it started working when i placed pcapDotNet DLL files into folder where Python interpreter exists. Dont know what is reason? can anybody know on this please.
With this snippet of code
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace ConsoleApplicationUnitTest
{
public class Msg
{
public static string ID = "5";
public static string CON = "Console.WriteLine";
public static string DEB = "System.Diagnostics.Debug.WriteLine";
}
[Microsoft.VisualStudio.TestTools.UnitTesting.TestClass]
public class MyTestClass
{
[TestMethod]
public void TestHelloWorld()
{
Program.Main(new string[] {""});
String Source = " Test: ";
Console.WriteLine(Msg.ID + Source + Msg.CON);
System.Diagnostics.Debug.WriteLine(Msg.ID + Source + Msg.DEB);
}
}
class Program
{
public static void Main(string[] args)
{
String Source = " Main: ";
Console.WriteLine(Msg.ID + Source + Msg.CON);
System.Diagnostics.Debug.WriteLine(Msg.ID + Source + Msg.DEB);
//Console.ReadLine();
}
}
}
I hit Ctrl + Shift + B (to build).
I hit Ctrl + R + A (to run the test).
I fumble around for the mouse, while swearing, and click the output link in TestExplorer.
Because, if I don't, the old Test Output window will just sit there continuing to look like this:
When what I need to see is this:
My question: How do I see the up-to-date Test Output without having to touch the mouse?
I am creating a desktop app that needs to save permanent data. The easiest way I could think of doing this is by writing important information about the file to a textfile. Just to make the data contained, professional and easily accessed by the app, I decided to put it in a newly created folder in the "Program Files" directory of the users computer. Unfortunately, this is blocked by the computer. It denies the access to my application. I know my code works because I ran the application as an administrator and encountered no errors. It also created the folder in "Program Files" as I wanted. Is there anyway to allow access. I'd also like to get the users' permission first. The code is posted below:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyAppNameSpace
{
static class DataManager
{
/* Create a dictionary that takes type "string" for its
* key (name) and type "object" for its value */
public static Dictionary<string, object> Data = new Dictionary<string, object>();
public static string FileName { get; private set; }
public static string ProgramFilesFolder;
// A method to clear all game data
public static void Clear()
{
}
public static void Save()
{
foreach (KeyValuePair<string, object> DataPair in Data)
{
}
}
public static string GetData()
{
return File.ReadAllText(FileName);
}
public static void Setup()
{
ProgramFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "/MyAppName";
FileName = ProgramFilesFolder + "/MyAppData";
if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "/MyAppName/README.txt"))
{
try
{
Directory.CreateDirectory(ProgramFilesFolder);
string text = "DO NOT move this folder. If you must, make sure to keep it " +
"in the same location as the SwingState it is. Also, do not edit the " +
"contents of the data file, which exists in this directory. " +
"This saves all of your progress in your game!";
File.WriteAllText(ProgramFilesFolder + "/README.txt", text);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ":" + ex.InnerException);
GameInfo.Game.Close();
}
}
if (!File.Exists(FileName))
{
Data = new Dictionary<string, object>()
{
{ "Name:", null + "," },
{ "Age:", null + "," },
{ "Description:", null + "," },
{ "Gender:", null + "," },
{ "Level:", 1 + "," },
{ "Drawing:", false + "," },
{ "Uploaded:", false + "," },
{ "Template:", false + "," },
{ "Left1:", null + "," },
{ "Left2:", null + "," },
{ "Left3:", null + "," },
{ "Right1:", null + "," },
{ "Right2:", null + "," },
{ "Right3:", null + "," },
{ "Idle:", null + "," },
{ "Template Number:", null + "," }
};
}
else if (File.Exists(FileName))
{
string[] DataText = File.ReadAllText(FileName).Split(',');
foreach (string s in DataText)
{
Data.Add(s.Split(':')[0], s.Split(':')[1]);
}
}
}
}
}
I fixed this by changing the special folder to AppData. Here is the code for that:
ProgramFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "/MyAppName";
FileName = ProgramFilesFolder + "/MyAppData";
if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "/MyAppName/README.txt"))
I've created my own little c# compiler using the tutorial on MSDN, and it's not working properly. I get a few errors, then I fix them, then I get new, different errors, then I fix them, etc etc.
The latest error is really confusing me.
---------------------------
---------------------------
Line number: 0, Error number: CS0006, 'Metadata file 'System.Linq.dll' could not be found;
---------------------------
OK
---------------------------
I do not know what this means.
Can somebody please explain what's going on here?
Here is my code.
MY SAMPLE C# COMPILER CODE:
using System;
namespace JTM
{
public class CSCompiler
{
protected string ot,
rt,
ss, es;
protected bool rg, cg;
public string Compile(String se, String fe, String[] rdas, String[] fs, Boolean rn)
{
System.CodeDom.Compiler.CodeDomProvider CODEPROV = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
ot =
fe;
System.CodeDom.Compiler.CompilerParameters PARAMS = new System.CodeDom.Compiler.CompilerParameters();
// Ensure the compiler generates an EXE file, not a DLL.
PARAMS.GenerateExecutable = true;
PARAMS.OutputAssembly = ot;
foreach (String ay in rdas)
{
if (ay.Contains(".dll"))
PARAMS.ReferencedAssemblies.Add(ay);
else
{
string refd = ay;
refd = refd + ".dll";
PARAMS.ReferencedAssemblies.Add(refd);
}
}
System.CodeDom.Compiler.CompilerResults rs = CODEPROV.CompileAssemblyFromFile(PARAMS, fs);
if (rs.Errors.Count > 0)
{
foreach (System.CodeDom.Compiler.CompilerError COMERR in rs.Errors)
{
es = es +
"Line number: " + COMERR.Line +
", Error number: " + COMERR.ErrorNumber +
", '" + COMERR.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
// Compilation succeeded.
es = "Compilation Succeeded.";
if (rn) System.Diagnostics.Process.Start(ot);
}
return es;
}
}
}
... And here is the app that passes the code to the above class:
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] f = { "Form1.cs", "Form1.Designer.cs", "Program.cs" };
string[] ra = { "System.dll", "System.Windows.Forms.dll", "System.Data.dll", "System.Drawing.dll", "System.Deployment.dll", "System.Xml.dll", "System.Linq.dll" };
JTS.CSCompiler CSC = new JTS.CSCompiler();
MessageBox.Show(CSC.Compile(
textBox1.Text, #"Test Application.exe", ra, f, false));
}
}
}
So, as you can see, all the using directives are there. I don't know what this error means. Any help at all is much appreciated.
Thank you
Solution:
Add this:
PARAMS.ReferencedAssemblies.Add(typeof(System.Xml.Linq.Extensions).Assembly.Location);
So the code now looks like this:
namespace JTM
{
public class CSCompiler
{
protected string ot,
rt,
ss, es;
protected bool rg, cg;
public string Compile(String se, String fe, String[] rdas, String[] fs, Boolean rn)
{
System.CodeDom.Compiler.CodeDomProvider CODEPROV = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
ot =
fe;
System.CodeDom.Compiler.CompilerParameters PARAMS = new System.CodeDom.Compiler.CompilerParameters();
// Ensure the compiler generates an EXE file, not a DLL.
PARAMS.GenerateExecutable = true;
PARAMS.OutputAssembly = ot;
PARAMS.ReferencedAssemblies.Add(typeof(System.Xml.Linq.Extensions).Assembly.Location);
foreach (String ay in rdas)
{
if (ay.Contains(".dll"))
PARAMS.ReferencedAssemblies.Add(ay);
else
{
string refd = ay;
refd = refd + ".dll";
PARAMS.ReferencedAssemblies.Add(refd);
}
}
System.CodeDom.Compiler.CompilerResults rs = CODEPROV.CompileAssemblyFromFile(PARAMS, fs);
if (rs.Errors.Count > 0)
{
foreach (System.CodeDom.Compiler.CompilerError COMERR in rs.Errors)
{
es = es +
"Line number: " + COMERR.Line +
", Error number: " + COMERR.ErrorNumber +
", '" + COMERR.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
// Compilation succeeded.
es = "Compilation Succeeded.";
if (rn) System.Diagnostics.Process.Start(ot);
}
return es;
}
}
}