Converting Microsoft EWS StreamingNotification Example to a service - c#

I've been working to try and convert Microsoft's EWS Streaming Notification Example to a service
( MS source http://www.microsoft.com/en-us/download/details.aspx?id=27154).
I tested it as a console app. I then used a generic service template and got it to the point it would compile, install, and start. It stops after about 10 seconds with the ubiquitous "the service on local computer started and then stopped."
So I went back in and upgraded to C# 2013 express and used NLog to put a bunch of log trace commands to so I could see where it was when it exited.
The last place I can find it is in the example code, SynchronizationChanges function,
public static void SynchronizeChanges(FolderId folderId)
{
logger.Trace("Entering SynchronizeChanges");
bool moreChangesAvailable;
do
{
logger.Trace("Synchronizing changes...");
//Console.WriteLine("Synchronizing changes...");
// Get all changes since the last call. The synchronization cookie is stored in the
// _SynchronizationState field.
// Only the the ids are requested. Additional properties should be fetched via GetItem
//calls.
logger.Trace("Getting changes into var changes.");
var changes = _ExchangeService.SyncFolderItems(folderId, PropertySet.IdOnly, null, 512,
SyncFolderItemsScope.NormalItems,
_SynchronizationState);
// Update the synchronization cookie
logger.Trace("Updating _SynchronizationState");
the log file shows the trace message ""Getting changes into var changes." but not the "Updating _SynchronizationState" message.
so it never gets past var changes = _ExchangeService.SyncFolderItems
I cannot for the life figure out why its just exiting. There are many examples of EWS streaming notifications. I have 3 that compile and run just fine but nobody as far as I can tell has posted an example of it done as a service.

If you don't see the "Updating..." message it's likely the sync threw an exception. Wrap it in a try/catch.
OK, so now that I see the error, this looks like your garden-variety permissions problem. When you ran this as a console app, you likely presented the default credentials to Exchange, which were for your login ID. For a Windows service, if you're running the service with one of the built-in accounts (e.g. Local System), your default credentials will not have access to Exchange.
To rectify, either (1) run the service under the account you did the console app with, or (2) add those credentials to the Exchange Service object.

Related

Microsoft Exchange oAuth - System.OutOfMemoryException

I've written a console app thats running as a service (using TopShelf) and using a while loop it continuously polls an office 365 inbox every 30 seconds to check for new messages. I'm doing this using oAuth and the below Microsoft libary
Microsoft.Exchange.WebServices 2.2.0.
I'm using the reccomended approach from MS to get the Access Token silently AcquireTokenByUsernamePassword & AcquireTokenSilent.
After about 5 days of running perfectly I'm getting the below exception form Microsoft library:
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.String.Concat(String str0, String str1)
at Microsoft.Exchange.WebServices.Data.OAuthCredentials..ctor(String token, Boolean verbatim) in \\REDMOND\EXCHANGE\BUILD\E15\15.00.0913.015\SOURCES\sources\dev\EwsManagedApi\src\EwsManagedApi\Credentials\OAuthCredentials.cs:line 79
at Microsoft.Exchange.WebServices.Data.OAuthCredentials..ctor(String token) in \\REDMOND\EXCHANGE\BUILD\E15\15.00.0913.015\SOURCES\sources\dev\EwsManagedApi\src\EwsManagedApi\Credentials\OAuthCredentials.cs:line 36
When I've traced this through its being generated by this section in my code:
exchangeService = new ExchangeService
{
Credentials = new OAuthCredentials(authResult.AccessToken),
Url = new Uri(rdr.O365ServiceURL)
};
I've got my exchangeService object declared outside of my while loop and then I'm instantiating it inside the loop so I can make use of the AcquireTokenSilent call, otherwise Microsoft refuse the connection and issue the below message back:
Error: Your app has been throttled by AAD due to too many requests. To avoid this, cache your tokens see https://aka.ms/msal-net-throttling.
Is this a bug in Microsoft code or can I do something better to manage the memory here?
Also the service that crashed out was upto 3.6gb memory footprint which is about 3.5gb too high.
There was nothing wrong with the code in question. Whilst not ideal (I'm going to look I to the notification stream approach instead of polling thanks #paulsm4) it still worked and the Exchange Service was not disposable, so could not be instantiated with a using block.
The issue was actually in the log4net framework where I had the memory appender enabled. I removed this from my logger setup and the memory footprint stays where it should be.
This project uses three separate loggers and they were all building up in memory even after it was written to the file.
The instantiating of the exchange object was just the straw that broke the camels back and a red herring.
The app is sitting at a health 14MB memory footprint now.
Thanks!

C# EventLog.Delete Access Denied

I have read other questions on SO in regards to security and registry keys, nothing has helped me solve my particular use case scenario.
Here's my scenario:
What I'm Trying To Do
I want to, in code, delete a windows event log.
The Problem
When executing the function, I receive a System.ComponentModel.Win32Exception. The exception message is "Access is denied".
How I Am Doing It Currently
I am using an impersonator function that I wrote which wraps around the EventLog.Delete function, it drops me into a user context that has full access to the EventLog Registry Hive. Subsequently the logs I am interested in also have full access for this particular user.
My Question
Why do I receive a "Access Is Denied" if the user I am running under (through impersonation) has full access to the log in question? I've tested my Impersonation function and it works as expected for other code I've written. I don't get why I would get access denied for this.
In another scenario with my impersonation function it works just fine, for example if I tried to write to a file that the user context that is running the program does not have write access to, then I would not be able to write to the text file, however if I use my impersonation to drop into a user context that does have write access then it works just fine (I can write to the file). So I just don't understand why the same concept can't be applied to registry keys.
What am I missing here?
The Code
Exception Message
My Test
Where sw-test is a user I created for testing purposes, it has full access permissions to the registry we are trying to delete.
[TestMethod]
public void DeleteEventLog_ValidatedUser_DeleteLog()
{
using (new Impersonator(Environment.UserDomainName, "sw-test", "pswd"))
{
Logging logging = new Logging();
logging.DeleteEventLog("testLog");
}
}
Okay I eventually got around to figuring this out, there were two issues at play here that were causing the mentioned exception being thrown, they are as follows:
1. Visual Studio was NOT running in administrator mode.
Not running visual studio in administrator mode was one part of the problem, this seems to be associated with access tokens in the windows OS. According to a source I read, if I run a program without UAC on (which is my scenario, I have it off), then the program being run gets a copy of my access token. However if I have UAC enabled, the program gets a copy of my access token but it is a restricted access token. (see: What precisely does 'Run as administrator' do?) - To be honest this doesn't really make sense in my case, why do I have to run as admin if I have UAC off? Shouldn't visual studio have an unrestricted copy of my access token? I am in the administrator group with UAC off...
2. Not Specifying NewCredentials As a Logon32Type In Impersonation
I don't really understand it but as soon as I specified this for my impersonation everything started working perfectly, I read a blog about it, it talks about how it was introduced in the VISTA days and how it was mainly used to specify credentials to outbound network connections to servers, and was mainly used to remedy security-related issues server-side. Don't see how it correlates to interfacing with local event logs though. (see: https://blogs.msdn.microsoft.com/winsdk/2015/08/25/logonuser-logon32_logon_new_credentials-what-is-this-flag-used-for/)
Code
using (new Impersonator(Environment.UserDomainName, "sw-test", "pswd", Advapi32.Logon32Type.NewCredentials))
{
EventLog.CreateEventSource("testSource", "testLog");
EventLog.Delete("testLog");
}
Where the NewCredentials is an int 9

When is a Kofax Workflow Agent run?

When are workflow agents actually called?
I've installed my own workflow agent (this one) and write to a log on the second line in ProcessWorkflow (the first one being the log4net XmlConfigurator.Configure call with a newly created FileInfo instance.
The log is always written after the KTM Server module. This WOULD make sense, because I read a configuration which prompts the WFA to do something with the workflow data. But after the KTM Validation module (where the WFA is also configured to do something) the log is not written.
Is there an explanation, why I don't see any log entries? I've checked the kofax logs too, but I found no evidence there.
The exact code snippet looks like this:
public void ProcessWorkflow(ref IACWorkflowData workflowData)
{
XmlConfigurator.Configure(new FileInfo(#"C:\Program Files (x86)\Kofax\CaptureSS\ServLib\Configuration Files\log4net.config"));
log.Info("Workflow Agent started ...");
// rest of the code
So, since I kind of figured out how to use Workflow Agents, I decided to answer this question for future reference.
A Workflow Agent is being run every time a module has been executed. IIRC this includes viewing the properties with Batch Manager. The Workflow Agent will be called on the site where the module has been executed. So if you execute your automatic modules (i.e. PDF Generator, Export) on a server and Scan and Validation on client sites, the Workflow Agent will be executed on the server or the client station which executed the module respectively.
I actually forgot what didn't work in my original question, but I also ran into problems because I didn't register the DLL using RegAsm.exe. See my other Kofax-related question for more information about this: How to correctly install Workflow Agents in Kofax?
You can also use this in your code so that it only runs the logic when you want it to:
if (workflowData.CurrentModule.Name != "Scan" || workflowData.get_NextState().Name != "Ready")
{
return;
}

Mathematica .Net/Link in an Asp.Net application

I am using the Mathematica .Net/Link platform to create a web service to format and calculate math problems. However I am unable to get it working.
I create it using this code:
_Log.IpDebug("Starting the Kernel Link");
if (string.IsNullOrEmpty(_MathLinkArguments))
_InternelKernel = MathLinkFactory.CreateKernelLink();
else
_InternelKernel = MathLinkFactory.CreateKernelLink(_MathLinkArguments);
_Log.IpDebug("Kernel Link Started");
_InternelKernel.WaitAndDiscardAnswer();
The value of _MathLinkArguments is -linkmode launch -linkname \"C:\\Program Files\\Wolfram Research\\Mathematica\\7.0\\Math.exe\".
This piece of code is called from the Application_Start method of the global.asax.cs file.
When it gets to the WaitAndDiscardAnswer() call it gives the server error:
Error code: 11. Connected MathLink program has closed the link, but there might still be data underway.
Note: The SampleCode given with the .NET/Link package (both a console app and a WinForms app) works.
Edit:
I copied the console app sample code given with Mathematica into an asp.net page and it gave me the same error the first load and then on subsequent loads it gave me:
Error code: 1. MathLink connection was lost.
Edit2:
I forgot to mention that when I have procmon and task manager open while running my app, I can tell that Math.exe starts but it immediately exits, which makes those error code make complete sense...but doesn't explain why that happened.
To allow the .Net/Link to work in Asp.net (at least in IIS 7.5) you need to enable the property loadUserProfile on the app pool for the web site.
I am not entirely sure why this is the case, but from what I found while trying to debug this, there are some things that are gotten from the user's profile. I know for a fact that the default location of the kernel is, which explains why I couldn't use it with no arguments, and so I can only assume that other things are needed as well and without the profile it couldn't determine that.
But whatever the reason is this is required, it is, or at least it is a fix if you are getting similar problems like this in your own application.
I got the same error in a .Net WinForm application.
mathKernel = new MathKernel();
mathKernel.Compute("<< XYZ`XYZGraphs`");
The error occurred on loading the package straight after instantiating the MathKernel.
To resolve it you can wait a couple of seconds and then instantiating the MathKernel works fine. During this state where there might still be data underway the following conditions are both false:
if (!MathKernel.IsConnected)
{
MathKernel.Connect();
}
if (MathKernel.IsComputing)
{
MathKernel.Abort();
}
Edit:
I've recieved the error again and this time was able to determine the problem.
Using a command line open the MathKernel.exe and view the error message:

Unable to debug WCF service in VS2008 after UserNamePasswordValidator fault

I have a WCF service that I secure with a custom UserNamePasswordValidator and Message security running over wsHttpBinding. The release code works great. Unfortunately, when I try to run in debug mode after having previously used invalid credentials (the current credentials ARE valid!) VS2008 displays an annoying dialog box (more on this below).
A simplified version of my Validate method from the validator might look like the following:
public override void Validate(string userName, string password)
{
if (password != "ABC123")
throw new FaultException("The password is invalid!");
}
The client receives a MessageSecurityException with InnerException set to the FaultException I explictly threw. This is workable since my client can display the message text of the original FaultException I wanted the user to see.
Unfortunately, in all subsequent service calls VS2008 displays an "Unable to automatically debug..." dialog. The only way I can stop this from happening is to exit VS2008, get back in and connect to my service using correct credentials. I should also add that this occurs even when I create a brand new proxy on each and every call. There's no chance MY channel is faulted when I make a call. Its likely, however, that VS2008 hangs on to the previously faulted channel and tries to use it for debugging purposes.
Needless to say, this sucks! The entire reason I'm entering "bad" credentials is to test the "bad-credential" handling.
Anyway, if anyone has any ideas as to how I can get around this bug (?!?) I'd be very very appreciative....
I'm starting to think that the problem has to do with proxy closure. I just saw an excellent set of WCF video's from Michele Leroux Bustamante (http://wcfguidanceforwpf.codeplex.com) that makes me think the problem may be in my client code. I'll give it a go today and report back how it did....

Categories