C# Trying to retrieve %logonserver% from remote machine - c#-4.0

I've seen a couple examples here and there, here's what I'm trying to achieve. I know the below does not work, but essentially I'm trying to pull the %logonserver% from a remote machine. For some reason, the wmi query does not return any data.
try
{
System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo("\\\\"+txtboxMachineName.Text+"\\c$\\Windows\\System32\\cmd.exe", "/c echo %logonserver%");
startinfo.RedirectStandardOutput = true;
startinfo.UseShellExecute = false;
startinfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new Process();
proc.StartInfo = startinfo;
proc.Start();
lblLogonServer.Text = proc.StandardOutput.ReadToEnd();
}
catch
{
lblLogonServer.Text = "Error has been encountered obtaining Logon Server";
}

Related

Closing Case in Acumatica through API

I want to close the case in Partners Portal remotely using Web API, whenever I close the case in my (client) side. I was able to implement the code but ran into below issue.
It is changing the status and resolution of the case in Partners Portal but Close Case button is enabled and it is visible in My Open Case bucket. Please let me know if I can close the case remotely using Web API or if I am missing anything.
protected virtual void CRCase_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
{
var caseRow = (CRCase)e.Row;
if (caseRow != null)
{
if (caseRow.Status == "C") // Closed
{
string cloud9CaseCD = null;
cloud9CaseCD = CRCaseForCreate.Current.CaseCD;
string acumaticaCaseCD = string.Empty;
CSAnswers aCCaseNoAttribute = PXSelect<CSAnswers,
Where<CSAnswers.refNoteID, Equal<Required<CSAnswers.refNoteID>>,
And<CSAnswers.attributeID, Equal<Required<CSAnswers.attributeID>>>>>.Select(new PXGraph(), CRCaseForCreate.Current.NoteID, "ACCASENO");
if (aCCaseNoAttribute != null)
{
acumaticaCaseCD = aCCaseNoAttribute.Value;
if(!string.IsNullOrEmpty(acumaticaCaseCD))
{
SP203000WS.Screen context = new SP203000WS.Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.AllowAutoRedirect = true;
context.EnableDecompression = true;
context.Timeout = 1000000;
context.Url = "https://sso.acumatica.com/Soap/SP203000.asmx";
PartnerPortalCreds loginCreds = GetCreds();
string username = loginCreds.PARTPRTUSE;
string password = loginCreds.PARTPRTPAS;
SP203000WS.LoginResult result = context.Login(username, password);
SP203000WS.Content CR306000 = context.GetSchema();
context.Clear();
SP203000WS.Content[] CR306000Content = context.Submit
(
new SP203000WS.Command[]
{
new SP203000WS.Value
{
Value = acumaticaCaseCD,
LinkedCommand = CR306000.Case.CaseID
},
new SP203000WS.Value
{
Value = "C",
LinkedCommand = new SP203000WS.Field { FieldName="Status", ObjectName="Case"}
},
new SP203000WS.Value
{
Value = "RD",
LinkedCommand = new SP203000WS.Field { FieldName="Resolution", ObjectName="Case"}
},
CR306000.Actions.Submit,
CR306000.Case.CaseID
}
);
context.Logout();
}
}
}
}
}
Tried below code using CloseCase Action: -
protected virtual void CRCase_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
{
var caseRow = (CRCase)e.Row;
if (caseRow != null)
{
if (caseRow.Status == "C") // Closed
{
string cloud9CaseCD = null;
cloud9CaseCD = CRCaseForCreate.Current.CaseCD;
string acumaticaCaseCD = string.Empty;
CSAnswers aCCaseNoAttribute = PXSelect<CSAnswers,
Where<CSAnswers.refNoteID, Equal<Required<CSAnswers.refNoteID>>,
And<CSAnswers.attributeID, Equal<Required<CSAnswers.attributeID>>>>>.Select(new PXGraph(), CRCaseForCreate.Current.NoteID, "ACCASENO");
if (aCCaseNoAttribute != null)
{
acumaticaCaseCD = aCCaseNoAttribute.Value;
if (!string.IsNullOrEmpty(acumaticaCaseCD))
{
SP203010WS.Screen context = new SP203010WS.Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.AllowAutoRedirect = true;
context.EnableDecompression = true;
context.Timeout = 1000000;
context.Url = "https://sso.acumatica.com/Soap/SP203010.asmx";
PartnerPortalCreds loginCreds = GetCreds();
string username = loginCreds.PARTPRTUSE;
string password = loginCreds.PARTPRTPAS;
SP203010WS.LoginResult result = context.Login(username, password);
SP203010WS.Content CR306000 = context.GetSchema();
context.Clear();
var commands1 = new SP203010WS.Command[]
{
new SP203010WS.Value
{
Value = acumaticaCaseCD,
LinkedCommand = CR306000.Case.CaseID
},
new SP203010WS.Value
{
Value = "Yes",
LinkedCommand = CR306000.Case.ServiceCommands.DialogAnswer, Commit = true
},
CR306000.Actions.CloseCase
};
var data = context.Submit(commands1);
context.Logout();
}
}
}
}
}
In the below image you can see that the case is already closed but Close Case menu button is still visible.
Close Case Confirmation Dialogbox on Partners Portal. How should I answer this dialogbox programatically while closing the case using Web API.
Have you tried to invoke Close action via Web API instead of changing values of the Status and Resolution fields? As far as I know, Close button on the Partner Portal updates support case Status to Open and Reason to Pending Closure. Then it's up to support personnel to manually close the case.
Finally found the solution. Updated the code for CloseCase (second code snippet). This will mark the case as Pending Closure in Partners Portal.

