Check if COM+ application is already running? - c#

Is it possible in C# (4.0) to get the list of installed Com+ applications on the same box and then retrieve the status (Running/Shut down) of each of them?
I can find methods to start/stop, but not retrieve status.

I think the COM+ Administrative components only lets you query the "static" configuration properties (e.g. Identity, IsEnabled) and doesn't let you query the dynamic properties of COM+ (e.g. PID).
The only way I found to do what you want is using the COMSVCSLib (COM+ Services Type Library).
UPDATE: Based on #Vagaus's comment, we can use either COM+ Administrative components or COM+ Services Type Library!
With quite a bit of help from the article Comonitor - A COM+ Monitor. I've cobbled together some code that uses COM+ Services Type Library:
public static bool IsComPlusApplicationRunning(string appName)
{
int appDataSize = Marshal.SizeOf(typeof(COMSVCSLib.appData));
Type appDataType = typeof(COMSVCSLib.appData);
uint appCount;
IntPtr appDataPtr = IntPtr.Zero;
GCHandle gh = GCHandle.Alloc(appDataPtr, GCHandleType.Pinned);
IntPtr addressOfAppDataPtr = gh.AddrOfPinnedObject();
COMSVCSLib.IGetAppData getAppData = null;
COMSVCSLib.TrackerServer tracker = null;
try
{
tracker = new COMSVCSLib.TrackerServerClass();
getAppData = (COMSVCSLib.IGetAppData)tracker;
getAppData.GetApps(out appCount, addressOfAppDataPtr);
appDataPtr = new IntPtr(Marshal.ReadInt32(addressOfAppDataPtr));
for (int appIndex = 0; appIndex < appCount; appIndex++)
{
COMSVCSLib.appData appData = (COMSVCSLib.appData)Marshal.PtrToStructure(
new IntPtr(appDataPtr.ToInt32() + (appIndex * appDataSize)),
appDataType);
string currentAppName = GetPackageNameByPID(appData.m_dwAppProcessId);
if (string.Compare(currentAppName, appName, StringComparison.OrdinalIgnoreCase) == 0)
{
Console.WriteLine("Application " + appName + " is running with PID " + appData.m_dwAppProcessId);
return true;
}
}
}
finally
{
Marshal.FreeCoTaskMem(appDataPtr);
if (tracker != null)
{
Marshal.ReleaseComObject(tracker);
}
gh.Free();
}
return false;
}
private static string GetPackageNameByPID(uint PID)
{
COMSVCSLib.MtsGrp grpObj = new COMSVCSLib.MtsGrpClass();
try
{
object obj = null;
COMSVCSLib.COMEvents eventObj = null;
for (int i = 0; i < grpObj.Count; i++)
{
try
{
grpObj.Item(i, out obj);
eventObj = (COMSVCSLib.COMEvents)obj;
if (eventObj.GetProcessID() == PID)
{
return eventObj.PackageName;
}
}
finally
{
if (obj != null)
{
Marshal.ReleaseComObject(obj);
}
}
}
}
finally
{
if (grpObj != null)
{
Marshal.ReleaseComObject(grpObj);
}
}
return null;
}
But we can also use the COM+ Administrative components (which seems simpler) to do the same thing:
public static bool IsComPlusApplicationRunning(string appName)
{
COMAdmin.COMAdminCatalog catalog = new COMAdmin.COMAdminCatalogClass();
COMAdmin.ICatalogCollection appCollection = (COMAdmin.ICatalogCollection)catalog.GetCollection("Applications");
appCollection.Populate();
Dictionary<string, string> apps = new Dictionary<string, string>();
COMAdmin.ICatalogObject catalogObject = null;
// Get the names of the applications with their ID and store for later
for (int i = 0; i < appCollection.Count; i++)
{
catalogObject = (COMAdmin.ICatalogObject)appCollection.get_Item(i);
apps.Add(catalogObject.get_Value("ID").ToString(), catalogObject.Name.ToString());
}
appCollection = (COMAdmin.ICatalogCollection)catalog.GetCollection("ApplicationInstances");
appCollection.Populate();
for (int i = 0; i < appCollection.Count; i++)
{
catalogObject = (COMAdmin.ICatalogObject)appCollection.get_Item(i);
if (string.Compare(appName, apps[catalogObject.get_Value("Application").ToString()], StringComparison.OrdinalIgnoreCase) == 0)
{
Console.WriteLine(appName + " is running with PID: " + catalogObject.get_Value("ProcessID").ToString());
return true;
}
}
return false;
}

