Identify processes that are using CLR - c#

The below code is not listing w3wp process, winforms application process!
How to identify the application pool for w3wp process. Is this approach correct?
Code
public static List<String> GetCLRManagedProcesses()
{
var managedProcesses = new List<Process>();
foreach (var process in Process.GetProcesses())
{
try
{
if (process != null && !process.HasExited)
{
for (int i = 0; (i < process.Modules.Count); i++)
{
try
{
var moduleName = process.Modules[i].ModuleName.ToLowerInvariant();
if (FrameworkLibraries().Contains(moduleName))
{
managedProcesses.Add(process);
}
else
{
// winforms, w3wp, all are entering here
}
}
catch (Exception e){ }
}
}
}
catch (Exception ex)
{
}
}
return managedProcesses
.Select(x => x.ProcessName)
.ToList();
}
private static IEnumerable<String> FrameworkLibraries()
{
return new[] { "mscoree.dll", "mscoreei.dll", "mscorwks.dll" };
}
any help appreciated

Related

Migrate QuotaBytesTotal/ QuotaBytesUsed from Google Drive Apis v2 to v3 in C# .Net

Under https://developers.google.com/drive/v3/web/migration I found that QuotaBytesTotal from the about section from GDrive v2 API was changed to storageQuota.limit.
QuotaBytesUsed was changed to storageQuota.usageInDrive. Can anyone give me an example on how I can call this in GApis.v3?
The old code I was using (Google Apis v2) was the following:
private long GetQuotaTotal(Google.Apis.Drive.v3.DriveService service)
{
var quotaBytesTotal = service.About.Get().Execute().QuotaBytesTotal;
if (quotaBytesTotal == null)
return 0;
return (long) quotaBytesTotal;
}
For the QuotaBytesUsed exactly the same thing:
private long GetQuotaUsed(Google.Apis.Drive.v3.DriveService service)
{
var quotaBytesUsed = service.About.Get().Execute().QuotaBytesUsed;
if (quotaBytesUsed == null)
return 0;
return (long) quotaBytesUsed;
}
I think this is what you want:
public long GetDriveSpaceUsage()
{
try
{
AboutResource.GetRequest ag = new AboutResource.GetRequest(_CurrentDriveService);
ag.Fields = "user,storageQuota";
var response = ag.Execute();
if (response.StorageQuota.Usage.HasValue)
{
return response.StorageQuota.Usage.Value;
}
else
{
return -1;
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
return -1;
}
}
public long GetDriveSpaceLimit()
{
try
{
AboutResource.GetRequest ag = new AboutResource.GetRequest(_CurrentDriveService);
ag.Fields = "user,storageQuota";
var response = ag.Execute();
if (response.StorageQuota.Limit.HasValue)
{
return response.StorageQuota.Limit.Value;
}
else
{
return -1;
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
return -1;
}
}

C# returning a list OR an int

Is it possible to return a List OR an int in a method?
Something like:
if it succeeded: return List
if it failed: return int (that gives an error number) or string with error message.
(failed as in no exceptions but the values are incorrect, like PointF.X = below 0 or Lowest value is over 10).
Now I'm doing it like this:
public List<PointF> GetContourInfoFromFile(string a_file)
{
ListContourPoints.Clear();
List<string> textLines = new List<string>();
bool inEntitiesPart = false;
bool inContourPart = false;
try
{
foreach (string str in File.ReadAllLines(a_file))
{
textLines.Add(str);//Set complete file in array
}
for (int i = 0; i < textLines.Count; i++)
{
//read complete file and get information and set them in ListContourPoints
}
//Check Coordinate values
for (int i = 0; i < ListContourPoints.Count; i++)
{
//Coordinates are below -1!
if (ListContourPoints[i].X < -1 || ListContourPoints[i].Y < -1)
{
ListContourPoints.Clear();
break;
}
//Lowest X coordinate is not below 10!
if (mostLowestXContour(ListContourPoints) > 10)
{
ListContourPoints.Clear();
break;
}
//Lowest Y coordinate is not below 10!
if (mostLowestYContour(ListContourPoints) > 10)
{
ListContourPoints.Clear();
break;
}
}
}
catch (Exception E)
{
string Error = E.Message;
ListContourPoints.Clear();
}
return ListContourPoints;
}
When I do it like this, I know there is something wrong with te values.. but not specifically what.
So how can I solve this? If it's not possible with returning a list OR string/int, what's the best solution?
You can
Solution 1:
throw exception if error, and in your code above do a try catch
Delete the part catch in your function, and when you call you function do it in try catch like this:
try
{
List<PointF> result = GetContourInfoFromFile(youfile);
}
catch (Exception E)
{
string Error = E.Message;
}
Solution 2:
return an object with Listresult and error as property
Instead of returning a number, you can throw an exception from the catch block so that it can be caught by the outer exception handler.
Here's a sample:
public void MainMethod()
{
try
{
var myList = SomeMethod();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); // prints out "SomeMethod failed."
}
}
public List<object> SomeMethod()
{
try
{
int i = 1 + 1;
// Some process that may throw an exception
List<object> list = new List<object>();
list.Add(1);
list.Add(i);
return list;
}
catch (Exception ex)
{
Exception newEx = new Exception("SomeMethod failed.");
throw newEx;
}
}
you could create a wrapper class which holds either the value or the errorcode. Example:
public class Holder<T>
{
private Holder(T value)
{
WasSuccessful = true;
Value = value;
}
private Holder(int errorCode)
{
WasSuccessful = false;
ErrorCode = errorCode;
}
public bool WasSuccessful { get; }
public T Value { get; }
public int ErrorCode { get; }
public static Holder<T> Success(T value)
{
return new Holder<T>(value);
}
public static Holder<T> Fail(int errorCode)
{
return new Holder<T>(errorCode);
}
}
Usage:
public Holder<PointF> MyFunc()
{
try
{
//
return Holder<PointF>.Success(new PointF());
}
catch
{
return Holder<PointF>.Fail(101);
}
}
one solution would be to return object
public object GetContourInfoFromFile(string a_file)
{
}
and in the method where you call this try to cast to both int and list and see which one succeeds.
a more elaborate solution would be to have a class
public class YourClassName{
public List<PointF> YourList {get; set;} //for success
public int YourVariable {get; set} // for failure
public string YourMEssage {get; set} // for failure
}
and return that one
public YourClassName GetContourInfoFromFile(string a_file)
{
}

Lucene.NET Lock obtain timed out error

I'm getting the following error when running a process that updates a Lucene index with some User data (a domain object).
Lucene.Net.Store.LockObtainFailedException: Lock obtain timed out:
AzureLock#write.lock. at Lucene.Net.Store.Lock.Obtain(Int64
lockWaitTimeout) in
d:\Lucene.Net\FullRepo\trunk\src\core\Store\Lock.cs: line 97 at
Lucene.Net.Index.IndexWriter.Init(Directory d, Analyzer a, Boolean
create, IndexDeletionPolicy deletionPolicy, Int32 maxFieldLength,
IndexingChain indexingChain, IndexCommit commit) in
d:\Lucene.Net\FullRepo\trunk\src\core\Index\IndexWriter.cs: line 1228
at Lucene.Net.Index.IndexWriter..ctor(Directory d, Analyzer a,
MaxFieldLength mfl) in
d:\Lucene.Net\FullRepo\trunk\src\core\Index\IndexWriter.cs: line 174
at
MyApp.ApplicationServices.Search.Users.UsersSearchEngineService.EnsureIndexWriter()
at
MyApp.ApplicationServices.Search.Users.UsersSearchEngineService.DoWriterAction(Action`1
action) at....
I've inherited the following code and my knowledge of Lucene is not great, so any pointers would be appreciated.
public class UsersSearchEngineService : IUsersSearchEngineService
{
private readonly Directory directory;
private readonly Analyzer analyzer;
private static IndexWriter indexWriter;
private static readonly Object WriterLock = new Object();
private bool disposed;
public UsersSearchEngineService (ILuceneDirectoryProvider directoryProvider)
{
directory = directoryProvider.GetDirectory();
analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
}
public int UpdateIndex(IEnumerable<User> itemsToIndex)
{
var updatedCount = 0;
foreach (var itemToIndex in itemsToIndex)
{
try
{
ExecuteRemoveItem(itemToIndex.UserId);
var document = CreateIndexDocument(itemToIndex);
DoWriterAction(writer => writer.AddDocument(document));
updatedCount++;
}
catch (Exception ex)
{
EventLogProvider.Error("Error updating index for User with id:[{0}]", ex, itemToIndex.UserId);
}
}
DoWriterAction(writer =>
{
writer.Commit();
writer.Optimize();
});
return updatedCount;
}
private static Document CreateIndexDocument(User itemToIndex)
{
var document = new Document();
document.Add(new Field("id", itemToIndex.UserId.ToString(CultureInfo.InvariantCulture), Field.Store.YES, Field.Index.NOT_ANALYZED));
//...
//omitted other fields being added here
//...
return document;
}
void ExecuteRemoveItem(int entryId)
{
var searchQuery = GetIdSearchQuery(entryId);
DoWriterAction(writer => writer.DeleteDocuments(searchQuery));
}
void DoWriterAction(Action<IndexWriter> action)
{
lock (WriterLock)
{
EnsureIndexWriter();
}
action(indexWriter);
}
void EnsureIndexWriter()
{
if (indexWriter != null)
{
return;
}
indexWriter = new IndexWriter(this.directory, this.analyzer, IndexWriter.MaxFieldLength.UNLIMITED);
indexWriter.SetMergePolicy(new LogDocMergePolicy(indexWriter) { MergeFactor = 5 });
var retryStrategy = new ExponentialBackoff(5, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10));
var retryPolicy = new RetryPolicy<LuceneWriterLockedErrorDetectionStrategy>(retryStrategy);
retryPolicy.Retrying += (sender, args) => EventLogProvider.Warn("Retrying lock delete Attempt: " + args.CurrentRetryCount);
if (IndexWriter.IsLocked(this.directory))
{
retryPolicy.ExecuteAction(() =>
{
EventLogProvider.Info("Something left a lock in the index folder: Attempting to it");
IndexWriter.Unlock(directory);
EventLogProvider.Info("Lock Deleted... can proceed");
});
}
}
~UsersSearchEngineService ()
{
Dispose();
}
public void Dispose()
{
lock (WriterLock)
{
if (!disposed)
{
var writer = indexWriter;
if (writer != null)
{
try
{
writer.Dispose();
}
catch (ObjectDisposedException e)
{
EventLogProvider.Error("Exception while disposing SearchEngineService", e);
}
indexWriter = null;
}
var disposeDirectory = directory;
if (disposeDirectory != null)
{
try
{
disposeDirectory.Dispose();
}
catch (ObjectDisposedException e)
{
EventLogProvider.Error("Exception while disposing SearchEngineService", e);
}
}
disposed = true;
}
}
GC.SuppressFinalize(this);
}
}
In case it's relevant:
the application is hosted as an Azure Web App, running 2 instances
the index is stored in Azure Storage
the procedure runs as a scheduled process defined in a CMS.
The CMS will only launch allow one instance of scheduled process to be running at any
one time in a load balanced scenario (e.g. when running 2
instances in Azure)
Does the EnsureIndexWriter method look correct? If not, how should it be reworked?

Task Blocking UI Thread

I have a Primedcommand class within a wpf solution to execute a quick action then execute a task on another thread to prevent the ui thread from being blocked as such:
public void Execute(object parameter)
{
if (CanExecute(parameter))
{
System.Windows.Application.Current.Dispatcher.Invoke(() => { _primer(); });
Task.Factory.StartNew(() => { _execute(parameter); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
}
And the PrimedCommand constructor:
public PrimedCommand(Action primer, Action<object> execute, Predicate<object> canExecute)
{
if (primer == null)
throw new ArgumentNullException("primer");
if (execute == null)
throw new ArgumentNullException("execute");
_primer = primer;
_execute = execute;
_canExecute = canExecute;
}
And one of the worker methods at request of #DanPuzey:
Executed action:
private static void AddChoices(ref Settings RunningSettings)
{
if (Processes.ShouldExit) return;
try
{
if (RunningSettings.Initialized)
{
if (Processes.ShouldExit) return;
if (RunningSettings.WorkingDirectory != null)
{
DirectoryInfo workingDir = new DirectoryInfo(RunningSettings.WorkingDirectory);
if (!workingDir.Exists)
{
throw new DirectoryNotFoundException("The Source Directory Didn't Exist");
}
RunningSettings.CurrentStatus.AddMoment(new Moment("Loading Customers"));
Dictionary<string, string> customerNames = new Dictionary<string, string>();
Dictionary<string, string> jobNumbers = new Dictionary<string, string>();
List<DirectoryInfo> availableFolders = new List<DirectoryInfo>();
if (Tools.IsCustomer(workingDir))
{
availableFolders.Add(workingDir);
}
else if (Tools.IsCustomerContainer(workingDir))
{
availableFolders.AddRange(workingDir.EnumerateDirectories().Where(c => Tools.IsCustomer(c)));
}
else if (Tools.IsJob(workingDir))
{
availableFolders.Add(workingDir.Parent);
}
foreach (DirectoryInfo customer in availableFolders)
{
if (Processes.ShouldExit) return;
try
{
RunningSettings.CurrentStatus.AddMoment(new Moment(String.Format(" Loading Jobs For: {0}", customer)));
if (!customerNames.ContainsKey(customer.Name))
{
customerNames.Add(customer.Name, null);
}
foreach (DirectoryInfo job in customer.GetDirectories().Where(j => Tools.IsJob(j)))
{
if (Processes.ShouldExit) return;
try
{
string tempNumber = job.Name.Substring(0, 6);
if (!jobNumbers.ContainsKey(tempNumber))
{
jobNumbers.Add(tempNumber, customer.Name);
}
}
catch (Exception except)
{
ErrorHandling.Handle(except, ref RunningSettings);
}
}
}
catch (Exception excep)
{
ErrorHandling.Handle(excep, ref RunningSettings);
}
}
int count = 0;
int index = 0;
if (customerNames != null && customerNames.Count > 0)
{
RunningSettings.ClearCustomerCollection();
count = customerNames.Count;
foreach (KeyValuePair<string, string> customer in customerNames)
{
if (Processes.ShouldExit) break;
try
{
index++;
RunningSettings.AddCustomer(customer.Key, customer.Value, (index == count));
}
catch (Exception excep)
{
ErrorHandling.Handle(excep, ref RunningSettings);
}
}
RunningSettings.SortCustomers();
}
if (Processes.ShouldExit) return;
count = 0;
index = 0;
if (jobNumbers != null && jobNumbers.Keys.Count > 0)
{
RunningSettings.ClearJobCollection();
count = jobNumbers.Count;
foreach (KeyValuePair<string, string> job in jobNumbers)
{
if (Processes.ShouldExit) break;
try
{
index++;
RunningSettings.AddJob(job.Key, job.Value, (index == count));
}
catch (Exception excep)
{
ErrorHandling.Handle(excep, ref RunningSettings);
}
}
RunningSettings.SortJobs();
}
if (Processes.ShouldExit) return;
RunningSettings.CurrentStatus.AddMoment(new Moment("Loading Customers Complete"));
}
else
{
throw new InvalidOperationException("The Working Directory Was Null");
}
}
else
{
throw new InvalidOperationException("The Settings Must Be Initialized Before Customer Folders Can Be Enumerated");
}
}
catch (Exception ex)
{
ErrorHandling.Handle(ex, ref RunningSettings);
}
}
Cancel action:
public static void Cancel()
{
KeepRunning = false; // Bool watched by worker processes
}
From the let's call it the execute button the primer's job is to set the value of a property showing the user the action is active.
This is fine, however when I click on the cancel button which will update that status property to cancelling then set a field in the worker class to indicate the action is cancelling, the UI takes about 2 seconds to respond to the button click. I've tried Task.Run and Task.Factory.StartNew with a variety of overloads and creating my own worker thread seems to work the best but still not how I want.
What I'm looking for is you click on execute button, status is updated to active(updating the ui) bound to that property then when the cancel button is clicked the status is changed to cancelling and the task to notify the worker sets the appropriate field(the worker thread checks this field often and exits when needed).
What's not working is the worker thread blocks the ui thread from updating to show the user the action is cancelling.(The cancel button is temporarily unable to be clicked after status is set to active)
Also noteworthy is this solution is using mvvm where the status is an enum value the ui binds to with a converter.
Any question just let me know.

Get Windows Firewall prompt for console app but not service

I have a c# .NET app that receives TCP and UDP streams from other devices on the network.
When I run it as console app, the Windows Firewall prompts me: "Windows Firewall has blocked some features of this program" and it ask me to allow vshost32.exe to communicate on the network.
I agree and the app works fine.
However when I run the app as a service (I have a separate console and service wrappers) I get no such prompt and I can only get it to work if switch off the firewall.
Is this expected for services? ()
Also, I have read some code snippets that suggest you can manually add exceptions to Windows Firewall list. Is this just for console apps or will it work for services also?
Some my code that listens on the ports in case this is usefull...
//
// Setup UDP listening
//
if (protocol == "UDP")
{
m_udp = new UdpConn("RedwallReceiver UDP", m_local, new NetAddress());
m_udp.Receive(new VDataHandler(ReceiveData));
}
//
// Setup TCP listening
//
if (protocol == "TCP")
{
m_listener = new TcpListener(m_local);
m_listener.Start();
m_listener.BeginAcceptSocket(AcceptSocket, null);
}
Services execute under restricted environments and are allowed to have very little or no interaction with the UI. His answer covers all the reasoning and here is how to achieve the same.
I would recommend adding an additional project to your solution (let's call it Configurator) which can be launched as part of the installation process. As far as I remember, adding a rule to the firewall requires administrative privileges. Here are the steps:
Create the Configurator project as a Console or WinForms application. No UI is needed here.
Add an application manifest file to the Configurator project. right-click project, Add > New Item > Application Manifest File. Change the <requestedExecutionLevel> tag to read <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />.
Add the output of the Configurator project to your setup/deployment project.
Select the deployment project and navigate to the Custom Actions tab. Add a new custom action under the Commit node and make it point to the output of the Configurator project.
In the Configurator project, add a reference to NetFwTypeLib from COM references.
Add the code below to the Configurator project.
Modify the Main method of the Configurator project to return an int (0 for success, non-zero for failure) and use the following code. Note that I've pasted this from my project directly so you may need to fix some decleration errors, etc.
private static int Main (string [] args)
{
var application = new NetFwAuthorizedApplication()
{
Name = "MyService",
Enabled = true,
RemoteAddresses = "*",
Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL,
IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY,
ProcessImageFileName = "ServiceAssemblyName.dll",
};
return (FirewallUtilities.AddApplication(application, out exception) ? 0 : -1);
}
namespace MySolution.Configurator.Firewall
{
using System;
using System.Linq;
using NetFwTypeLib;
public sealed class NetFwAuthorizedApplication:
INetFwAuthorizedApplication
{
public string Name { get; set; }
public bool Enabled { get; set; }
public NET_FW_SCOPE_ Scope { get; set; }
public string RemoteAddresses { get; set; }
public string ProcessImageFileName { get; set; }
public NET_FW_IP_VERSION_ IpVersion { get; set; }
public NetFwAuthorizedApplication ()
{
this.Name = "";
this.Enabled = false;
this.RemoteAddresses = "";
this.ProcessImageFileName = "";
this.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
this.IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY;
}
public NetFwAuthorizedApplication (string name, bool enabled, string remoteAddresses, NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion, string processImageFileName)
{
this.Name = name;
this.Scope = scope;
this.Enabled = enabled;
this.IpVersion = ipVersion;
this.RemoteAddresses = remoteAddresses;
this.ProcessImageFileName = processImageFileName;
}
public static NetFwAuthorizedApplication FromINetFwAuthorizedApplication (INetFwAuthorizedApplication application)
{
return (new NetFwAuthorizedApplication(application.Name, application.Enabled, application.RemoteAddresses, application.Scope, application.IpVersion, application.ProcessImageFileName));
}
}
}
namespace MySolution.Configurator.Firewall
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using NetFwTypeLib;
public static class FirewallUtilities
{
public static bool GetApplication (string processImageFileName, out INetFwAuthorizedApplication application, out Exception exception)
{
var result = false;
var comObjects = new Stack<object>();
exception = null;
application = null;
if (processImageFileName == null) { throw (new ArgumentNullException("processImageFileName")); }
if (processImageFileName.Trim().Length == 0) { throw (new ArgumentException("The argument [processImageFileName] cannot be empty.", "processImageFileName")); }
try
{
var type = Type.GetTypeFromProgID("HNetCfg.FwMgr", true);
try
{
var manager = (INetFwMgr) Activator.CreateInstance(type);
comObjects.Push(manager);
try
{
var policy = manager.LocalPolicy;
comObjects.Push(policy);
var profile = policy.CurrentProfile;
comObjects.Push(profile);
var applications = profile.AuthorizedApplications;
comObjects.Push(applications);
foreach (INetFwAuthorizedApplication app in applications)
{
comObjects.Push(app);
if (string.Compare(app.ProcessImageFileName, processImageFileName, true, CultureInfo.InvariantCulture) == 0)
{
result = true;
application = NetFwAuthorizedApplication.FromINetFwAuthorizedApplication(app);
break;
}
}
if (!result) { throw (new Exception("The requested application was not found.")); }
}
catch (Exception e)
{
exception = e;
}
}
catch (Exception e)
{
exception = e;
}
finally
{
while (comObjects.Count > 0)
{
ComUtilities.ReleaseComObject(comObjects.Pop());
}
}
}
catch (Exception e)
{
exception = e;
}
finally
{
}
return (result);
}
public static bool AddApplication (INetFwAuthorizedApplication application, out Exception exception)
{
var result = false;
var comObjects = new Stack<object>();
exception = null;
if (application == null) { throw (new ArgumentNullException("application")); }
try
{
var type = Type.GetTypeFromProgID("HNetCfg.FwMgr", true);
try
{
var manager = (INetFwMgr) Activator.CreateInstance(type);
comObjects.Push(manager);
try
{
var policy = manager.LocalPolicy;
comObjects.Push(policy);
var profile = policy.CurrentProfile;
comObjects.Push(profile);
var applications = profile.AuthorizedApplications;
comObjects.Push(applications);
applications.Add(application);
result = true;
}
catch (Exception e)
{
exception = e;
}
}
catch (Exception e)
{
exception = e;
}
finally
{
while (comObjects.Count > 0)
{
ComUtilities.ReleaseComObject(comObjects.Pop());
}
}
}
catch (Exception e)
{
exception = e;
}
finally
{
}
return (result);
}
public static bool RemoveApplication (string processImageFileName, out Exception exception)
{
var result = false;
var comObjects = new Stack<object>();
exception = null;
if (processImageFileName == null) { throw (new ArgumentNullException("processImageFileName")); }
if (processImageFileName.Trim().Length == 0) { throw (new ArgumentException("The argument [processImageFileName] cannot be empty.", "processImageFileName")); }
try
{
var type = Type.GetTypeFromProgID("HNetCfg.FwMgr", true);
try
{
var manager = (INetFwMgr) Activator.CreateInstance(type);
comObjects.Push(manager);
try
{
var policy = manager.LocalPolicy;
comObjects.Push(policy);
var profile = policy.CurrentProfile;
comObjects.Push(profile);
var applications = profile.AuthorizedApplications;
comObjects.Push(applications);
applications.Remove(processImageFileName);
result = true;
}
catch (Exception e)
{
exception = e;
}
}
catch (Exception e)
{
exception = e;
}
finally
{
while (comObjects.Count > 0)
{
ComUtilities.ReleaseComObject(comObjects.Pop());
}
}
}
catch (Exception e)
{
exception = e;
}
finally
{
}
return (result);
}
}
}

Categories

Resources