Null Reference Excepion when saving data on subsonic 3 - subsonic3

I am testing subsonic 3, i can query my database but when i am inserting a record i have an exception. Here is my code:
Client lClient = new Client();
lClient.Name = "Peter";
lClient.FullName = "Richards";
lCliente.Save();
And i have a null reference exception on this generated code:
var newKey=_repo.Add(this,provider);
Any help is appreciated.
I am using ActiveRecords

I had a similar problem, with code not unlike the following:
var pending = myTable.SingleOrDefault(x => x.Id == 1);
if (pending == null)
pending = new myTable();
pending.Id = 1;
pending.MyDate = DateTime.Now;
pending.MyString = someString;
pending.Save();
This worked the first time I ran it, on an empty table, but not the second time when updating. I got a nullreference exception somewhere inside the subsonic repository. The solution was to add a primary key, as Rob suggested.
Just thought I'd mention it (thanks Rob).

Where does the null reference exception actually happen? Is _repo null?
Try and double check that you don’t have any columns in the “Client” table which are not nullable and you don’t set any value.
Also make sure you PK is handled correctly (check you have the [Property.IsForeignKey=true;] attribute)

Do you have NullReferenceException Checked in (file menu) Debug -> Exceptions (press Find and type NullReferenceException, press OK)?
I downloaded the SubSonic code and used it as reference for my project, the exception is thrown in SubSonic.Core\Repository\SubSonicRepository.cs:209 because prop is not checked for null at line 208, and any exceptions are swallowed as evidenced by line 213.
What happens is visual studio breaks on all the exceptions checked in the mentioned dialog. So in one way, this is the expected behaviour from the code.
What actually causes prop to become null, in my case, the table field name is lower-case, but the property is actually cased properly.
From Immediate:
tbl.PrimaryKey.Name
"playerinformationid"
item.GetType().GetProperties()
{System.Reflection.PropertyInfo[11]}
[0]: {System.Collections.Generic.IList`1[SubSonic.Schema.IColumn] Columns}
// *snip*
[5]: {Int32 PlayerInformationid}
// *snip*
item.GetType().GetProperty("PlayerInformationid")
{Int32 PlayerInformationid} // Works!
item.GetType().GetProperty(tbl.PrimaryKey.Name)
null
I hacked this together to "just make it work" (Warning: newbie at 3.5 stuff)
-var prop = item.GetType().GetProperty(tbl.PrimaryKey.Name);
+var lowerCasedPrimaryKeyName = tbl.PrimaryKey.Name.ToLowerInvariant();
+var prop = item.GetType().GetProperties().First<System.Reflection.PropertyInfo>(x => x.Name.ToLowerInvariant() == lowerCasedPrimaryKeyName);

Does your table have a PrimaryKey? It doesn't sound like it does. If not - this is your problem.

Related

Unparsable MOF Query When Trying to Register Event

Update 2
I accepted an answer and asked a different question elsewhere, where I am still trying to get to the bottom of this.
I don't think that one-lining this query is the answer, as I am still not getting the required results (and multi-lining queries is allowed in .mof, as shown in the URLs in comments to the answer ...
Update
I rewrote the query as a one-liner as suggested, but still got the same error! As it was still talking about lines 11-19 I knew there must be another issue. After saving a new file with the change, I reran mofcomp and it appears to have loaded, but the event which I have subscribed to simply does not work.
I really feel that there is not enough documentation on this topic and it is hard to work out how I am meant to debug this - any help on this would be much appreciated, even if this means using a different more appropriate method.
I have the following .mof file, which I would like to use to register an event on my system :
#pragma namespace("\\\\.\\root\\subscription")
instance of __EventFilter as $EventFilter
{
Name = "Event Filter Instance Name";
Query = "Select * from __InstanceCreationEvent within 1 "
"where targetInstance isa \"Cim_DirectoryContainsFile\" "
"and targetInstance.GroupComponent = \"Win32_Directory.Name=\"c:\\\\test\"\"";
QueryLanguage = "WQL";
EventNamespace = "Root\\Cimv2";
};
instance of ActiveScriptEventConsumer as $Consumer
{
Name = "TestConsumer";
ScriptingEngine = "VBScript";
ScriptText =
"Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
"Set objFile = objFSO.OpenTextFile(\"c:\\test\\Log.txt\", 8, True)\n"
"objFile.WriteLine Time & \" \" & \" File Created\"\n"
"objFile.Close\n";
// Specify any other relevant properties.
};
instance of __FilterToConsumerBinding
{
Filter = $EventFilter;
Consumer = $Consumer;
};
But whenever I run the command mfcomp myfile.mof I am getting this error:
Parsing MOF file: myfile.mof
MOF file has been successfully parsed
Storing data in the repository...
An error occurred while processing item 1 defined on lines 11 - 19 in file myfile.mof:
Error Number: 0x80041058, Facility: WMI
Description: Unparsable query.
Compiler returned error 0x80041058
This error appears to be caused by incorrect syntax in the query, but I don't understand where I have gone wrong with this - is anyone able to advise?
There are no string concatenation or line continuation characters being used in building "Query". To keep it simple, you could put the entire query on one line.

What properties replace obsoleted Sitecore.Data.Fields.ImageField properties?

It is unclear to me from the compiler warning which fields I should be using in this code:
Sitecore.Data.Fields.ImageField imgField = item.Fields[FieldName];
if (imgField != null)
{
//Finally, save the actual values for our intended Image into the item
imgField.Src = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);
imgField.MediaID = mediaItem.ID;
imgField.MediaPath = mediaItem.MediaPath;
imgField.Alt = mediaItem.Alt;
}
I get a compiler warning about imgField.Src and imgField.MediaPath. The Src warning is 'Use MediaItem property' instead... which makes little sense, because those are entirely different property types. The MediaPath warning says 'You can retrive[sic] Path from MediaItem." Well... Again, this makes very little sense because what I'm actually doing here is setting the necessary properties for MediaItem. It would be empty or NULL otherwise. Should these four lines of code just be changed to imgField.MediaItem = mediaItem? I am skeptical.
What it's trying to transition you away from doing is getting properties from the Imagefield and instead just getting the MediaItem that is referenced by the ImageField and then calling the properties that way..since it's the actual Sitecore item in the media library. Once you do that, you've got access to all the properties just like you would any other Sitecore item.

How to Mole SPFieldUser from SPField

Im writing the unit test case using Moles for my SharePoint application
I'm stuck up at the below lines of code I'm unable to type cast SPField to SPFieldUser.
SField subfield = list.Fields.GetField("Subscriber");
SPFieldUser userfield = (SPFieldUser)subfield;
userfield.SelectionGroup = web.Groups["Focal Points"].ID; //error line shown in pex
I'm getting "NullReference" exception at the above line
Can someone guide me here..
Although I am sure you have already checked these...:
Does GetField("Subscriber") return an object?
Does userfield get set to an object?
Is userfield.SelectionGroup null?
Try this syntax:
SPFieldUser userfield = subfield as SPFieldUser;
So, these all fail. Let's examine covariance of SPFieldUser to SField. The inheritance hierarchy is:
System.Object
Microsoft.SharePoint.SPField
Microsoft.SharePoint.SPFieldLookup
Microsoft.SharePoint.SPFieldUser
Unfortunately, I do not have the Microsoft.SharePoint library, to see if the SPFieldLookup classis hiding something important in SPField.

Can't access a new field programmatically on a template in Sitecore

my question is basically the same as #Bob Black's Cannot access sitecore item field via API but I agree with #techphoria414 that the accepted solution is not necessary and in my case does not work.
In my own words, I have a template Departure that I have been using for about a year now creating and updating items programmatically. I have added a new field Ship to the template. When I create a new item the field comes up as null when I try to access it using departure.Fields["Ship"]. If I step over the line causing the exception then after calling departure.Editing.EndEdit() I can then see the Ship field if I call departure.Fields.ToList(). If I add the template to a content item via the Sitecore GUI I can see the field and use it, and if I look at a content item which is based on the template I can see the new field too. So it is only when I access the template/item programmatically that it is null.
I have sitecore running on my local machine with a local sqlserver, and publish to my local machine.
Here is my code
String ship = "MSDisaster";
foreach (Language language in SiteLanguages)
{
departure = departure.Database.GetItem(departure.ID, language);
departure.Editing.BeginEdit();
try
{
departure.Fields["StartDate"].Value = GetSitecoreDateString(xDep, "StartDate");
departure.Fields["EndDate"].Value = GetSitecoreDateString(xDep, "EndDate");
departure.Fields["Guaranteed"].Value = xDep.SelectSingleNode("./Guaranteed").InnerText;
departure.Fields["Status"].Value = xDep.SelectSingleNode("./Status").InnerText;
departure.Fields["Currency"].Value = ConvertLanguageToCurrency(language);
departure.Fields["Market"].Value = ConvertLanguageToMarket(language);
departure.Fields["TwinSharePrice"].Value = GetPrice(xDep, "twn", language);
departure.Fields["SinglePrice"].Value = GetPrice(xDep, "sgl", language);
if (!String.IsNullOrEmpty(ship))
departures.Fields["Ship"].Value = ship;
}
catch (Exception ex)
{
departure.Editing.CancelEdit();
log.Error(ex);
throw ex;
}
departure.Editing.EndEdit();
}
So, how do I get the field be picked up?
Thanks,
James.
Firstly do you see the field in the web database in the sitecore administration.
If you do the item has the fields, you then should check the template assigned on the item and double check that the field is actually called "ship" and check the case as ive seen this as an issue before.
Also check the security on the item and field just in case anyone changed anything.
Next try and get the data from the item but instead of using the field name, use the field ID.
Let me know how you go?
Chris
Sorry Chris, StackOverflow, and the others who looked at my questions. It was a stupid typo. It's even there in my question
departure.Fields["SinglePrice"].Value = GetPrice(xDep, "sgl", language);
if (!String.IsNullOrEmpty(ship))
departures.Fields["Ship"].Value = ship;
}
departure is the item I am working on, departures is the collection it belongs to... doh.
So what is the protocol here? Do I delete my question now because it isn't really going to help anyone code better?
James.

Resolving incidents (closing cases) in CRM4 through webservices?

I'm trying to resolve/close Dynamics CRM4 cases/incidents through webservices.
A single SetStateIncidentRequest is not enough and returns a Server was unable to process request error message. I think it has something to do with active workflows that trigger on case's attribute changes. I don't know if there's anything else preventing the request to work.
Since it is possible to close those cases through the GUI, I guess there's a "correct" set of steps to follow in order to achieve it through CrmService; unfortunately, I've been googleing it for a while without finding what I want. Could anybody help me, please?
To resolve a case in CRM (in VB.NET), I do the following:
Try
Dim activity As New incidentresolution
Dim closeRequest As New CloseIncidentRequest
Dim closeResponse As New CloseIncidentResponse
Dim strErrors As String = String.Empty()
activity.incidentid = New Lookup
activity.incidentid.type = EntityName.incident.ToString
activity.incidentid.Value = //[GUID OF INCIDENT]
activity.ownerid = New Owner
activity.ownerid.type = EntityName.systemuser.ToString
activity.ownerid.Value = //[GUID OF USER PERFORMING ACTION]
activity.statecode = New IncidentResolutionStateInfo
activity.statecode.Value = 1 //Resolved
activity.statuscode = New Status
activity.statuscode.Value = 5 //Problem Solved
closeRequest.IncidentResolution = activity
closeRequest.Status = 5 //Problem Solved
// IF REQUIRED:
activity.timespent = New CrmNumber
activity.timespent.Value = //[INTEGER REPRESENTING No. OF MIN SPENT ON CASE]
closeResponse = objCrm.Execute(closeRequest)
Catch ex As System.Web.Services.Protocols.SoapException
Dim root As XmlElement = ex.Detail
strErrors = strErrors & vbCrLf & vbCrLf & root.ChildNodes(0).ChildNodes(3).InnerText
Return False
End Try
Here's a tip - catch the SoapException and examine the Detail.OuterXML property and you will get a more detailed error message. It's possible you're not building your request correctly.
Indeed, I didn't know that there exists a CloseIncidentRequest class to use with the CrmService.Execute() method. Most probably the SetStateIncidentRequeset won't work because it's expected that incident resolutions are created that way. Pity that names for classes and actions aren't used consistently (case/incident, resolution/closing)...