Something is deleting a console app. Why is it being deleted? - c#

I need to learn how to use SMO within a C# program, so the first thing I did was start a new, console app and then began putting in the basics. I decided to make the app accept parameters so I can pass in things like usernames, logins, etc. As I work on it and build it I have a PowerShell window open where I can call the app, give it parameters or not, etc. But something weird is happening which I don't understand. Sometimes when I run the app in the PowerShell window, it's then deleted for some reason. Why is it doing that? I discovered it when it first gave me the following error message:
Program 'SmoListLogins.exe' failed to run: The system cannot find the file specifiedAt line:1 char:1 + .\SmoListLogins.exe "MYCOMPANY\Rod"
My SmoListLogins.exe program isn't there. Naturally I can easily re-create it, but I don't understand why its being deleted.
So you can see what I'm working with, here's the source code. I took it from a MSDN article and have added a little bit:
using System;
using System.Data;
using Microsoft.SqlServer.Management.Smo;
namespace SmoListLogins
{
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
var userName = args[0];
ListLogins(userName);
}
else
{
ListLogins();
}
}
static private void ListLogins(string userName = "")
{
var userNamePassed = (userName != "");
Server srv = new Server("YOURSQLINSTANCE");
//Iterate through each database and display.
foreach (Database db in srv.Databases)
{
Console.WriteLine("========");
Console.WriteLine("Login Mappings for the database: " + db.Name);
Console.WriteLine(" ");
//Run the EnumLoginMappings method and return details of database user-login mappings to a DataTable object variable.
DataTable d;
try
{
d = db.EnumLoginMappings();
//Display the mapping information.
foreach (DataRow r in d.Rows)
{
var userNameMatches = false;
var starting = true;
foreach (DataColumn c in r.Table.Columns)
{
if (!userNamePassed)
{
Console.WriteLine(c.ColumnName + " = " + r[c]);
}
else
{
if (starting)
{
starting = false;
if (userName == r[c].ToString())
{
userNameMatches = true;
}
}
if (userNameMatches)
{
Console.WriteLine(c.ColumnName + " = " + r[c]);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error processing database: {db.Name}");
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine();
}
}
}
}
}

I believe I now know what was deleting my executable. It wasn't something I thought of, so I'm sharing with everyone the answer. Today I got an email from our chief security officer, informing me that the program I wrote was being blocked by Symantec Endpoint Protection. In my testing I'd run my app over and over again. After a few iterations of that it would disappear. It didn't occur to me that it was our corporate AV that might be doing it. Now it looks as though that is exactly what was going on.
Thank you everyone for your input in trying to help me resolve this. I hope that if anyone else encounters this problem they might consider the possibility of their AV as the reason why the app they wrote disappears.

Related

MapReduce.SDK: How to wait for MapReduce job?

I'm using the Microsoft MapReduce SDK to start a Mapper only job.
The call to hadoop.MapReduceJob.ExecuteJob is throwing a "Response status code does not indicate success: 404 (not found)" exception immediately.
When inspecting the HDInsight Query Console the job successfully starts and finishes later. It also writes proper output files.
My guess is, ExecuteJob is trying to access output data before the job has finished.
What is the correct way to handle this situation?
using System;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Microsoft.WindowsAzure.Management.HDInsight;
using Microsoft.Hadoop.MapReduce;
using AzureAnalyzer.MultiAnalyzer;
namespace AzureAnalyzer
{
class Program
{
static void Main(string[] args)
{
IHadoop hadoop = Hadoop.Connect(Constants.azureClusterUri, Constants.clusterUser,
Constants.hadoopUser, Constants.clusterPassword, Constants.storageAccount,
Constants.storageAccountKey, Constants.container, true);
try {
var output = hadoop.MapReduceJob.ExecuteJob<MultiAnalyzerJob>();
}
catch (Exception ex)
{
Console.WriteLine("\nException: " + ex.Message);
}
}
}
}
I got another way to do the same thing but takes a bit of effort since it requires the mapper and reducer files to be transferred to the hadoop cluster storage.
you need to add Microsoft.Hadoop.Client then Microsoft Azure HDInsight NuGet package as well.
var jobcred = new BasicAuthCredential();
jobcred.UserName = "clusteruserid";
jobcred.Password = "clusterpassword";
jobcred.Server = new Uri("https://clusterurl");
StreamingMapReduceJobCreateParameters jobpara = new StreamingMapReduceJobCreateParameters()
{
JobName="mapreduce",
Mapper = "Mapper.exe",
Reducer = "Reducer.exe",
Input= "wasb:///mydata/input",
Output = "wasb:///mydata/Output",
StatusFolder= "wasb:///mydata/sOutput"
};
jobpara.Files.Add("wasb:///mydata/Mapper.exe");
jobpara.Files.Add("wasb:///mydata/Reducer.exe");
// Create a Hadoop client to connect to HDInsight.
var jobClient = JobSubmissionClientFactory.Connect(jobcred);
// Run the MapReduce job.
JobCreationResults mrJobResults = jobClient.CreateStreamingJob(jobpara);
// Wait for the job to complete.
Console.Write("Job running...");
JobDetails jobInProgress = jobClient.GetJob(mrJobResults.JobId);
while (jobInProgress.StatusCode != JobStatusCode.Completed
&& jobInProgress.StatusCode != JobStatusCode.Failed)
{
Console.Write(".");
jobInProgress = jobClient.GetJob(jobInProgress.JobId);
Thread.Sleep(TimeSpan.FromSeconds(10));
}
// Job is complete.
Console.WriteLine("!");
Console.WriteLine("Job complete!");
Console.WriteLine("Press a key to end.");
Console.Read();
Hope this helps. I was able to run jobs without throwing any exceptions.
this in fact waits for the job to be complete.
Please verify if all required services to run the program are up and running. The 404 error indicates that some URL the program tries to access internally is not accessible.

ASP.NET C# get list of valid domains?

Is there any way to query a list of valid domains from ASP.NET C#, similar to the list shown when logging into widows? I would like to provide this to the client users so they can select the appropriate domain with which to login to an intranet web application. I've tried using Forest.GetCurrentForest but I always seem to only get one domain back, when I definitely know there are others.
UPDATE: (CODE)
using System;
using System.Configuration;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory;
namespace Domains {
class Program {
static void Main(string[] args) {
try {
using (Forest forest = Forest.GetCurrentForest()) {
Console.WriteLine("FOREST");
Console.WriteLine(" {0}", forest.Name);
Console.WriteLine("-------------------------------------------------------------------------------");
Console.WriteLine(" DOMAINS");
foreach (Domain domain in forest.Domains) {
Console.WriteLine(String.Format(" {0}", domain.Name));
Console.WriteLine(" TRUSTS");
TrustRelationshipInformationCollection domainTrusts = domain.GetAllTrustRelationships();
if (domainTrusts.Count == 0) {
Console.WriteLine(" N/A");
} else {
foreach (TrustRelationshipInformation trust in domainTrusts) {
DirectoryContext x = new DirectoryContext(DirectoryContextType.Domain, trust.TargetName);
Console.WriteLine(String.Format(" {0} -> {1}", trust.SourceName, trust.TargetName));
}
}
domain.Dispose();
}
Console.WriteLine("-------------------------------------------------------------------------------");
Console.WriteLine(" TRUSTS");
TrustRelationshipInformationCollection forestTrusts = forest.GetAllTrustRelationships();
if (forestTrusts.Count == 0) {
Console.WriteLine(" N/A");
} else {
foreach (TrustRelationshipInformation trust in forestTrusts) {
Console.WriteLine(String.Format(" {0} -> {1}", trust.SourceName, trust.TargetName));
}
}
}
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
Console.WriteLine("\nPress ESC to exit...");
do {
while (!Console.KeyAvailable) {
// Do something
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
}
}
}
Now when I go to log into the machine directly (remote desktop, etc.) I get a list of 6 domains I can log into, but when the above code runs on the same machine (currently just a console app for testing, not ASP.NET enabled yet), I get one domain, the current domain I'm logged into on the machine.
EDIT:
I think maybe I'm getting confused, perhaps what I am really looking for is the NetBios domain names. Because I just realized the domain + all the trusts equal the count of domains I'm looking for, but these are the full names, not short names I expected.
UPDATE:
So I was able to acquire the netbiosname of the main domains using an LDAP query, but I'm not sure how to go about getting the netbiosname for the trusted domains...
If you are looking for all domains in teh forest use:
Forest.Domains
property. returns a DomainCollection.
GetCurrentForest returns only Forest for the current user context.
Forest.GetCurrentForest().Domains
Should return all domains.

Programmatically get site status from IIS, gets back COM error

I am trying to programmatically get my site status from IIS to see if it's stopped, but I kept getting the following error,
The object identifier does not represent a valid object. (Exception from HRESULT: 0x800710D8)
The application is using ServerManager Site class to access the site status. Here is the code,
//This is fine, gets back the site
var serverManager = new Microsoft.Web.Administration.ServerManager(ConfigPath);
var site = serverManager.Sites.FirstOrDefault(x => x.Id == 5);
if (site == null) return;
var appPoolName = site.Applications["/"].ApplicationPoolName;
//error!
var state = site.State;
I've test with static site to isolate the issue, making sure that the site is up and running, all configuration are valid, point to the valid application pool...etc.
Let me know if you need more details. Is it the COM thing?
I figured out where the problem is. Basically, there are two parts to the Server manager, the first part of the server manager allows you to read site details from configuration file, which is what I've been doing above. The problem with that is you will only able get the information that's in file and site state is not part of it.
The second part of the Server Manager allows you to connect to the IIS directly and it does this by interacting with the COM element. So what I should be doing is this:
ServerManager manager= ServerManager.OpenRemote("testserver");
var site = manager.Sites.First();
var status = site.State.ToString() ;
I had a similar problem but mine was caused by the delay needed to activate the changes from the call to CommitChanges on the ServerManager object. I found the answer I needed here:
ServerManager CommitChanges makes changes with a slight delay
It seems like polling is required to get consistent results. Something similar to this solved my problem (I got the exception when accessing a newly added application pool):
...
create new application pool
...
sman.CommitChanges();
int i = 0;
const int max = 10;
do
{
i++;
try
{
if (ObjectState.Stopped == pool.State)
{
write_log("Pool was stopped, starting: " + pool.Name);
pool.Start();
}
sman.CommitChanges();
break;
}
catch (System.Runtime.InteropServices.COMException e)
{
if (i < max)
{
write_log("Waiting for IIS to activate new config...");
Thread.Sleep(1000);
}
else
{
throw new Exception(
"CommitChanges timed out efter " + max + " attempts.",
e);
}
}
} while (true);
...

Manipulate the output receiving from command RUN and act accordingly - C#

I guess you all misunderstood my question and closed it at How to run a Command in C# and retrieve data from it?
I had said in that post also :-
want to run a Command from command promt and want its output and maipulate its output. If required, want to close the process and display error or appropriate message. To stop the process, I have to press "F4' key on command prompt. Till the process is stopeed or killed, it has to be alive only.
I have created a class to handle running the cmd. And I keep getting the output. But on reading the output's each line I want to stop or throw exception if found anything improper in the output.
I am tying to connect to server via cmd. Server keeps on giving output. Suppose the server gave output as :
Trying to start .....
Cananot load file
.....
Exiting
While retrieving the output, I want to check for lines like "Cannot find file", "Connected Successfully, etc and set properties ccordingly (like connected = true, errorMsg = "Cannot find file". Where I am calling the class, I can take care of those proeprties and stop if found connected == true or errorMsg.length > 0. With this inform the user that "Connection is achieved or error msg stating regarding "Cannot load file" and disconnect the server if errorMsg found.
I didn't find anywhere doing any manipulation on the output receving and that's where I find myself stuck. I found a lot on internet. Am stuck and trying to figre out this part from last 3-4 days. Then have posted here.
I need help in that. Please help me. If requiried I will psot code snippets. But please help me. AND don't close this thread as answered ithout understanding my question fully. This is no duplicate.
My code is class :
public int ConnectToServer()
{
int error = 0;
connected = false;
try
{
process = Process.Start(processInfo);
process.BeginOutputReadLine();
process.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
//if (errorMsg.Length > 0)
// throw new Exception(errorMsg);
}
catch (Exception e)
{
Console.WriteLine("Error Processing ConnectToServer : " + e.Message);
connected = false;
errorMsg = e.Message;
error = -1;
return error;
}
return error;
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
errorMsg = "";
connected = false;
string d = e.Data;
if (!string.IsNullOrEmpty(d))
{
if (sb != null)
sb.Append(d + "\n");
Console.WriteLine("LINE = " + d);
if (d.IndexOf("Initialization Completed") > 0)
{
connected = true;
Console.WriteLine("********* Connected = " + connected);
}
else if (isInValidLine(d))
{
//throw new Exception(d);
connected = false;
errorMsg = d;
return;
}
}
return;
}
private bool isInValidLine(string line)
{
if (line.IndexOf("Cannot load file") > 0)
{
errorMsg = line;
return true;
}
return false;
}
IS THE ABOVE CLASS CODE CORRECT WITH MY REQUIREMENTS ?
In impementation :
while (!oc.Connected)
{
timepassed = (int)(DateTime.Now - start).TotalMilliseconds;
if (timepassed > timeout)
{
oc.DisconnectServer();
connectedToVpn = false;
throw new Exception("NotConnectedException");
} else if (oc.ErrorMessage.Length > 0)
{
oc.DisconnectServer();
connectedToVpn = false;
throw new Exception(oc.ErrorMessage);
}
Thread.Sleep(100);
}
Here what I am doing is, when I get the output line, I check if it states as Conneced or is invalid. If its invalid, I set the line as the errorMsg. In my while loop I keep chekcing for Connected and errorMessage, but the value of errorMessage stays as "" only. It never gets updated, which tell me that the processing output code is never executed. Nor in debug mode I find the cursor at that line, but the Line = is displayed proeprly in Console. So, don't understand what's going wrong and where.
Hope this helps you more understand.
Thanks
once you have redirected the standard output of the process you have executed you could parse what you receive as it arrives, I believe also line by line, then you can post commands to control your process.
to read output you have redirected the standard output, to send input you should also redirect the standard input of the process.

Hudson Doesn't Seem to Run Process.Start Correctly

For a project I have to start an application in C#, rip out the AutomationElement tree related to the process, and then close the application and output the tree. I'm doing this by opening the application using Process.Start. Then I'm finding the AutomationElements related to the spawned process and walking the tree using a combination of TreeWalker and AutomationElement's FindFirst and FindAll methods.
This runs fine on my computer and runs correctly using NUnit locally. It also runs on the other people in my groups computers. The problem is that it never runs on our central testing server that's running Hudson. After some hours of debugging, I had a test on Hudson start the application and then print the first level of the AutomationTree. On my computer, this prints all of the windows I have on my desktop. On Hudson, this only prints the Desktop.
Thinking there might be multiple desktops, I tried using TreeWalker's GetNextSibling function on the RootElement. It still only reported one desktop.
Here's the code I'm using to start a process.
public bool connect(string[] args)
{
if (this.process != null) {
Console.WriteLine("ERROR: Process already connected");
return false;
}
if (!File.Exists(sApplicationPath)) {
Console.WriteLine(sApplicationPath + " does not exist");
return false;
}
// Turn the command arguments into a single string
string arguments = "";
foreach (string arg in args) {
arguments += arg + " ";
}
try {
// Start the application
ProcessStartInfo processStartInfo =
new ProcessStartInfo(sApplicationPath);
processStartInfo.Arguments = arguments;
this.process = Process.Start(processStartInfo);
// Must be a positive integer (non-zero)
if ( !( iInitialDelay > 0 ) ) {
Console.WriteLine("Invalid initial delay. " +
"Defaulting to 5 seconds.");
this.iInitialDelay = 5000;
}
Thread.Sleep(this.iInitialDelay);
} catch (Exception ex) {
Console.WriteLine("WGApplication.connect: " + ex.Message);
return false;
}
// Check if the process still exists
try {
/** This part does not return an error, so I think that means the process exists and is started */
Process check = Process.GetProcessById(process.Id);
} catch (ArgumentException ex) {
Console.WriteLine("The process expired before connection was complete");
Console.WriteLine("Make sure the process is not open anywhere else");
Console.WriteLine("and that it is able to execute on the host machine.");
return false;
}
// Check if the base automation element exists to verify open
AutomationElement rootWindow =
AutomationElement.RootElement.FindChildProcessById(process.Id);
/** This part returns null, so it can't find the window associated with this process id */
if (this.process == null) {
return false;
} else if (rootWindow == null) {
// A root window with this process id has not been found
Console.WriteLine("Cannot find the root window of the created " +
"process. Unknown error.");
return false;
} else {
// Everything is good to go
return true;
}
}
sApplicationPath is set to the absolute path of the executable. iInitialDelay is a delay to make sure the application has time to start. I'm running this on 'C:\Windows\System32\notepad.exe' on Windows Vista SP2 and compiling it with the v3.5 C# compiler.
FindChildProcessById is defined as follows:
public static AutomationElement FindChildProcessById(
this AutomationElement element, int processId)
{
var result = element.FindChildByCondition(
new PropertyCondition(AutomationElement.ProcessIdProperty,
processId));
return result;
}
Remember that this compiles and works on my computer. My test program on Hudson said that the RootElement had no children at all.
So I start the application, confirm it exists, and then I can't find any windows associated with the process. I can't find any windows associated with anything except the desktop.
Is this a problem with Hudson? Does Hudson work in some specific way that this code wouldn't work on it? Is it a problem with my code? The Hudson server is running on a Windows Server 2003 computer. Any help would be appreciated. I know this is a very specific problem which is a reason why I can't find any solutions online.
Is Hudson running as a service? If so, it may not have the necessary rights to show windows.

Categories