C# Can't access Properties.Resources - c#

so, I am making a file binder.
saves1 and saves2 are the embedded resources and
I want to extract it in the temp folder.
Here's my code:
using System.IO;
using System.Diagnostics;
namespace _123
{
class Program
{
static void Main(string[] args)
{
string patdth = #"C:\Users\Alfred\AppData\Local\Temp";
byte[] lel1 = Properties.Resources.saves2;
byte[] lel = Properties.Resources.saves1;
File.WriteAllBytes(patdth + "\\hdhtehyr.exe", lel);
File.WriteAllBytes(patdth + "\\hdhdhdhgd.exe", lel1);
Process.Start(patdth + "\\hdhtehyr.exe");
Process.Start(patdth + "\\hdhdhdhgd.exe");
}
}
}
I get this error:
"Error CS0103 The name 'Properties' does not exist in the current
context ConsoleApplication3".
edit:
I am inserting the resources dynamically here, as you can see my code "/resources" + Path" is my way of adding the resources.
public void compile2(string file)
{
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters compars = new CompilerParameters();
compars.ReferencedAssemblies.Add("System.dll");
compars.ReferencedAssemblies.Add("System.Reflection.dll");
compars.ReferencedAssemblies.Add("System.IO.dll");
compars.GenerateExecutable = true;
compars.GenerateInMemory = false;
compars.TreatWarningsAsErrors = false;
compars.OutputAssembly = "Binded.exe";
compars.CompilerOptions = "/resources:" + textBox10.Text;
compars.CompilerOptions = "/resources:" + textBox11.Text;
compars.CompilerOptions = "/t:winexe";
if (string.IsNullOrWhiteSpace(textBox12.Text))
{
}
else
{
compars.CompilerOptions = "/win32icon:" + textBox12.Text;
}
CompilerResults res = provider.CompileAssemblyFromSource(compars, file);
{
MessageBox.Show("Code compiled!", "Success");
}
}

Under 'ConsoleApplication3' Project, double click 'Properties' -> Select 'Resources' tab -> Click on "This project does not contain a default resources file. Click here to create one." message. Add the files ('saves1' and 'saves2') here.

Related

embed pcap dll files into c# project created DLL

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.

How to compile code in C# Dot Net on run time?

