How to run IISWeb.vbs command in an asp.net application - asp.net

Can somebody please help me in executing the IISWeb.vbs commands from the c# code which I am trying to use for starting and stopping the websites on remote IIS servers (IIS 6.0).
I have tried other options like using DirectorServises with SyytemManagement or with WMI but in all cases code works fine for the local IIS server but displays error for the remote servers. I get 'Access denied' error for remote servers
I have got the all the servers in the same domian and network area and trying with a user account with administrative priviledge but nothing works for remote machine so giving it a try using IISWeb.vbs.
Please note that from my dev machine I am able to stop and start the websites on remote machines using this IISWeb.vbs commands without any problem when I run it from command prompt. So definitely there is no permission issues.
Code I am using:
Process p = new Process();
p.StartInfo.FileName = "cscript.exe";
p.StartInfo.Arguments = "iisweb.vbs /stop w3svc/87257621 test /s servername /u userid /p password";
p.StartInfo.UseShellExecute = false;
p.Start();
p.WaitForExit();
int i= p.ExitCode;
Surprisingly I am not getting any error and i get return code '0' but nothing but website is not getting stopped.
Please help me out.

Figured out the problem, code was trying to find out the iisweb.vbs file inside c:\program files\Visual Studio\.........and was unable to find it out. So I amended the code to specifically look for the iisweb.vbs file at C:\Windows\System32 location and it is working fine now.
Here is the working version of code for stopping and starting a website on remote machine having IIS 6.0.
ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName = #"C:\WINDOWS\system32\cscript.exe";
psi.Arguments = #"C:\WINDOWS\system32\iisweb.vbs /stop w3svc/1 test /s ServerName /u UserId /p Password";
psi.RedirectStandardOutput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process listFiles;
listFiles = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader myOutput = listFiles.StandardOutput;
listFiles.WaitForExit(2000);
if (listFiles.HasExited)
{
string output = myOutput.ReadToEnd();
//this.processResults.Text = output;
}

Related

asp.net core executing powershell some commands work while others return result 0