C# CommandTimeout Using statement issue

I have a method which has served me well, but now the queries have changed and I need to add a CommandTimeout to allow for the fact that some of the client machines on which this is executed are a little under-powered. The issue I'm having is the using lines as adding a CommandTimeout doesn't work.
The program itself pulls queries down from an SFTP server each night and then executes the queries against the client DB, writes the results to file then sends the results back to the SFTP server.
I can't improve the efficiency of the query (read only access) on the client machines, so I'm stuck with this method.
public void DumpTableToFile(string connection, string destinationFile, string QueryToExec)
{
string logDirectory = VariableStorage.logDirectory;
string Practice = VariableStorage.Practice;
try
{
SqlConnection conn = new SqlConnection(connection);
conn.Open();
using (var command = new SqlCommand(QueryToExec, conn))
using (var reader = command.ExecuteReader())
using (var outFile = File.CreateText(destinationFile))
{
string[] columnNames = GetColumnNames(reader).ToArray();
int numFields = columnNames.Length;
outFile.WriteLine(string.Join("\t", columnNames));
if (reader.HasRows)
{
while (reader.Read())
{
string[] columnValues =
Enumerable.Range(0, numFields)
.Select(i => reader.GetValue(i).ToString())
.Select(field => string.Concat("", field.Replace("\"", "\"\""), ""))
.ToArray();
outFile.WriteLine(string.Join("\t", columnValues));
}
}
}
}
catch (Exception e)
{
Program log = new Program();
log.WriteToLog(" Error: " + e);
SendEmailReport(Practice + " - Data Collection Error", " Error: " + e);
}
}
OK, found the answer. I had to remove the Using statements.
var command = new SqlCommand(QueryToExec, conn);
command.CommandTimeout = 300;
var reader = command.ExecuteReader();
var outFile = File.CreateText(destinationFile);

.InvalidOperationException in Process.start

I have the following code
foreach (Items it in sortedList)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = true;
startInfo.FileName = it.filePath;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
try
{
Process p = new Process();
p.StartInfo = startInfo;
p.Start();
p.WaitForExit();
}
catch(Exception ew)
{
// Log error.
}
}
Every time I open a mp4 file I get an
InvalidOperationException
and it says that there is no program linked to this format, but at the same time the windows media player starts up and shows the file.
Can someone explain to me why this code is throwing the InvalidOperationException and also how I can fix the issue?
Thanks.

Creating loggers for a windows service and a wcf service hosted by that windows service

