ASP.NET : PerformanceCounter displays nothing - c#

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.

Related

Rename a Windows Computer / Server with C# WPF

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;

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"

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.

MailMessage is not working even with system.net.mail reference

MailMessage is not working i don't know what I'm missing. Pls correct my program if there is missing codes or did i use wrong namespace?
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.Web.Mail;
using System.Data.SqlClient;
using System.Data;
protected void btnsend_Click(object sender, EventArgs e)
{
try
{
SmtpClient smtp=new SmtpClient("smtp.gmail.com",587);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials=new NetworkCredential(txtemail.Text,txtpassword.Text);
MailMessage mail = new MailMessage(txtemail.Text, ddlemail.Text, txtsubject.Text, txtbody.Text);
smtp.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
The problem is because you have referenced
using System.Net.Mail;
using System.Web.Mail;
So there was ambiguous reference between System.Web.Mail.MailMessage and System.Net.Mail.MailMessage
Remove using System.Web.Mail; reference

Categories