how can I fix this error, The message filter indicated that the application is busy - vsto

I keep getting this error in word, excel powerpoint how can i fix it
Error=The message filter indicated that the application is busy.
(Execption from HRESULT: 0x8001010A(RPC_E_SERVERCALL_RETRYLATER))
foreach (Presentation document in Globals.ThisAddIn.Application.Presentations.Cast<Presentation>().ToList())
{
while (document.ReadOnly!= Microsoft.Office.Core.MsoTriState.msoTrue)
{
break;
}
var item = FODocumentRepository.GetByLocalPath(document.FullName);
if (item == null)
{
if (DocHelper.IfFileOrbisDocument(document.FullName))
{
FODocumentRepository.Add(document.FullName, document.FullName);
}
}
}
var repositoryList = FODocumentRepository.GetAll().ToList();
// var abc = Globals.ThisAddIn.Application.Workbooks.Cast<Workbook>().Select(x => x.FullName).ToList();
List<FODocument> deleteList = new List<FODocument>();
foreach (var item in repositoryList)
{
bool founded = false;
foreach (Presentation document in Globals.ThisAddIn.Application.Presentations)
{
if (item.LocalPath == document.FullName)
{
founded = true;
break;
}
}
if (!founded)
{
MessageBox.Show("DocumentClosed");
FileorbisConflictManager.DocumentClosed(ServiceSettings.GetToken(), DocHelper.GetDocumentKey(item.FOPath),DocumentType.PowerPoint);
deleteList.Add(item);
}
}
foreach (var item in deleteList)
{
FODocumentRepository.Remove(item.LocalPath);
}

These kind of errors occur due to threading contention issues between external multi-threaded applications and Visual Studio. They can be eliminated by implementing IOleMessageFilter error handlers in your Visual Studio automation application. Read more about that in the How to: Fix 'Application is Busy' and 'Call was Rejected By Callee' Errors article.
Also you can find the same issue described on the Exception thread.

Related

Accessing HttpContext.Session from static method

I am getting following error when accessing HttpContext.Session from static method placed in separate task:
Session has not been configured for this application or request.
I used this article to implement access to HttpContext outside the controller
From controller I invoke this static method that used to retrieve image data:
public static void CreateDummyGallery(Gallery gallery)
{
Logger.LogDebug(LogModule.Dummy, $"Starting gallery creation.");
Task.Factory.StartNew(() =>
{
try
{
List<DummyPicture> pictures;
using (var context = new MyzeumContext())
{
int top = 10;
pictures = context.DummyPictures.FromSql($"SELECT * FROM dummypictures ORDER BY RAND() LIMIT {top}").ToList();
}
Logger.LogDebug(LogModule.Dummy, $"Starting retrieving images.");
Parallel.ForEach(pictures, picture => {
using (WebClient client = new WebClient())
{
}
});
Logger.LogDebug(LogModule.Dummy, $"Done retrieving images.");
}
catch(Exception e)
{
Logger.LogError(LogModule.Server, e.Message, e);
}
});
}
The problem occurs in Logger.LogDebug() because this is where I access HttpContext:
public void LogDebug(LogModule module, string message, Exception stackTrace = null)
{
Log record = new Log();
record.Module = module;
record.ThreadId = Environment.CurrentManagedThreadId;
record.SessionId = HttpContextHelper.Current?.Session?.Id;
record.Message = message;
record.Logged = DateTime.UtcNow;
if(stackTrace != null)
{
record.Message += $" :{stackTrace.StackTrace}";
}
queue.Enqueue(record);
}
The problem 99% occurs in the first call inside task:
Logger.LogDebug(LogModule.Dummy, $"Starting retrieving images.");
BUT, right after application starts this whole task block works fine and does not throw any exception. Problem starts after following requests.

The security validation for this page is invalid error trying to add sharepoint approval workflow to List in ListAdded eventreceiver

