NSPersistentStoreCoordinator not created on a UIManagedDocument - core-data

I'm starting to learn about UIManagedDocument and its abilities. From what I understand of it its a form of database stored in a location in the documents directory.
Anyway, I'm trying to use it as a database, by storing data within its NSManagedObjectContext however, after a few seconds of creating the UIManagedDocument and saving data to its context (after I'm guessing timing out), the app crashes and it tells me there is no persistent store coordinator.
There doesn't seem to be much guidance on the Apple docs as to how to create a persistent store coordinator after creating the managed document.
How do I do this exactly?
Thanks!
Edit
Code I'm using:
NSURL *url = [[self iCloudDocumentsURL] URLByAppendingPathComponent:nameOfDocument];
NSMutableArray *books = [self.books mutableCopy];
[books addObject:url];
[self setBooks:books];
UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url];
NSDictionary *options = #{ NSMigratePersistentStoresAutomaticallyOption : #YES,
NSInferMappingModelAutomaticallyOption : #YES,
NSPersistentStoreUbiquitousContentNameKey : document.fileURL.lastPathComponent,
NSPersistentStoreUbiquitousContentURLKey : [self iCloudCoreDataLogFilesURL] };
[document setPersistentStoreOptions:options];
if (document.documentState == UIDocumentStateClosed) {
[document openWithCompletionHandler:^(BOOL success) {
Book *book = [Book newBookWithTitle:bookTitle
inManagedObjectContext:document.managedObjectContext];
[document updateChangeCount:UIDocumentChangeDone];
}];
}
Update
After performing this code on a background thread. My app still logs 'NO' for the success on the completion handler after opening the document. However, my app does not crash, instead I get the following log:
2013-04-23 00:01:08.381 Notable[193:4b0b] -[_PFUbiquityRecordsImporter rollResponseOperation:encounteredAnError:whileTryingToAdoptBaseline:](1545): CoreData: Ubiquity: <PFUbiquityBaselineRollResponseOperation: 0x1fa561d0> localPeerID: mobile.2DDB96C5-A317-5BE5-8F29-9F5E6681A27A, storeName: A-B893A0AB-B764-42F1-9402-38790DCEF96B, modelVersionHash: NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=
ubiquityRootLocation: <PFUbiquityLocation: 0x1e59b790>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs
Encountered an error while trying to respond to the roll of baseline: <PFUbiquityBaseline: 0x1e54deb0>(0)
permanentLocation: <PFUbiquityLocation: 0x1f8e7120>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs/.baseline/A-B893A0AB-B764-42F1-9402-38790DCEF96B/NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=/baseline.zip
safeLocation: <PFUbiquityLocation: 0x1f8eb1b0>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs/.baseline/A-B893A0AB-B764-42F1-9402-38790DCEF96B/NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=/mobile.2DDB96C5-A317-5BE5-8F29-9F5E6681A27A
currentLocation: <PFUbiquityLocation: 0x1f8e7120>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs/.baseline/A-B893A0AB-B764-42F1-9402-38790DCEF96B/NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=/baseline.zip
storeName: A-B893A0AB-B764-42F1-9402-38790DCEF96B
modelVersionHash: NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=
baselineArchiveLocation: <PFUbiquityLocation: 0x1f8e7120>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs/.baseline/A-B893A0AB-B764-42F1-9402-38790DCEF96B/NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=/baseline.zip
Error: Error Domain=NSCocoaErrorDomain Code=134310 "The operation couldn’t be completed. (Cocoa error 134310.)" UserInfo=0x1f8d2ae0 {baseline=<PFUbiquityBaseline: 0x1e54deb0>(0)
permanentLocation: <PFUbiquityLocation: 0x1f8e7120>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs/.baseline/A-B893A0AB-B764-42F1-9402-38790DCEF96B/NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=/baseline.zip
safeLocation: <PFUbiquityLocation: 0x1f8eb1b0>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs/.baseline/A-B893A0AB-B764-42F1-9402-38790DCEF96B/NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=/mobile.2DDB96C5-A317-5BE5-8F29-9F5E6681A27A
currentLocation: <PFUbiquityLocation: 0x1f8e7120>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs/.baseline/A-B893A0AB-B764-42F1-9402-38790DCEF96B/NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=/baseline.zip
storeName: A-B893A0AB-B764-42F1-9402-38790DCEF96B
modelVersionHash: NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=
baselineArchiveLocation: <PFUbiquityLocation: 0x1f8e7120>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs/.baseline/A-B893A0AB-B764-42F1-9402-38790DCEF96B/NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=/baseline.zip
, localStoreKV=<PFUbiquityKnowledgeVector: 0x1f8220c0> ()}
userInfo: {
baseline = "<PFUbiquityBaseline: 0x1e54deb0>(0)\n\tpermanentLocation: <PFUbiquityLocation: 0x1f8e7120>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs/.baseline/A-B893A0AB-B764-42F1-9402-38790DCEF96B/NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=/baseline.zip\n\tsafeLocation: <PFUbiquityLocation: 0x1f8eb1b0>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs/.baseline/A-B893A0AB-B764-42F1-9402-38790DCEF96B/NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=/mobile.2DDB96C5-A317-5BE5-8F29-9F5E6681A27A\n\tcurrentLocation: <PFUbiquityLocation: 0x1f8e7120>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs/.baseline/A-B893A0AB-B764-42F1-9402-38790DCEF96B/NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=/baseline.zip\n\n\tstoreName: A-B893A0AB-B764-42F1-9402-38790DCEF96B\n\tmodelVersionHash: NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=\n\tbaselineArchiveLocation: <PFUbiquityLocation: 0x1f8e7120>: /private/var/mobile/Library/Mobile Documents/my~app~identifier/Logs/.baseline/A-B893A0AB-B764-42F1-9402-38790DCEF96B/NK3BysbustJxxyi2O8bX8eof15YimkUnegxqX6HDkas=/baseline.zip\n";
localStoreKV = "<PFUbiquityKnowledgeVector: 0x1f8220c0> ()";
}
This method also creates a 'DocumentMetaData.plist' (which I believe is necessary according to this files mention in the CS193P video I mentioned in a comment) instead of a file entitled 'persistentStore'.