I have the following simple code that works and executes a powershell command in asp.net core website running on my cshtml.cs code behind page
using System.Management.Automation;
public void Execute()
{
using (var ps = PowerShell.Create())
{
ps.AddScript("Get-Date");
var results = ps.Invoke();
foreach (var result in results)
{
string test = result.ToString();
}
}
}
This works i get the current date reported as a string and results variable contains a count of 1.
"7/16/2020 4:38:27 PM"
If i then change it to another command say
ps.AddScript("Get-WmiObject");
or
ps.AddScript("Get-LocalGroupMember -group my_local_group_name");
Then i get no results, results comes back as count of 0 ?? The only thing i can determine is that Get-Date is a single string where as the other commands Get-WmiObject and Get-LocalGroupMember are multiple lines of text in the outputs when i execute them from a normal Powershell window.
my goal is to be able to execute the Get-LocalGroupMember command and get it's output. Is there something else i'm missing or not doing in terms of Powershell commands ? why is it some commands are working and producing output and others are not ?
UPDATE:
So i was getting error in the error stream of the ps object it states
{The 'Get-LocalGroupMember' command was found in the module 'Microsoft.PowerShell.LocalAccounts', but the module could not be loaded. For more information, run 'Import-Module Microsoft.PowerShell.LocalAccounts'.}
if i open a x86 Powershell window and run the Get-LocalGroupMember cmd it gives me error
Get-LocalGroupMember : The term 'Get-LocalGroupMember' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.
running the Get-LocalGroupMember cmd in a regular Powershell window (that is x64) the cmd runs perfect.
My project is set to x64 :( so am failing to understand why asp.net is using what seems to me a 32bit version of powershell. That's what i need i need to be able to execute my powershell cmds as x64 because Get-LocalGroupMember cmd is only available in Powershell x64 .
Please Help ? thanks
so i ended up having to do the following for some reason in order to get certian commands like Get-LocalGroupMember to work, other commands like Get-Date don't require the import, and even though on my system i had execution policy unrestricted, whenever i use c# in asp.net and checked errors on my ps object it was acting like it wasn't and would not let me run a script using AddScript. So i had to be administrator running visual studio and use set-executionpolicy like below, then be able to add the localaccounts module to be able to use Get-LocalGroupMember.. again if i open a x64 Powershell window on the system i can run Get-LocalGroupMember fine. seems c# is doing some weird things with the Powershell shell that it is creating and running in memory. Anyway hopefully this saves someone else time if they run into the same situation.
using (var ps = PowerShell.Create())
{
ps.AddScript("Set-ExecutionPolicy Unrestricted -force");
ps.AddScript("Import-Module Microsoft.PowerShell.LocalAccounts");
ps.AddScript("Get-LocalGroupMember -group your_local_group_name | Out-String");
var results = ps.Invoke();
foreach (var result in results)
{
string test = result.ToString();
TestText = test;
}
}

Error adding attachment file to batch job generated email in AX 2009

I have an error while sending email through batch job "unable to create CLR object". The code works fine if there's no attachment,Permissions are OK on files and directories where attachments are located.
Here's my code:
permissionSet = new Set(Types::Class);
permissionSet.add(new InteropPermission(InteropKind::ClrInterop));
permissionSet.add(new FileIOPermission(_filename, 'rw'));
CodeAccessPermission::assertMultiple(permissionSet);
smtpClient = new System.Net.Mail.SmtpClient();
smtpClient.set_Port(25);
smtpClient.set_DeliveryMethod(System.Net.Mail.SmtpDeliveryMethod::Network);
smtpClient.set_UseDefaultCredentials(true);
smtpClient.set_Host('smtp-out.adista.fr');
mail = new System.Net.Mail.MailMessage(sendFrom,sendTo);
mail.set_Subject(subject);
mail.set_IsBodyHtml(true);
mail.set_Body(emailBody);
mailAttachementCollection = mail.get_Attachments();
mailAttachment = new System.Net.Mail.Attachment(filename);
mailAttachementCollection.Add(mailAttachment);
smtpClient.Send(mail);
CodeAccessPermission::revertAssert();
I debugged and the error comes in "mail attachment =new System.Net.Mail.Attachment(filename);" line. Is there a path coding error ? I used UNC path like '\network\directory\file.csv' and #path, hardcoding path and filename with the same error.
I tried with sysmailer class and I also have an error while adding attachment.
Any ideas?
Thanks for any help
regards,
The AOS service account must have Windows file permission to read the file.
Access problems are the most common cause of batch file problems, or maybe second to non-UNC file names.

Running command prompt arguments by ASP.Net application

I want to run command prompt arguments using a ASP.Net application. I am using visual studio 2013.
Is it possible?
the followings are the command prompt commands I want to execute using MVC application to create and run a job in jenkins
C:\Users\ .jenkins java -jar C:\Users.jenkins\war\WEB-INF\jenkins- cli.jar -s http://localhost create-job myjob < C:\Users\Desktop\config.xml
C:\Users\ .jenkins java -jar C:\Users.jenkins\war\WEB-INF\jenkins-cli.jar -s http://localhost / build myjob
Just to be sure, you want to run these command line tools on thee webserver, right? Not on the client connecting to the web application.
If the former, it's pretty straightforward, make sure that you IIS application pool is running under a user account that is allowed to execute these tools and use the Process class together with the ProcessStartInfo class to invoke the commandline and wait for the results:
string jobname = jobNameFromInput;
if (!Regex.IsMatch(jobname, "^(\"[a-z0-9-_ ]+\"|'[a-z0-9-_ ]+'|[a-z0-9-_]+)$", RegexOptions.IgnoreCase)
{
throw SecurityException("Invalid job name");
}
ProcessStartInfo startInfo = new ProcessStartInfo("C:\Users.jenkins\java.exe");
string argumentTemplate = "-jar C:\\Users.jenkins\\war\\WEB-INF\\jenkins-cli.jar -s http://localhost / build {0}";
startInfo.Arguments = string.Format(argumentTemplate, jobname);
Process.Start(startInfo);
Process.WaitForExit();
See:
Process.WaitForExit
Process.Start

Getting error while connecting to oracle [duplicate]

I Google[d] for this error ORA-12560: TNS:protocol adaptor error but not able to find the actual reason and how to solve this error ?
Can anyone tell me a perfect solution to solve login problem.
Go to the windows machine that hosts the Oracle database server
Go to Start -> Run -> Services.msc in Windows.
Locate OracleService < SID > (here OracleServiceORCL) and click on Start to start the oracle database service (if not already running)
Once it is up and running, from the command prompt run the following:
tnsping < tnsalias >
(tnsalias entry you can find it in tnsnames.ora file)
In my case I didn't have an OracleService (OracleServiceORCL) in Windows Services.msc as described in Bharathi's answer.
I executed this command:
C:\> ORADIM -NEW -SID ORCL
and then the OracleService called OracleServiceORCL just showed up and got started in Services.msc. Really nice.
Source: https://forums.oracle.com/forums/message.jspa?messageID=4044655#4044655
Seems like database is not up. It might be due to restarting machine and the instance is not set to autostart and it so not started munually after starting from services Screen.
Just goto Command prompt
Set Oracle SID
C:>set oracle_sid=ORCL
Now run Net start command.
C:>net start oracleserviceORCL
from command console, if you get this error you can avoid it by typing
c:\> sqlplus /nolog
then you can connect
SQL> conn user/pass #host:port/service
Add to the enviroment vars the following varibale and value to identify the place of the tnsnames.ora file:
TNS_ADMIN
C:\oracle\product\10.2.0\client_1\network\admin
In my case (for OracleExpress) the service was running, but I got this issue when trying to access the database via sqlplus without connection identifier:
sqlplus sys/mypassword as sysdba
To make it work I needed to add the connection identifier (XE for Oracle Express), so following command worked ok:
sqlplus sys/mypassword#XE as sysdba
If you still get ORA-12560, make sure you can ping the XE service. Use:
tnsping XE
And you should get OK message along with full connection string (tnsping command is located in oracle's installation dir: [oracle express installation dir]\app\oracle\product\11.2.0\server\bin). If you can not ping make sure your tnsnames.ora file is reachable for sqlplus. You might need to set TNS_ADMIN environment variable pointing to your ADMIN directory, where the file is located, for example:
TNS_ADMIN=[oracle express installation dir]\app\oracle\product\11.2.0\server\network\ADMIN
After searching alot got a simple way to solve it.
Just follow the steps.
Check status of your listener.
open command prompt and type lsnrctl status
You will get no listener.
Now open listener.ora file which is present in following directory: C:\oraclexe\app\oracle\product\11.2.0\server\network\ADMIN
Open that file and change the host parameter with you computer name
You can get your computer name by right click on My Computer and check you computer name, and replace host parameter with your computer name as follows:
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
(ADDRESS = (PROTOCOL = TCP)(HOST = Electron-PC)(PORT = 1521)
)
)
)
So here you can observe HOST = Electron-PC, which is my computer name.
Save the listener.ora file and again return to cammand propt
3.Type the following in command prompt lsnrctl start
This will start the OracleTNSListner.
you can check it in the service by opening services tab of Task Manager. if not started automatically you can start it.
Just this much and you are ready to work again on oracle.
Best of Luck.
Quite often this means that the listener hasn't started. Check the Services panel.
On Windows (as you are) another common cause is that the ORACLE_SID is not defined in the registry. Either edit the registry or set the ORACLE_SID in a CMD box. (Because you want to run sqlplusw.exe I suggest you edit the registry.)
I have solved the problem the easy way. My oracle was running just fine in the past. After I installed MS SQL Server was when I noticed this problem. I just uninstalled MS SQL Server on my machine then the problem was gone. Make sure you restart your computer after that. Now I can connect to Oracle database through SQLPlus again. My guess is that there's some conflict between the two. Hope this helps.
Another possible solution that just worked for me...considering I was using my local login as the dba permissions.
Follow the steps to get to Services. Right click on the instance and go to 'Log On'? (might not be the name but it's one of the tabs containing permissions). Change the settings to use LOCAL.
If none the above work, then try this :
Modify the LISTENER.ora (mine is found in : oracle\product\11.2.0\dbhome_1\NETWORK\ADMIN\listener.ora) ==> add a custom listener that points to your database(SID), example my SID is XZ0301, so :
## Base XZ03001
SID_LIST_LISTENER_XZ03001=(SID_LIST=(SID_DESC=(ORACLE_HOME =
E:\oracle\product\11.2.0\dbhome_1)(SID_NAME= XZ03001)))
LISTENER_XZ03001=(DESCRIPTION_LIST=(ADDRESS=(PROTOCOL =
TCP)(HOST=MyComputerName)(PORT= 1521)))
DIAG_ADR_ENABLED_LISTENER_XZ03001=ON
ADR_BASE_LISTENER_XZ03001=E:\oracle
Restart your machine
For Windows 7, use the following to modify the LISTENER.ora:
- Go to Start > All Programs > Accessories
- Right click Notepad and then click Run as Administrator .
- File>open and navigate to the tnsnames.ora file.
- Make the changes then it should allow you to save
It really has worked on my machine. But instead of OracleServiceORCL I found OracleServiceXE.
Flow the flowing steps :
Edit your listener.ora and tnsnames.ora file in
$Oracle_home\product\11.2.0\client_1\NETWORK\ADMIN location
a. add listener.ora file
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))
)
)
ADR_BASE_LISTENER = C: [here c is oralce home directory]
b. add in tnsnames.ora file
SCHEMADEV =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = dabase_ip)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = SCHEMADEV)
)
)
Open command prompt and type
sqlplus username/passowrd#oracle_connection_alias
Example : username : your_database_username
password : Your_database_password
oracle_connection_alias : SCHEMADEV for above example.
Just to add up, follow the screenshot and choose local account to start if not selected. Then start the service.
You need to tell SQLPlus which database you want to log on to. Host String needs to be either a connection string or an alias configured in your TNSNames.ora file.
ORA-12560: TNS:erro de adaptador de protocolo
set Environment Variables: ORACLE_BASE, ORACLE_HOME, ORACLE_SID
make sure your user is part of ORACLE_GROUP_NAME (Windows)
make sure the file ORACLE_HOME/network/admin/sqlnet.ora is:
SQLNET.AUTHENTICATION_SERVICES = (NTS)
(Windows) Be carefull when you add a new Oracle client: adding a new path to the PATH env. variable can mess things up. The first entry in this variable makes a difference: certify that the sqlplus executable in the ORACLE_HOME (ORACLE_HOME/bin) comes first in the PATH env. variable.
I try 2 option:
You change service OracleService in Service Tab -> Running
Login with cmd command: sqlplus user_name/pass_word#orcl12C
Note: orcle12c -> name of OracleService name run in you laptop
Below fixes can be applied to resolve TNS 12560 error
Get Latest patch for SQL*NET client software
Set $ORACLE_HOME and $PATH variable (should be accessible for System user)
Check permissions on PC client
Check $TNS_ADMIN variable
Check if network has firewall or antivirus issues
Check if windows services Run >> Services.msc has OracleXE or OracleORCL service running
Check below link in case of net tracing error:
http://dba-oracle.com/t_sql_net_tracing.htm
In my case, (ORA-12560: TNS protocol adapter error)Issue cause of database connection issue like database, user name and password.
Once you got the issue. Initially you have to check connection details, after check the oracle service and further more.
I missed some connection details, So only i got TNS protocol adapter error,
I will changed the connection details, It would be working fine.

