C Sharp - auto-mate/CheatSheetWiki GitHub Wiki
Async
Automation
Basic DLL
Cast Convert
Code As A Library
Constants in a Class
CurlIsh
Datagrid AddColumn
Datagrid Add Data Manually
Datagrid Color
Datagrid Filter
Directory List Recursive
Dotnet Browser and VSC Debug Attach
Encryption
Excel Example
Exit
File List Recursive
Fill Unconnected Datagrid
Forms From Form Project Debug Help
Forms From Scratch
Image in picture box
if debug
LDAP
Library Code
List Top Level Window Handles
Message Box
Multiple Code Files
Printing
Selenium Example
Settings Multiple Files
Simple Crypto
SQL Connection
Start External App
Switch
Table Array With Add as SQL Table Returns List<String[]>
Text Box And Rich Text Box
WebClient
WinApi
WMI WMIC
VS2015
- In VS 2015 Start a "New Project" as a C# Classic Class Library
- Rename The NameSpace/Class as desired
- Add functions e.g. e.g. public static int fName() {...; return n;}
- In "Solution Explorer" right click "Add" and "New Project" and "Test" and "Unit Test Project"
- In "Solution Explorer" under "New Test Project" right click Add Ref (add the ClassLib we made)
- Add code under "public void TestMethod()" NB Console.write() or similar to see results
- Test > Run > All Tests to test the dll
****Class1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace My_NA
{
public class My_CL
{
public static int retTen()
{
return 10;
}
}
}
****UnitTest1.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
//UTP Named on Creating Test
namespace UTP
{
[TestClass]
public class UnitTestMy //Edited to UnitTestMy
{
[TestMethod]
public void TestMethod1()
{
int z=My_NA.My_CL.retTen();
Console.Write(z);
}
}
}
void Main()
{
RecDir("C:\\TEMP"); // Directory To Walk
}
void RecDir(string root) {
foreach (string dir in System.IO.Directory.EnumerateDirectories(root))
{
try {RecDir(dir);} // Skips Unauthorised Access Error
catch {}
Console.WriteLine(dir);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Core;
using Microsoft.Office.Interop;
using Microsoft.Vbe.Interop;
namespace CS_Excel
{
class Program
{
static void Main(string[] args)
{
Microsoft.Office.Interop.Excel.Application xls = new Microsoft.Office.Interop.Excel.Application();
xls.Application.Visible = true;
System.Threading.Thread.Sleep(7000);
xls.Application.Workbooks.Open("C:\\users\\username\\desktop\\someFile.xlsx");
xls.Workbooks.Close();
xls.Application.Quit();
}
}
}
Based on Extending Directory List Recursive
void Main()
{
RecDir("C:\\TEMP");
}
void RecDir(string root) {
foreach (string dir in System.IO.Directory.EnumerateDirectories(root))
{
try {RecDir(dir);}
catch {}
DirFileList(dir);
}
}
void DirFileList(string dir) {
foreach (string fName in System.IO.Directory.EnumerateFiles(dir))
{
Console.WriteLine(fName);
}
}
using System;
using System.Drawing; // ** Required For Color
// ### If Console Type App then Change to Windows App in Properties and re build! Hides Terminal ###
namespace ConsoleApplication // ** Here Originally set up as Console App.[default name]
{
class Program
{
// ### Create a Class with Preset Colours for App [Here Its Just The Exit Button] ###
public class AppColors {
public Color Exit_Fore = Color.Black;
public Color Exit_Back = Color.LightGray;
}
// ### Main Entry Point [Note String[] and args] ###
static void Main(string[] args)
{
// ### Create Object "Ob" containing App Colors ###
AppColors Ob = new AppColors();
// ### Make New Form ###
System.Windows.Forms.Form frm = new System.Windows.Forms.Form();
// ### Make New Button Set Details and Add to Form ###
System.Windows.Forms.Button btn1 = new System.Windows.Forms.Button();
btn1.Text = "Exit";
btn1.Left = 100;
btn1.Top = 100;
btn1.Width = 150;
btn1.Height = 50;
btn1.BackColor = Ob.Exit_Back; // ** Use AppColors Background
btn1.ForeColor = Ob.Exit_Fore; // ** Use AppColors Foreground
btn1.MouseHover += ButtonHover; // ** Call Action on Mouse Hover
btn1.MouseLeave += ButtonHoverEnd; // ** Call Action on Mouse Leave
btn1.Click += Btn1_Click; // ** Call Click Action. ## Note += to handler function ##
frm.Controls.Add(btn1); // ** ADD BUTTON
// ### Make New Button Set Details and Add to Form ###
System.Windows.Forms.Button btn2 = new System.Windows.Forms.Button();
btn2.Text = "Show Message Box";
btn2.Left = 100;
btn2.Top = 200;
btn2.Width = 150;
btn2.Height = 50;
btn2.Click += (sender,btn2Args) => // ** Optional Click Method
{
System.Windows.Forms.MessageBox.Show("OK");
};
frm.Controls.Add(btn2); // ** ADD BUTTON
// Change some Form Settings
frm.Text = "Window Title";
frm.Width = 600;
frm.Height = 600;
// Show Form (use Dialog else closes immediately!)
frm.ShowDialog();
}
private static void Btn1_Click(object sender, EventArgs e)
{
// ### Close Active Form of Application ###
System.Windows.Forms.Form.ActiveForm.Close();
}
private static void ButtonHover(object sender, EventArgs e)
{
// ### Note brackets around object on RHS ###
System.Windows.Forms.Control btn = (System.Windows.Forms.Control) sender;
btn.BackColor = Color.Red;
}
private static void ButtonHoverEnd(object sender, EventArgs e )
{
AppColors Ob = new AppColors();
System.Windows.Forms.Control btn = (System.Windows.Forms.Control) sender;
if (btn.Text == "Exit")
{
btn.BackColor = Ob.Exit_Back;
btn.ForeColor = Ob.Exit_Fore;
}
}
}
}
System.Windows.Forms.MessageBox.Show("Hello");
Start a new console project and run NuGet Install-Package Selenium.WebDriver -Version 3.12.0
Load ChromeDriver For Relevent version of Chrome See details on ChromeDriver web page.
Example opens BBC and Clicks list item for Weather... Nb Thread.Sleep
NB Run in comand line as C:...\dotnet projectname.dll
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumExample01
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Selenium Example!");
IWebDriver MyDriver = new ChromeDriver(@"C:\ChromeDriverWin32");
MyDriver.Navigate().GoToUrl("http://www.bbc.co.uk");
MyDriver.FindElements(By.ClassName("orb-nav-weather"))[0].Click();
System.Threading.Thread.Sleep(3000);
MyDriver.Quit();
}
}
}
using System;
using System.Net;
namespace CurlIsh
{
class Program
{
static void Main(string[] args) {
/* Returns Initial Returned HTML NO JavaScript Is Run!!! */
WebClient NewWc = new WebClient();
String HTMLListing;
HTMLListing=NewWc.DownloadString(args[0]);
Console.Write(HTMLListing);
Console.WriteLine("Code For " + args[0] + "\nPress Return To Close");
Console.Read();
}
}
}
// Make New Text Box; Set Details and Add to Form
System.Windows.Forms.TextBox TB = new System.Windows.Forms.TextBox();
TB.Top = 300;
TB.Left = 100;
TB.Height = 50;
TB.Width = 300;
frm.Controls.Add(TB);
// Make New Rich Text Box; Set Details and Add to Form
System.Windows.Forms.RichTextBox RTB = new System.Windows.Forms.RichTextBox();
RTB.Top = 400;
RTB.Left = 100;
RTB.Height = 300;
RTB.Width = 300;
frm.Controls.Add(RTB);
// File Initial.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyNameSpaceName
{
public partial class Form1 : Form
{
\\...Statements etc
}
}
// NewFile.cs
namespace MyNameSpaceName
{
public partial class Form1
{
\\...Statements etc
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace YourProjectName
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//A form class has been created as Form 1 below is the standard Run method
//Application.Run(new Form1());
// Run this way so that the form can be viewed as local variable FF in debug....
Form1 FF = new Form1();
FF.ShowDialog();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CS_code_decode
{
class Program
{
const int paddStartCount = 50;
const int paddEndCount = 50;
static void Main(string[] args)
{
if ((args).Length != 3)
{
Console.Write("Simple (En)(De)cryption: Usage 3 parameters:\n" +
"E or D for (E)ncode or (D)ecode\n" +
"FE for File(Encode) or FD for File(Decode)" +
"Key as string in \"\"\n" +
"String to Encode or Decode in \"\"\n" +
"by A Harper");
}
else
{
string key = args[ 1 ];
string secret = args[ 2 ];
char toEncChar;
int toEncCharInt;
string toDecChar;
int toDecCharInt;
int decodedInt;
int keyPosition = 0;
int keyLength = args[1].Length;
char offsetChar;
int offsetInt;
string coded = "";
string decoded = "";
string A2 = args[2];
if (args[0] == "FE") {
A2 = System.IO.File.ReadAllText(args[2]);
secret = A2;
}
if (args[0] == "E" || args[0] == "FE")
{
// Make Padding
string padd = randomString(paddStartCount + paddEndCount);
string paddStart = padd.Substring(0, paddStartCount * 2);
string paddEnd = padd.Substring(paddStartCount * 2, paddEndCount * 2);
// Loop String To Encrypt
int strToCodeLen = A2.Length;
for (int n = 0; n < strToCodeLen; n++)
{
// Move to start of key string if past end
if (keyPosition >= keyLength) { keyPosition = 0; }
// Determine Offset
offsetChar = Convert.ToChar(key.Substring(keyPosition, 1));
offsetInt = Convert.ToByte(offsetChar);
// Get Char to Encode
toEncChar = Convert.ToChar(secret.Substring(n, 1));
toEncCharInt = Convert.ToByte(toEncChar);
// Encode only to characters 255
if ((toEncCharInt + offsetInt) > 0xFF)
{
offsetInt = offsetInt - 0xFF;
}
//Encode
coded = coded + (toEncCharInt + offsetInt).ToString("X2");
keyPosition = keyPosition + 1;
}
if (args[0] == "E") { Console.Write(paddStart + coded + paddEnd); }
if (args[0] == "FE") { System.IO.File.WriteAllText(args[2] + ".enc",paddStart + coded + paddEnd); }
}
else if (args[0] == "D" || args[0] == "FD")
{
if (args[0] == "FD")
{
secret = System.IO.File.ReadAllText(args[2]);
}
int actlen = secret.Length - paddStartCount * 2 - paddEndCount * 2;
coded = secret.Substring(paddStartCount * 2, actlen);
//Console.Write(coded);
for (int n = 0; n < coded.Length; n = n + 2)
{
// Move to start of key string if past end
if (keyPosition >= keyLength) { keyPosition = 0; }
// Determine Offset
offsetChar = Convert.ToChar(key.Substring(keyPosition, 1));
offsetInt = Convert.ToByte(offsetChar);
// Get Char to DeEncode
toDecChar = coded.Substring(n, 2);
toDecCharInt = Convert.ToInt32(toDecChar, 16);
// Encode only to characters 32 to 126
if (toDecCharInt - offsetInt <= 0)
{
// offsetInt = -offsetInt + 255;
decodedInt = toDecCharInt - offsetInt + 255;
}
else
{
decodedInt = toDecCharInt - offsetInt;
}
//Decode
//decoded = decoded + Convert.ToChar(toDecCharInt - offsetInt);
decoded = decoded + Convert.ToChar(decodedInt);
keyPosition = keyPosition + 1;
}
if (args[0] == "D")
{ Console.Write(decoded); }
if (args[0] == "FD")
{ System.IO.File.WriteAllText( args[2].Replace(".enc","") , decoded); }
}
else
{
Console.Write("First Parameter Must be E or D!\n");
Console.Write(args[0] + "\n");
Console.Write(args[1] + "\n");
Console.Write(A2 + "\n");
}
}
// Generate a random string with a given size
string randomString(int slen)
{
Random random = new Random();
string chx="";
for (int i = 0; i < slen; i++)
{
chx = chx + Convert.ToInt64( (255 * random.NextDouble()) ).ToString("X2") ;
}
return chx;
}
}
}
}
Example to loop through and find windows with given text
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Runtime.InteropServices;
using System.Windows.Automation;
namespace Win32Application
{
public class Win32
{
[DllImport("User32.dll")]
public static extern Int32 FindWindow(String lpClassName, String lpWindowName);
[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);
[DllImport("User32.dll")]
public static extern Boolean EnumChildWindows(int hWndParent, Delegate lpEnumFunc, int lParam);
[DllImport("User32.dll")]
public static extern Int32 GetWindowText(int hWnd, StringBuilder s, int nMaxCount);
[DllImport("User32.dll")]
public static extern Int32 GetWindowTextLength(int hwnd);
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
public static extern int GetDesktopWindow();
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lclassName, string windowTitle);
}
}
namespace myApp
{
class Program
{
static void Main(string[] args)
{
Int32 txtLen;
IntPtr newHWND = new IntPtr();
bool foundString = false;
// Get Window Handle and its pointer
////////////////////////////////////
string MainWindowSearchString = "<SOME WINDOW TEXT>"
Int32 hwnd = Win32Application.Win32.FindWindow(null, MainWindowSearchString);
IntPtr HWND = new IntPtr(hwnd);
do
{
newHWND = Win32Application.Win32.FindWindowEx(HWND, newHWND, null, null);
if (newHWND.ToString() != "0")
{
txtLen = Win32Application.Win32.GetWindowTextLength(newHWND.ToInt32());
StringBuilder title = new StringBuilder(txtLen + 1);
Win32Application.Win32.GetWindowText(newHWND.ToInt32(), title, txtLen + 1);
if (title.ToString().Length > 0)
{
string ttl = "";
string mr = "";
for (int n = 0; n < title.ToString().Length; n++)
{
if (!title.ToString()[n].Equals('\\'))
{
ttl += title.ToString()[n];
}
}
for (int n = 0; n < MatchRequest.Length; n++)
{
if (!MatchRequest[n].Equals('\\'))
{
mr += MatchRequest[n];
}
}
if (ttl.Contains(mr))
{
foundString = true;
}
}
}
} while (newHWND.ToString() != "0");
Console.WriteLine(foundString);
Console.ReadKey();
}
}
}
Might need to right click on "dependencies" and "add project reference" browse and add "UIAutomationClient.dll" and "UIAutomationTypes.dll"
Setting the Root Element
AutomationElement RootEle = AutomationElement.RootElement;
Finding Children of the root
AutomationElementCollection RootChldrn = RootEle.FindAll(System.Windows.Automation.TreeScope.Children, Condition.TrueCondition);
Loop Children to find app
for (n = 0; n < RootChldrn.Count; n++)
{
ElemName = RootChldrn[n].Current.Name;
if (ElemName.Contains("<SomeSearchString>"))
{
RootChldFound = true;
break;
}
}
Loop Apps Children to Find Target
(NB TreeScope.Subtree include the item itself children and all decendants)
AutomationElementCollection TargetElCol = RootChldrn[n].FindAll(TreeScope.Subtree, Condition.TrueCondition);
for (p = 0; p < TargetElCol.Count; p++)
{
TargetElColItemName = TargetElCol[p].Current.Name;
if (TargetElColItemName.Contains("<SOMETEXT>"))
{
TargetElFound = true;
break;
}
}
Loop Apps Children to Find Target and Invoke a button called Close
(NB TreeScope.Subtree include the item itself children and all decendants)
AutomationElementCollection TargetElCol = RootChldrn[n].FindAll(TreeScope.Subtree, Condition.TrueCondition);
for (p = 0; p < TargetElCol.Count; p++)
{
if (TargetElCol[p].Current.IsEnabled &&
TargetElCol[p].Current.ClassName=="Button" &&
TargetElCol[p].Current.Name == "Close")
{
InvokePattern IP = TargetElCol[p].GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
IP.Invoke();
}
}
Add References to
UIAutomationClient
UIAutomationClientsideProviders
UIAutomationProvider
UIAutomationTypes
Below reads window titles from two files else the CMD window includes the searched for strings and it finds the command window rather than the intended target.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Runtime.InteropServices;
using System.Windows.Automation;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
if (args.Count() == 0)
{
Console.Write(TestFunc());
}
else
{
Console.Write(
"Usage\n" +
" : save <Part Of Top Window Title> in a file called \"winstrMainParam.txt\"\n" +
" : save <Part Of Sub Window Title> in a file called \"winstrSecondParam.txt\"\n" +
" now run WinStrExists.exe in the command line.\n" +
" NB Case sensitive");
}
}
static string TestFunc()
{
string z = "";
int n = 0;
bool mainFound = false;
bool subFound = false;
string MainWindowSearchString = "";
string MatchRequest = "";
if (System.IO.File.Exists("winstrMainParam.txt"))
{
MainWindowSearchString = System.IO.File.ReadAllText("winstrMainParam.txt");
}
else
{
return "No file winstrMainParam.txt";
}
if (System.IO.File.Exists("winstrSecondParam.txt"))
{
MatchRequest = System.IO.File.ReadAllText("winstrSecondParam.txt");
}
else
{
return "No file winstrSecondParam.txt";
}
AutomationElement x = AutomationElement.RootElement;
AutomationElementCollection y = x.FindAll(System.Windows.Automation.TreeScope.Children, Condition.TrueCondition);
for (n = 0; n < y.Count; n++)
{
z = y[n].Current.Name;
if (z.Contains(MainWindowSearchString))
{
mainFound = true;
break;
}
}
if (mainFound)
{
AutomationElementCollection a = y[n].FindAll(TreeScope.Subtree, Condition.TrueCondition);
string w = "";
for (n = 0; n < a.Count; n++)
{
w = a[n].Current.Name;
if (w.Contains(MatchRequest))
{
subFound = true;
break;
}
}
if (subFound)
{
return "Matched As App [" + z + "] Window [" + w + "]";
}
else
{
return "NOT FOUND SECOND";
}
}
return "NOT FOUND MAIN";
}
}
}
// Form
System.Windows.Forms.Application.Exit();
// Console
System.Environment.Exit(0);
int myInt = Convert.ToInt64(myString);
System.Diagnostics.Process.Start("http://bbc.co.uk");
With options - create process vs and run cscript with parameters. NB use or credentials
System.Diagnostics.Process vs = new System.Diagnostics.Process();
vs.StartInfo.RedirectStandardError = true;
vs.StartInfo.RedirectStandardOutput = true;
vs.StartInfo.FileName = "cscript";
vs.StartInfo.WorkingDirectory = constants.appDir; // string - here from class constants
vs.StartInfo.Arguments = script + " " + arg; // string variables used but not shown in this code
vs.StartInfo.UseShellExecute = false;
vs.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
vs.StartInfo.CreateNoWindow = true;
// credentials
vs.StartInfo.UserName = "<WINDOWS_UID>";
vs.StartInfo.PasswordInClearText = getPassword(); // String from function
vs.StartInfo.Domain = "<WINDOWS_DOMAIN>";
vs.Start();
// Dont continue until vbs scriot is complete
vs.WaitForExit();
Reading Command Output:
ArrayList cmdOutputData = new ArrayList();
while (!vs.StandardOutput.EndOfStream)
{
cmdOutputData.Add(vs.StandardOutput.ReadLine());
}
private string getPassword() {
string pw = "";
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=<SERVER_NAME>;Initial Catalog=<DATABASE_NAME>;Integrated Security=SSPI;";
con.Open();
System.Data.SqlClient.SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT CONVERT(varchar, DECRYPTBYPASSPHRASE('<PASSPHRASE>',<fieldWithEncryptedPassword>)) from <TABLENAME>";
System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
pw = dr.GetValue(0).ToString().Trim();
}
con.Close();
return pw;
}
static class constants
{
public const string passPhase = "<SOME_PASS_PHRASE>";
public const string appDir = @"C:\Temp";
}
/* EXAMPLE PRINTS ABARCODE PNG FILE */
// create print dialog to choose printer etc and
// print preview dialog to confirm happy before print
PrintDialog pDlg = new PrintDialog();
PrintPreviewDialog ppDlg = new PrintPreviewDialog();
// show print dialog
pDlg.ShowDialog();
// create a PrintDocument
System.Drawing.Printing.PrintDocument prtDoc = new System.Drawing.Printing.PrintDocument();
// add data of what to print and parameters
prtDoc.PrintPage += (a,b) =>
{
// add the image from a file
Image bCodeLbl = Image.FromFile(@"<PATH TO FILE>");
// add 3 points to align and size image
System.Drawing.Point[] MyPoints = new System.Drawing.Point[] {
new System.Drawing.Point{X = 10 ,Y = 10 },
new System.Drawing.Point{X = 500 ,Y = 10 },
new System.Drawing.Point{X = 10 ,Y = 500 },
};
// create the data for printing from the image and coordinates)
b.Graphics.DrawImage(bCodeLbl, MyPoints);
};
// can use prtDoc.PrinterSettings.PrinterName to confirm/check printer
// tell print preview what document to use and display for user to OK or reject
ppDlg.Document = prtDoc;
ppDlg.Show();
// Address for Data Request
string webAddr = "http://<SOME_WEB_ADDRESS>";
// create web client to mange request
System.Net.WebClient wc = new System.Net.WebClient();
// download reply data as string
string dl = wc.DownloadString(webAddr);
// If there is an image say a label you wish to extract and save
// get start position of base64 image string
int imgTxtStart = dl.IndexOf("data:image/png;base64,") + 22;
// get length of base64 image string
int imgTxtLen = dl.IndexOf("<STRING AT END OF IMAGE>") - imgTxtStart;
// extract the base64 image string
string imgTxt = dl.Substring(imgTxtStart, imgTxtLen - <INT AS REQUIRED>);
// convert string to bytes
byte[] imBytes = Convert.FromBase64String(imgTxt);
// create memory stream to hold image byte data
System.IO.MemoryStream ms = new System.IO.MemoryStream(imBytes);
// create image from byte string
Image label = Image.FromStream(ms);
// save label image
label.Save("C:\\temp\\label.png");
String Res;
Switch (<SOME_VAR>)
{
case "<SOME_VAL_VAR_MIGHT_HOLD>":
<SOME_CMD E.G> Res = 1;
break;
case "<SOME_VAL_VAR_MIGHT_HOLD>":
<SOME_CMD E.G> Res = 2;
break;
// etc
}
// for picture box called imgLabel
this.imgLabel.ImageLocation = "<SOME IMAGE FILE LOCATION OK WITH PNG>";
this.imgLabel.Refresh();
In the Menu select Project/Add Existing Item then add .cs file (will be copied to your project )
Example of Library File ( Note PUBLIC statement for function )
namespace HelloWorld
{
class Hello {
public static void ConsoleOut()
{
System.Console.WriteLine("Hello World");
}
}
}
Main Program:
using System; // etc
namespace <WhateverYouWant>
{
class Program
{
static void Main(string[] args) {
HelloWorld.Hello.ConsoleOut();
Console.ReadKey();
}
}
}
WMI PDF Available here
using System.Management; // May need to browse and add manually
ManagementObjectSearcher MOS = new ManagementObjectSearcher( "SELECT * FROM Win32_Process" );
// Loop Processes to find this process
foreach ( ManagementObject MO in MOS.Get() )
{
//Check for this process and record Parent when found
if ( MO["Name"].ToString() == "<NAME_OF_THIS_EXE>")
{
Parent = MO["ParentProcessId"].ToString();
}
}
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace simpleSymetricEncryption
{
class Program
{
// Example Works in .Net5 !!!
//===========================
// 16byte = 128bit (Must Be 16 byte change below as required)
static private byte[] IV = { 0x01, 0x02, 0x01, 0x02, 0x03, 0x04, 0x02, 0xFF,
0x01, 0x02, 0x01, 0x02, 0x03, 0x04, 0x02, 0x03};
static void Main(string[] args) {
// Use our Encrypt method to return encrypted bytes for our text string using our key "MySecret".
byte[] EncBytes = Encrypt("Hello World :-)","MySecret");
// Convert our encrypted bytes to base 64 so they can be managed as a string.
string EncString = Convert.ToBase64String(EncBytes);
// Show our final encrypted string
Console.WriteLine(EncString);
// Use our Decrypt method to return our original string in base64 string format using our key "MySecret".
Console.WriteLine(Decrypt(EncString, "MySecret"));
}
static public byte[] PassTo16Byte(string Pass)
{
// The key must be 16 bytes long so we must truncate or extend anything not 16 bytes long
if (Pass.Length > 16)
{
// Reduce over long key
Pass = Pass.Substring(0, 16);
}
else if (Pass.Length < 16)
{
// Increase short key by repeating it unlit its a 16 long string
int InitPassLen = Pass.Length;
int Padd = (16 - Pass.Length);
int passPos = 0;
for (int i = 0; i < Padd; i++) {
Pass += Pass[passPos];
passPos += 1;
if (passPos >= InitPassLen) {
passPos = 0;
}
}
}
// Return the Key in Byte array format
return Encoding.UTF8.GetBytes(Pass);
}
static public byte[] Encrypt(string clearText,string key)
{
// Create an AES encryption object
using Aes aes = Aes.Create();
// Set it to use our 16 bytes key by sending our key to PassTo16Byte
aes.Key = PassTo16Byte(key);
// Set it to use our 16 bytes random Initiation vector (must be the same in encode and decode functions)
aes.IV = IV;
// Confirm the std padding mode (must be the same in encode and decode functions)
aes.Padding = PaddingMode.PKCS7;
// Create a memory stream to hold the encrypted data
MemoryStream output = new();
// Create a CryptoStream as an Encryptor in Write mode set to write to our memory stream
CryptoStream cryptoStream = new(output, aes.CreateEncryptor(), CryptoStreamMode.Write);
// Use the .Write command to read bytes from our converted to byte clearText and write encryted data to our output stream
cryptoStream.Write(Encoding.Unicode.GetBytes(clearText));
// ensure all data is flushed to the stream before returning
cryptoStream.FlushFinalBlock();
// return the encrpted stream as a byte array
return output.ToArray();
}
static public string Decrypt(string crypt64Text,string key)
{
// Create an AES encryption object
using Aes aes = Aes.Create();
// Set it to use our 16 bytes key by sending our key to PassTo16Byte
aes.Key = PassTo16Byte(key);
// Set it to use our 16 bytes random Initiation vector (must be the same in encode and decode functions)
aes.IV = IV;
// Confirm the std padding mode (must be the same in encode and decode functions)
aes.Padding = PaddingMode.PKCS7;
// get the input data and convert from B64 to Bytes
byte[] inputBytes = Convert.FromBase64String(crypt64Text);
// create a memory stream for the input data and load with the inputBytes
using MemoryStream input = new(inputBytes);
// Create a CryptoStream as an Dencryptor in Read mode set to Read to our input memory stream
using CryptoStream cryptoStream = new(input, aes.CreateDecryptor(), CryptoStreamMode.Read);
// create an empty memory stream for the output data
using MemoryStream output = new();
// use try to catch error on bad passkey etc
try
{
// write data from our decrypting cryptoStream to our output stream
cryptoStream.CopyTo(output);
}
catch (Exception)
{
return "Error!";
}
// if all is ok return the output stream converted to a byte array and finally our original UTF string
return Encoding.Unicode.GetString(output.ToArray());
}
}
}
using System; // Requires System
using System.Runtime.InteropServices; // Requires System.Runtime.InteropServices
namespace WinList // Any Name
{
// Add Delegate(Pointer to method) in namespace (Name as reqiured, parameters c# version of winapi declared params)
public delegate bool MyCallBack(IntPtr hWnd, IntPtr lParam);
class Program
{
// Enter the dll to use with any parameters. NB this is OK as
[DllImport("user32.dll", CharSet = CharSet.Unicode)] // just [DllImport("user32.dll")] if required.
private static extern int EnumWindows(MyCallBack A, int B); // EnumWindows takes a callback pointer and an integer
// Our delegate is the pointer and declared here with the
static void Main(string[] args) // function declaration.
{
MyCallBack CallBackInstance = new MyCallBack(Program.ListHandles); // The call back is described but not set up
EnumWindows(CallBackInstance, 0); // it is created with the new <delegate>(function to use)
} // NB this function must have same inputs and outputs as the
// Delegate
public static bool ListHandles(IntPtr hwnd, IntPtr lParam)
{ // When EnumWindows is called our CallBackInstance is set to go to
Console.Write("Window handle is "); // ListHandles. It passes the handles here and this then writes them to the
Console.WriteLine(hwnd); // Console
return true;
}
}
}
To Add The Title add the following
using System.Text; // For String Builder
// ........
class Program
{
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);
// ........
// in List Handles use
Console.Write("Window handle is ");
StringBuilder sb = new StringBuilder(tLen + 1); // Create A StringBuilder of size +1 to catch WinText
GetWindowText(hwnd, sb, sb.Capacity ); // Get WinText into sb
Console.WriteLine(hwnd + ": " + sb.ToString());
If unable to create in VS, create a new windows forms app with
dotnet new winforms -lang c#
Add WebView2 with below (change version as required)
dotnet add package Microsoft.Web.Webview2 --version 1.0.2151.40
If debugging in VSC rather than VS, VSC debug seems to miss the loading of the webviewer. Run instead from the project root dir as
dotnet run --confguration Debug
Then attach to projectname.exe e.g it should be listed in attach list something like
c:\...\<project name>\bin\debug\net.....\<project name>.exe --confguration Debug
c# console (pick .net as multiple types) if wrong type some .net platforms don't show.
// command line accepts samAccountName as argument and returns pre @ sign part of "mail" property. Change <dc> values as required.
// remove Console.ReadLine(); unless debugging.
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LDAPQuery
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 1)
{
try
{
DirectoryEntry de = new DirectoryEntry("LDAP://dc=<SITE>,dc=<com/net/etc>");
DirectorySearcher ds = new DirectorySearcher("samAccountName=" + args[0]);
SearchResult res = ds.FindOne();
if (res == null)
{
Console.WriteLine("ERROR");
}
else
{
Console.WriteLine(res.Properties["mail"][0].ToString().Split('@')[0]);
}
ds.Dispose();
de.Close();
de.Dispose();
}
catch (Exception)
{
Console.WriteLine("ERROR");
}
} else
{
Console.WriteLine("ERROR ARGS != 1");
}
Console.ReadLine();
}
}
}
static public List<String[]> sqlData(string sql) {
string server = <SOME-SQL-SERVER>;
string db = <SOME-DB>;
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=" + server + ";Initial Catalog=" + db + ";Integrated Security=SSPI;";
con.Open();
System.Data.SqlClient.SqlCommand cmd = con.CreateCommand();
cmd.CommandText = sql;
System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
List<String> recordList = new List<String>();
List<String[]> table = new List<String[]>();
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
recordList.Add(
dr.GetSqlValue(i).ToString()
);
}
table.Add(recordList.ToArray());
recordList.Clear();
}
con.Close();
return table;
}
private void LoadDataGrid()
{
// add and size columns only if not already added
if (this.dataGridView1.ColumnCount == 0)
{
this.dataGridView1.Columns.Add("dbSkill", "Skill");
this.dataGridView1.Columns.Add("dbLevel", "Level");
this.dataGridView1.Columns[0].Width = 400;
this.dataGridView1.Columns[1].Width = 50;
}
// clear any prior rows
this.dataGridView1.Rows.Clear();
// e.g populate with data from sqlData() above
string sql= "SELECT * FROM <SOME-DB>";
List<String[]> retTable= sqlData(sql);
// loop data and write to table 1st and 2nd column data
for (int i = 0; i < retTable.Count; i++)
{
this.dataGridView1.Rows.Add(retTable[i][0], retTable[i][1]);
}
}
}
Run different code for DEBUG and RELEASE
#if DEBUG
Console.WriteLine("Mode=Debug");
#else
Console.WriteLine("Mode=Release");
#endif
To use multiple different settings files, 1st create additional settings files then name them e.g. SettingsLive.settings, SettingsQA.settings, SettingsTest.settings. Ensure the file you want to get used is renamed to Settings.settings then to use it do the following:
When renaming a file to Settings.settings (you may want to rename current Settings.settings to SettingsXXX.settings where XXX is Live, Qa or whatever.)
Delete content of the App.config file
Edit the now live Settings.settings file & save (this regenerates config file)
Start your App
Assuming dgsender is from an event where the sender id a datagrid and sender has cast to datagrid as dgsender e.g.
DataGridView dgSender = (DataGridView)sender;
Loop columns and update back color for the current row (refresh to apply)
for (int i = 0; i < dgSender.ColumnCount; i++)
{
dataGridMaster.Rows[(dgSender.CurrentCell.RowIndex)].Cells[i].Style.BackColor = Color.Orange;
}
dataGridMaster.Refresh();
// requires CurrencyManager to allow update dynamically
CurrencyManager cM = (CurrencyManager)BindingContext[<dataGridName>.DataSource];
cM.SuspendBinding();
// hide row 1
<dataGridName>.Rows[1].Visible = false;
cM.ResumeBinding();
Manually add a column.
DataGridViewColumn dGVColumn = new DataGridViewColumn();
// simple text col
dataGridView1.Columns.Add("123", "super");
// complex text col
DataGridViewColumn cN = new DataGridViewButtonColumn();
dataGridView1.Columns.Add(cN);
-- OR --
//! * make datagridview cell template
dGVColumn.CellTemplate = new DataGridViewTextBoxCell();
//! * add settings
dGVColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dGVColumn.HeaderText = "My Header";
//! * add column
this.<dataGridName>.Columns.Add(dGVColumn);
List<String[]> MyVar = <Some array of arrays>;
// loop list and add data to rows
for (int i = 0; i < MyVar.Count; i++)
{
this.<dataGridName>.Rows.Add(MyVar[i]);
}
Use async before public/private
use await (only in async function)
to use async in sync way use Task.Run( async() => <@@@YOUR_FUNCTION@@>() ).Result;
static public bool hasImgSync() {
return Task.Run(async () => await hasImg()).Result;
}
static async public Task<bool> hasImg()
{
String imgRef = "<@@@X@@@>.png";
string webAddressImg = "<@@@ROOT@@@>" + imgRef;
bool finalRes;
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(httpClientHandler);
HttpResponseMessage res = await client.GetAsync(webAddressImg);
if (res.IsSuccessStatusCode)
{
finalRes = true;
} else
{
finalRes = false;
}
client.Dispose();
return finalRes;
}