You're not supposed to create it yourself when using UIManagedDocument-- that happens for you. However it's not that reliable in practice. Internally, UIManagedDocument sets up the persistent store and the persistent store coordinator. But that doesn't happen until the underlying iCloud code finishes getting its act together, talking to the server, downloading any new data, etc. In the meantime, you can't save changes, because until this process finishes there's nowhere to save those changes.
Also, sometimes iCloud fails to get its act together, for no reason that's under your control.
You probably need to check the success value in your open completion handler. If it's NO, you're kind of stuck. When iCloud flakes out there's no recovery path except sometimes if you're lucky you can just try again a few times until it works. File bugs, please, we need Apple to fix this.

Not sure if you ever fixed this Adam but you persistentStore should not be in the Cloud. Always create the uiManagedDocument in the local store and just set the iCloud options for addPersistentStore. CoreData will provide an immediate store for your app to use while it builds the real version and gets any data from iCloud if there is any. Once done it will switch you to the ICloud connected store which is also local. Only the transactions logs are posted to iCloud but that's done under the covers for you.

There's sample code in the UIDocument Class Reference, and also in the Core Data Programming Guide. You can also see an example of the Core Data stack setup by creating a Core Data based project using the Master-Detail template.
If this is your first experience with Core Data, I suggest you work through one of the books on the subject, either Core Data for iOS, by Tim Isted and Tom Harrington, or Core Data (2nd edition): Data Storage and Management for iOS, OS X, and iCloud, by Marcus Zarra.
I see a couple of things that look odd:
Does [self iCloudDocumentsURL] point to the local file system?
Why is the URL being inserted into the array of books?
Test the success variable in your block before assuming that the open succeeded.
Even in iOS 6.x, iCloud Core Data is not ready for prime time. It's certainly not something a new iOS dev wants to tackle. See what the very bright people at Black Pixel had to say about it with respect to one of their own products: http://blackpixel.com/blog/2013/03/the-return-of-netnewswire.html.

Related

Core data and cloudkit sync wwdc 2019 not working for beta 3