Have you checked the COM+ administration components? I'd bet that you can find this information using these interfaces.
Best

Related

Creating a folder under Inbox using Mocrosoft.Graph 2.0.14

I'm trying to create a folder under my Inbox in Office 365 using MS Graph 2.0, but I'm finding surprisingly little information on the topic anywhere on the internet. The authentication works fine, and I was able to read the existing test folder. My method for doing this is below:
private void SetupMailBoxes()
{
SmartLog.EnterMethod("SetupMailBoxes()");
MailFolder inbox = null;
try
{
bool dbErrorFolder = false;
bool exchangeErrorFolder = false;
inbox = _journalMailbox.MailFolders.Inbox.Request().GetAsync().GetAwaiter().GetResult();
if (inbox.ChildFolderCount > 0)
{
inbox.ChildFolders = _journalMailbox.MailFolders.Inbox.ChildFolders.Request().GetAsync().GetAwaiter().GetResult();
}
if (inbox.ChildFolders != null)
{
for (int i = 0; i < inbox.ChildFolders.Count && (!dbErrorFolder || !exchangeErrorFolder); i++)
{
if (inbox.ChildFolders[i].DisplayName.ToLower() == "db-error-items")
{
dbErrorFolder = true;
}
else if (inbox.ChildFolders[i].DisplayName.ToLower() == "exchange-error-items")
{
exchangeErrorFolder = true;
}
}
}
if (!dbErrorFolder)
{
try
{
//inbox.ODataType = "post";
var folder = _journalMailbox.MailFolders.Inbox.Request().CreateAsync(
new MailFolder()
{
DisplayName = "DB-Error_Items",
}).GetAwaiter().GetResult();
//inbox.ChildFolders.Add(folder);
}
catch (Exception ex)
{
throw;
}
}
}
catch (Exception exp)
{
SmartLog.LeaveMethod("SetupMailBoxes()");
throw;
}
finally
{
}
SmartLog.LeaveMethod("SetupMailBoxes()");
}
Where _clientSecretCredential is created like this:
_graphServiceClient = null;
_options = new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud };
_clientSecretCredential = new ClientSecretCredential(
this.FindString(config.TenentID)
, this.FindString(config.AppID)
, this.FindString(config.Secret)
, _options);
string[] apiScope = new string[] { this.FindString(config.Scope) };
_token = _clientSecretCredential.GetToken(new Azure.Core.TokenRequestContext(apiScope));
graphServiceClient = new GraphServiceClient(_clientSecretCredential, apiScope);
IUserRequestBuilder _journalMailbox = _graphServiceClient.Users["journal#mycompany.com"];
The code seems correct, but everytime I execute "_journalMailbox.MailFolders.Inbox.Request().CreateAsync", I get the following error:
Code: ErrorInvalidRequest
Message: The OData request is not supported.
ClientRequestId:Some Guid.
From what I could figure out by searching on the internet, it has to do with the method using the wrong method to access the API. I mean like, its using "GET" in stead of "POST" or something like that, but that would mean its a bug in the MS code, and that would an unimaginably big oversight on Microsoft's part, so I can't think its that.
I've tried searching documentation on how to create subfolders, but of the preciously few results I'm getting, almost none has C# code samples, and of those, all are of the previous version of Microsoft Graph.
I'm really stumped here, I'm amazed at how hard it is to find any documentation to do something that is supposed to be simple and straight forward.
Ok, so it turned out that I was blind again. Here is the correct code for what I was trying to do:
private void SetupMailBoxes()
{
SmartLog.EnterMethod("SetupMailBoxes()");
MailFolder inbox = null;
try
{
bool dbErrorFolder = false;
bool exchangeErrorFolder = false;
inbox = _journalMailbox.MailFolders.Inbox.Request().GetAsync().GetAwaiter().GetResult();
if (inbox.ChildFolderCount > 0)
{
inbox.ChildFolders = _journalMailbox.MailFolders.Inbox.ChildFolders.Request().GetAsync().GetAwaiter().GetResult();
}
if (inbox.ChildFolders != null)
{
for (int i = 0; i < inbox.ChildFolders.Count && (!dbErrorFolder || !exchangeErrorFolder); i++)
{
if (inbox.ChildFolders[i].DisplayName.ToLower() == "db-error-items")
{
dbErrorFolder = true;
}
else if (inbox.ChildFolders[i].DisplayName.ToLower() == "exchange-error-items")
{
exchangeErrorFolder = true;
}
}
}
else
{
inbox.ChildFolders = new MailFolderChildFoldersCollectionPage();
}
if (!dbErrorFolder)
{
try
{
var folder = new MailFolder()
{
DisplayName = "DB-Error-Items",
IsHidden = false,
ParentFolderId = inbox.Id
};
folder = _journalMailbox.MailFolders[inbox.Id].ChildFolders.Request().AddAsync(folder).GetAwaiter().GetResult();
inbox.ChildFolders.Add(folder);
}
catch (Exception ex)
{
throw;
}
}
}
catch (Exception exp)
{
SmartLog.LeaveMethod("SetupMailBoxes()");
throw;
}
finally
{
}
SmartLog.LeaveMethod("SetupMailBoxes()");
}

