Reputation: 90
I have to write event receivers for SharePoint lists (SharePoint 2013). For logging purposes, I am declaring my Guid variable (corresponding to a Project) globally and then assigning a value to it whenever required in the event receivers (Item Adding, Item Updating, etc...).
Below is the code sample:
public class ClassName : SPItemEventReceiver
{
Guid prjguid;
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
try
{
prjguid = new Guid(properties.Site.OpenWeb().AllProperties["MSPWAPROJUID"].ToString());
.
.
.
}
catch (Exception ex)
{
// Exception Handling
WriteLog(prjguid + ex.message);
}
}
public void WriteLog(string message)
{
// Logging
}
}
This code throws en exception: Object reference not set to an instance of an object.
Any possible explanations where I am going wrong ?
Upvotes: 0
Views: 240
Reputation: 1018
As you do not mention where this exception is thrown there are several possible reasons for this exception:
Possible reason 1:
If an exception is happening within your properties.Site.OpenWeb().AllProperties["MSPWAPROJUID"].ToString()
call the prjguid variable will not get assigned.
Then in your catch WriteLog method you want to print out this *prjguid * variable.
This is where your variable can be null.
Inside your catch you could try to change your code to
catch (Exception ex)
{
// Exception Handling
if(prjguid != null)
{
WriteLog(prjguid + ex.message);
}else
{
WriteLog(ex.message);
}
}
Possible reason 2:
properties.Site.OpenWeb() returns null
Possible reason 3:
properties.Site.OpenWeb().AllProperties["MSPWAPROJUID"] returns null
For case 2 and 3 you have to seperate those calls an check for null for both parts.
Upvotes: 1