I am trying to replicate the result of WWDC talk on syncing core data with cloud kit automatically.
I tried three approaches:
Making a new master slave view app and following the steps at in
wwdc 2019 talk, in this case no syncing happens
Downloading the sample wwdc 2019 app also in this case no symcing happens
I made a small app with a small core data and a cloud kit container in this case syncing happens but I have to restart the app. I suspected it had to do with history management so observed the NSPersistentStoreRemoteChange notification not nothing receives.
Appreciate any help.
I also played around with CoreData and iCloud and it work perfectly. I would like to list some important points that may help you go further:
You have to run the app on a real device with iCloud Acc We can now test iCloud Sync on Simulator, but it will not get notification automatically. We have to trigger manually by select Debug > Trigger iCloud Sync
Make sure you added Push Notification and iCloud capability to your app. Make sure that you don't Dave issue with iCloud container (in this case, you will see red text on iCloud session in Xcode)
In order to refresh the view automatically, you need to add this line into your Core Data Stack: container.viewContext.automaticallyMergesChangesFromParent = true.
Code:
public lazy var persistentContainer: NSPersistentCloudKitContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentCloudKitContainer(name: self.modelName)
container.viewContext.automaticallyMergesChangesFromParent = true
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
When you add some data, normally you should see console log begin with CloudKit: CoreData+CloudKit: ..........
Sometimes the data is not synced immediately, in this case, I force close the app and build a new one, then the data get syncing.
There was one time, the data get synced after few hours :(
I found that the NSPersistentStoreRemoteChange notification is posted by the NSPersistentStoreCoordinator and not by the NSPersistentCloudKitContainer, so the following code solves the problem:
// Observe Core Data remote change notifications.
NotificationCenter.default.addObserver(
self, selector: #selector(self.storeRemoteChange(_:)),
name: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator)
Also ran into the issue with .NSPersistentStoreRemoteChange notification not being sent.
Code from Apples example:
// Observe Core Data remote change notifications.
NotificationCenter.default.addObserver(
self, selector: #selector(type(of: self).storeRemoteChange(_:)),
name: .NSPersistentStoreRemoteChange, object: container)
Solution for me was to not set the container as object for the notification, but nil instead. Is it not used anyway and prevents the notification from being received:
// Observe Core Data remote change notifications.
NotificationCenter.default.addObserver(
self, selector: #selector(type(of: self).storeRemoteChange(_:)),
name: .NSPersistentStoreRemoteChange, object: nil)
Update:
As per this answer: https://stackoverflow.com/a/60142380/3187762
The correct way would be to set container.persistentStoreCoordinator as object:
// Observe Core Data remote change notifications.
NotificationCenter.default.addObserver(
self, selector: #selector(type(of: self).storeRemoteChange(_:)),
name: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator)
I had the same problem, reason was that iCloudDrive must be enabled in your devices. Check it in the Settings of every your device
I understand this answer comes late and is not actually specific to the WWDC 19 SynchronizingALocalStoreToTheCloud Apple's sample project to which OP refers to, but I had syncing issues (not upon launch, when it synced fine, but only during the app being active but idle, which seems to be case 3 of the original question) in a project that uses Core Data + CloudKit with NSPersistentCloudKitContainer and I believe the same problems I had - and now apparently I have solved - might affect other Users reading this question in the future.
My app was built using Xcode's 11 Master-Detail template with Core Data + CloudKit from the start, so I had to do very little to have syncing work initially:
Enable Remote Notifications Background Mode in Signing & Capabilities for my target;
Add the iCloud capability for CloudKit;
Select the container iCloud.com.domain.AppName
Add viewContext.automaticallyMergesChangesFromParent = true
Basically, I followed Getting Started With NSPersistentCloudKitContainer by Andrew Bancroft and this was enough to have the MVP sync between devices (Catalina, iOS 13, iPadOS 13) not only upon launch, but also when the app was running and active (thanks to step 4 above) and another device edited/added/deleted an object.Being the Xcode template, it did not have the additional customisations / advanced behaviours of WWDC 2019's sample project, but it actually accomplished the goal pretty well and I was satisfied, so I moved on to other parts of this app's development and stopped thinking about sync.
A few days ago, I noticed that the iOS/iPadOS app was now only syncing upon launch, and not while the app was active and idle on screen; on macOS the behaviour was slightly different, because a simple command-tab triggered sync when reactivating the app, but again, if the Mac app was frontmost, no syncing for changes coming from other devices.
I initially blamed a couple of modifications I did in the meantime:
In order to have the sqlite accessible in a Share Extension, I moved the container in an app group by subclassing NSPersistentCloudKitContainer;
I changed the capitalisation in the name of the app and, since I could not delete the CloudKit database, I created a new container named iCloud.com.domain.AppnameApp (CloudKit is case insensitive, apparently, and yes, I should really start to care less about such things).
While I was pretty sure that I saw syncing work as well as before after each one of these changes, having sync (apparently) suddenly break convinced me, for at least a few hours, that either one of those modification from the default path caused the notifications to stop being received while the app was active, and that then the merge would only happen upon launch as I was seeing because the running app was not made aware of changes.
I should mention, because this could help others in my situation, that I was sure notifications were triggered upon Core Data context saves because CloudKit Dashboard was showing the notifications being sent:
So, I tried a few times clearing Derived Data (one never knows), deleting the apps on all devices and resetting the Development Environment in CloudKit's Dashboard (something I already did periodically during development), but I still had the issue of the notifications not being received.
Finally, I realised that resetting the CloudKit environment and deleting the apps was indeed useful (and I actually rebooted everything just to be safe ;) but I also needed to delete the app data from iCloud (from iCloud's Settings screen on the last iOS device where the app was still installed, after deleting from the others) if I really wanted a clean slate; otherwise, my somewhat messed up database would sync back to the newly installed app.
And indeed, a truly clean slate with a fresh Development Environment, newly installed apps and rebooted devices resumed the notifications being detected from the devices also when the apps are frontmost.So, if you feel your setup is correct and have already read enough times that viewContext.automaticallyMergesChangesFromParent = true is the only thing you need, but still can't see changes come from other devices, don't exclude that something could have been messed up beyond your control (don't get me wrong: I'm 100% sure that it must have been something that I did!) and try to have a fresh start... it might seem obscure, but what isn't with the syncing method we are choosing for our app?

CoreData: lightweight migration and iCloud

After a few weeks of integration my CoreData app with iCloud it started working well enough. I mean data are syncing between devices. But then I added a new version of model, and after that the app cannot add iCloud store to coordinator. Method addPersistentStoreWithType:configuration:URL:options:error: always returns
Error Domain=NSCocoaErrorDomain Code=512 "The file upload timed out."
And log looks like:
-PFUbiquitySafeSaveFile waitForFileToUpload:: CoreData: Ubiquity: (0) ...
Sure, I add iCloud store to coordinator with lightweight migration's options:
NSInferMappingModelAutomaticallyOption = 1;
NSMigratePersistentStoresAutomaticallyOption = 1;
After I rollback the app to previous version of CoreData's model - everything is working again.
Does anyone have any idea what's going on?
Thank you in advance for participation.

Calling WCF Service Operation in multithreaded Console Application

I have below application:
Its windows console .NET 3.0 application
I'm creating 20 workloads and assigning them to threadpool to process.
Each thread in ThreadPool creates WCF Client and calls service with request created using workload assigned.
Sometimes on production servers[12 core machines], I get following exception:
There was an error reflecting type 'xyz' while invoking operation using WCF client. This starts appearing in all threads. After sometime it suddenly disappears and starts appearing again.
Code:
Pseudo Code:
for(int i=0;i<20;i++)
{
MultiThreadedProcess proc =new MultThreadedProcess(someData[i]);
ThreadPool.QueueUserWorkItem(proc.CallBack,i);
}
In Class MultiThreadedProcess, I do something like this:
public void Callback(object index)
{
MyServiceClient client = new MyServiceClient();
MyServiceResponse response =client.SomeOperation(new MyServiceRequest(proc.SomeData));
client.close();
//Process Response
}
Can anyone suggest some resolutions for this problem?
If you can turn on diagnostic, appears to me serialization issue, there might be chance that certain data members/values are not able to de-serialized properly for operation call.

Setting Core Data persistent store (SQLite) as NORMAL locking-mode

I'm building a prototype of an app where persistent store uses SQLite via AFP on a "server" machine (the same LAN).
However, I can't connect to the store from 2 different instances of my app.
I set SQLite pragma setting (related to locking) on persistent store coordinator like this:
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
NSMutableDictionary *pragmaOptions = [NSMutableDictionary dictionary];
[pragmaOptions setObject:#"NORMAL" forKey:#"locking_mode"];
NSDictionary *storeOptions = [NSDictionary dictionaryWithObject:pragmaOptions forKey:NSSQLitePragmasOption];
if (![coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:storeOptions error:&error]) {
[[NSApplication sharedApplication] presentError:error];
return nil;
}
and error message I'm getting when trying to connect to the store from 2nd client (i.e. when the 1st one is already successfully connected) is:
ERROR: sqlite database is locked because it is in use by another host that holds a host-exclusive lock on .../TestDBApp.storedata; this host UID... cannot override the host-exclusive lock until the other host UID... releases its locks on .../.TestDBApp.storedata-conch
Am I doing something wrong?
Is accessing the same store from 2 clients possible with Core Data and SQLite?
Is this a bug in Core Data and/or SQLite API?
SQLite does not allow a database file to have multiple write locks. Write locks are taken for any transaction that changes data, or when the applications explicitly requests one.
Apparently, a Core Data connection holds a write transaction or a write lock open.
As far as I could remember, Core data will use the exclusive lock mode for save method. I suggest you to pass argument "-com.apple.CoreData.SQLDebug 1" to your app . If you find "BEGIN EXCLUSIVE" in console, I guess your setting is ignored by Core Data.

An unhandled access exception has occurred, msmq, Sharepoint error

I have an issue that is occurring after my server reboots. I have some features in SharePoint, for doing various things. One thing they do is add items into a couple of different MSMQ queues. Immediately after a server reboot, if I try to log in to SharePoint and I go to a custom page of mine, and click on a button within that page (which would then create the msmq item) I get taken to a page that displays the following:
The website declined to show this webpage
This error (HTTP 403 Forbidden) means that Internet Explorer was able to connect to the website, but it does not have permission to view the webpage
If I dig in to the Event Logs I find the following errors in Application:
Event ID: 1314
An unhandled access exception has occurred
AND in the Security event logs:
3 of these:
Event ID: 560
Object Open:
Object Server: SC Manager
Object Type: SERVICE OBJECT
Object Name: MSDTC
....
Accesses: Query status of service
Event ID: 560
Object Open:
Object Server: SC Manager
Object Type: SC_MANAGER OBJECT
Object Name: ServicesActive
...
Image File Name: C:\WINDOWS\system32\services.exe
...
Accesses: Connect to service controller
Query service database lock state
Event ID: 560
Object Open:
Object Server: SC Manager
Object Type: SERVICE OBJECT
Object Name: MSDTC
...
Image File Name: C:\WINDOWS\system32\services.exe
...
Accesses: Query service configuration information
ALSO, if I dig in to the SharePoint logs, I find the following errors:
Application error when access /my/site/url/MyPage.aspx, Error=Access
is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Server stack trace: at
System.Transactions.Oletx.IDtcProxyShimFactory.ConnectToProxy(String
nodeName, Guid resourceManagerIdentifier, IntPtr managedIdentifier,
Boolean& nodeNameMatches, UInt32& whereaboutsSize, CoTaskMemHandle&
whereaboutsBuffer, IResourceManagerShim& resourceManagerShim) at
System.Transactions.Oletx.DtcTransactionManager.Initialize() at
System.Transactions.Oletx.DtcTransactionManager.get_ProxyShimFactory()
at
System.Transactions.Oletx.OletxTransactionManager.CreateTransaction(TransactionOptions
properties) at
System.Transactions.TransactionStatePromoted.EnterState(InternalTransaction
tx) ...
...at System.Transactions.EnlistableStates.Promote(InternalTransaction tx)
at System.Transactions.Transaction.Promote() at
System.Transactions.TransactionInterop.ConvertToOletxTransaction(Transaction
transaction) at
System.Transactions.TransactionInterop.GetDtcTransaction(Transaction
transaction) at
System.ServiceModel.Channels.MsmqQueue.GetNativeTransaction(MsmqTransactionMode
transactionMode) at
System.ServiceModel.Channels.MsmqQueue.SendDtcTransacted(NativeMsmqMessage
message, MsmqTransactionMode transactionMode) at
System.ServiceModel.Channels.MsmqQueue.Send(NativeMsmqMessage message,
MsmqTransactionMode transactionMode) at
System.ServiceModel.MsmqIntegration.MsmqIntegrationOutputChannel.OnSend(Message
message, TimeSpan timeout) at System.ServiceModel.Chann...
I have two VMs, one for the web (sharepoint) machine, and one of the DB machine (where all the content dbs etc are stored). The DB server is a primary domain controller, and both machines are part of the same domain. I've created a domain user to use for the SharePoint application pool.
Strangely, it is possible to make the errors go away by going to a different part of my application and running that code (which also adds an entry into the msmq). Once that is done, then all of the rest of the application works as normal.
Any help would be incredibly appreciated.
Note: I noticed that the error had something to do with the anonymous user (IUSR...) in IIS for the SharePoint site. I changed that user to be a domain administrator user, and the error no longer happens. So, it's something to do with the permissions of the IUSR.. user, but I don't know what...
O M G
Ok, so I tried something, it was a LONG shot, but I was at my wits end.
I wrapped all of the code that was talking to the MSMQ (adding items to the queue) in the run with elevated privelages thang, and it worked!!!!
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//MSMQCode here
});
Now, I can reboot the server, and do the stuff that was erroring before, and it works fine!
Consider running warm up scripts upon server reboot.
http://blogs.msdn.com/joelo/archive/2006/08/13/697044.aspx
Give everyone read permission to the bin directory under inetpub\wss etc..

Resources