So I would like to compile a whole folder of .cs files and then create a DLL file and then use that DLL in my project on runtime.
I searched the internet and found out CSharpCodeProvider can help me in this.
But what got me confused is that most of the example on this site showed how to read one single file, not a folder as whole.
So I am assuming that my folder containing the .cs files will be linked together.
Example Files:
File: TestMain.cs
class TestMain
{
public static void Main(string[] args)
{
Test t = new Test();
t.Hello();
}
}
File: Test.cs
public class Test
{
public void Hello()
{
Console.Write(#"Hello");
}
}
Any guidance will be well appreciated.
Ok So after searching and guidance here is my working code:
public static Assembly CompileAssembly(string[] sourceFiles, string outputAssemblyPath)
{
var codeProvider = new CSharpCodeProvider();
var compilerParameters = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = false,
OutputAssembly = outputAssemblyPath
};
// Add CSharpSimpleScripting.exe as a reference to Scripts.dll to expose interfaces
//compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
var result = codeProvider.CompileAssemblyFromFile(compilerParameters, sourceFiles); // Compile
if (result.Errors.Count > 0)
{
MessageBox.Show(#"Error Occured");
}
else
{
return result.CompiledAssembly;
}
return null;
}
Basically, You can use CodeDom.Compiler to compile the dll, i wrote somethinglike this long back then use Reflection later to reference it dynamically
//dot net compiler
using System;
using System.CodeDom.Compiler;
using System.IO;
namespace IndiLogix.dotCompiler
{
class dotCompiler
{
FileInfo sourceFile;// = new FileInfo(sourceName);
CodeDomProvider provider = null;
bool compileOk = false;
// Compile Executable
public bool CompileExecutable(String sourceName)
{
sourceFile = new FileInfo(sourceName);
I_GetProvider(sourceFile);
if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".CS")
{
provider = CodeDomProvider.CreateProvider("CSharp");
//return "CSharp";
}
if (provider != null)
{
// Format the executable file name.
// Build the output assembly path using the current directory
// and _cs.exe or _vb.exe.
String exeName = String.Format(#"{0}\{1}.exe",
System.Environment.CurrentDirectory,
sourceFile.Name.Replace(".", "_"));
string dllName = String.Format(#"{0}\{1}.dll", System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_"));
CompilerParameters cp = new CompilerParameters();
// Generate an executable instead of a class library.
cp.GenerateExecutable = true;
// Specify the assembly file name to generate.
cp.OutputAssembly = exeName;
// Save the assembly as a physical file.
cp.GenerateInMemory = false;
// Set whether to treat all warnings as errors.
cp.TreatWarningsAsErrors = false;
// Invoke compilation of the source file.
CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName);
string temp;
if (cr.Errors.Count > 0)
{
// Display compilation errors.
temp = sourceName + "\n" + cr.PathToAssembly;
foreach (CompilerError ce in cr.Errors)
{
temp += "\nError:" + ce.ToString();
}
System.Windows.Forms.MessageBox.Show(temp, "dotCompiler Error:", System.Windows.Forms.MessageBoxButtons.OK);
}
else
{
// Display a successful compilation message.
//Console.WriteLine("Source {0} built into {1} successfully.",sourceName, cr.PathToAssembly);
System.Windows.Forms.MessageBox.Show("Solution build sucessfully..\n\n" + sourceName + "\n" + cr.PathToAssembly,"dotCompiler:)",System.Windows.Forms.MessageBoxButtons.OK);
}
// Return the results of the compilation.
if (cr.Errors.Count > 0)
{
compileOk = false;
}
else
{
compileOk = true;
}
}
return compileOk;
}
private void I_GetProvider(FileInfo sourceFile)
{
// Select the code provider based on the input file extension.
if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".CS")
{
provider = CodeDomProvider.CreateProvider("CSharp");
}
else if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".VB")
{
provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VisualBasic");
}
else
{
//Console.WriteLine("Source file must have a .cs or .vb extension");
//_Notify("Error:", "Source file must have a .cs or .vb extension", ToolTipIcon.Error);
System.Windows.Forms.MessageBox.Show(
"Source file must have *.cs or *.vb extension", "dotCompiler Error",
System.Windows.Forms.MessageBoxButtons.OK);
}
}
private string I_GetProvider_RetStr(FileInfo sourceFile)
{
// Select the code provider based on the input file extension.
if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".CS")
{
provider = CodeDomProvider.CreateProvider("CSharp");
return "CSharp";
}
else if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".VB")
{
provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VisualBasic");
return "VisualBasic";
}
else
{
//Console.WriteLine("Source file must have a .cs or .vb extension");
//_Notify("Error:", "Source file must have a .cs or .vb extension", ToolTipIcon.Error);
return "Source file must have *.cs or *.vb extension";
}
}
public bool CompileDll(String sourceName)
{
sourceFile = new FileInfo(sourceName);
I_GetProvider(sourceFile);
if (provider != null)
{
// Format the executable file name.
// Build the output assembly path using the current directory
// and _cs.exe or _vb.exe.
String exeName = String.Format(#"{0}\{1}.exe",
System.Environment.CurrentDirectory,
sourceFile.Name.Replace(".", "_"));
string dllName = String.Format(#"{0}\{1}.dll", System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_"));
CompilerParameters cp = new CompilerParameters();
// Generate an executable instead of a class library.
cp.GenerateExecutable = false;
// Specify the assembly file name to generate.
cp.OutputAssembly = dllName;
// Save the assembly as a physical file.
cp.GenerateInMemory = false;
// Set whether to treat all warnings as errors.
cp.TreatWarningsAsErrors = false;
// Invoke compilation of the source file.
CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName);
string temp;
if (cr.Errors.Count > 0)
{
// Display compilation errors.
temp = "compiling " + sourceName + " to " + cr.PathToAssembly;
foreach (CompilerError ce in cr.Errors)
{
temp += "\nError:" + ce.ToString();
}
System.Windows.Forms.MessageBox.Show(temp, "dotCompiler Error:", System.Windows.Forms.MessageBoxButtons.OK);
}
else
{
// Display a successful compilation message.
//Console.WriteLine("Source {0} built into {1} successfully.",sourceName, cr.PathToAssembly);
System.Windows.Forms.MessageBox.Show("Solution build sucessfully..\n\n" + sourceName + "\n" + cr.PathToAssembly, "dotCompiler:)", System.Windows.Forms.MessageBoxButtons.OK);
}
// Return the results of the compilation.
if (cr.Errors.Count > 0)
{
compileOk = false;
}
else
{
compileOk = true;
}
}
return compileOk;
}
}
}
string sourceCode = #"
public class Test
{
public void Hello()
{
Console.Write(#'Hello');
}
}";
var compParms = new CompilerParameters{
GenerateExecutable = false,
GenerateInMemory = true
};
var csProvider = new CSharpCodeProvider();
CompilerResults compilerResults =
csProvider.CompileAssemblyFromSource(compParms, sourceCode);
object typeInstance =
compilerResults.CompiledAssembly.CreateInstance("Test");
MethodInfo mi = typeInstance.GetType().GetMethod("Hello");
mi.Invoke(typeInstance, null);
Console.ReadLine();

I can read and write from a txt file internal storage (documents folder) but cannot browse to that location because it doesn't exist

Alright so I've managed to read/write files programatically in C# in Xamarin Studio. And it's working on my device.
However, when I output the exact path that the file is being written to, to the console, that path doesn't even exist anywhere in the entire phone!!!!
How is that?
using System;
using System.IO;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace ToolbarSample
{
[Activity(Label = "ToolbarSample", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
string content = "Jason rules";
string filename = "file.txt";
var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.button);
TextView viewer = FindViewById<TextView>(Resource.Id.textView1);
if (File.Exists(documents + #"/" + filename))
{
string newContent = File.ReadAllText(documents + #"/" + filename);
if (viewer != null)
{
viewer.Text = newContent;
Console.WriteLine("File exists in: " + documents + #"/" + filename);
}
}
if (button != null)
{
button.Click += delegate
{
button.Enabled = false;
if (!Directory.Exists(documents))
{
viewer.Text = "Directory not found: " + documents;
}
else
{
Console.WriteLine("Directory exists.");
File.WriteAllText(documents + #"/" + filename, content);
if (!File.Exists(documents + #"/" + filename))
{
viewer.Text = "File not found: " + documents + #"/" + filename;
}
else
{
string newContent = File.ReadAllText(documents + #"/" + filename);
if (viewer != null)
{
viewer.Text = newContent;
Console.WriteLine("File exists in: " + documents + #"/" + filename);
}
}
}
};
}
}
}
}
The following gets outputted to the console upon successful read from internal sdcard:
Directory exists. File exists in:
/data/data/ToolbarSample.ToolbarSample/files/file.txt
But using (many different) file managers - all with root access - and hidden files being shown - I cannot navigate to that path because it does not exist. I even did a whole phone search for "file.txt" and not a single result showed up. Yet I am able to read that file whenever I open my app and click the button.
The file at the location you have specified does exist. You cannot access that location from your PC via USB and File Explorer, but you can access the location (and the file) if you use a good File Manager app like Root Explorer.
If you really want your users to be able to access these saved files, I'd suggest that you save these files to a better location so that the user can easily transfer files from their phone to the computer via USB.
It quite simple both Read/Write data from File .
public String ReadFileData()
{
var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filename = Path.Combine(path.ToString(), "loginSystem.txt");
String line;
objData = new List<UsersData>();
// Read the file and display it line by line.
StreamReader file = new StreamReader(filename);
while ((line = file.ReadLine()) != null)
{
string[] words = line.Split(',');
if (words.Length != 1)
objData.Add(new UsersData(words[0], words[1], words[2]));
}
file.Close();
return String.Empty;
}
Save data into file
private string SaveDataToSd(String FirstName, String Address, String Password)
{
var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filename = Path.Combine(path.ToString(), "loginSystem.txt");
String contents = FirstName + "," + Password + "," + Address;
try
{
using (StreamWriter data_file = new StreamWriter(filename, true))
{
data_file.WriteLine(contents);
}
return contents;
}
catch (Exception ex)
{
RunOnUiThread(() =>
{
var builder = new AlertDialog.Builder(this);
builder.SetMessage(ex.InnerException + "Saving file went wrong");
builder.SetTitle("Unable to save file");
builder.Show();
});
return String.Empty;
}
}

Unable to Uninstall SIlverlight Out Of Browser Application Programatically

I'm trying to remove a Silverlight Out Of Browser app programatically passing the arguments to sllauncher in following this post: http://timheuer.com/blog/archive/2010/03/25/using-sllauncher-for-silent-install-silverlight-application.aspx However it won't uninstall the app when given the origin.
It turns out that when you have an automatically updating Out-Of-Browser application, Silverlight stamps each application Uri with a time stamp that can be found in the application's folder in the C:\Users\Trevor\AppData\Local\Microsoft\Silverlight\OutOfBrowser(AppFolderName) metadata file. So to facilitate the removal of our app in preparation for our new one, I implemented the following:
UninstallExisting(GetInstalledAppUri()); // This is how it's called
//This is the two method's implementation
// TODO: Change to your app name.
const string appName = "YourAppNameHere";
static string silverlightOutOfBrowserFolder =
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
+ #"\Microsoft\Silverlight\OutOfBrowser";
private static string GetInstalledAppUri()
{
string xapFolderPath = Path.Combine(silverlightOutOfBrowserFolder, GetXapFolder());
string[] lines = File.ReadAllLines(Path.Combine(xapFolderPath, "metadata"), Encoding.Unicode);
string finalAppUriLine = lines.First(i => i.Contains("FinalAppUri="));
return "\"" + finalAppUriLine.Replace("FinalAppUri=", "") + "\"";
}
private static string GetXapFolder()
{
string AppXapFolder = "";
foreach (var dir in Directory.GetDirectories(silverlightOutOfBrowserFolder))
{
if (dir.Contains(appName))
{
AppXapFolder = dir;
}
}
return AppXapFolder ;
}
private static string silverlightExe
{
get
{
return Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
#"Microsoft Silverlight\sllauncher.exe");
}
}
private static void UninstallExisting(string xapUriToRemove)
{
string installArgs = "/uninstall" + " /origin:" + xapUriToRemove;
ProcessStartInfo pstart = new ProcessStartInfo(silverlightExe, installArgs);
Process p = new Process();
pstart.UseShellExecute = false;
p.StartInfo = pstart;
p.Start();
p.WaitForExit();
}
I hope this serves to save someone else the hours of time it took me to figure out about the metadata file and all the peculiarities of sllauncher.exe

how to prevent to open in console my dynamically generated exe

I am working in c# 4.0, i want to generate an executable file dynamically, so i used Code Dome, but when i executes it open in console and after then my form displays, i want to generate winform executable file. How can i achieve my aim. the code is below :
string Code = #"
using System;
using System.Windows.Forms;
namespace CSBSS
{
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());
}
}
public class Form1 : Form
{
}
}
";
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
string tempFolder = #"..\DynamicOutput";
string Output = System.IO.Path.Combine(tempFolder, #"CSBSS.exe");
if (!System.IO.Directory.Exists(tempFolder))
{
System.IO.Directory.CreateDirectory(tempFolder);
}
else
{
if (System.IO.File.Exists(Output)) System.IO.File.Delete(Output);
}
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
parameters.TempFiles = new TempFileCollection(tempFolder, false);
//Make sure we generate an exe.
parameters.GenerateExecutable = true;
parameters.GenerateInMemory = false;
parameters.OutputAssembly = Output;
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, Code);
string OutputMsg = "";
if (results.Errors.Count > 0)
{
string msgDescr = "";
foreach (CompilerError CompErr in results.Errors)
{
msgDescr += "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
OutputMsg = #"Error occured while generating executable file, please check following internal error
" + msgDescr;
//return false;
}
else
{
OutputMsg = "Executable file has been generated successfully.";
}
Specify the output type to be a Windows application by using the CompilerOptions:
parameters.CompilerOptions = "/target:winexe";

Categories

Resources