Item is not added into the list (from code) - sharepoint-2010

We have some strange problem here. We have feature event receiver, where we are creating custom fields -> content type -> list. After that, one default item is added. On my VM it was working just fine, but after moving into pre-prod environment, we got this strange behavior with no exception or error in logs.
First thing, item was created only sometimes, with no trace what happened. Mostly it was not created. I even experienced this: when I activated feature, I went to the list and so item there, but after refresh it was gone!
We tried to put there some Thread.Sleep() cycle (while debugging, item was in Items collection, but ItemsCount property of the list was always showing 0).
Now I am out of ideas what is wrong. It's not about execution time (maybe). Looks like, for some reason, SP is killing SPItem.Update before it is created for real and we don't know why. Any help is really welcome!

When you try to access sharepoint items from code and not have admin permissions to update/ delete them then set website website.AllowUnsafeUpdates = true; property
//Set AllowUnsafeUpdates = true to update the database / sharepoint list from code.
FormWeb.AllowUnsafeUpdates = true;
NewItem.Update();
FormWeb.AllowUnsafeUpdates = false;
you code should be like this to make changes in the list.. when you adding item to list.
Use Update statement in same manner when you accessing list and updating its data.
Check whether you updating the list correctly.. There may be some SharePoint security issue.
Reference Link:
http://blogs.msdn.com/b/infopath/archive/2010/04/01/add-items-to-a-sharepoint-list-using-managed-code.aspx.
You can check this [SPSecurity.RunWithElevatedPrivileges][1]
[1]: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx , link, link
you can check that what is going over there by adding your events in sharepoint..
Check this post and debug it..
http://developmentsolutionsjunction.blogspot.com/2011/06/adding-events-and-eventhandlers-in.html

so I was finally able to find out where the problem was. After deeper study and trying that and this I found out that there was a third party feature. It was adding event to each created list and was deleting everything what wasn't consistent with CT defined by company. This is weird and I don't really understand why somebody wants this. But ok, they pay, their rules.
So if you encounter such problem, try also this possibility.
However, I also leard few things during this, e.g. if you are working with SP instances from web scope, use web scoped features, not site ones, also, SP has a nasty habit to silent som exceptions. Also, if you e.g. take instance of SPWeb from event properties, it doesn't necessarily means it is already created. It takes some time, also, Update() itself is a thing that DB has to perform. Sometimes it's better to alsways check if you really have instance and if not, threadsleep for a while.

Have you used .Update() method in your code??

Related

Run code when user deletes module from a page

I'm currently developing a DNN module. It would be nice if we were able to run custom code whenever a module is deleted from a page by the user, and also when a module gets restored from recycle bin.
I haven't found any examples on how this could be done, so I'm not sure if this is possible? Any ideas?
I am unaware of any event mechanism inside DNN where you could set your hooks. You could probably debug the DNN code and trace the call stack until you find a usable spot where you can inject some code (which would likely be destroyed after the next DNN update), or maybe detect a way that was intended to be used by the core team.
However, if a module is deleted from a page, the IsDeleted field in the Modules table is set to true. If it gets restored from the bin, it is again set to false.
You can use a TRIGGER in your Sql Server that fires when the Modules table is updated, checks if the update refers to an IsDeleted field, write stuff into a Notification table, and use Sql Query Notification based on SqlDependency to run some code (see http://www.codeproject.com/Articles/144344/Query-Notification-using-SqlDependency-and-SqlCach for an introduction).
Some steps to go, but it should work (and be less exhausting than climbing the Matterhorn :-) ).
There is absolutely hooks in DNN Platform (DotNetNuke) that a developer can attached C# code to.
While there isn't a turn key example that I can provide at the moment, check out the following:
https://github.com/dnnsoftware/Dnn.Platform/blob/c35fdc7fb75db0438f3b872ce4e279e3ea73e7c2/DNN%20Platform/Library/Entities/EventManager.cs
You are looking to hook onto the ModuleRemoved event by the sounds of it.
Here is an example for the user logging in that you could adapt to your event:
Does DNN fire an event when a user logs in?
I hope this helps in the future.

LINQPad Dump() method not working for Sharepoint Client Object Model

I'm using LINQPad (2.42) to test some snippets that make use of SharePoint Client Object Model.
Basically messing with SPSite, SPWeb, SPList, SPFolder and SPFile.
The problem is that LINQPad seems to dislike calling .Dump() for any of the previous objects. It just keeps "Executing" for ever without showing any results.
Does anyone experience the same problem? Any workaround or fix?
Thanks
Try calling .Dump(0) to only dump the first level of Properties, or dumping the results to a Grid.
I have not looked at the SharePoint Client Objects but if they are anything like the TFS API classes, some of the properties are lazy loaded. Calling .Dump() will walk it's way down each every single result making server calls for every property (and property of property, etc.). This is probably what's taking the time.

Why is Mage_Persistent breaking /api/wsdl?soap

