I am trying to connect to IBM remote MQ and I am facing this System.DllNotFoundException error . I built a simple console application using C# and wrote MQ connection code .
My code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IBM.WMQ;
using System.Diagnostics;
namespace MQMessageSender
{
public class MQTest
{
public static void Main()
{
ConnectMQ();
}
public static int ConnectMQ()
{
MQQueueManager queueManager;
MQQueue queue;
MQMessage queueMessage;
MQPutMessageOptions queuePutMessageOptions;
MQGetMessageOptions queueGetMessageOptions;
string QueueName;
string QueueManagerName;
string ChannelInfo;
string channelName;
string PortNumber;
string transportType;
string connectionName;
string message;
QueueManagerName = "******";
QueueName = "********";
ChannelInfo = "********/TCP/********(****)";
PortNumber = "****";
char[] separator = { '/' };
string[] ChannelParams;
ChannelParams = ChannelInfo.Split(separator);
channelName = ChannelInfo;
transportType = ChannelParams[1];
connectionName = ChannelParams[2];
String strReturn = "";
try
{
queueManager = new MQQueueManager(QueueManagerName,
channelName, connectionName);
strReturn = "Connected Successfully";
}
catch (MQException exp)
{
strReturn = "Exception: " + exp.Message;
}
Console.WriteLine(strReturn);
Console.WriteLine("Press any key to continue . . .");
Console.ReadLine();
return 0;
}
}
}
Can anyone help me with this . Mostly try block is generating this error . Any kind of information will help . Please help . Error screenshot is attached .
Related
So I have created a form to allow our Marketing team to restart a computer that displays a slideshow/important information for visitors etc
The plan is to deploy this to other user comptuers and then they can do one of the three following tasks:
Restart now
Timed/Scheduled restart
Cancel Timed/Scheduled restart
The application works fine on my computer just fine in debug and in build.
When installing on other people's computers it seems as if it is launching psexec but then not doing anything.
I added some catch exceptions in at which point it shows me the following error:
standardout has not been redirected
However when researching into this I seem to already have the code most people suggest to fix this issue.
My code is as below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace Media_Wall_Restart_Scheduler
{
public partial class frm_mediawall_startform : Form
{
public frm_mediawall_startform()
{
InitializeComponent();
input_time.Value = DateTime.Now;
}
static class Programmability
{
/* Secure Credential Store - This is for remote reboots */
public static readonly string mediawallcomputername = #"\\computername";
public static readonly string adminusername = "computeraccount";
public static readonly string admindomainame = "domainname";
public static readonly string adminpassword = "computeraccountpassword";
public static readonly string addadminpassword = " -p " + adminpassword;
public static readonly string adminuseraccount = admindomainame + #"\" + adminusername;
public static readonly string addadminuseraccount = " -u " + admindomainame + #"\" + adminusername;
public static readonly string Restartnow = mediawallcomputername + addadminuseraccount + addadminpassword + " shutdown -r -t 30";
public static readonly string CancelShutdown = mediawallcomputername + addadminuseraccount + addadminpassword + " shutdown -a";
public static readonly string psexecpath = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "Resources", "PsExec.exe"));
/* End Secure credential Store */
}
private void Btn_restart_now_Click(object sender, EventArgs e)
{
/* Quick and simple Restart now command */
Process Restart_now = new Process();
Restart_now.StartInfo.UseShellExecute = false;
Restart_now.StartInfo.RedirectStandardOutput = true;
Restart_now.StartInfo.RedirectStandardError = true;
Restart_now.StartInfo.RedirectStandardInput = true;
Restart_now.StartInfo.FileName = Programmability.psexecpath;
var Restartnow_args = new List<string> { Programmability.mediawallcomputername, Programmability.addadminuseraccount, Programmability.addadminpassword, "shutdown -s -t 30" };
Restart_now.StartInfo.Arguments = string.Join(" ", Restartnow_args);
{
Restart_now.Start();
string Output = Restart_now.StandardOutput.ReadToEnd();
string Errormessage = Restart_now.StandardError.ReadToEnd();
Restart_now.WaitForExit();
}
}
public void Btn_scheduled_restart_Click(object sender, EventArgs e)
{
/* Gets the current time */
DateTime Timenow = DateTime.Now;
DateTime Restarttime = input_time.Value;
/* Takes the Scheduled time and subtracts from now time above */
var ScheduledRestartTime = Math.Ceiling((Restarttime - Timenow).TotalSeconds);
/* Run the command to restart the Media wall at the specifed time */
Process Timed_Restart = new Process();
Timed_Restart.StartInfo.UseShellExecute = false;
Timed_Restart.StartInfo.RedirectStandardOutput = true;
Timed_Restart.StartInfo.RedirectStandardError = true;
Timed_Restart.StartInfo.RedirectStandardInput = true;
Timed_Restart.StartInfo.FileName = Programmability.psexecpath;
var TimedRestart_args = new List<string> { Programmability.mediawallcomputername, Programmability.addadminuseraccount, Programmability.addadminpassword, "shutdown -r", $"-t {ScheduledRestartTime}" };
Timed_Restart.StartInfo.Arguments = string.Join(" ", TimedRestart_args);
{
Timed_Restart.Start();
string Output = Timed_Restart.StandardOutput.ReadToEnd();
string Errormessage = Timed_Restart.StandardError.ReadToEnd();
Timed_Restart.WaitForExit();
}
}
private void Btn_stop_restart_Click(object sender, EventArgs e)
{
Process Stop_Restart = new Process();
Stop_Restart.StartInfo.UseShellExecute = false;
Stop_Restart.StartInfo.RedirectStandardOutput = true;
Stop_Restart.StartInfo.RedirectStandardError = true;
Stop_Restart.StartInfo.RedirectStandardInput = true;
Stop_Restart.StartInfo.FileName = Programmability.psexecpath;
var cancel_args = new List<string> { Programmability.mediawallcomputername, Programmability.addadminuseraccount, Programmability.addadminpassword, "shutdown -a" };
Stop_Restart.StartInfo.Arguments = String.Join(" ", cancel_args);
{
Stop_Restart.Start();
string Output = Stop_Restart.StandardOutput.ReadToEnd();
string Errormessage = Stop_Restart.StandardError.ReadToEnd();
Stop_Restart.WaitForExit();
}
}
}
}
I added the following changes when trying to catch the error but this has not helped me get any further. I will add just one of the controls for show here but it has been applied to each button
private void Btn_stop_restart_Click(object sender, EventArgs e)
{
try
{
Process Stop_Restart = new Process();
Stop_Restart.StartInfo.UseShellExecute = false;
Stop_Restart.StartInfo.RedirectStandardOutput = true;
Stop_Restart.StartInfo.RedirectStandardError = true;
Stop_Restart.StartInfo.RedirectStandardInput = true;
Stop_Restart.StartInfo.FileName = Programmability.psexecpath;
var cancel_args = new List<string> { Programmability.mediawallcomputername, Programmability.addadminuseraccount, Programmability.addadminpassword, "shutdown -a" };
Stop_Restart.StartInfo.Arguments = String.Join(" ", cancel_args);
using (var stopreader = Stop_Restart.StandardOutput)
{
Stop_Restart.BeginOutputReadLine();
Stop_Restart.Start();
string Output = Stop_Restart.StandardOutput.ReadToEnd();
string Errormessage = Stop_Restart.StandardError.ReadToEnd();
Stop_Restart.WaitForExit();
var StopConsoleOut = stopreader.ReadToEnd();
MessageBox.Show(StopConsoleOut, "Success", MessageBoxButtons.OK);
}
}
catch (Exception)
{
MessageBox.Show($"Running psexec failed as {Programmability.psexecpath}", "Error", MessageBoxButtons.OK);
throw;
}
}
I'm going to answer based on your information of "it works on my machine" and "PSExec is opening but not doing anything".
Remember that when PSExec is run for the first time you are required to use -accepteula as per PSExec's output:
"This is the first run of this program. You must accept EULA to
continue. Use -accepteula to accept EULA."
Have you completed this step on the machines which you are deploying this form app to?
Edit:
If you have accepted the EULA, then you should try to identify what var "Errormessage" is.
I would - for troubleshooting on the machines you are deploying to sake - recommend that you do something like
Restart_now.Start();
string Output = Restart_now.StandardOutput.ReadToEnd();
string Errormessage = Restart_now.StandardError.ReadToEnd();
MessageBox.Show(Errormessage);
Restart_now.WaitForExit();
So that you can see what is failing, if anything, on the device you are deploying this app to. You may find that the PSExec command is not running on their machines for a number of reasons (cannot connect to remote PC, insufficient permissions, etc)
I wanted to download the file\files from SharePoint online to my local and I am struggling with the code samples. I searched on google but didn't get any valuable information.
Try the code snippet below, download file from Library to Local using SharePoint Online CSOM:
using Microsoft.SharePoint.Client;
using System.IO;
using System.Linq;
using System.Security;
namespace CSOM
{
class Program
{
static void Main(string[] args)
{
using (ClientContext ctx = new ClientContext("https://tenantname.sharepoint.com/sites/sitename/"))
{
string password = "********";
string account = "username#tenantname.onmicrosoft.com";
var secret = new SecureString();
foreach (char c in password)
{
secret.AppendChar(c);
}
ctx.Credentials = new SharePointOnlineCredentials(account, secret);
ctx.Load(ctx.Web);
ctx.ExecuteQuery();
List list = ctx.Web.Lists.GetByTitle("libraryTitle");
FileCollection files = list.RootFolder.Folders.GetByUrl("/sites/sitename/shared documents/foldername").Files;
ctx.Load(files);
ctx.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.File file in files)
{
FileInformation fileinfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);
ctx.ExecuteQuery();
using (FileStream filestream = new FileStream("C:" + "\\" + file.Name, FileMode.Create))
{
fileinfo.Stream.CopyTo(filestream);
}
}
};
}
}
}
Following C# program works for downloading files from SharePoint
Using NuGet Packet Manager, install Microsoft.SharePointOnline.CSOM
This package contains SharePoint and Client Object Model libraries
C# Code
using Microsoft.SharePoint.Client;
using System;
using System.IO;
using System.Linq;
using System.Security;
namespace SharePointFileDownlaload
{
class Program
{
static void Main(string[] args)
{
string UserName = String.Empty;
Console.Write("Type username and press enter: ");
UserName = Console.ReadLine();
string Pwd = String.Empty;
Console.Write("Type password and press enter: ");
Pwd = Console.ReadLine();
string drive = String.Empty;
Console.Write("Type the computer drive where you want to store the file and press enter: ");
drive = Console.ReadLine();
Console.WriteLine("Process started .... ");
try
{
DownloadFilesFromSharePoint("MyFolder", UserName, Pwd, drive);
}
catch(Exception ex)
{
Console.WriteLine("ERROR: "+ex.Message);
}
Console.ReadLine();
}
private static void DownloadFilesFromSharePoint(string folderName, string UserName, string Pwd, string driveName)
{
//Load Libraries from SharePoint
ClientContext ctxSite = GetSPOContext(UserName, Pwd);
ctxSite.Load(ctxSite.Web.Lists);
ctxSite.ExecuteQuery();
Web web = ctxSite.Web;
var docLibs = ctxSite.LoadQuery(web.Lists.Where(l => l.BaseTemplate == 101)); //DocumentLibrary only
ctxSite.ExecuteQuery();
foreach (var list in docLibs)
{
//Console.WriteLine(list.Title);
ctxSite.Load(list.RootFolder.Folders);
ctxSite.ExecuteQuery();
string listTitle = list.Title;
//Console.WriteLine("List Tile ------------------------------- " + listTitle);
foreach (Folder folder in list.RootFolder.Folders)
{
ctxSite.Load(folder.Files);
ctxSite.ExecuteQuery();
if (String.Equals(folder.Name, folderName, StringComparison.OrdinalIgnoreCase))
{
var folderDestination = driveName+#":\Test\SharePoint\" + listTitle + #"\" + folderName + #"\";
ctxSite.Load(folder.Files);
ctxSite.ExecuteQuery();
foreach (var file in folder.Files)
{
var fileName = Path.Combine(folderDestination, file.Name);
if (!System.IO.File.Exists(fileName))
{
Directory.CreateDirectory(folderDestination);
var fileRef = file.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctxSite, fileRef);
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}
}
}
Console.WriteLine("Downloaded the file in " + folderDestination);
}
}
}
}
private static ClientContext GetSPOContext(string UserName, string Pwd)
{
string spsiteurl = "https://company.sharepoint.com/sites/YourSite/";
var secure = new SecureString();
foreach (char c in Pwd)
{
secure.AppendChar(c);
}
ClientContext spoContext = new ClientContext(spsiteurl);
spoContext.Credentials = new SharePointOnlineCredentials(UserName, secure);
return spoContext;
}
private static void GetAllItemNamesInSP(string UserName, string Pwd)
{
//Load Libraries from SharePoint
ClientContext ctxSite = GetSPOContext(UserName, Pwd);
ctxSite.Load(ctxSite.Web.Lists);
ctxSite.ExecuteQuery();
foreach (List list in ctxSite.Web.Lists)
{
string nameTest = list.Title;
string testVal = list.BaseType.ToString();
Console.WriteLine(nameTest + " -------------- " + testVal);
if (list.BaseType.ToString() == "DocumentLibrary")
{
}
}
Console.ReadLine();
}
}
}
I'm basically trying to create a console application which executes a given script on a remote machines within a given IP range and stores the results.
This is my code so far but something is going wrong when I try to create a runspace with the WSManConnectionInfo object as arg.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Security;
namespace GetSysInfo
{
class Program
{
private static string outPath;
static void Main(string[] args)
{
//get script path
Console.WriteLine("Enter full path to script.");
string path = Convert.ToString(Console.ReadLine());
//get IP range
Console.WriteLine("Input start IPv4.");
IPAddress sIP = IPAddress.Parse(Console.ReadLine().ToString());
Console.WriteLine("Input end IPv4.");
IPAddress eIP = IPAddress.Parse(Console.ReadLine().ToString());
//get list of IPs in range
RangeFinder rf = new RangeFinder();
List<string> IPrange = rf.GetIPRangeList(sIP, eIP);
//run script
foreach (var IP in IPrange)
{
try
{
RunScriptRemote(LoadScript(path), IP);
}
catch (Exception e)
{
Console.WriteLine("An error occured" + Environment.NewLine + e.Message);
}
}
}
//script executer
private static void RunScriptRemote(string script, string address)
{
Console.WriteLine("Enter username.");
String username = Console.ReadLine();
Console.WriteLine("Enter password.");
ConsoleKeyInfo key;
SecureString pass = new SecureString();
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
pass.AppendChar(key.KeyChar);
Console.Write("*");
}
else
{
if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
{
pass.RemoveAt(pass.Length);
Console.Write("\b \b");
}
else if (key.Key == ConsoleKey.Enter && pass.Length > 0)
{
Console.Write(Environment.NewLine);
pass.MakeReadOnly();
}
}
}
while (key.Key != ConsoleKey.Enter);
PSCredential credential = new PSCredential(username, pass);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://" + address + ":5985/wsman"), "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Negotiate;
connectionInfo.EnableNetworkAccess = true;
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);//point of crash
runspace.Open();
//set path to save results
Console.WriteLine("Enter full path to save results. Must be a directory.\nThis can be a local path or a network path.");
Console.WriteLine("In case of a network path the results will be merged automatically");
outPath = Convert.ToString(Console.ReadLine());
runspace.SessionStateProxy.SetVariable("filepath", outPath);
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
ps.AddScript(script);
ps.Invoke();
}
//Pipeline pipeline = runspace.CreatePipeline();
//pipeline.Commands.AddScript(script);
//pipeline.Invoke();
runspace.Close();
}
//script loader
private static string LoadScript(string filename)
{
try
{
using (StreamReader sr = new StreamReader(filename))
{
StringBuilder fileContents = new StringBuilder();
string curLine;
while ((curLine = sr.ReadLine()) != null)
{
fileContents.Append(curLine + Environment.NewLine);
}
return fileContents.ToString();
}
}
catch (Exception e)
{
return e.Message;
}
}
}
public class RangeFinder
{
public IEnumerable<string> GetIPRange(IPAddress startIP,
IPAddress endIP)
{
uint sIP = ipToUint(startIP.GetAddressBytes());
uint eIP = ipToUint(endIP.GetAddressBytes());
while (sIP <= eIP)
{
yield return new IPAddress(reverseBytesArray(sIP)).ToString();
sIP++;
}
}
public List<string> GetIPRangeList(IPAddress startIP,
IPAddress endIP)
{
uint sIP = ipToUint(startIP.GetAddressBytes());
uint eIP = ipToUint(endIP.GetAddressBytes());
List<string> IPlist = new List<string>();
while (sIP <= eIP)
{
IPlist.Add(new IPAddress(reverseBytesArray(sIP)).ToString());
sIP++;
}
return IPlist;
}
//reverse byte order in array
protected uint reverseBytesArray(uint ip)
{
byte[] bytes = BitConverter.GetBytes(ip);
bytes = bytes.Reverse().ToArray();
return (uint)BitConverter.ToInt32(bytes, 0);
}
//Convert bytes array to 32 bit long value
protected uint ipToUint(byte[] ipBytes)
{
ByteConverter bConvert = new ByteConverter();
uint ipUint = 0;
int shift = 24;
foreach (byte b in ipBytes)
{
if (ipUint == 0)
{
ipUint = (uint)bConvert.ConvertTo(b, typeof(uint)) << shift;
shift -= 8;
continue;
}
if (shift >= 8)
ipUint += (uint)bConvert.ConvertTo(b, typeof(uint)) << shift;
else
ipUint += (uint)bConvert.ConvertTo(b, typeof(uint));
shift -= 8;
}
return ipUint;
}
}
}
I get the following error when trying to run: Common Language Runtime detected an invalid program.
I tried creating a new solution as Google suggested but it's obviously going wrong when creating the runspace.
I'm out of idea's and sources for help, so I'm reaching out to the Stackoverflow community.
Thanks in advance,
X3ntr
EDIT:
I tried cleaning my solution, manually deleting any pbd's, changed the target CPU, turned off code optimalization, allowed unsafe code, rebuilding, creating a new solution,... as suggested in this post.
I followed the advice from this answer: I added a reference to C:\windows\assembly\GAC_MSIL\System.Management.Automation and then ran this command in an elevated powershell: Copy ([PSObject].Assembly.Location) C:\
I have a RFID devices connected to my laptop through Port COM1(Confirmed correct whereby i had using device manager). However, when i run these code in C# language. It give me an exception Access to the port "COM1" is denied. Anyone can help me to solve this problem? Below is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO.Ports;
using System.Threading;
namespace Testing1
{
public class Testing1
{
public static SerialPort iSerialPort = new SerialPort();
static int Main()
{
string strException = string.Empty;
string strComPort = "COM1";
int nBaudrate=Convert.ToInt32(9600);
int nRet = OpenCom(strComPort, nBaudrate, out strException);
if (nRet != 0)
{
string strLog = "Connect reader failed, due to: " + strException;
Console.WriteLine(strLog);
//return;
}
else
{
string strLog = "Reader connected " + strComPort + "#" + nBaudrate.ToString();
Console.WriteLine(strLog);
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
iSerialPort.Close();
return 0;
}
public static int OpenCom(string strPort, int nBaudrate, out string strException)
{
strException = string.Empty;
if (iSerialPort.IsOpen)
{
iSerialPort.Close();
}
try
{
iSerialPort.PortName = strPort;
iSerialPort.BaudRate = nBaudrate;
iSerialPort.ReadTimeout = 200;
iSerialPort.DataBits = 8;
iSerialPort.Parity = Parity.None;
iSerialPort.StopBits = StopBits.One;
iSerialPort.Open();
}
catch (System.Exception ex)
{
strException = ex.Message;
return -1;
}
return 0;
}
}
}
This exception can occur when some other program is accessing the COM1 port. Do you have any other program open that uses the RFID device?
You can check what programs use what ports using Portmon.
I'm using Visual C# Express 2010 with the Google custom search API and the Newtonsoft.Json.dll. I'm getting a 400 error back from Google. I think I'm not forming the search string (mySearchString) correctly but I can't see the error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace Test_Console1
{
class Program
{
//Google keys
const string APIKey = "{key}";
const string CSEKey = "{key}";
//base url for the search query
const string GoogleBaseURL = "https://www.googleapis.com/customsearch/v1?";
public static void Main (string[] args)
{
string myQuery = "Action Motivation, Inc. South San Francisco";
int startResult = 0;
int numResults = 10;
string result;
result = submitSearch(makeSearchString(myQuery, startResult, numResults));
Console.WriteLine(result);
string dummy = Console.ReadLine();
}
public static string makeSearchString(string myQuery, int startResult, int numResults)
{
//add keys
string mySearchString = GoogleBaseURL + "key=" + APIKey + "&cx=" + CSEKey + "&q=";
//add query string: replace space+plus sign pattern with just a plus sign
string[] keys = myQuery.Split(' ');
foreach(string key in keys)
{
mySearchString += key +"+"; //append keywords
}
//specify JSON response format
mySearchString += "&alt=json";
//specify starting result number
mySearchString += "&start=" + startResult;
//specify number of results
mySearchString += "&num=" + numResults;
return mySearchString;
}
public static string submitSearch(string mySearchString)
{
//try
//{
Uri url = new Uri(mySearchString);
//url looks like this:
//"https://www.googleapis.com/customsearch/v1?key=AZaaAaAaA0aaAA0ZAZA0aaAA00aaA0aaAaAa0aA&cx=012345678901234567890:aaaaaaaa0aa&q=Action+Motivation,+Inc.+South+San+Francisco+&alt=json&start=0&num=10"
WebRequest myRequest = WebRequest.Create(url);
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Stream myStream = myResponse.GetResponseStream ();
StreamReader myReader = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = myReader.ToString();
//JObject myJo = JObject.Parse(myReader.ReadToEnd());
//int resultcount = (int)myJo.SelectToken("responseData.cursor.estimatedResultCount");
myStream.Close();
myReader.Close();
myResponse.Close();
return result;
//}
//catch (Exception e)
//{
// //debug statement
//}
return null;
}
}
}