Reset performance counter from command line - command-line

I want to execute a command from command line to reset given performance counter to 0.
I could write a simple "3" lines console app to do that, but wondering if VS or Windows or Windows SDK already comes with such utility. I did not find such option in either typeperf or logman.
Context:
Windows 7 x64 (with Admin access)
Background:
I use a performance counter to debug/develop/stress-test a web service. Web service increments a performance counter every time it is hit.
So the scenario is to hit web service 10000 times and verify no messages have been lost (I test MSMQ + out-of-order processing + persistence + Windows Workflow Service)

While I'm waiting for a better answer, here is a complete "rstpc.exe" utility to reset performance counter (of NumberOfItems32 type):
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ResetPerformanceCounter
{
internal class Program
{
private static int Main(string[] args)
{
if (args.Length != 2)
{
string fileName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
Console.WriteLine("Usage: {0} <PC Category> <PC Name>", fileName);
Console.WriteLine("Examlpe: {0} {1} {2}", fileName, "GEF", "CommandCount");
return -1;
}
string cat = args[0];
string name = args[1];
if (!PerformanceCounterCategory.CounterExists(name, cat))
{
Console.WriteLine("Performance Counter {0}\\{1} not found.", cat, name);
return - 2;
}
var pc = new System.Diagnostics.PerformanceCounter(cat, name, false);
if (pc.CounterType != PerformanceCounterType.NumberOfItems32)
{
Console.WriteLine("Performance counter is of type {0}. Only '{1}' countres are supported.", pc.CounterType.ToString(), PerformanceCounterType.NumberOfItems32);
return -3;
}
Console.WriteLine("Old value: {0}", pc.RawValue);
pc.RawValue = 0;
Console.WriteLine("New value: {0}", pc.RawValue);
Console.WriteLine("Done.");
return 0;
}
}
}

Related

How to make sockets work in xamarin?

In the Answer to this question Here:Server Client Application with .NET and Xamarin
the person who answered said: "On Xamarin.Android you can use all of the regular .Net socket classes"
I tried using the code in example of the Microsoft documentation and i had no errors but application just is just displaying like that on the phone:
If I delete the socket code it would display the page normally.My code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Net;
using System.Net.Sockets;
namespace App14
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page2 : ContentPage
{
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
var label = new Label() { Text = "searching for a connection" };
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
label.Text = "Found a Connection";
data = null;
// An incoming connection needs to be processed.
while (true)
{
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
// Show the data on the console.
label.Text = "Text received" + data;
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public Page2 ()
{
StartListening();
Title = "Sign in page";
InitializeComponent();
}
private void page2_click(object sender,EventArgs e)
{
Navigation.PushAsync(new Page1(), true);
}
}
}
Xaml File code:
Why is this?.and can you please provide an example of client mobile or server mobile socket
You are blocking the UI Thread with your StartListening call, since it has a infinite while loop.
The label you create in the while loop is never added as content on the page. Hence the text you add to it will never be shown. You already have a label defined with the name l on the page. In this case you could just use that to add text:
l.Text = "hello";
As commented, you should start your socket listening code on another thread to not block you UI. This could be as simple as writing Task.Run(() => StartListening());. Make sure you understand what this does and possibly how you cancel this Task again when navigating away from the page or during App lifecycle.
If you try to Connect from your mobile with the correct ip address and port number of the Listener when both devices are in the same LAN it should work. If one of the devices is behind a different LAN router/modem you won't be able to connect because the router will block all incoming connections unless you use a port routing mechanism like UPnP.

Matlab can not read the socket for the second time

