SharePoint SPRequest Leak - sharepoint

I have been getting this weird message in the ULS ever since I ported the code over to SharePoint 2010.
Here is the message:
w3wp.exe (0x1320)
0x1168 SharePoint Foundation
General
90hv
Unexpected
Detected use of SPRequest for previously closed SPWeb object. Please close SPWeb objects when you are done with all objects obtained from them, but not before.
Stack trace:
at Microsoft.SharePoint.SPWorkItem.FetchData()
at Microsoft.SharePoint.SPWorkItem.retrieveSchema(Schema schemaIndex)
at Microsoft.SharePoint.SPWorkItem.get_SiteId()
at Microsoft.SharePoint.SPWorkItem.Delete()
at Microsoft.SharePoint.Workflow.SPWinOeHostServices.WorkItemDequeue(Transaction txn, Object[] transData)
at Microsoft.SharePoint.Workflow.SPPendingWorkBatch.Commit(Transaction transaction, ICollection items)
at System.Workflow.Runtime.WorkBatch.PendingWorkCollection.Commit(Transaction transaction)
at System.Workflow.Runtime.WorkBatch.Commit(Transaction transaction)
at System.Workflow.Runtime.Hosting.WorkflowCommitWorkBatchService.CommitWorkBatch(CommitWorkBatchCallback commitWorkBatchCallback)
at System.Workflow.Runtime.Hosting.DefaultWorkflowCommitWorkBatchService.CommitWorkBatch(CommitWorkBatchCallback commitWorkBatchCallback)
at System.Workflow.Runtime.WorkflowExecutor.CommitTransaction(Activity activityContext)
at System.Workflow.Runtime.WorkflowExecutor.Persist(Activity dynamicActivity, Boolean unlock, Boolean needsCompensation)
at System.Workflow.Runtime.WorkflowExecutor.System.Workflow.ComponentModel.IWorkflowCoreRuntime.PersistInstanceState(Activity activity)
at System.Workflow.ComponentModel.Activity.MarkClosed()
at System.Workflow.ComponentModel.Activity.ReleaseLockOnStatusChange(IActivityEventListener1 eventListener)
at System.Workflow.ComponentModel.FaultAndCancellationHandlingFilter.SafeReleaseLockOnStatusChange(ActivityExecutionContext context)
at System.Workflow.ComponentModel.FaultAndCancellationHandlingFilter.OnEvent(Object sender, ActivityExecutionStatusChangedEventArgs e)
at System.Workflow.ComponentModel.ActivityExecutorDelegateInfo1.ActivityExecutorDelegateOperation.Run(IWorkflowCoreRuntime workflowCoreRuntime)
at System.Workflow.Runtime.Scheduler.Run()
at System.Workflow.Runtime.WorkflowExecutor.RunScheduler()
at System.Workflow.Runtime.WorkflowExecutor.RunSome(Object ignored)
at System.Workflow.Runtime.Hosting.DefaultWorkflowSchedulerService.WorkItem.Invoke(WorkflowSchedulerService service)
at System.Workflow.Runtime.Hosting.ManualWorkflowSchedulerService.RunOne(Guid workflowInstanceId)
at System.Workflow.Runtime.Hosting.ManualWorkflowSchedulerService.RunWorkflow(Guid workflowInstanceId)
at Microsoft.SharePoint.Workflow.SPWinOeHostServices.Send(SPWorkflow workflow, SPWinOeWorkflow winoeworkflow, SPWorkflowEvent e)
at Microsoft.SharePoint.Workflow.SPWinOeEngine.RunWorkflow(SPWorkflowHostService host, SPWorkflow workflow, Collection1 events, TimeSpan timeOut)
at Microsoft.SharePoint.Workflow.SPWorkflowManager.RunWorkflowElev(SPWorkflow workflow, Collection1 events, SPWorkflowRunOptionsInternal runOptions)
at Microsoft.SharePoint.Workflow.SPWorkflowManager.StartWorkflowElev(Object context, SPWorkflowAssociation association, DateTime elevationTimeUtc, SPWorkflowEvent startEvent, SPWorkflowRunOptions runOptions)
at Microsoft.SharePoint.Workflow.SPWorkflowAutostartEventReceiver.<>c_DisplayClass1.b_0(SPSite superUserSite, SPWeb superUserWeb)
at Microsoft.SharePoint.SPSecurity.<>c_DisplayClassf.b_e()
at Microsoft.SharePoint.SPSecurity.<>c_DisplayClass4.b_2()
at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)
at Microsoft.SharePoint.Workflow.SPWorkflowAutostartEventReceiver.AutoStartWorkflow(SPItemEventProperties properties, Boolean bCreate, Boolean bChange, AssocType atyp)
at Microsoft.SharePoint.Workflow.SPWorkflowAutostartEventReceiver.ItemUpdated(SPItemEventProperties properties)
at Microsoft.SharePoint.SPEventManager.RunItemEventReceiver(SPItemEventReceiver receiver, SPUserCodeInfo userCodeInfo, SPItemEventProperties properties, SPEventContext context, String receiverData)
at Microsoft.SharePoint.SPEventManager.RunItemEventReceiverHelper(Object receiver, SPUserCodeInfo userCodeInfo, Object properties, SPEventContext context, String receiverData)
at Microsoft.SharePoint.SPEventManager.<>c_DisplayClassc`1.b_6()
at Microsoft.SharePoint.SPSecurity.RunAsUser(SPUserToken userToken, Boolean bResetContext, WaitCallback code, Object param)
at Microsoft.SharePoint.SPEventManager.InvokeEventReceivers[ReceiverType](SPUserToken userToken, Guid tranLockerId, RunEventReceiver runEventReceiver, Object receivers, Object properties, Boolean checkCancel)
at Microsoft.SharePoint.SPEventManager.InvokeEventReceivers[ReceiverType](Byte[] userTokenBytes, Guid tranLockerId, RunEventReceiver runEventReceiver, Object receivers, Object properties, Boolean checkCancel)
at Microsoft.SharePoint.SPEventManager.HandleEventCallback[ReceiverType,PropertiesType](Object callbackData)
at Microsoft.SharePoint.Utilities.SPThreadPool.WaitCallbackWrapper(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.Run(ExecutionContextexecutionContext, ContextCallback callback, Object state)
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack)
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)
This message comes up whenever I run the workflow, it does not appear to have any harmful effects to the workflow.
Please let me know anything you folks know.

Here's the guidance from MS around the proper disposal of SharePoint objects. Odds are good that if you're following all of these (correctly) then your code will be ok. The SPDisposeCheck tool can also be helpful, although in my exeprience you still need to know all of the disposal rules. This tool only does a static analysis and can return a lot of candidate issues that may actually be fine.

When you read the exception more carefully you can see that you don't Forget to dispose the object. you reference it after it got disposed!
you can read more about it from the german SharePoint Guru Stefan Gossner

Related

Object reference not set to an instance of an object when trying to add a value to a collection in a Comos Db record - Entity Framework

I have a record with an array of objects on it and whenever I try to add a value to it and then save the changes it throws this error:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the the item with id ... See the inner exception for details.
---> System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.EntityFrameworkCore.Cosmos.Update.Internal.DocumentSource.GetCurrentDocument(IUpdateEntry entry)
at Microsoft.EntityFrameworkCore.Cosmos.Update.Internal.DocumentSource.UpdateDocument(JObject document, IUpdateEntry entry, Nullable`1 ordinal)
at Microsoft.EntityFrameworkCore.Cosmos.Update.Internal.DocumentSource.UpdateDocument(JObject document, IUpdateEntry entry)
at Microsoft.EntityFrameworkCore.Cosmos.Update.Internal.DocumentSource.UpdateDocument(JObject document, IUpdateEntry entry, Nullable`1 ordinal)
at Microsoft.EntityFrameworkCore.Cosmos.Update.Internal.DocumentSource.UpdateDocument(JObject document, IUpdateEntry entry)
at Microsoft.EntityFrameworkCore.Cosmos.Update.Internal.DocumentSource.UpdateDocument(JObject document, IUpdateEntry entry, Nullable`1 ordinal)
at Microsoft.EntityFrameworkCore.Cosmos.Update.Internal.DocumentSource.UpdateDocument(JObject document, IUpdateEntry entry)
at Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal.CosmosDatabaseWrapper.SaveAsync(IUpdateEntry entry, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal.CosmosDatabaseWrapper.SaveChangesAsync(IList`1 entries, CancellationToken cancellationToken)
This is the code that adds the values and saves them business.staffIds is a ICollection.
var staffIdToAdd = new StaffId() { Value = staffId };
business.StaffIds.Add(staffIdToAdd);
await _dbContext.SaveChangesAsync(cancellationToken);
Reproduced the code issue.
Step 1 :- The CosmosDB have only two records.
Step 2 :- Through code tried to fetch record where id == 3
and this code throws exception
As db doesn't contain any document with id = 3.
Solution:- Before adding staffid/item to the business.staffIds Collection put a null check whether the object business is null or not.
if(business != null){
/* Your Code to add new item to the staffids and saveChanges*/
}

CodeNameNotUniqueException after applying hotfix Kentico 7

I am having a 'CodeNameNotUniqueException' error whereby after upgrading from v7.0.37 to v7.0.70 I am getting an error on loading my website. It looks like it is related to something to do with roles as the code name 'int-sg-ctx-nz-xa6-publisheddesktopoffice2013' is a role in my website. It basically happens to all the roles and not just this one. This is the error message that I get in event viewer:
Exception information:
Exception type: CodeNameNotUniqueException
Exception message: The object with code name 'int-sg-ctx-nz-xa6-publisheddesktopoffice2013' already exists.
at CMS.DataEngine.AbstractInfoProvider`2.SetInfoInternal(InfoType info)
at CMS.DataEngine.AbstractInfoProvider`2.SetInfo(InfoType info)
at CMS.SiteProvider.UserInfoProvider.EnsureRolesAndSitesInternal(UserInfo uInfo, Boolean isWindowsAuth)
at CMS.CMSHelper.AuthenticationHelper.EnsureExternalUser(UserInfo uInfo)
at CMS.CMSHelper.AuthenticationHelper.AuthenticateWindowsUser(String userName, SecurityIdentifier sid, String siteName, String[] roles)
at CMS.CMSHelper.ContextData.GetCurrentUser(Boolean& loadUserData, Boolean cacheResult)
at CMS.CMSHelper.ContextData.get_CurrentUser()
at CMSAppBase.CMSSessionStart(Object sender, EventArgs e)
at System.Web.SessionState.SessionStateModule.CompleteAcquireState()
at System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Request information:
Request URL: http://aainsurance/CMSPages/PortalTemplate.aspx?aliaspath=/home
Request path: /CMSPages/PortalTemplate.aspx
User host address: 10.212.210.58
User: INT\U362515
Is authenticated: True
Authentication Type: NTLM
Thread account name: IIS APPPOOL\AAI.Intranet
Thread information:
Thread ID: 58
Thread account name: IIS APPPOOL\AAI.Intranet
Is impersonating: False
Stack trace: at CMS.DataEngine.AbstractInfoProvider`2.SetInfoInternal(InfoType info)
at CMS.DataEngine.AbstractInfoProvider`2.SetInfo(InfoType info)
at CMS.SiteProvider.UserInfoProvider.EnsureRolesAndSitesInternal(UserInfo uInfo, Boolean isWindowsAuth)
at CMS.CMSHelper.AuthenticationHelper.EnsureExternalUser(UserInfo uInfo)
at CMS.CMSHelper.AuthenticationHelper.AuthenticateWindowsUser(String userName, SecurityIdentifier sid, String siteName, String[] roles)
at CMS.CMSHelper.ContextData.GetCurrentUser(Boolean& loadUserData, Boolean cacheResult)
at CMS.CMSHelper.ContextData.get_CurrentUser()
at CMSAppBase.CMSSessionStart(Object sender, EventArgs e)
at System.Web.SessionState.SessionStateModule.CompleteAcquireState()
at System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Can anyone help with this? As of now I've had to rollback the database and restore the files for version 37 which is a shame as this version is not fully compatible with IE11.
Are you somewhere editing/creating user`s ID or GUID manually in your custom code?
Just FYI - kentico 7 has released more than one year before release of IE11 so it is really hard to support not existing product... Source: wiki devnet

C# windows server 2008 r2 win32exception

We have a .net 2.0 exe that we are running on windows server 2008 r2. It gets stucks and stops with below info on Event log.
The same used to run correctly on windows server 2003. there are no code changes or rebuilds done in the migration to windows server 2008 r2.
We have tried putting lots of logs in exception in our code, but not sure from which line of code this error popups, but our normal logs do popup in the eventvwr, so doesnt look like permission issue on event viewer.
Any help or pointers on this would be helpful.
1) Exception Information
*********************************************
Exception Type: System.ComponentModel.Win32Exception
NativeErrorCode: 87
ErrorCode: -2147467259
Message: The parameter is incorrect
Data: System.Collections.ListDictionaryInternal
TargetSite: Void InternalWriteEvent(UInt32, UInt16, System.Diagnostics.EventLogEntryType, System.String[], Byte[], System.String)
HelpLink: NULL
Source: System
2) StackTrace Information
*********************************************
at System.Diagnostics.EventLog.InternalWriteEvent(UInt32 eventID, UInt16 category, EventLogEntryType type, String[] strings, Byte[] rawData, String currentMachineName)
at System.Diagnostics.EventLog.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData)
at System.Diagnostics.EventLog.WriteEntry(String source, String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData)
at System.Diagnostics.EventLog.WriteEntry(String source, String message, EventLogEntryType type, Int32 eventID, Int16 category)
at DefaultPublisher.WriteToLog(String entry, EventLogEntryType type)
at DefaultPublisher.Publish(Exception exception, NameValueCollection additionalInfo, NameValueCollection configSettings)
at ExceptionManager.Publish(Exception exception, NameValueCollection additionalInfo)
The message passed to WriteEntry() is too long. It's length must be less than 32706 characters