What I am trying to do is to attach the OOTB sharepoint workflow [Approval Sharepoint - 2010] to each and every document library that ever gets created. To accomplish this I created a List Added event reciever and put this code in it -
public override void ListAdded(SPListEventProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUtility.ValidateFormDigest();
using (SPSite site = new SPSite(properties.SiteId))
{
using (SPWeb web = site.OpenWeb())
{
try
{
base.ListAdded(properties);
if (currentList is SPDocumentLibrary)
{
SPDocumentLibrary docLib = (SPDocumentLibrary)properties.List;
//workflows need a tasks and history list. Here we assume they exist
SPList taskList = web.Lists["Tasks"];
SPList historyList = web.Lists["Workflow History"];
//loop through the workfows in the web and grab the one we want by name
SPWorkflowTemplate wfTemp = null;
foreach (SPWorkflowTemplate wt in web.WorkflowTemplates)
{
if (wt.Name == "Approval - SharePoint 2010")
{
wfTemp = wt;
Common.AddToLog(web, "Found " + wt.Name + " in current web " +
web.Url, false);
break;
}
}
//Now add the workflow to the doc library
SPWorkflowAssociation workFlow = SPWorkflowAssociation.CreateListAssociation(wfTemp, wfTemp.Name, taskList, historyList);
workFlow.AllowManual = true;
workFlow.AutoStartChange = false;
workFlow.AutoStartCreate = true;
workFlow.AssociationData = null;
web.AllowUnsafeUpdates = true;
web.ValidateFormDigest();
docLib.WorkflowAssociations.Add(workFlow);
docLib.EnableModeration = true;
docLib.Update();
web.Update();
web.AllowUnsafeUpdates = false;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
web.AllowUnsafeUpdates = false;
}
}
}
});
}
I am getting this error-
The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.
at this line
docLib.WorkflowAssociations.Add(workFlow);
Any any have any suggestions please ? Thanks for your feedback.
Why do you need "SPUtility.ValidateFormDigest()" at all?
Your code was running in an event receiver, not on a form or aspx page, there is nothing to validate.
Could you remove this line and try again?
I believe updating this code block:
web.AllowUnsafeUpdates = true;
web.ValidateFormDigest();
docLib.WorkflowAssociations.Add(workFlow);
docLib.EnableModeration = true;
docLib.Update();
web.Update();
web.AllowUnsafeUpdates = false;
and replacing it with:
web.Site.WebApplication.FormDigestSettings.Enabled = false;
docLib.WorkflowAssociations.Add(workFlow);
docLib.EnableModeration = true;
docLib.Update();
web.Update();
web.Site.WebApplication.FormDigestSettings.Enabled = true;
Let me know if this works for you or if you still encounter the same error.

How do I log EntityValidation errors using ELMAH MVC?

I've been writing an application using MVC4 and EF5.x, and using ELMAH for logging exceptions for review. We recently released the application, and as expected the ELMAH log filled up with several dozen exceptions. Great (and not)! The problem is that one of those exceptions is
System.Data.Entity.Validation.DbEntityValidationException
Validation failed for one or more entities.
See 'EntityValidationErrors' property for more details.
Of course, there's no way to see the EntityValidationErrors property for more details and the stack trace wraps up to my SubmitChanges()
I know ELMAH has the capability of allowing us to raise our own exceptions, and in some way customize what gets logged and how. Unfortunately, I'm still very new to ELMAH and MVC and a Google search didn't turn up anything relevant. I did find a blog article on logging EntityValidationErrors, and the author specifically mentioned that he would post how to do so in ELMAH but that was posted in September of 2012 and I didn't see anything since then.
Any help would be greatly appreciated!
Probably the best thing to do in this case would be to wrap your context.SaveChanges(); call in a try...catch block and then log the individual items from the ValidationExceptions. Something like the following should get you started:
try
{
context.SaveChanges();
}
catch (DbEntityValidationException ve)
{
var error = ve.EntityValidationErrors.First().ValidationErrors.First();
var msg = String.Format("Validation Error :: {0} - {1}",
error.PropertyName, error.ErrorMessage);
var elmahException = new Exception(msg);
Elmah.ErrorSignal.FromCurrentContext().Raise(elmahException);
}
How about this extension method based on the above..
public static void SaveChangesWithBetterValidityException(this DbContext context)
{
try
{
context.SaveChanges();
}
catch (DbEntityValidationException ve)
{
var errors = new List<string>();
foreach (var e in ve.EntityValidationErrors)
{
errors.AddRange(e.ValidationErrors.Select(e2 => string.Join("Validation Error :: ", e2.PropertyName, " : ", e2.ErrorMessage)));
}
var error = string.Join("\r\n", errors);
var betterException = new Exception(error, ve);
throw betterException;
}
}
Elmah will then have a much better exception in it's log
I added the following to my Global.asax.cs in order to forward all DbEntityValidationException exceptions to Elmah across my MVC application:
private void ElmahEntityValidationException()
{
var dbEntityValidationException = Server.GetLastError() as DbEntityValidationException;
if (dbEntityValidationException != null)
{
var errors = new List<string>();
foreach (var entityError in dbEntityValidationException.EntityValidationErrors)
{
errors.AddRange(entityError.ValidationErrors.Select(e2 => string.Join("Validation Error :: ", e2.PropertyName, " : ", e2.ErrorMessage)));
}
var error = string.Join("\r\n", errors);
var betterException = new Exception(error, dbEntityValidationException);
Elmah.ErrorSignal.FromCurrentContext().Raise(betterException);
}
}
protected void Application_Error(object sender, EventArgs e)
{
ElmahEntityValidationException();
}
Some of this code was reused from #Paige Cook's and #Original10's posts.
Re-throwing as per the code below is not perfect (although I don't mind resetting the call stack here, as Elmah's logged details of the address posted to will show me what lead to the exception) and you will have to work out your own security implications, but this is fairly concise & meets my needs:
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException e)
{
var de = new DetailedEntityValidationException(e);
throw de;
}
public class DetailedEntityValidationException : Exception
{
public DetailedEntityValidationException(DbEntityValidationException ve)
: base(ve.Message + ":\r\n\t-" + string.Join(new string('-',20) + "\r\n\t-", ve.EntityValidationErrors.Select(ev=>string.Join("\r\n\t-",ev.ValidationErrors.Select(e=>e.ErrorMessage)))))
{}
}
Here is my implementation for Global Web API solution for Elmah and EF Validation errors:
public class ElmahHandleWebApiErrorAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
var e = context.Exception;
// Try parse as entity error (i'm not sure of performance implications here)
var efValidationError = e as DbEntityValidationException;
if (efValidationError == null)
{
RaiseErrorSignal(e);
}
else
{
RaiseEntityFrameWorkValidationErrorSignal(efValidationError);
}
}
private static bool RaiseErrorSignal(Exception e)
{
var context = HttpContext.Current;
if (context == null)
return false;
var signal = ErrorSignal.FromContext(context);
if (signal == null)
return false;
signal.Raise(e, context);
return true;
}
private static bool RaiseEntityFrameWorkValidationErrorSignal(DbEntityValidationException e)
{
var context = HttpContext.Current;
if (context == null)
return false;
var signal = ErrorSignal.FromContext(context);
if (signal == null)
return false;
//Taken from post above
var errors = new List<string>();
foreach (var entityError in e.EntityValidationErrors)
{
errors.AddRange(entityError.ValidationErrors.Select(e2 => string.Join("Validation Error :: ", e2.PropertyName, " : ", e2.ErrorMessage)));
}
var error = string.Join("\r\n", errors);
var betterException = new Exception(error, e);
signal.Raise(betterException, context);
return true;
}
}
and then I register the attribute in the WebApiConfig.cs file under App_Start
config.Filters.Add(new ElmahHandleWebApiErrorAttribute());

