Rename a Windows Computer / Server with C# WPF - c#

I am trying to create a Configuration Tool for new devices, which has to be set up.
That's why I am trying to set the local hostname with a Button.
I want to use the name which I wrote in a textbox
public void SetMachineName(string newName)
{
// Create a new process
ProcessStartInfo process = new ProcessStartInfo();
// set name of process to "WMIC.exe"
process.FileName = "WMIC.exe";
// pass rename PC command as argument
process.Arguments = "computersystem where caption='" + System.Environment.MachineName + "' rename " + newName;
// Run the external process & wait for it to finish
using (Process proc = Process.Start(process))
{
proc.WaitForExit();
// print the status of command
Console.WriteLine("Exit code = " + proc.ExitCode);
}
}
public void Click_sethostname(object sender, RoutedEventArgs e)
{
SetMachineName(Textbox_sethostname.Text);
}
WPF setup
I have following namespaces:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using Microsoft.Win32;
using System.Management;
using System.Diagnostics;

Related

The name 'TextBox1' does not exist in the current context(usually)

I am currently developing a website by visual studio c# language and right now I am working on the user password reset page design. The problem I met is that I want to add the control to the textboxes and labels by using basic textbox.text = ""; method. But it keeps telling me it did not exist. I have searched a lot of solutions I am sure that:
1, It is the same name between the label name and the coding name.
2, There were no other same name pages since I was re-created another page with different names.
3, All these are added:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Drawing;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.IO;
Can anyone help? I confused here for a few days already:)
protected void SubmitButton_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spResetPassword", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramUsername = new SqlParameter("#UserName", userTextBox.text);
cmd.Parameters.Add(paramUsername);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (Convert.ToBoolean(rdr["ReaturnCode"]))
{
SendPasswordResetEmail(rdr["Email"].ToString(), TextBox1.Text, rdr["UniqueId"].ToString());
msgLabel.Text = "An reset password Email has sent to your Email address.";
}
else
{
msgLabel.Text = "username not found!";
}
}
}
Does your textbox control have the following attribute?
runat="server"

System.Data.OleDb.OleDbException' occurred in System.Data.dll

Hey Members i am new to C# Language and Visual Studio Platform recently i am learning how to connect access Database with visual Studio and first time with same code i have connected with database but after some time when i compiled again then there is error given in Title.
why this is happening ?
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.Data.OleDb;
namespace Clinic_Management_System
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users
\Hassan Gillani\Documents\Clinic Management System.accdb; Persist Security Info = False; ";
connection.Open();
label1.Text = "Connected to Clinic Management System Database";
connection.Close();
}
catch (Exception exp)
{
MessageBox.Show("Error " + exp);
}
}
}
}
please visit given like to view screen short
http://s33.postimg.org/5ltm4dtnj/Error.png
Using the verbatim character (#) and splitting your path in the middle in not a good idea.
Spaces counts in paths so the filename used for your connection is
C:\Users \Hassan Gillani\Documents\Clinic Management System.accdb;
If you try to use File.Exists on this string you get false as result.
Do not split your connection string in the middle of the path
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\Hassan Gillani\Documents\Clinic Management System.accdb;
Persist Security Info = False; ";

ManagementEventWatcher.Start() Access Denied

I'm trying to create an application in C#.Net, and I need it to scan the processes that the user start and stop, but I'm getting an "Access Denied" on the .Start()
Here is what I've got so far
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Management;
using Security;
using MySQLConnectivity;
namespace MyApp
{
public partial class Login : Form
{
MySQLClass sql = new MySQLClass();
ManagementEventWatcher processStartEvent = new ManagementEventWatcher("SELECT * FROM Win32_ProcessStartTrace");
ManagementEventWatcher processStopEvent = new ManagementEventWatcher("SELECT * FROM Win32_ProcessStopTrace");
public Login()
{
InitializeComponent();
processStartEvent.EventArrived += new EventArrivedEventHandler(processStartEvent_EventArrived);
processStartEvent.Start();
processStopEvent.EventArrived += new EventArrivedEventHandler(processStopEvent_EventArrived);
processStopEvent.Start();
}
void processStartEvent_EventArrived(object sender, EventArrivedEventArgs e)
{
string processName = e.NewEvent.Properties["ProcessName"].Value.ToString();
string processID = Convert.ToInt32(e.NewEvent.Properties["ProcessID"].Value).ToString();
MessageBox.Show("Process started. Name: " + processName + " | ID: " + processID);
}
void processStopEvent_EventArrived(object sender, EventArrivedEventArgs e)
{
string processName = e.NewEvent.Properties["ProcessName"].Value.ToString();
string processID = Convert.ToInt32(e.NewEvent.Properties["ProcessID"].Value).ToString();
MessageBox.Show("Process stopped. Name: " + processName + " | ID: " + processID);
}
}
}
I've searched online hours, but couldn't find anything. People that had this problem, had it remotelly, and not locally. I am using Windows Pro 8.1 + Microsoft Visual Studio Ultimate 2013, just in case that versions of VS or OS may be important in this case.
The problem triggers on processStartEvent.Start() saying "Access denied".
I also tried to switch from .Start() to .WaitForNextEvent() with the same result
Anything that I'm missing here?
ClickOnce was activated. Disabling it solved my problem. Thanks tho.

System.InvalidProgramException when trying to run Powershell commands in C#

I have ran a debug stepping through the program and it crashes at the following line
Runspace runspace = RunspaceFactory.CreateRunspace();
It gives the following error
An unhandled exception of type 'System.InvalidProgramException' occurred in PrimarySMTP_Fix.exe
Additional information: Common Language Runtime detected an invalid program.
This is my first time working with Power Shell through C# and I'm having trouble getting some simple code execution. The point of the project is to automate a simple fix for a common issue with our company's exchange server.
The complete code is below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
namespace PrimarySMTP_Fix
{
public partial class MainWindow : Window
{
//Variable Declarations
string userName = "";
string confirmUser = "";
string primarySMTP = "";
string confirmSMTP = "";
public MainWindow()
{
InitializeComponent();
}
private string RunScript(string scriptText)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
userName = adUser.Text;
confirmUser = confirmAD.Text;
primarySMTP = mail.Text;
confirmSMTP = confirmMail.Text;
outPut.Text = RunScript(userName);
}
}
}
The above is just setup to test. For now it's taking just the username information and running it directly as a command. If I can get that to work and output information then I can re-write it to do what I want it to do.
After playing around for a while I found that I needed to reinstall the Windows Management Framework to get it to work. Figured that out when I put the debug build on the server and ran the test there and it worked.

ASP.NET : PerformanceCounter displays nothing

I am a complete beginner in asp.net, C#, etc...
I saw this and this
Then I try this:
using System;
using System.Configuration;
using System.Data;
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.IO;
using System.Text;
using System.Net;
using System.Collections.Generic;
using System.Xml;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Hello from code behind");
PerformanceCounter cpuload = new PerformanceCounter();
cpuload.CategoryName = "Processor";
cpuload.CounterName = "% Processor Time";
cpuload.InstanceName = "_Total";
//or PerformanceCounter cpuload = new PerformanceCounter("Processor", "% Processor Time", "_Total");
Console.WriteLine(cpuload.NextValue() + "%");
}
}
But that only displays Hello from code behind. Why please?
You're writing to the console, which won't work, write to the response instead (just as your string does):
Response.Write(cpuload.NextValue().ToString() + "%");
While applications types that aren't strictly console applications can have an associated console, they're not visible unless explicitly made so, and couldn't be in a web application.

Categories