GetSchema() throws UciException "*HS.OLEDBINFO" is not in the CATALOG space"

I installed UniVerse on the administrator account of a Parallels Windows installation. I subsequently created a second administrator account whose credentials I'm using to create the U2Connection.
However, when attempting to call GetSchema(...) I'm getting the following exception. I suspect this is permission-related but I'm not sure what I need to change.
{" [U2][UCINET-UO] [U2][UCINET][UNIVERSE]:\"*HS.OLEDBINFO\" is not in the CATALOG space.\r\n"}
at U2.Data.Client.Ucinet.UciStatement.ExecuteDirect(String pSQL)
at U2.Data.Client.U2Command.a(CommandBehavior A_0)
at U2.Data.Client.U2Command.ExecuteReaderObject(CommandBehavior behavior, String method, U2CursorType reqCursorType, Boolean abortOnOptValueChg, Boolean skipDeleted, Boolean isResultSet, Int32 maxRows, Boolean skipInitialValidation)
at U2.Data.Client.U2Command.ExecuteReaderObject(CommandBehavior behavior, String method)
at U2.Data.Client.U2MetaDataFactory.b(U2Command& A_0, String A_1)
at U2.Data.Client.U2MetaDataFactory.v(String[] A_0)
at U2.Data.Client.U2MetaDataFactory.GetSchema(String collectionName, String[] restrictionValues)
at U2.Data.Client.U2Connection.GetSchema(String collectionName, String[] restrictionValues)
at U2.Data.Client.U2Connection.GetSchema(String collectionName)
at Connection.Program.Main(String[] args) in c:\Program Files (x86)\Rocket Software\U2 Toolkit for .NET\U2 Database Provider\samples\C#\UniVerse\Connection\Program.cs:line 30
I'm told: He is right for the second administrator account. All UniVerse users must have the permission to access the global catalog subroutines. That “*HS.OLEDBINFO” (%AHS.OLEDBINFO) will be in the “C:\U2\UV\catdir” folder by default.
Does that help?