I get the following error within Magento CE 1.6.1.0
Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cookie - headers already sent by (output started at /home/dev/env/var/www/user/dev/wdcastaging/lib/Zend/Controller/Response/Abstract.php:586) in /home/dev/env/var/www/user/dev/wdcastaging/app/code/core/Mage/Core/Model/Session/Abstract/Varien.php on line 119
when accessing /api/soap/?wsdl
Apparently, a session_start() is being attempted after the entire contents of the WSDL file have already been output, resulting in the error.
Why is magento attempting to start a session after outputting all the datums? I'm glad you asked. So it looks like controller_front_send_response_after is being hooked by Mage_Persistent in order to call synchronizePersistentInfo(), which in turn ends up getting that session_start() to fire.
The interesting thing is that this wasn't always happening, initially the WSDL loaded just fine for me, initially I racked my brains to try and see what customization may have been made to our install to cause this, but the tracing I've done seems to indicate that this is all happening entirely inside of core.
We have also experienced a tiny bit of (completely unrelated) strangeness with Mage_Persistent which makes me a little more willing to throw my hands up at this point and SO it.
I've done a bit of searching on SO and have found some questions related to the whole "headers already sent" thing in general, but not this specific case.
Any thoughts?
Oh, and the temporary workaround I have in place is simply disabling Mage_Persistent via the persistent/options/enable config data. I also did a little bit of digging as to whether it might be possible to observe an event in order to disable this module only for the WSDL controller (since that seems to be the only one having problems), but it looks like that module relies exclusively on this config flag to determine it's enabled status.
UPDATE: Bug has been reported: http://www.magentocommerce.com/bug-tracking/issue?issue=13370
I'd report this is a bug to the Magento team. The Magento API controllers all route through standard Magento action controller objects, and all these objects inherit from the Mage_Api_Controller_Action class. This class has a preDispatch method
class Mage_Api_Controller_Action extends Mage_Core_Controller_Front_Action
{
public function preDispatch()
{
$this->getLayout()->setArea('adminhtml');
Mage::app()->setCurrentStore('admin');
$this->setFlag('', self::FLAG_NO_START_SESSION, 1); // Do not start standart session
parent::preDispatch();
return $this;
}
//...
}
which includes setting a flag to ensure normal session handling doesn't start for API methods.
$this->setFlag('', self::FLAG_NO_START_SESSION, 1);
So, it sounds like there's code in synchronizePersistentInf that assumes the existence of a session object, and when it uses it the session is initialized, resulting in the error you've seen. Normally, this isn't a problem as every other controller has initialized a session at this point, but the API controllers explicitly turns it off.
As far as fixes go, your best bet (and probably the quick answer you'll get from Magento support) will be to disable the persistant cart feature for the default configuration setting, but then enable it for specific stores that need it. This will let carts
Coming up with a fix on your own is going to be uncharted territory, and I can't think of a way to do it that isn't terribly hacky/unstable. The most straight forward way would be a class rewrite on the synchronizePersistentInf that calls it's parent method unless you've detected this is an API request.
This answer is not meant to replace the existing answer. But I wanted to drop some code in here in case someone runs into this issue, and comments don't really allow for code formatting.
I went with a simple local code pool override of Mage_Persistent_Model_Observer_Session to exit out of the function for any URL routes that are within /api/*
Not expecting this fix to need to be very long-lived or upgrade-friendly, b/c I'm expecting them to fix this in the next release or so.
public function synchronizePersistentInfo(Varien_Event_Observer $observer)
{
...
if ($request->getRouteName() == 'api') {
return;
}
...
}

Simultaneous LINQ data retrieval problem

I came across a very strange problem which never happened to me before.
In the login code:
var sqlLogin = db.LoginRetrieve(loginID, archived).SingleOrDefault();
//(db is the linq data context)
--problem:
If two users login at the same time, this line of code will throw an exception which is "The required column 'UserLoginID' does not exist in the results."
But if a single user logs in or two users don't click the button at the same time, it will have no exception.
Is there anyone can share some lights on this? Thanks in advance.
Han
I suspect that your DataContext is shared between requests.
Don't do that.
You should create a separate DataContext for each request.
Otherwise, you'll get nasty threading issues like this one. (DataContext isn't thread-safe)
In general, you should be very careful when sharing objects between requests (eg, statics or Application / Session state).
Unless you know specifically otherwise, you should assume that the object is not thread-safe and cannot be shared.

Unloading a data reference in Entity Framework

Currently I am struggling with a Entity Framework issue. I have a wcf service that sits on top of the ef framework, and allows queries to the framework. At some point the user is able to request a file from the framework. The files are referenced by solution entries, so when you request a file from a solution, the reference is loaded to gain access to the file store.
That all works fine, but from that point onward, whenever you do another query that returns that solution entry, the whole file gets attached to the return result. I need some way of detaching or unloading the reference, such that the result entries will only contain an unloaded reference to the file store again.
I have tried to create a new context and query that context to retrieve information from, but when I do that, the entity in the original context is also changed.
I have tried to detach the entity from the original context and then query from the new context. That does not work either.
I have found one way of doing this. For all the non file-download queries, I detach the result entity, and send that over the wire. I am not sure if that is the best way to go about it though.
I hope someone might be able to provide some insight, thanks for the effort.
The issue you are experiencing is probably do to Change Tracking, which is on by default.
Possible Solution:
Disable Change Tracking with MergeOption.NoTracking
using (MyEntities _context = new MyEntities())
{
_context.Widgets.MergeOption = MergeOption.NoTracking;
return _context.Widgets.ToList();
}
This article may help to point you in the right direction on how to handle this issue if the solution above does not work.
I struggled with a similar issue recently. The problem was the result of the context maintaining a reference to the object I was using (obviously). Every time I made a change to an object of the same type, even when obtained with a new context (so I thought), the object was being changed.
With help from one of my peers, we determined the context was hanging around due to the way I was registering it with my IoC container (lifestyle per web request). When I changed the lifestyle to transient (which definitively provided a new instance) then changes to objects of the same type were unaffected.
Hope this helps.