Adding CampaignActivityItem in CRM 2011 gives 403 error

I am creating a Silverlight 4 web resource in CRM 2011 using the Otganizational Data service. I am able to create Campaigns, Marketing Lists, and Print Activities as well as linking the lists to the campaigns. However when I go to link the marketing lists to the print activity using the CampaignActivityItem I get a 403 Forbidden error. Below is the code I am using.
Models.CampaignActivityItem activityItem = new CampaignActivityItem()
{
CampaignActivityItemId = Guid.NewGuid(),
ItemId = EmailMarketingList.ListId, //Id of my marketing list I have
//already created
CampaignActivityId = new Models.EntityReference()
{
Id = MyCampaignPrintActivity.ActivityId, //Id of the print activity
//I have already created
LogicalName = "CampaignActivity",
Name = "CampaignActivity"
}
};
context.AddObject("CampaignActivityItemSet", activityItem);
context.BeginSaveChanges(System.Data.Services.Client.SaveChangesOptions.ContinueOnError, OnChangesSaved, context);
private void OnChangesSaved(IAsyncResult result)
{
// Use the Dispatcher to ensure that the
// asynchronous call returns in the correct thread.
OnUiThread(() =>
{
try
{
DataServiceResponse response = context.EndSaveChanges(result);
}
catch (DataServiceRequestException ex) // Errors with code=403
// message=Forbidden
{
WriteOperationResponse(ex.Response, "ListLink");
}
catch (InvalidOperationException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
);
}
Any direction on what I am doing wrong would be greatly appreciated. Using the context I am able to perform actions on other objects but not the CampaignActivityItemSet.

JavaMail - Pop3Folder accidentally gets closed

After successfully opening Pop3Folder, and retrieving messages from it, I then sometimes get to the point, when folder.isOpen returns false. At the same time, when looking at the Pop3Folder's fields in debug mode, I see that the field opened set to true.
Could somebody give me a hint, what might go wrong here?
Here is the code:
public void popMail(MessageProcessor messageProcessor) throws MessagingException {
Folder inboxFolder = null;
Store store = null;
try {
store = mailSession.getStore();
store.connect(mailSession.getProperty("mail.user"),
mailSession.getProperty("mail.password"));
// OK. Connected to POP3 Store.
inboxFolder = store.getFolder("inbox");
inboxFolder.open(Folder.READ_WRITE);
// The folder is successfully opened.
Message[] msgs = inboxFolder.getMessages();
// Messages are successfully retrieved.
if (msgs != null && msgs.length > 0) {
for (Message msg : msgs) {
if (messageProcessor != null) {
// Calling custom listener to process message
messageProcessor.processMessage(msg);
}
msg.setFlag(Flag.DELETED, true);
}
}
} finally {
// Oops, inboxFolder.isOpen returns false.
// Meanwhile I see in debug mode that inboxFolder#opened is set to true
if (inboxFolder != null && inboxFolder.isOpen()) {
try {
inboxFolder.close(true);
} catch (MessagingException e) {
log.warn("Error while closing folder");
}
} if (store != null) {
try {
store.close();
} catch (MessagingException e) {
log.warn("Error while closing store");
}
}
}
}
The server may be timing out the connection if your processMessage method takes too long. Turn on Session debugging and examine the protocol trace for clues.