I have a question about running cmd from winform.
I have managed to connect and get information from the remote machine(infotrend disk server).
However I could not make a operation on the remote machine such "create disk part
below I have written these code....
InfotrendProcess.StartInfo.UseShellExecute = false;
InfotrendProcess.StartInfo.RedirectStandardInput = true;
InfotrendProcess.StartInfo.RedirectStandardOutput = true;
InfotrendProcess.StartInfo.RedirectStandardError = true;
InfotrendProcess.StartInfo.WorkingDirectory = workingPath;
InfotrendProcess.StartInfo.FileName = "C:\\Windows\\System32\\cmd.exe";
InfotrendProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
InfotrendProcess.StartInfo.CreateNoWindow = true;
const string quote = "\"";
cmd_message = "java -jar " + quote + "runCLI" + quote; (MANAGED TO START CLI RUN COMMAND STEP 1)
InfotrendProcess.StartInfo.Arguments = "/K " + cmd_message;
InfotrendProcess.OutputDataReceived += InfotrendProcess_OutputDataReceived1;
InfotrendProcess.ErrorDataReceived += InfotrendProcess_ErrorDataReceived;
InfotrendProcess.Start();
using (StreamWriter sw = InfotrendProcess.StandardInput) (MANAGED TO CONNECT AND SEND DELETE
PART COMMAND STEP 2)
{
sw.WriteLine("connect " + IPNumber);
Thread.Sleep(1000);
sw.WriteLine("del part 01D9F2C6614DF837"); (COULD NOT SEND RESPOND y/s, MAKES NEW LINE)
sw.WriteLine("y")
}
I could not send the "y/n" respond because I have to send it in the same line after a period. Instead it makes a new line. Should I use a different way? Could anyone help me, how I can run the final command.
Related
According to the Snowflake docs, when a user executes a copy command it will return 1 of 3 status values:
loaded
load failed
partially loaded
My question is if I use the Python Snowflake Connector (see example code below) to execute a copy command is an exception raised if the status returned is load failed or partially loaded?
Thank you!
copy_dml = 'copy into database.schema.table ' \
'from #fully_qualified_stage pattern = \'.*'+ table_name +'.*[.]json\' ' \
'file_format = (format_name = fully_qualified_json_format) ' \
'force = true;'
try:
import snowflake.connector
#-------------------------------------------------------------------------------------------------------------------------------
#snowflake variables
snowflake_warehouse = credentials.iloc[0]['snowflake_warehouse']
snowflake_account = credentials.iloc[0]['snowflake_account']
snowflake_role = credentials.iloc[0]['snowflake_role']
snowflake_username = credentials.iloc[0]['Username']
snowflake_password = credentials.iloc[0]['Password']
snowflake_connection = ''
cs = ''#snowflake connection cursor
exec_copy_dml = ''
copy_result_field_metadata = ''
copy_result = ''
snowflake_copy_result_df = ''
#-------------------------------------------------------------------------------------------------------------------------------
# load JSON file(s) into Snowflake
snowflake_connection = snowflake.connector.connect(
user = snowflake_username,
password = snowflake_password,
account = snowflake_account,
warehouse = snowflake_warehouse,
role = snowflake_role)
cs = snowflake_connection.cursor()
exec_copy_dml = cs.execute(copy_dml)
copy_result = exec_copy_dml.fetchall()
copy_result_field_metadata = cs.description
snowflake_copy_result_df = snowflake_results_df(copy_result_field_metadata,copy_result)
except snowflake.connector.errors.ProgrammingError as copy_error:
copy_exception_message = "There was a problem loading JSON files to Snowflake," + \
"a snowflake.connector.errors.ProgrammingError exception was raised."
print(copy_exception_message)
raise
except Exception as error_message:
raise
finally:
snowflake_connection.close()
I believe it won't raise exception for load status, you have to check the load status and take necessary action if required.
After you issue your COPY INTO dml, you can run the following query -
SELECT * FROM TABLE(VALIDATE(TABLE_NAME, job_id => '_last'))
This will give you details on the files that you were trying to load. It will normally return empty, unless you encountered issues upload.
You can save this save results in an object and make necessary control adjustments.
I have a series of PowerShell scripts that are run by a TFS agent are part of a build process. These are run on several servers(Windows Server 2012 R2) that publish a series of DACPAC's to a given set of Databases. Recently I updated all the TFS build agents to the latest version(TFS 2018)
Today I noticed that one of these servers in my build process is no longer running, in particular it is failing to run "SqlPackage.exe" due to a "System.StackOverflowException" error(So very appropriate for this site).
This same issue can be reproduced by running the power shell script by hand, but only on this one server, all the others run without issue. The script looks like this:
$arguments = '/a:Publish /pr:"' + $scriptPath + $database + ".publish.xml" + '" /sf:"' + $dacPac + '" /tcs:"Data Source=' + $servername + ';Persist Security Info=True;User ID=' + $username + ';Password=' + $password + ';Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True"'
Start-Process -FilePath "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\130\SqlPackage.exe" -ArgumentList $arguments -NoNewWindow -PassThru -Wait
When run by hand, the debugged the exception is:
An unhandled exception of type 'System.StackOverflowException' occurred in Microsoft.SqlServer.TransactSql.ScriptDom.dll
I'm really not sure what configuration on this server would cause this sort of issue. Resource wise the server is very powerful with large amounts of available memory, the other servers run it just fine. I've tried various versions of "SqlPackage"(13, 14) but it doesn't seem to have any effect. I've swapped out the DacPac's but that doesn't seem to work either...
Has anyone seen this issue before? What sort of server configuration can cause this sort of issue?
Update 1: hmmm, just switch to the new "14.0", "SqlPackage.exe" now I'm getting it on all my machines, I wonder if it has to do with any realated dll's such as the ones I installed in SSDT.
Actually now that I think about this, I think this issue started on the server when I first installed VS 2017, I wonder if that has any effect on "SqlPackage.exe"?
I also found this interesting post, I wonder if I can work around it this way...
I never figured out how to solve this for "SqlPackage", we ended up creating our own package deployer console app and calling that instead via a console app ("DacpacDeployUtility"):
static int Main(string[] args)
{
try
{
string destinationServer = args[0];
string destinationDatabase = args[1];
string userID = args[2];
string password = args[3];
string publishFileFullPath = args[4];
string dacpacFileFullPath = args[5];
SetupRegistryQueryExecutionTimeout();
PublishDacpacSimple(destinationServer, destinationDatabase, userID, password, publishFileFullPath, dacpacFileFullPath);
return 0; //where 0 = success
}
catch (Exception ex)
{
Console.WriteLine("Error in Main: " + ex.Message + "\n" + ex.StackTrace);
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("Value in args[" + i + "]: " + (i == 3 ? "**********" : args[i]));
}
Console.WriteLine("Failed to publish dacpac.");
//Return error state
return 1;
}
}
private static void SetupRegistryQueryExecutionTimeout()
{
//Fixes an annoying issue with slow sql servers: https://stackoverflow.com/a/26108419/2912011
RegistryKey myKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\VisualStudio\\12.0\\SQLDB\\Database", true);
if (myKey != null)
{
myKey.SetValue("QueryTimeoutSeconds", "0", RegistryValueKind.DWord);
myKey.Close();
}
myKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\VisualStudio\\14.0\\SQLDB\\Database", true);
if (myKey != null)
{
myKey.SetValue("QueryTimeoutSeconds", "0", RegistryValueKind.DWord);
myKey.Close();
}
myKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\VisualStudio\\15.0\\SQLDB\\Database", true);
if (myKey != null)
{
myKey.SetValue("QueryTimeoutSeconds", "0", RegistryValueKind.DWord);
myKey.Close();
}
}
private static void PublishDacpacSimple(string destinationServer,
string destinationDatabase,
string userID,
string password,
string publishFileFullPath,
string dacpacFileFullPath)
{
string connectionString = BuildConnectionString(destinationServer, destinationDatabase, userID, password);
XmlDocument xdoc = new XmlDocument();
xdoc.Load(publishFileFullPath);
DacServices ds = new DacServices(connectionString);
using (DacPackage package = DacPackage.Load(dacpacFileFullPath))
{
var options = new DacDeployOptions();
options.CommandTimeout = 600;
ds.Message += (object sender, DacMessageEventArgs eventArgs) => Console.WriteLine(eventArgs.Message.Message);
ds.Deploy(package, destinationDatabase, true, options);
}
}
Then call that in the PowerShell script:
$DacPacDeployerPath = """" + $scriptPath + "..\..\..\DacpacDeployUtility\bin\release\EBMDacpacDeployUtility.exe"""
$Output = Start-Process -FilePath $DacPacDeployerPath -ArgumentList $arguments -NoNewWindow -PassThru -Wait
I have a multi screen computers system. Once in a while, for a reason I don't understand, the dialog boxes are on the wrong monitor. For instance, I'll have a program running in monitor A and an OK box will open in monitor D. This is very frustrating.
I found a VBS script called "PositionDialogs.vbs" found here: https://www.realtimesoft.com/ultramon/scripts/
Const SNAP_TO_MONITOR = False 'set this to True to ensure dialogs aren't placed between two monitors
Const INTERVAL = 2 'number of seconds the script waits before enumerating open windows again
Set sys = CreateObject("UltraMon.System")
Set wnd = CreateObject("UltraMon.Window")
Set wndParent = CreateObject("UltraMon.Window")
'create the two maps used to store positioned windows
Set arrAdd = CreateObject("Scripting.Dictionary")
Set arrLookup = CreateObject("Scripting.Dictionary")
Do While True
'enumerate all application windows
For Each w In wnd.GetAppWindows(True)
If w.HWndParent <> 0 Then
wndParent.HWnd = w.HWndParent
move = True
If arrLookup.Exists(w.HWnd) = True Then move = False
arrAdd.Add w.HWnd, 0
If move = True Then
If SNAP_TO_MONITOR = False Then
If w.Monitor <> wndParent.Monitor Then
w.Monitor = wndParent.Monitor
w.ApplyChanges 1 + 2 'WNDCHANGE_RESIZE_TO_FIT + WNDCHANGE_CLIP_TO_WORKSPACE
End If
Else
Set parentMon = sys.Monitors(wndParent.Monitor - 1)
parentLeft = parentMon.WorkLeft
parentTop = parentMon.WorkTop
parentRight = parentLeft + parentMon.WorkWidth
parentBottom = parentTop + parentMon.WorkHeight
dlgLeft = w.Left
dlgTop = w.Top
dlgRight = dlgLeft + w.Width
dlgBottom = dlgTop + w.Height
If dlgLeft < parentLeft Then
w.Left = parentLeft
ElseIf dlgRight > parentRight Then
w.Left = parentRight - w.Width
End If
If dlgTop < parentTop Then
w.Top = parentTop
ElseIf dlgBottom > parentBottom Then
w.Top = parentBottom - w.Height
End If
w.ApplyChanges 0
End If
End If
End If
Next
'swap maps, then clear arrAdd. this way we don't have entries for windows which no longer exist
Set temp = arrLookup
Set arrLookup = arrAdd
Set arrAdd = temp
Set temp = Nothing
arrAdd.RemoveAll
WScript.Sleep INTERVAL * 1000
Loop
that will move the dialog box to whatever monitor called it.
I have it running on Windows startup using a batch file, and it runs as a process. My problem is that the console window that shows doesn't go away unless I click the X to close it.
The bath files looks like this:
wscript PositionDialogs.vbs
exit
I assume there is something I can add to the script to make it close after it loads itself into memory? If so, what?
aschipf was correct.
I made the batch file
start PositionDialogs.vbs
exit
(used START instead of WSCRIPT) and it closed as expected, while the process still ran in task manager
Hi all i've got a complex SSIS package, however i'm hitting my head against a brick wall with a particular part. I've got a maintenance part that will delete files that are older than 3 months old (from today's date). The files all have the date in the filename, for example AA-CDR-20110606030000-2-001A648E6F74-026874.xml
So i've written a task that will loop over all the files in a particular folder using a Foreach loop, then i have a script that will load in the filename using a variable set using the foreach loop. Then delete the file using the script below. This works fine when running in debug mode. However when trying to execute this on the server i get a failure with a "System.FormatException: String was not recognized as a valid DateTime.". I really dont understand why, any ideas?
DateTime deleteDate = DateTime.Today.AddMonths(-3);
String file = Dts.Variables["FileName"].Value.ToString();
String fileDateString = file.Substring(42, 8);
String fileDateYear = fileDateString.Substring(0, 4);
String fileDateMonth = fileDateString.Substring(4, 2);
String fileDateDay = fileDateString.Substring(6, 2);
DateTime fileDateTime = Convert.ToDateTime(fileDateDay + "-" + fileDateMonth + "-" + fileDateYear);
if (fileDateTime < deleteDate)
{
System.IO.File.Delete(file);
}
It seems that there is a file on the production server that does not follow the pattern and the date cannot be extracted from its name.
Try to use something like this:
try
{
DateTime fileDateTime = Convert.ToDateTime(fileDateDay + "-" + fileDateMonth + "-" + fileDateYear);
if (fileDateTime < deleteDate)
{
System.IO.File.Delete(file);
}
}
catch (System.FormatException)
{
// log the Dts.Variables["FileName"] value here to see why it could not be parsed
}
I have used Oracle Advanced Security to encrypt data during data transfer. I have successfully configured ssl with below parameters and I have restarted the instance. I am retrieving data from a Java class given below. But I could read the data without decrypting, the data is not getting encrypted.
Environment:
Oragle 11g database
SQLNET.AUTHENTICATION_SERVICES= (BEQ, TCPS, NTS)
SSL_VERSION = 0
NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)
SSL_CLIENT_AUTHENTICATION = FALSE
WALLET_LOCATION =
(SOURCE =
(METHOD = FILE)
(METHOD_DATA =
(DIRECTORY = C:\Users\kcr\Oracle\WALLETS)
)
)
SSL_CIPHER_SUITES= (SSL_RSA_EXPORT_WITH_RC4_40_MD5)
Java class:
try{
Properties properties = Utils.readProperties("weka/experiment/DatabaseUtils.props");
// Security.addProvider(new oracle.security.pki.OraclePKIProvider()); //Security syntax
String url = "jdbc:oracle:thin:#(DESCRIPTION =\n" +
" (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))\n" +
" (CONNECT_DATA =\n" +
" (SERVER = DEDICATED)\n" +
" (SERVICE_NAME = sal)\n" +
" )\n" +
" )";
java.util.Properties props = new java.util.Properties();
props.setProperty("user", "system");
props.setProperty("password", "weblogic");
// props.setProperty("javax.net.ssl.trustStore","C:\\Users\\kcr\\Oracle\\WALLETS\\ewallet.p12");
// props.setProperty("oracle.net.ssl_cipher_suites","SSL_RSA_EXPORT_WITH_RC4_40_MD5");
// props.setProperty("javax.net.ssl.trustStoreType","PKCS12");
//props.setProperty("javax.net.ssl.trustStorePassword","welcome2");
DriverManager.registerDriver(new OracleDriver());
Connection conn = DriverManager.getConnection(url, props);
/*8 OracleDataSource ods = new OracleDataSource();
ods.setUser("system");
ods.setPassword("weblogic");
ods.setURL(url);
Connection conn = ods.getConnection();*/
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select * from iris");
///////////////////////////
while(rset.next()) {
for (int i=1; i<=5; i++) {
System.out.print(rset.getString(i));
}
}
Are you expecting that your SELECT statement would return encrypted data and that your System.out.print calls would result in encrypted output going to the screen? If so, that's not the way advanced security works-- Advanced Security allows you to encrypt data over the wire but the data is unencrypted in the SQLNet stack. Your SELECT statement, therefore, would always see the data in an unencrypted state. You would need to do a SQLNet trace or use some sort of packet sniffer to see the encrypted data flowing over the wire.
You'll find the documentation in "SSL With Oracle JDBC Thin Driver".
In particular you should probably use PROTOCOL = TCPS instead of PROTOCOL = TCP. I'd also suggest using a stronger cipher suite (and avoid the anonymous ones, since with them you don't verify the identity of the remote server).