I have written code that uses a .bat file (code: rwvinstat /server:servername) that populates a DataGrid of users logged in to a terminal service session in c#. The .bat lives on the server with the app. files and will run properly if executed manually on the server .Also if i run the app. locally and call the .bat file on the server it works fine.
The problem is when i deploy my web app on the server the DataGrid never populates nor do i get any errors. i have given full permissions to IUSER_MACHINENAME(and various users) and i set the virtual directory permissions to read, run, execute. Ialso have set my web.conf fig to:< "identity impersonate="true" userName="username" password="password"/>
Here is my Source code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.IO;
public partial class ilsap01_users : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("C:\\listUsersIlsap01.bat");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process listFiles;
listFiles = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader rawUserData = listFiles.StandardOutput;
listFiles.WaitForExit(20000);
try
{
DataTable table2 = new DataTable();
table2.Columns.Add(new DataColumn("UserName", typeof(string)));
table2.Columns.Add(new DataColumn("SessionId", typeof(string)));
String myString = rawUserData.ReadToEnd();
string exp = #"([\w_]+)"; ;
MatchCollection matches = Regex.Matches(myString, exp, RegexOptions.IgnoreCase);
IEnumerator en = matches.GetEnumerator();
if (en.MoveNext())
{
while (en.MoveNext())
{
Match match = (Match)en.Current;
if (en.Current.ToString() == "rdpwd")
{
if (en.MoveNext())
{
if (en.Current.ToString() == "rdp")
{
en.MoveNext();
en.MoveNext();
en.MoveNext();
Match match_Item = (Match)en.Current;
string item = match_Item.Value;
en.MoveNext();
Match match_Item2 = (Match)en.Current;
string item2 = match_Item2.Value;
DataRow row = table2.NewRow();
row[0] = item.Split()[0];
row[1] = item2.Split()[0];
table2.Rows.Add(row);
}
}
}
}
}
this.displayUsers.DataSource = table2;
this.displayUsers.DataBind();
}
catch (Exception ex)
{
Response.Write(ex);
}
}
protected void dg_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("ILSRF01_USERS.ASPX");
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
Is the executable that the batch file is calling (rwvinstat) in the system path? You might need to call it explicitly - c:\windows\system32\rwvinstat.exe or wherever it is located.
Did you grant the user the application pool is running as the appropriate Remote Desktop Services permissions?
Also, you might find the Cassia library a bit easier to use for your purposes.
Related
I'm trying to do something that is probably very simple, but I can't seem to get it working. I'm writing small app that displays some information including the IP Address. Everything is working perfectly, except that when the IP address changes (Network disconnect, LAN to WiFi, etc), I can't get it to update the text field with a message saying disconnected, or with the new IP Address. I've tried so many things and nothing works. A workaround that I am using is to shut the program down, and then start it immediately.
Here is the workaround code that I am using:
`
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Management.Automation;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Threading;
using Microsoft.Win32;
using System.Diagnostics;
using System.Xml.Linq;
using System.Net;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Microsoft.TeamFoundation.Common.Internal;
using Microsoft.TeamFoundation.Framework.Common;
namespace JIC_BackgroundInfo
{
public partial class MainWindow : Window
{
private UserPreferenceChangedEventHandler UserPreferenceChanged;
public MainWindow()
{
InitializeComponent();
this.WindowStartupLocation = WindowStartupLocation.Manual;
this.Left = System.Windows.SystemParameters.WorkArea.Width - this.Width;
this.Top = System.Windows.SystemParameters.WorkArea.Height - this.Height;
NetworkChange.NetworkAddressChanged += new
NetworkAddressChangedEventHandler(AddressChangedCallback);
}
static void AddressChangedCallback(object sender, EventArgs e)
{
Process.Start(#"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\JIC_BackgroundInfo.exe");
Thread.Sleep(8500);
Application.Current.Shutdown();
}
`
I tried the following code, along with many other variations, but it just crashes the app:
`
public void AddressChangedCallback(object sender, EventArgs e)
{
using (PowerShell powerShell = PowerShell.Create())
{
try
{
var ps1 = $#"(Get-NetIPAddress -AddressFamily IPv4 -AddressState Preferred -PrefixOrigin Dhcp).IPv4Address";
powerShell.AddScript(ps1);
Collection<PSObject> PSOutput = powerShell.Invoke();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject pSObject in PSOutput)
{
stringBuilder.AppendLine(pSObject.ToString());
}
TxtBoxIPAddress.Text = stringBuilder.ToString();
}
catch { TxtBoxIPAddress.Text = "No Address Found!"; return; }
}
}
`
Look into the ManagementEventWatcher class.
https://learn.microsoft.com/en-us/dotnet/api/system.management.managementeventwatcher?view=dotnet-plat-ext-7.0
You can use it to look for IP Addr changes and then ship those to your window that displays it.
private void AddressChangedCallback(object sender, EventArgs e)
{
Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate
{
using (PowerShell powerShell = PowerShell.Create())
{
try
{
var ps1 = $#"(Get-NetIPAddress -AddressFamily IPv4 -AddressState Preferred -PrefixOrigin Dhcp).IPv4Address";
powerShell.AddScript(ps1);
Collection<PSObject> PSOutput = powerShell.Invoke();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject pSObject in PSOutput)
{
stringBuilder.AppendLine(pSObject.ToString());
}
TxtBoxIPAddress.Text = stringBuilder.ToString();
}
catch { TxtBoxIPAddress.Text = "No Address Found!"; }
}
});
}
Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
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.IO;
using System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.
I have a GUI designed on Visual Studio using C#. I am a beginner in C# but good at C++ programming but due to requirements of task, I am designing it in C#. In this GUI, i have a button that connects to remote ssh server and as a trial, i have following commands to run when user presses button1.
client.Connect();
var output = client.RunCommand("echo happy test");
var dltOutput = client.RunCommand("rm /home/helloWorld.txt");
var launchFirst = client.RunCommand("bash /root/first.sh");
client.Disconnect();
Console.WriteLine(output.Result);
The command to delete "helloWorld.txt" in my home folder runs fine but could not running the command to run the shell script "first.sh". I would like to attach complete code below for your reference.
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 Renci.SshNet;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
//Connection information
string user = "root";
string pass = "hello123ado";
string host = "192.168.38.50";
int port = 22;
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
Console.WriteLine("Say Button1_Clicked");
using (var client = new SshClient(host,user,pass))
{
client.Connect();
var output = client.RunCommand("echo happy test");
var dltOutput = client.RunCommand("rm /home/helloWorld.txt");
var launchFirst = client.RunCommand("bash /root/first.sh");
client.Disconnect();
Console.WriteLine(output.Result);
}
}
private void Button2_Click(object sender, EventArgs e)
{
Console.WriteLine("Say Button2_Clicked");
}
private void Button3_Click(object sender, EventArgs e)
{
Console.WriteLine("Say Button3_Clicked");
}
}
}
I'm trying to create an app that communicate with a Firebird 3.0 embedded database.
I need that two or more of my app instances can connect and edit the same database at the same time.
I had create the connection part and it works.
When I start the first instance it connects correctly, but when I try to access to the database with another app it raise this error: Error while trying to open file -Impossible to open the file.
I also had try to connect with different account for example user2 and user1 (manually created with isql) but without results.
I search on google all day but I found nothing.
Any suggestion? Thanks in advance
This is the acutal code:
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 Firebird;
namespace Firebird_multiuser
{
public partial class Form1 : Form
{
//private TextBox console = new TextBox();
Firebird.Firebird conn = new Firebird.Firebird();
public Form1()
{
InitializeComponent();
input_box.Text = #"G:\Coding\oribruniv8\Firebird\Firebird_multiuser\test.fdb";
}
private void button1_Click(object sender, EventArgs e)
{
if (conn.connect(input_box.Text))
console.AppendText("Successfully connect to database\n");
else
{
console.AppendText("Error during connection ...\n");
return;
}
}
}
}
Firebird class
using FirebirdSql.Data.FirebirdClient;
using FirebirdSql.Data.Isql;
namespace Firebird
{
public class Firebird
{
FbConnectionStringBuilder csb = new FbConnectionStringBuilder();
int pageSize = 8192;
bool forcedWrites = true;
bool overwrite = true;
FbConnection conn;
public Firebird()
{
csb.ClientLibrary = **correct path to fbclient.dll**;
csb.UserID = "sysdba";
csb.Password = "masterkey";
csb.ServerType = FbServerType.Embedded;
}
public bool create(string path)
{
csb.Database = path;
FbConnection.CreateDatabase(csb.ToString(), pageSize, forcedWrites, overwrite);
this.conn = new FbConnection(csb.ToString());
this.conn.Open();
return this.connection_check();
}
public bool connect(string path)
{
csb.Database = path;
this.conn = new FbConnection(csb.ToString());
this.conn.Open();
return this.connection_check();
}
public void query(string SQLquery)
{
this.conn.Open();
using (var transaction = this.conn.BeginTransaction())
using (var command = new FbCommand())
{
command.Connection = this.conn;
command.Transaction = transaction;
command.CommandText = SQLquery;
command.ExecuteNonQuery();
transaction.Commit();
}
}
private bool connection_check()
{
if (this.conn.State == ConnectionState.Open)
{
conn.Close();
return true;
}
else
{
return false;
}
}
}
}
If you want two or more apps to connect to the same database, it is time to consider installing Firebird server instead.
That said, if you are using Firebird 3 embedded, it is possible. By default, Firebird 3 embedded will require exclusive access to the database. This can be changed by making sure there is a firebird.conf in the same location as your fbclient.dll used by your application, and setting the ServerMode setting to SuperClassic (or ThreadedShared).
Doing this carries a small risk. If the database is shared, then all processes must use the same lock files. By default that is the case, but if applications have different FIREBIRD_LOCK environment variable settings, this can corrupt a database as each process will think it doesn't have contenders for its locks.
i am developping a really simple program in c# with Visual studio, it consists simply by extracting data from an Excel sheet and transfer it to a database (only one table ), using MySql it worked i just saved the files as CSV and then imported them into my database but i had a big problem which was the encoding UTF8 i have many french characters ans arabic ones that just showed as random characters, so i went back to OleDb but it keeps shong exceptions now i am stuck with this one: System.Data.OleDb.OleDbException (0x80004005)
i ve tried to change running config to x86 but nothing (notice that i am using a windows 8 X64). its a cummon ISAM problem.
please help me .
this is my code :
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 Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
using System.Data.OleDb;
namespace testoledb
{
public partial class Form1 : Form
{
DataSet OleDs = new DataSet();
OleDbDataAdapter OleAdapter = new OleDbDataAdapter();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void upload_excl_Click(object sender, EventArgs e)
{
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
path = Path.Combine(path, "AGENDA.xlsx");
string OleConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+path+#";Extend Properties=Excel 12.0 Macro;MDR=Yes;ImportMixedTypes=Text;TypeGuessRows=0"; //,HDR=Yes;IMEX=1""";
OleDbConnection OleConn = new OleDbConnection(OleConnectionString);
string OleStrCmd = "select * from [SHeet1$A1:H330]";
OleDbCommand OleCmd = new OleDbCommand(OleStrCmd, OleConn);
try
{
OleConn.Open();
OleDs.Clear();
OleAdapter.SelectCommand = OleCmd;
OleAdapter.Fill(OleDs);
dataGridView1.DataSource = OleDs.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
OleConn.Close();
}
}
}
}