MSdeploy in Powershell - show or help me something really working

I set up TFS Deployer currenlty at work and have been tried to write a Powershell script for the deployment. I have been researched and read many posted questions and answers at StackoverFlow but I couldn't really making the script working yet.
So far, when I run the following PS on windows PowerShell ISE, it runs.
$envMsDeploy = $env:msdeploy
$DirMsDeploy = split-Path -Parent $envMsDeploy
# defined the current location to $DirMSDeploy = C:\Program Files\IIS\Microsoft Web Deploy V2
set-location $DirMsDeploy
$arg = #(
'-verb:sync';
'-source:contentPath=' + $buildDroppedLocation;
'-dest:contentPath=' + $destinationPath;
' -whatif > c:\temp\msdeploy.log'
)
$runMSDeploy = ($DirMsDeploy + "\Msdeploy.exe " + $arg)
$runMSDeploy | Out-file c:\temp\MsDeployTest.bat
I put the last sentence to confirm what gets saved $runMSDeploy. Now looks like $runMSDeploy saves what I want to put finally.
MSDeployTest.Bat contains C:\Program Files\IIS\Microsoft Web Deploy V2\Msdeploy.exe -verb:sync -source:contentPath=[[c:\source folder]] -dest:contentPath=[[Detination UNC path]] -whatif > c:\temp\msdeploy.log
This is where I'm stuck at right now. Because of the c:\Program files contains the empty folder, cmd doesn't run successfully rather giving me the error, "cmd.exe : 'C:\Program' is not recognized as an internal or external command"
If you have any suggestions or idea, please let me know.
thanks,
wanttogoshreddingeveryday
Here is a small example which start notepad.exe with a parametter
function F([string]$file)
{
notepad.exe $file
}
Clear-Host
F "c:\Temp\fic.txt"
JP
Try this gist. It should have everything you need to deploy via powershell https://gist.github.com/579086
It uses Psake, but it will work without it as well.

Resources