Identify the w3wp System.Diagnostics.Process for a given application pool - iis

I got few web sites running on my server.
I have a "diagnostic" page in an application that shows the amount of memory for the current process (very useful).
Now this app is 'linked' to another app, and I want my diagnostic page to be able to display the amot of memory for another w3wp process.
To get the amount of memory, I use a simple code :
var process = Process.GetProcessesByName("w3wp");
string memory = this.ToMemoryString(process.WorkingSet64);
How can I identify my second w3wp process, knowing its application pool ?
I found a corresponding thread, but no appropriate answer :
Reliable way to see process-specific perf statistics on an IIS6 app pool
Thanks

You could use WMI to identify to which application pool a given w3wp.exe process belongs:
var scope = new ManagementScope(#"\\YOURSERVER\root\cimv2");
var query = new SelectQuery("SELECT * FROM Win32_Process where Name = 'w3wp.exe'");
using (var searcher = new ManagementObjectSearcher(scope, query))
{
foreach (ManagementObject process in searcher.Get())
{
var commandLine = process["CommandLine"].ToString();
var pid = process["ProcessId"].ToString();
// This will print the command line which will look something like that:
// c:\windows\system32\inetsrv\w3wp.exe -a \\.\pipe\iisipm49f1522c-f73a-4375-9236-0d63fb4ecfce -t 20 -ap "NAME_OF_THE_APP_POOL"
Console.WriteLine("{0} - {1}", pid, commandLine);
}
}

You can also get the PID using the IIS ServerManager component; way, if you need to access it in code, without redirecting and parsing console output;
public static int GetIISProcessID(string appPoolName)
{
Microsoft.Web.Administration.ServerManager serverManager = new
Microsoft.Web.Administration.ServerManager();
foreach (WorkerProcess workerProcess in serverManager.WorkerProcesses)
{
if (workerProcess.AppPoolName.Equals(appPoolName))
return workerProcess.ProcessId;
}
return 0;
}

Related

Append to Azure Append Blob Using AppendTextAsync Results in Missing Data

I'm attempting to create a logger for an application in Azure using the new Azure append blobs and the Azure Storage SDK 6.0.0. So I created a quick test application to get a better understanding of append blobs and their performance characteristics.
My test program simply loops 100 times and appends a line of text to the append blob. If I use the synchronous AppendText() method everything works fine, however, it appears to be limited to writing about 5-6 appends per second. So I attempted to use the asynchronous AppendTextAsync() method; however, when I use this method, the loop runs much faster (as expected) but the append blob is missing about 98% of the appended text without any exception being thrown.
If I add a Thread.Sleep and sleep for 100 milliseconds between each append operation, I end up with about 50% of the data. Sleep for 1 second and I get all of the data.
This seems similar to an issue that was discovered in v5.0.0 but was fixed in v5.0.2: https://github.com/Azure/azure-storage-net/releases/tag/v5.0.2
Here is my test code if you'd like to try to reproduce this issue:
static void Main(string[] args)
{
var accountName = "<account-name>";
var accountKey = "<account-key>;
var credentials = new StorageCredentials(accountName, accountKey);
var account = new CloudStorageAccount(credentials, true);
var client = account.CreateCloudBlobClient();
var container = client.GetContainerReference("<container-name>");
container.CreateIfNotExists();
var blob = container.GetAppendBlobReference("append-blob.txt");
blob.CreateOrReplace();
for (int i = 0; i < 100; i++)
blob.AppendTextAsync(string.Format("Appending log number {0} to an append blob.\r\n", i));
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Does anyone know if I'm doing something wrong with my attempt to append lines of text to an append blob? Otherwise, any idea why this would just lose data without throwing some kind of exception?
I'd really like to start using this as a repository for my application logs (since it was largely created for that purpose). However, it would be quite unreliable if logs would just go missing without warning if the rate of logging went above 5-6 logs per second.
Any thoughts or feedback would be greatly appreciated.
I now have a working solution based upon the information provided by #ZhaoxingLu-Microsoft. According to the the API documentation, the AppendTextAsync() method should only be used in a single-writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks which does not work in a multiple-writer scenario.
Here is the documentation that specifies this behavior is by design:
https://msdn.microsoft.com/en-us/library/azure/mt423049.aspx
So the solution is to use the AppendBlockAsync() method instead. The following implementation appears to work correctly:
for (int i = 0; i < 100; i++)
{
var message = string.Format("Appending log number {0} to an append blob.\r\n", i);
var bytes = Encoding.UTF8.GetBytes(message);
var stream = new MemoryStream(bytes);
tasks[i] = blob.AppendBlockAsync(stream);
}
Task.WaitAll(tasks);
Please note that I am not explicitly disposing the memory stream in this example as that solution would entail a using block with an async/await inside the using block in order to wait for the async append operation to finish before disposing the memory stream... but that causes a completely unrelated issue.
You are using async method incorrectly. blob.AppendTextAsync() is non-blocking, but it doesn't really finish when it returns. You should wait for all the async tasks before exiting from the process.
Following code is the correct usage:
var tasks = new Task[100];
for (int i = 0; i < 100; i++)
tasks[i] = blob.AppendTextAsync(string.Format("Appending log number {0} to an append blob.\r\n", i));
Task.WaitAll(tasks);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();

j2me - Out of memory exception, does it have anything to do with the maximum heap or jar size?

I'm currently developing an app for taking orders. Before I ask my question, let me give you a few details of the basic functionality of my app:
The first thing the app does once the user is logged in, is to read data from a webservice (products, prices and customers) so that the user can work offline.
Once the user have all the necessary data, they can starting taking orders.
Finally, at the end of the day, the user sends all the orders to a server for its processing.
Now that you know how my app works, here's the problem :
When I run my app in the emulator it works, but now that running tests on a physical device When I read data from the webservice, the following error appears on the screen :
Out of memory error java/lang/OutOfMemoryError
At first I thought that the data that is read from the WS (in json format) was too much for the StringBuffer :
hc = (HttpConnection) Connector.open(mUrl);
if (hc.getResponseCode() == HttpConnection.HTTP_OK) {
is = hc.openInputStream();
int ch;
while ((ch = is.read()) != -1) {
stringBuffer.append((char) ch);
}
}
But it turned out that the error occurs when I tried to convert the result from the WS (string in json Format) into a JSONArray .
I do this because I need to loop through all the objects (for example the Products) and then save them using RMS. Here's part of the code I use:
rs = RecordStore.openRecordStore(mRecordStoreName, true);
try {
// This is the line that throws the exception
JSONArray js = new JSONArray(data);
for (int i = 0; i < js.length(); i++) {
JSONObject jsObj = js.getJSONObject(i);
stringJSON = jsObj.toString();
id = saveRecord(stringJSON, rs);
}
The saveRecord Method
public int saveRecord(String stringJSON, RecordStore rs) throws JSONException {
int id = -1;
try {
byte[] raw = stringJSON.getBytes();
id= rs.addRecord(raw, 0, raw.length);
} catch (RecordStoreException ex) {
System.out.println(ex);
}
return id;
}
Searching a little , I found these functions : Runtime.getRuntime().freeMemory() and Runtime.getRuntime().totalMemory()
With those functions I found out that the total memory is : 2097152 and the free memory before the error occurs is : 69584 bytes.
Now the big question(or rather questions) is :
Where this little amount of memory is taken from ?? The heap size??
The device's specifications says that it has 4MB
Another thing that worries me is if RMS increases the JAR size
because the specifications also say that the maximum jar size is 2
MB.
As always, I really appreciate all your comments and suggestions.
Thanks in advance.
i don't know what is the exact reason but these J2ME devices indeed have a memory problem.
my app is working with contacts, and when i tried to receive the JSON of contacts from the server, if it was too long the conversion indeed caused an out of memory error.
the solution that i found is paging. divide the data that you receive from the server into parts and read it part by part.

BlackBerry - App freezes when background thread executing

I have a BlackBerry App that sends data over a web service when a button has it state set to ON. When the button is ON a timer is started which is running continuously in the background at fixed intervals. The method for HttpConnection is called as follows:
if(C0NNECTION_EXTENSION==null)
{
Dialog.alert("Check internet connection and try again");
return;
}
else
{
confirmation=PostMsgToServer(encryptedMsg);
}
The method PostMsgToServer is as follows:
public static String PostMsgToServer(String encryptedGpsMsg) {
//httpURL= "https://prerel.track24c4i.com/track24prerel/service/spi/post?access_id="+DeviceBoardPassword+"&IMEI="+IMEI+"&hex_data="+encryptedGpsMsg+"&device_type=3";
httpURL= "https://t24.track24c4i.com/track24c4i/service/spi/post?access_id="+DeviceBoardPassword+"&IMEI="+IMEI+"&hex_data="+encryptedGpsMsg+"&device_type=3";
//httpURL= "http://track24.unit1.overwatch/track24/service/spi/post?access_id="+DeviceBoardPassword+"&IMEI="+IMEI+"&hex_data="+encryptedGpsMsg+"&device_type=3";
try {
String C0NNECTION_EXTENSION = checkInternetConnection();
if(C0NNECTION_EXTENSION==null)
{
Dialog.alert("Check internet connection and try again");
return null;
}
else
{
httpURL=httpURL+C0NNECTION_EXTENSION+";ConnectionTimeout=120000";
//Dialog.alert(httpURL);
HttpConnection httpConn;
httpConn = (HttpConnection) Connector.open(httpURL);
httpConn.setRequestMethod(HttpConnection.POST);
DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
byte[] request_body = httpURL.getBytes();
for (int i = 0; i < request_body.length; i++) {
_outStream.writeByte(request_body[i]);
}
DataInputStream _inputStream = new DataInputStream(
httpConn.openInputStream());
StringBuffer _responseMessage = new StringBuffer();
int ch;
while ((ch = _inputStream.read()) != -1) {
_responseMessage.append((char) ch);
}
String res = (_responseMessage.toString());
responce = res.trim();
httpConn.close();
}
}catch (Exception e) {
//Dialog.alert("Connection Time out");
}
return responce;
}
My Question: The App freezes whenever the method is called, i.e. whenever the timer has to execute and send data to the web service the App freezes - at times for a few seconds and at times for a considerable amount of time applying to the user as if the handset has hanged. Can this be solved? Kindly help!!
You are running your networking operation on the Event Thread - i.e. the same Thread that processes your application's Ui interactions. Networking is a blocking operation so effectively this is stopping your UI operation. Doing this on the Event Thread is not recommended and to be honest, I'm surprised it is not causing your application to be terminated, as this is often what the OS will do, if it thinks the application has blocked the Event Thread.
The way to solve this is start your network processing using a separate Thread. This is generally the easy part, the difficult part is
blocking the User from doing anything else while waiting for the
response (assuming you need to do this)
updating the User Interface with the results of your networking
processing
I think the second of these issues are discussed in this Thread:
adding-field-from-a-nonui-thread-throws-exception-in-blackberry
Since it appears you are trying to do this update at regular intervals in the background, I don't think the first is an issue, - for completeness, you can search SO for answers including this one:
blackberry-please-wait-screen-with-time-out
There is more information regarding the Event Thread here:
Event Thread

NSCFString autoreleased with no pool in place - just leaking?

I suddenly get hundreds of these lines in my console log running a process which uses a progress controller I implemented:
** __NSAutoreleaseNoPool(): Object 0x7afafd0 of class NSCFString autoreleased with no pool in place - just leaking
** __NSAutoreleaseNoPool(): Object 0xd8ca4a0 of class __NSCFData autoreleased with no pool in place - just leaking
I'm in a multithreaded environment on iPhone Simulator, downloading a file from the web using WebClient(). I am puzzled how to deal with this as I have no idea what might cause the problem. The thread that is running the download is embedded in
using ( var oAutoRelease = new NSAutoreleasePool ( ) )
I'm attaching to the WebClient's DownloadProgressChanged method and in there I call a delegate which updates the progress view. If I remove this line, the warnings are gone:
ProgressInfo(ACTION.ReceivingResponse, e.ProgressPercentage);
Calling the delegate in turns will go back to my progress controller and udpate a label:
// iIndicator = the value of e.ProgressPercentage.
oProgressController.CurrentActivity = "Percentage done: " + iInidicator.ToString ( ) + "%";
// ProgressController.CurrentActivity:
this.InvokeOnMainThread(delegate { this.oLblCurrentActivity.Text = value; });
What am I missing here!?
EDIT: I figured out that I had to put another NSAutoReleasePool() around this.InvokeOnMainThread(delegate { this.oLblCurrentActivity.Text = value; });
But why? The whole thing is already in a separate pool.
This link should help you http://blog.datispars.com/tasks-in-background-thread-cocoa-performselectorinbackground/
Each thread should have it's own autorelease pool

Can I embed an external component in a Windows 7 gadget?

Some features I needed is not available in the Javascript API. Is it possible to use an external component (C++ or whatever) in a gadget? In particular, I'd like to get a list of running processes.
You can access WMI objects (or pretty much any COM object) from a gadget. For example the following WMI JScript will dump all processes on the system to the gadget window (put it in the HTML).
try {
var wmi = GetObject("winmgmts:\\\\.\\root\\CIMV2");
var items = wmi.ExecQuery("SELECT * FROM Win32_Process");
var i = 0;
while(i < items.Count)
{
var item = items.ItemIndex(i);
document.writeln(item.Name);
i++;
}
} catch(e) {
document.write(e.message);
}

Resources