Cannot update document property on ItemAdded event when using Vista

We are trying to create a custom event handler that would fire on ItemAdded event. The event handler then updates the document with a unique ID value to a column in this document library.
Our solution works fine, except when a user on Vista is trying to save a new document from Office 2007. In this scenario the document is stored to document library but Unique ID column is empty, and there is no exception.
Vista Users can upload document(s) to library without a problem. Everything else works fine on XP and Win2k3 operating systems.
Has anyone seen something similar, and what might be the problem here? To demonstrate the problem we are using DateTime.Now as unique ID.
using Microsoft.SharePoint;
public class TestReciever : SPItemEventReceiver
{
public override void ItemAdded(Microsoft.SharePoint.SPItemEventProperties properties)
{
try {
DisableEventFiring();
properties.ListItem("UniqueID Column") = DateTime.Now.ToString();
properties.ListItem.SystemUpdate();
EnableEventFiring();
}
catch (Exception ex) {
// handle exception
}
}
}
We have noticed exactly the same thing happening. When the 2007 doc is added to the library, the properties from the list are added to it (blank).
Then the (synchronous) event handler is called, updating the list with the correct values for the UniqueID column.
Then the inbuilt property mapping to 2007 docs kicks in and overwrites your values with those stored in the 2007 doc (not raising an item updated event again).
This means that the list now has a blank for your column.
If you change to an asynchronous event you may see what we did and that the slight delay for asynchronous meant that the property mapping to 2007 docs happened first (we think) meaning the value was stored correctly.
It is possible to break the property mapping between the list and office, but that is only a workaround.
I cannot for the life of me find where this info is on an MS site, but it is a known problem. Perhaps you can hang in there for SP2 (may even be fixed in SP1, but am unsure).
At the end we contacted Microsoft and they provided us with the following workaround solution. The key here is to delay item update in a separate thread.
private Guid listID;
private Guid itemID;
private Guid siteID;
public override void ItemAdded(Microsoft.SharePoint.SPItemEventProperties properties)
{
DisableEventFiring();
item = properties.ListItem;
listID = properties.ListId;
itemID = properties.ListItem.UniqueId;
siteID = properties.SiteId;
Threading.Thread setDocumentInternalIDThread = new Threading.Thread(SetInternalID);
setDocumentInternalIDThread.Start();
EnableEventFiring();
}
private void SetInternalID()
{
try {
Threading.Thread.Sleep(10000);
using (SPSite site = new SPSite(siteID)) {
using (SPWeb web = site.OpenWeb()) {
SPList list = web.Lists(listID);
SPListItem item = list.Items(itemID);
item(Common.CustomID) = Common.GetAlphaPrefix() + Common.GetDocNumber();
item.SystemUpdate();
}
}
}
catch (Exception ex) {
Log(ex.Message);
}
}
Another workaround is to set the custom field that is being updated in the event receiver to be read only (set the fields ReadOnly property to TRUE). This has a few pros and cons. This is ideal for a unique id solution, because there is no way for the user to modify the value. However, the field is hidden to the UI, so managing it becomes more troublesome, and the field can't be used in labels, or quick parts. You can set the ShowInDisplayForm property of the field to TRUE to have the field display in the view form, but not the edit form. The field can also be added to your views. This is the best workaround I have found for this issue to date.
This is an issue with Office 2007 and the WSS 3.0 xml parser. When the properties are promoted from the Office 2007 document, the parser attempts to assign document properties to the list properties in SharePoint (property promotion). The problem is that this event occurs after any ItemAdded, or ItemUpdated events, so the property gets overwritten with the value in the document, which is of course, blank. Microsoft has raised this as a bug, and I was hoping for a fix in SP2, but no such luck.

Resources