I create a logger in my windows service and it works fine until that service creates/hosts a wcf service. When I create the logger in the wcf service, logging destined for the windows service log is actually logged to the wcf service log. Here's some code excerpts:
Windows Service:
enum LoggingListeningPorts
{
MCMessageService = 8182,
MCService = 8183,
MCWCFService = 8184,
MyCourtsAdmin = 8185,
MyCourtsWeb = 8186,
MCManager = 8187,
MCSupport = 8188,
MyCourts = 8189
}
First I start logging in the Windows Service to the file directly as the TCP Listeners haven't been initialized:
private void startFileLogging()
{
string location = "target";
try
{
LoggingConfiguration config = new LoggingConfiguration();
FileTarget target = new FileTarget();
target.Layout = "${longdate} ${machineName} ${callsite} ${message} ${exception:format=tostring}";
target.FileName = Path.Combine(dataDirectory, "MCService.log");
target.KeepFileOpen = false;
eventLog1.WriteEntry(string.Format("target.FileName [{0}]", target.FileName), EventLogEntryType.Information);
LoggingRule normalRule = new LoggingRule("*", LogLevel.Trace, target);
config.LoggingRules.Add(normalRule);
LogManager.Configuration = config;
location = "Config";
LogFactory fac = logger.Factory as LogFactory;
fac.GlobalThreshold = loglevel;
location = "Logging";
//logger.Debug(string.Format("### NRMAP{0}_{1}", Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version));
//logger.Debug(string.Format("### MCCommon_{0}", mccommonVersionNumber));
logger.Debug("##########################################");
logger.Debug(string.Format("######## MyCourts Service {0} ", Assembly.GetExecutingAssembly().GetName().Version).PadRight(42, '#'));
logger.Debug("##########################################");
//logger.Debug(string.Format("#### MyCourts Service {0} StartUp ", Assembly.GetExecutingAssembly().GetName().Version));
logger.Debug(string.Format("Database directory [{0}]", dataDirectory));
logger.Log(LogLevel.Trace, "Trace level is [{0}]", logger.IsTraceEnabled);
}
catch (Exception ex)
{
eventLog1.WriteEntry(string.Format("MCService Service logging failed at location [{0}]: {1}", location, ex.Message), EventLogEntryType.Warning);
}
}
Then I start the wcf service:
mcwcfServiceHost.Open();
logger.Trace("MCWCFService opened.");
At this stage the logging for the Windows Service is working perfectly. I then execute the following method in my Windows Service which includes starting logging on the wcf service:
private void initializeMCWCFService()
{
logger.Debug("Set DB Path in MCWCFService");
int pauseTime = 2000;
System.Threading.Thread.Sleep(pauseTime);
EndpointAddress basicHTTPendpoint = null;
EndpointAddress serverTCPEndpoint = null;
var discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
var findCriteria = FindCriteria.CreateMetadataExchangeEndpointCriteria(typeof(MCWCFService.MCManagementService));
findCriteria.MaxResults = 1;
var findResults = discoveryClient.Find(findCriteria);
if (findResults.Endpoints.Count > 0)
{
var endpoints = MetadataResolver.Resolve(typeof(MCWCFService.MCManagementService), findResults.Endpoints[0].Address);
if (endpoints.Count > 0)
{
foreach (var item in endpoints)
{
if (item.Address.Uri.Scheme == "net.tcp")
{
logger.Debug("Discovered NetTcpAddress [{0}]", item.Address);
//serverTCPEndpoint = item.Address;
IPAddress[] serverIPAddresses = Dns.GetHostAddresses(item.Address.Uri.Host);
foreach (var address in serverIPAddresses)
{
if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
serverTCPEndpoint = item.Address;
break;
}
}
}
if (item.Address.Uri.Scheme == "http")
{
logger.Debug("Discovered basicHTTPAddress [{0}]", item.Address);
basicHTTPendpoint = item.Address;
}
}
}
}
else
logger.Debug("Discovery failed for MCWCFService");
logger.Debug("MCWCFService TCPEndpoint = [{0}]", serverTCPEndpoint);
mcWCFEndpointAddress = serverTCPEndpoint;
string hostName = Dns.GetHostName();
IPAddress hostIPAddress = null;
IPHostEntry host;
host = Dns.GetHostEntry(hostName);
//logger.Debug("Host = [{0}]", host);
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
hostIPAddress = ip;
logger.Debug("MCService Host [{0}] IP address = [{1}]", hostName, ip);
}
}
ChannelFactory<MCWCFService.IMCManagementService> scf = null;
string location = "";
try
{
location = "create scf";
scf = new ChannelFactory<MCWCFService.IMCManagementService>(
new NetTcpBinding(SecurityMode.None),
serverTCPEndpoint);
location = "create channel";
MCWCFService.IMCManagementService channel = scf.CreateChannel();
location = "set db path";
channel.SetMyCourtsDataDirectory(dataDirectory);
location = "set hostIPaddress";
channel.SetMCServiceIPAddress(hostIPAddress);
location = "start logging";
channel.StartLogging();
}
catch (Exception ex)
{
logger.Fatal("Unable to complete setdb path in MCWCFService # [{0}]: {1}", location, ex);
}
finally
{
if (scf != null && scf.State != CommunicationState.Faulted)
{
if (scf.State == CommunicationState.Opened)
scf.Close();
}
}
}
Here's the method to start the logging on the WCF Service:
public void StartLogging()
{
try
{
LoggingConfiguration cfg = new LoggingConfiguration();
NetworkTarget networkTarget = new NetworkTarget();
networkTarget.Layout = "${longdate} ${machineName} ${callsite} ${message} ${exception:format=tostring}";
networkTarget.Address = string.Format("tcp://{0}:{1}", mcServiceIPAddress, (int)LoggingListeningPorts.MCWCFService);
networkTarget.NewLine = false;
networkTarget.KeepConnection = false;
networkTarget.Name = "network1";
LoggingRule networkRule = new LoggingRule("*", LogLevel.Trace, networkTarget);
cfg.LoggingRules.Add(networkRule);
LogManager.Configuration = cfg;
mcmLogger = LogManager.GetLogger("MCManagementService");
mcmLogger.Fatal("##########################################");
mcmLogger.Trace(string.Format("######## MCWCFService {0} ",
Assembly.GetExecutingAssembly().GetName().Version).PadRight(42, '#'));
mcmLogger.Fatal("##########################################");
}
catch (Exception ex)
{
eventlog.WriteEntry(string.Format("MCManagemntService error {0}", ex), EventLogEntryType.Error);
//errorLogger.FatalException("Unable to start logging: ", ex);
}
At this point, the loging from the Windows Service now gets logged to the WCF Service log.
The obvious solution is that I have mixed up the TCP Listening ports but I've checked that so many times I've got a headache.
I have also tried executing the following method on the Windows Service immediately after starting the logging on the WCF Service but it doesn't do anything...
private void startTCPLogging()
{
logger.Debug("Starting TCP Logger");
try
{
if (logger != null)
logger = null;
LoggingConfiguration cfg = new LoggingConfiguration();
NetworkTarget networkTarget = new NetworkTarget();
networkTarget.Layout = "${longdate} ${machineName} ${callsite} ${message} ${exception:format=tostring}";
networkTarget.Address = string.Format("tcp://{0}:{1}", mcWCFEndpointAddress, (int)LoggingListeningPorts.MCService);
networkTarget.NewLine = false;
networkTarget.KeepConnection = false;
networkTarget.Name = "network1";
LoggingRule networkRule = new LoggingRule("*", LogLevel.Trace, networkTarget);
cfg.LoggingRules.Add(networkRule);
LogManager.Configuration = cfg;
logger = LogManager.GetCurrentClassLogger();
logger.Fatal("Logger switched to TCP Listener");
}
catch (Exception ex)
{
//eventlog1.WriteEntry(string.Format("MCManagemntService error {0}", ex), EventLogEntryType.Error);
//errorLogger.FatalException("Unable to start logging: ", ex);
}
I need two separate logs and I can't see why they are combined into the WCF Service log?
If you are running the Windows Service and the WCF Service in the same process, then it could be due to the fact that you are resetting the LogManager.Configuration .
The instance of LogManager is available within your whole process. So, every time you set the configuration with a new LoggingConfiguration(), you loose the previous set configuration.
Try to set the LogManager.Configuration once, and from there just add or remove targets with methods like :
LogManager.Configuration.FindTargetByName(..)
LogManager.Configuration.RemoveTarget(..)
LogManager.Configuration.AddTarget(...)
or with the help of the property :
LogManager.Configuration.AllTargets

ProcessStartInfo Browser Output

I have tried everything I can think of and every code sample imaginable but I cannot get any type of output using Process.Start when opening a browser. I have tried just looking at error output and eliciting 404 errors and Standard Output using actual URLs - nothing works. Here is the simplest example - although it fails as well even though the browser launches every time...
//Default Browser
RegistryKey key = null;
string defaultPath = "";
try
{
key = Registry.ClassesRoot.OpenSubKey("HTTP\\shell\\open\\command", false);
defaultPath = key.GetValue("").ToString().ToLower().Replace("\"", "");
if (!defaultPath.EndsWith(".exe"))
defaultPath = defaultPath.Substring(0, defaultPath.LastIndexOf(".exe") + 4);
}
catch { }
finally
{
if (key != null)
key.Close();
}
None Working Code:
ProcessStartInfo browserInfo = new ProcessStartInfo();
browserInfo.CreateNoWindow = true;
browserInfo.WindowStyle = ProcessWindowStyle.Hidden;
browserInfo.FileName = defaultPath;
browserInfo.Arguments = "http://www.google.com";
browserInfo.UseShellExecute = false;
browserInfo.RedirectStandardError = true;
browserInfo.RedirectStandardOutput = true;
string error = "";
string output = "";
String strProcessResults;
try
{
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = defaultPath;
p.StartInfo.Arguments = "http://www.google.com/NoneYa.html";
p.Start();
// Read the output stream first and then wait.
strProcessResults = p.StandardError.ReadToEnd();
p.WaitForExit();
}
catch (System.ComponentModel.Win32Exception BrowserX)
{
//We ignore the error if a browser does not exist!
if (BrowserX.ErrorCode != -2147467259)
throw BrowserX;
}
OR
try
{
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = defaultPath;
p.StartInfo.Arguments = "http://www.google.com";
p.Start();
// Read the output stream first and then wait.
strProcessResults = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
catch (System.ComponentModel.Win32Exception BrowserX)
{
//We ignore the error if a browser does not exist!
if (BrowserX.ErrorCode != -2147467259)
throw BrowserX;
}
I've never actually checked, but I'd be surprised if your browser printed anything to stdout. It's a Windowed application.

Resources