c# - Programmatically remove attachments from outlook email

I want to remove all attachments form a mail in outlook. Don't know, what I'm doing wrong. The code does not cause an exception, but the attachments are still available after removing. This is my code:
This gives me an outlook.application object if it is running or is running outlook, if it's not running:
public static OL.Application GetOutlook(out bool StillRunning)
{
OL.Application OLApp = null;
if (System.Diagnostics.Process.GetProcessesByName("OUTLOOK").Count() > 0)
{
StillRunning = true;
return System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
}
else
{
StillRunning = false;
OLApp = new OL.Application();
OL.NameSpace nameSpace = OLApp.GetNamespace("MAPI");
nameSpace.Logon("", "", System.Reflection.Missing.Value, System.Reflection.Missing.Value);
nameSpace = null;
return OLApp;
}
}
This function returns a mail by its EntryID:
public static OL.MailItem GetMailByEntryId(OL.Application OlApp, string MailItemEntryID)
{
OL.NameSpace olNS = null;
object obj = null;
olNS = OlApp.GetNamespace("MAPI");
if (olNS == null) { throw new System.Exception("ERROR: Unable to get Namespace 'MAPI' in Outlook.Application object!"); }
OL.MailItem MI = null;
obj = olNS.GetItemFromID(MailItemEntryID);
if (obj != null && obj is OL.MailItem) { MI = obj as OL.MailItem; }
if (MI == null) { throw new System.Exception("ERROR: Unable to get mail item by ID " + System.Environment.NewLine + MailItemEntryID); }
return MI;
}
Here, I try to remove the attachments of the mail:
public static void RemoveAttachments(string EntryID)
{
bool StillRunning = false;
OL.Application OLApp = GetOutlook(out StillRunning);
OL.MailItem MI = GetMailByEntryId(OLApp, EntryID);
for(int i = 0; i < MI.Attachments.Count; i++) { MI.Attachments.Remove(i); } //Methode Delete() not available...
MI.Save();
if (!StillRunning) { OLApp.Quit(); OLApp = null; System.GC.Collect(); KillOutlook(); }
}
Thank you all for your help...
All collections in OOM (including MailItem.Attachments) are 1 based, not 0. You are also modifying the collection while looping - use a down loop:
Attachments attachments = MI.Attachments;
for(int i = attachments.Count; i >= 1; i--) { Attachments.Remove(i); }
Ahh, got it - You can make it work that way:
foreach(OL.Attachment Att in MI.Attachments){Att.Delete();}