I want to communicate between two programs. MATLAB is able to read the socket once but when it tries to read it again, I get the following warning
Warning: Unsuccessful read: A timeout occurred before the Terminator was reached.
Matlab code:
clc
clear all
while(1)
clear tcpipServer
tcpipServer = tcpip('127.0.0.1', 55000, 'NetworkRole', 'Server');
set(tcpipServer, 'Timeout', 30);
fopen(tcpipServer);
rawData = fgetl(tcpipServer);
fclose(tcpipServer);
end
The data which is sent to Matlab is defined as string and the value is "y\n".
The problem is that I only receive "y\n" once.
The other side connected to the socket is the Unity game engine. I think the code in the unity is correct because I tested that by c# windows app and I can get the value as long as program is running.
Does anyone know why this is happening?
This is the solution i found.
Matlab code:
clc
clear all
%% server initialization
tcpipServer = tcpip('127.0.0.1',55000,'NetworkRole','Server');
set(tcpipServer,'Timeout',30);
while(1)
%% server code: listening for incoming requests
fopen(tcpipServer);
%rawData = fread(tcpipServer,1,'char');
rawData = fgetl(tcpipServer)
extractedData=str2double(strsplit(rawData,'-'))
fclose(tcpipServer);
Unity C# code:
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System;
using System.IO;
using System.Text;
public class server : MonoBehaviour {
// Use this for initialization
TcpListener listener;
String msg;
StreamWriter theWriter1;
internal Boolean socketReady = false;
TcpClient mySocket;
NetworkStream theStream;
StreamWriter theWriter;
StreamReader theReader;
String Host = "localhost";
Int32 Port = 55000;
bool firstTimeRun=true;
void Start () {
}
// Update is called once per frame
void Update () {
setupSocket ();
if (Input.GetMouseButtonDown (0))
{
setupSocket ();
}
}
public void setupSocket() {
try {
TcpClient mySocket1;
NetworkStream theStream1;
//StreamWriter theWriter1;
mySocket1 = new TcpClient(Host, Port);
theStream1 = mySocket1.GetStream();
theWriter1 = new StreamWriter(theStream1);
Invoke("write", 0.2f);
}
catch (Exception e) {
Debug.Log("Socket error: " + e);
}
}
void write()
{
float x;float y;
x = GameObject.FindGameObjectWithTag ("Player").transform.position.x;
y=GameObject.FindGameObjectWithTag ("Player").transform.position.y;
theWriter1.Write(x+"-"+y+"\n");
theWriter1.Flush();
}
The reason I used "\n" is using fgetl function in Matlab code. if you want to make the code more functional use delay along with Asynchronous tasks in Unity. for those wandering why using delay is required, see the comments under question.

Powershell Invoke method neither throwing exception nor returning result

I am trying to build an ASP.Net, c# application to expose few IIS management related activities through web interface for a distributed Admin group.
I am making use of System.Management.Automation V3.0 library to wrap power shell commands. As a first step I wanted to list all Web Applications that are currently up and running on local IIS by invoking Get-WebApplication command.
This is where I am facing the issue. Method call is neither throwing any exception nor its returning the result. Does anyone know the root cause of this issue? Please share your experience of building such interface using System.Management.Automation.dll.
var shell = PowerShell.Create();
shell.Commands.AddScript("Get-WebApplication | Out-String");
try
{
var results = shell.Invoke();
if (results.Count > 0)
{
var builder = new StringBuilder();
foreach (var psObject in results)
{
builder.Append(psObject.BaseObject.ToString() + "\r\n");
}
}
}
catch(Exception ex)
{
throw;
}
PS: Get-Service in place of Get-WebApplication works absolutely fine by returning list of services available on the machine.
PowerShell.Create() does not create new PowerShell process. If you does not specify Runspace for it, then it will create new in-process Runspace. Since it run in your process, it will match your process bitness and you can not change that. To create Runspace with different bitness you need to create out of process Runspace. Here is a sample console application, which demonstrate how you can do that:
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
public static class TestApplication {
public static void Main() {
Console.WriteLine(Environment.Is64BitProcess);
using(PowerShellProcessInstance pspi = new PowerShellProcessInstance()) {
string psfn = pspi.Process.StartInfo.FileName;
psfn=psfn.ToLowerInvariant().Replace("\\syswow64\\", "\\sysnative\\");
pspi.Process.StartInfo.FileName=psfn;
using(Runspace r = RunspaceFactory.CreateOutOfProcessRunspace(null, pspi)) {
r.Open();
using(PowerShell ps = PowerShell.Create()) {
ps.Runspace=r;
ps.AddScript("[Environment]::Is64BitProcess");
foreach(PSObject pso in ps.Invoke()) {
Console.WriteLine(pso);
}
}
}
}
}
}
If you compile this application as x32, it still will use x64 out of process Runspace on x64 operation system.

Why doesn't the NetworkUp event fire on the .Net Gadgeteer GHI WiFi RS21 module?

I'm trying to debug why the event NetworkUp never fires on the WiFi RS21 Gadgeteer module and I've distilled it down to a very simple code listing:
using Microsoft.SPOT;
using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
namespace NetworkUpTest
{
public partial class Program
{
void ProgramStarted()
{
wifi_RS21.UseDHCP();
wifi_RS21.NetworkUp += wifi_RS21_NetworkUp;
wifi_RS21.NetworkDown += wifi_RS21_NetworkDown;
var scans = wifi_RS21.Interface.Scan("LLOYDREGANS");
if (scans != null && scans.Length > 0)
{
Debug.Print("Joining " + scans[0].SSID);
wifi_RS21.Interface.Join(scans[0], "**********");
}
var giveUpWaitingForTheNetworkUpEvent = new GT.Timer(300000, GT.Timer.BehaviorType.RunOnce);
giveUpWaitingForTheNetworkUpEvent.Tick += giveUpWaitingForTheNetworkUpEvent_Tick;
giveUpWaitingForTheNetworkUpEvent.Start();
}
void wifi_RS21_NetworkUp(GTM.Module.NetworkModule sender, GTM.Module.NetworkModule.NetworkState state)
{
Debug.Print("NetworkUp");
}
void wifi_RS21_NetworkDown(GTM.Module.NetworkModule sender, GTM.Module.NetworkModule.NetworkState state)
{
Debug.Print("NetworkDown");
}
void giveUpWaitingForTheNetworkUpEvent_Tick(GT.Timer timer)
{
Debug.Print("Give up waiting for the NetworkUp event and try requesting the router homepage");
var request = HttpHelper.CreateHttpGetRequest("http://192.168.1.1/");
request.ResponseReceived += request_ResponseReceived;
request.SendRequest();
}
void request_ResponseReceived(HttpRequest sender, HttpResponse response)
{
Debug.Print("Response received. response.Text.Length = " + response.Text.Length);
}
}
}
Here's the listing from the output window when the program runs (minus the thread exited reports):
Using mainboard GHI Electronics FEZSpider version 1.0
RS9110 firmware version Number is 4.4.5
RS9110 driver version Number is 4.4.5
Joining LLOYDREGANS
NetworkDown
Give up waiting for the NetworkUp event and try requesting the router homepage
Response received. response.Text.Length = 2509
Given that the network is demonstrably up, why is "NetworkDown" the only event that fires from the WiFi RS21 module?
The answer on the GHI forum suggests that the correct events to use are:
Interface.WirelessConnectivityChanged
Interface.NetworkAddressChanged
instead of the exemplar code on GHI's WiFi RS21 Gadgeteer module page.

Running Selenium via NUnit and Cruise Control .NET

I'm having an issue running Selenium tests in NUnit from Cruise Control .NET. I have a simple test that runs fine when I run from the NUnit GUI on our continuous integration server. However when the NUnit test is run from Cruise Control .NET on the same server, the test always fails. Tests that don't use Selenium run fine from both the NUnit GUI and from Cruise Control.
[SetUp]
public void SetupTest()
{
Driver = new InternetExplorerDriver();
}
[TearDown]
public void TeardownTest()
{
Driver.Quit();
}
/// <summary>
/// Test basic Selenium functionality.
/// </summary>
[Test]
public void SeleniumTest()
{
Driver.Navigate().GoToUrl(TestConfig.TestURL);
IWebElement testEle = WaitForElement(Driver, By.Id, "body", TestConfig.TestWaitMS);
Assert.IsTrue(true);
}
private static IWebElement WaitForElement(IWebDriver driver, ByFunc byFunc, string elementId, int waitMs,
string waitOutput = null, int pause = 50)
{
bool elementFound = false;
int i = 0;
IWebElement webElement = null;
while (!elementFound && (i * pause) < waitMs)
{
try
{
webElement = driver.FindElement(byFunc(elementId));
elementFound = true;
}
catch (NoSuchElementException)
{
i++;
Thread.Sleep(pause);
if (waitOutput != null)
Console.Write(waitOutput);
}
}
if (elementFound)
return webElement;
else
throw new NoSuchElementException(string.Format("Could not find element {0} after waiting {1}ms.", elementId, waitMs));
}
WaitForElement is just a helper function that allows me to assign specific waits for certain elements rather than have a blanket waiting time for the entire test run.
The test fails when the NoSuchElementException is raised from the WaitForElement function.
I've found some links on Google saying that you need to run SeleniumRC as a service to get it to run from Cruise Control. I don't think that applies here as I'm using the WebDriver version. Please correct me if I'm wrong.
IE version 8
Cruise Control .NET 1.8.3.0
NUnit 2.6
Selenium 2.0.0
Thanks for the pointers #Arran. Switching to a Firefox driver fixed the issue. I guess the fault must lie somewhere in the Internet Explorer driver.
[SetUp]
public void SetupTest()
{
Driver = new FirefoxDriver();
}