Validating digitaly signed PDF Spire.Pdf C#

So I am developing a web app that generates a PDF contract from a partial view, and then validates the digital signiture. I came accross an example here . The problem is that an exception is thrown when validating the signiture and for the life of me I cant figure out why...
Here is the code :
public async Task<ActionResult> Upload(HttpPostedFileBase FileUpload)
{
ActionResult retVal = View();
AspNetUser user = DbCtx.AspNetUsers.Find(User.Identity.GetUserId());
bool signitureIsValid = false;
string blobUrl = string.Empty;
if (FileUpload != null && FileUpload.ContentLength > 0)
{
string fileName = Guid.NewGuid().ToString() + RemoveAllSpaces(FileUpload.FileName);
string filePath = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/Content/pdfs"), fileName);
FileUpload.SaveAs(filePath);
List<PdfSignature> signatures = new List<PdfSignature>();
using (var doc = new PdfDocument(filePath))
{
var form = (PdfFormWidget) doc.Form;
int count = 0;
try
{
count = form.FieldsWidget.Count;
}
catch
{
count = 0;
}
for (int i = 0; i < count; ++i)
{
var field = form.FieldsWidget[i] as PdfSignatureFieldWidget;
if (field != null && field.Signature != null)
{
PdfSignature signature = field.Signature;
signatures.Add(signature);
}
}
}
PdfSignature signatureOne = signatures[0];
try
{
signitureIsValid = signatureOne.VerifySignature(); // HERE SHE BLOWS !
if (signitureIsValid)
{
blobPactUrl = await BlobUtil.BasicStorageBlockBlobOperationsAsync(System.IO.File.ReadAllBytes(filePath));
if (!string.IsNullOrEmpty(blobPactUrl))
{
ApplicantInfo info = DbCtx.ApplicantInfoes.FirstOrDefault(x => x.UserId == user.Id);
info.URL = blobUrl;
info.SignatureIsValid = true;
info.ActivationDate = DateTime.Now;
info.ActiveUntill = DateTime.Now.AddYears(1);
DbCtx.Entry(info).State = System.Data.Entity.EntityState.Modified;
DbCtx.SaveChanges();
retVal = RedirectToAction("Publications");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
System.IO.File.Delete(filePath);
}
}
return retVal;
}
Here is an image of
what it looks like when I'm debuging:
I have checked the signiture and it is valid and cerified... I know I'm missing something basic here... Please help me internet!
Just noticed that I posted this. . . Turns out that the problem was due to bug in the package itself. Upon asking the lovely people at E-Iceblue, the bug was recreated, solved and a new version of Spire.PDF was up on nuget within a week.
great job E-Iceblue, it worked fine :)

Method replys unplugged NFC readers

I currently use pcsc-sharp to read ids from NFC tags. I got this methode to lists all available readers. But this replys me all readers I ever used. There are also old readers listed that aren´t plugged in. Does anyone know how to fix that?
public void SelectDevice()
{
List<string> availableReaders = this.ListReaders();
this.RdrState = new Card.SCARD_READERSTATE();
readername = availableReaders[0].ToString();
this.RdrState.RdrName = readername;
}
public List<string> ListReaders()
{
int ReaderCount = 0;
List<string> AvailableReaderList = new List<string>();
retCode = Card.SCardListReaders(hContext, null, null, ref ReaderCount);
if (retCode != Card.SCARD_S_SUCCESS)
{
MessageBox.Show(Card.GetScardErrMsg(retCode));
}
byte[] ReadersList = new byte[ReaderCount];
retCode = Card.SCardListReaders(hContext, null, ReadersList, ref ReaderCount);
if (retCode != Card.SCARD_S_SUCCESS)
{
MessageBox.Show(Card.GetScardErrMsg(retCode));
}
string rName = "";
int indx = 0;
if (ReaderCount > 0)
{
while (ReadersList[indx] != 0)
{
while (ReadersList[indx] != 0)
{
rName = rName + (char)ReadersList[indx];
indx = indx + 1;
}
AvailableReaderList.Add(rName);
rName = "";
indx = indx + 1;
}
}
return AvailableReaderList;
}
Okay I think I solved the problem. Don´t know if this is the best way, but it works. I also don´t know why the ListReaders()-Method delivers me all readers I ever used, but I found another way to get the reader name of the reader that is currently plugged in.
public void SelectDevice()
{
string[] readerNames = new string[1];
using (var context = new SCardContext())
{
context.Establish(SCardScope.System);
readerNames = context.GetReaders();
}
readername = readerNames[0];
this.RdrState.RdrName = readername;
}
If there´s a better way, or someone knows why I get all readers ever used, please comment.

SqlWorkflowInstanceStore WaitForEvents returns HasRunnableWorkflowEvent but LoadRunnableInstance fails

Dears
Please help me with restoring delayed (and persisted) workflows.
I'm trying to check on self-hosted workflow store is there any instance that was delayed and can be resumed. For testing purposes I've created dummy activity that is delayed and it persists on delay.
generally resume process looks like:
get WF definition
configure sql instance store
call WaitForEvents
is there event with HasRunnableWorkflowEvent.Value name and if it is
create WorkflowApplication object and execute LoadRunnableInstance method
it works fine if store is created|initialized, WaitForEvents is called, store is closed. In such case store reads all available workflows from persisted DB and throws timeout exception if there is no workflows available to resume.
The problem happens if store is created and loop is started only for WaitForEvents (the same thing happens with BeginWaitForEvents). In such case it reads all available workflows from DB (with proper IDs) but then instead of timeout exception it is going to read one more instance (I know exactly how many workflows is there ready to be resumed because using separate test database). But fails to read and throws InstanceNotReadyException. In catch I'm checking workflowApplication.Id, but it was not saved with my test before.
I've tried to run on new (empty) persistent database and result is the same :(
This code fails:
using (var storeWrapper = new StoreWrapper(wf, connStr))
for (int q = 0; q < 5; q++)
{
var id = Resume(storeWrapper); // InstanceNotReadyException here when all activities is resumed
But this one works as expected:
for (int q = 0; q < 5; q++)
using (var storeWrapper = new StoreWrapper(wf, connStr))
{
var id = Resume(storeWrapper); // timeout exception here or beginWaitForEvents continues to wait
What is a best solution in such case? Add empty catch for InstanceNotReadyException and ignore it?
Here are my tests
const int delayTime = 15;
string connStr = "Server=db;Database=AppFabricDb_Test;Integrated Security=True;";
[TestMethod]
public void PersistOneOnIdleAndResume()
{
var wf = GetDelayActivity();
using (var storeWrapper = new StoreWrapper(wf, connStr))
{
var id = CreateAndRun(storeWrapper);
Trace.WriteLine(string.Format("done {0}", id));
}
using (var storeWrapper = new StoreWrapper(wf, connStr))
for (int q = 0; q < 5; q++)
{
var id = Resume(storeWrapper);
Trace.WriteLine(string.Format("resumed {0}", id));
}
}
Activity GetDelayActivity(string addName = "")
{
var name = new Variable<string>(string.Format("incr{0}", addName));
Activity wf = new Sequence
{
DisplayName = "testDelayActivity",
Variables = { name, new Variable<string>("CustomDataContext") },
Activities =
{
new WriteLine
{
Text = string.Format("before delay {0}", delayTime)
},
new Delay
{
Duration = new InArgument<TimeSpan>(new TimeSpan(0, 0, delayTime))
},
new WriteLine
{
Text = "after delay"
}
}
};
return wf;
}
Guid CreateAndRun(StoreWrapper sw)
{
var idleEvent = new AutoResetEvent(false);
var wfApp = sw.GetApplication();
wfApp.Idle = e => idleEvent.Set();
wfApp.Aborted = e => idleEvent.Set();
wfApp.Completed = e => idleEvent.Set();
wfApp.Run();
idleEvent.WaitOne(40 * 1000);
var res = wfApp.Id;
wfApp.Unload();
return res;
}
Guid Resume(StoreWrapper sw)
{
var res = Guid.Empty;
var events = sw.GetStore().WaitForEvents(sw.Handle, new TimeSpan(0, 0, delayTime));
if (events.Any(e => e.Equals(HasRunnableWorkflowEvent.Value)))
{
var idleEvent = new AutoResetEvent(false);
var obj = sw.GetApplication();
try
{
obj.LoadRunnableInstance(); //instancenotready here if the same store has read all instances from DB and no delayed left
obj.Idle = e => idleEvent.Set();
obj.Completed = e => idleEvent.Set();
obj.Run();
idleEvent.WaitOne(40 * 1000);
res = obj.Id;
obj.Unload();
}
catch (InstanceNotReadyException)
{
Trace.TraceError("failed to resume {0} {1} {2}", obj.Id
, obj.DefinitionIdentity == null ? null : obj.DefinitionIdentity.Name
, obj.DefinitionIdentity == null ? null : obj.DefinitionIdentity.Version);
foreach (var e in events)
{
Trace.TraceWarning("event {0}", e.Name);
}
throw;
}
}
return res;
}
Here is store wrapper definition I'm using for test:
public class StoreWrapper : IDisposable
{
Activity WfDefinition { get; set; }
public static readonly XName WorkflowHostTypePropertyName = XNamespace.Get("urn:schemas-microsoft-com:System.Activities/4.0/properties").GetName("WorkflowHostType");
public StoreWrapper(Activity wfDefinition, string connectionStr)
{
_store = new SqlWorkflowInstanceStore(connectionStr);
HostTypeName = XName.Get(wfDefinition.DisplayName, "ttt.workflow");
WfDefinition = wfDefinition;
}
SqlWorkflowInstanceStore _store;
public SqlWorkflowInstanceStore GetStore()
{
if (Handle == null)
{
InitStore(_store, WfDefinition);
Handle = _store.CreateInstanceHandle();
var view = _store.Execute(Handle, new CreateWorkflowOwnerCommand
{
InstanceOwnerMetadata = { { WorkflowHostTypePropertyName, new InstanceValue(HostTypeName) } }
}, TimeSpan.FromSeconds(30));
_store.DefaultInstanceOwner = view.InstanceOwner;
//Trace.WriteLine(string.Format("{0} owns {1}", view.InstanceOwner.InstanceOwnerId, HostTypeName));
}
return _store;
}
protected virtual void InitStore(SqlWorkflowInstanceStore store, Activity wfDefinition)
{
}
public InstanceHandle Handle { get; protected set; }
XName HostTypeName { get; set; }
public void Dispose()
{
if (Handle != null)
{
var deleteOwner = new DeleteWorkflowOwnerCommand();
//Trace.WriteLine(string.Format("{0} frees {1}", Store.DefaultInstanceOwner.InstanceOwnerId, HostTypeName));
_store.Execute(Handle, deleteOwner, TimeSpan.FromSeconds(30));
Handle.Free();
Handle = null;
_store = null;
}
}
public WorkflowApplication GetApplication()
{
var wfApp = new WorkflowApplication(WfDefinition);
wfApp.InstanceStore = GetStore();
wfApp.PersistableIdle = e => PersistableIdleAction.Persist;
Dictionary<XName, object> wfScope = new Dictionary<XName, object> { { WorkflowHostTypePropertyName, HostTypeName } };
wfApp.AddInitialInstanceValues(wfScope);
return wfApp;
}
}
I'm not workflow foundation expert so my answer is based on the official examples from Microsoft. The first one is WF4 host resumes delayed workflow (CSWF4LongRunningHost) and the second is Microsoft.Samples.AbsoluteDelay. In both samples you will find a code similar to yours i.e.:
try
{
wfApp.LoadRunnableInstance();
...
}
catch (InstanceNotReadyException)
{
//Some logging
}
Taking this into account the answer is that you are right and the empty catch for InstanceNotReadyException is a good solution.

Categories