Dynamics crm 2015 through error while setting value in a field - dynamics-crm-2015

Dyanamics crm 2015 sp 1, throw exception "Unable to get property 'trim' of undefined or null reference" While setting a lookup value.
CustomerId have all three properties i.e Id,Name and LogicalName
Field "new_customerprofileid" is populated too,but setValue() function throw error
Error location is in global.ashx, there is a line b.trim which through the error.
Code:
var Entity = RetrieveEntityById(Id, "SalesOrder");
if (Entity != null) {
var CustomerId = Entity.CustomerId;
if (CustomerId != null)
if (Xrm.Page.getAttribute("new_customerprofileid") != null)
Xrm.Page.getAttribute("new_customerprofileid").setValue([{ id: CustomerId.Id, name: CustomerId.Name, entityType: CustomerId.LogicalName }]);
}
One fix is to place line( .setValue("") ) in try catch block.
var Entity = RetrieveEntityById(Id, "SalesOrder");
if (Entity != null) {
var CustomerId = Entity.CustomerId;
if (CustomerId != null)
if (Xrm.Page.getAttribute("new_customerprofileid") != null)
try {
Xrm.Page.getAttribute("new_customerprofileid").setValue([{ id: CustomerId.Id, name: CustomerId.Name, entityType: CustomerId.LogicalName }]);
} catch (ex) { }
}
Please answer if anybody reach to some other fix for this error.

The system tries to trim the input values but at least one of them was null and not a String. I guess this means that one of the values provided in the setValue dictionary is null: either CustomerId.Name or CustomerId.LogicalName. You might exclude those data sets or you might want to set their value to an empty string.

I've received this same problem. In my case, native CRM .js is trying to access a property named "type" on the lookup value that is being set, and then calling .trim on it resulting in b.trim is undefined. "type" is not a property that the documentation says needs to be set, so I suspect a bug in the CRM javascript, though trying to track down exactly why it is occurring has been difficult.
I've tried setting the property "type" to the object type code of the entity, however this seems to cause other problems that have been equally difficult to figure out.
As I am setting the id, name, and entityType, I've found that catching the exception has been the best solution thus far. I will most likely submit a ticket to MS to take a look at the issue.

Related

Update Dynamics form field when item is selected on another field

I have a Dynamics entity that has a relationship to another entity with a Main form in UX. I have a lookup control on the form to select that related entity. Doing so correctly writes the ID of that related entity record to the current record being edited. I need help grabbing the name value of that linked entity and writing it to the name value of the current record when the lookup selection changes. The form designer makes this so much more difficult than it needs to be! Is there a set of basic jscript libraries that I can add to my solution and call for such simple tasks?
After literally HOURS of hunting down bits and pieces, I finally got this to work!
function updateName(){
var name = "";
var lookupField = Xrm.Page.getAttribute("lookupentityproperty");
// Verify the field does exist on the form and has a selected value
if (lookupField != null && lookupField.getValue() != null && lookupField.getValue()[0] != null) {
name = lookupField.getValue()[0].name;
}
else { name = null; }
var nameField= Xrm.Page.getAttribute("nameproperty");
nameField.setValue(name);
}

Why can't my Sitecore custom validator read the item as it has been edited in Content Editor?

I have created a custom validator in Sitecore. It executes correctly, and I can debug it and step through it.
I extended my validator from StandardValidator, which in turn extends from BaseValidator.
In my validator, I get the item:
var item = GetItem();
GetItem is a method from BaseValidator. Based on my reading, this is the standard method to get the item to be validated.
The problem: the item I get back doesn't reflect the values that have been edited in Content Editor. Instead, it appears to simply be the item from the database (so, what it looked like when it first loaded in Content Editor, without reflecting any changes that might have been made to it).
Thus, I cannot validate. To validate the data an editor might have changed in Content Editor, I need to be able to see those changes. Seeing how the item sits in the database right now doesn't help me.
I did some extended debugging, which may or may not be helpful --
I decompiled the kernel, and walked through both StandardValidator and BaseValidator.
The GetItem method from BaseValidator does what I suspect -- it gets the item from the database. But then it runs it through a method called UpdateItem which appears be intended to overlay the inputted values from Content Editor on top of the stored values (thus returning an object that accurately reflects the data which is currently sitting in the editor). This is clearly what I want.
However, UpdateItem only appears to overlay anything if a property called ControlToValidate has a value...and it never does. I've tried this validator as both a Field Validator and an Item Validator. I've initiated it by both saving an item and by tabbing off a field. I put a breakpoint in Visual Studio and a watch on ControlToValidate. One time (inexplicably) it had a value of FIELD165901047 (which corresponded to a field ID in content editor), but in all other cases, it's been null.
What this means is that UpdateItem effectively does nothing, and the item is simply returned as it currently sits in a database, which doesn't help -- I'm trying to validator values entered in Content Editor before saving to the database.
Regardless of my investigation (I think I understand UpdateItem, but I concede that I might be misinterpeting it, and I'm not accounting for potential decompilation errors), I still have this basic problem:
var item = GetItem();
That never seems to return the values from Content Editor. It returns the item directly from the database, which doesn't help me.
In my validator (a field type validator) I've used
var field = this.GetField();
to get new value of the field to validate. The same should work for a field validator. It's probably a bit different for an item validator but I've never written an item validator.
It's also a method of the BaseValidator and returns a value of the type Field. You can assign this directly to the type of the target field you want, e.g. HtmlField (Sitecore has implemented the casting operators so you can do this):
HtmlField htmlField = field;
I managed to create a work-around for this, and it seems to be working for me. I'm not that happy that I don't know why controlToValidate never has a value, but my workaround manages to get the new value that hasn't yet been saved.
Basically, I've overridden the code that runs GetItem(), and I find the new value in the page's SaveArgs as shown below. The magic happens on the line that has:
field.Value = ((((SaveArgs) ((ClientPage) page)?.CurrentPipelineArgs)?.Items[0].Fields) ?? Array.Empty<SaveArgs.SaveField>()).FirstOrDefault(x => x.ID == field.ID)?.Value ?? field.Value;
protected override Item GetItem()
{
var obj = base.GetItem();
if (obj == null || obj.Versions.Count == 0)
return null;
UpdateItem(obj);
return obj;
}
private void UpdateItem(Item item)
{
Assert.ArgumentNotNull(item, nameof(item));
using (new SecurityDisabler())
item.Editing.BeginEdit();
var page = (Page)null;
var current = HttpContext.Current;
if (current != null)
page = current.Handler as Page;
foreach (Field field in item.Fields)
{
var controlToValidate = ControlToValidate;
if (string.IsNullOrEmpty(controlToValidate) || field.ID != FieldID)
{
field.Value = ((((SaveArgs) ((ClientPage) page)?
.CurrentPipelineArgs)?.Items[0].Fields) ?? Array.Empty<SaveArgs.SaveField>()).FirstOrDefault(x => x.ID == field.ID)
?.Value ?? field.Value;
}
else
{
var str = current != null ? RuntimeValidationValues.Current[controlToValidate] : null;
if (page != null && str != null)
{
var control = page.FindControl(controlToValidate);
if (control != null)
{
if (control is IContentField contentField)
str = contentField.GetValue();
else if (ReflectionUtil.GetAttribute(control, typeof(ValidationPropertyAttribute)) is ValidationPropertyAttribute attribute)
str = ReflectionUtil.GetProperty(control, attribute.Name) as string;
}
}
if (str == null && current != null)
str = current.Request.Form[controlToValidate];
if (str != null && str != "__#!$No value$!#__")
field.Value = str;
}
}
}

MS Dynamics CRM Form Field OnChange check for Existing Value in Entity

Unless someone can explain what I'm missing, CRM 2013 does not have any way to check for a duplicate WHILE entering a new Lead record. I want to check for a duplicate BEFORE the new record is saved. I can't seem to figure this one out.
Basically, when a user enters the Company Name on a new Lead record, I'd like JavaScript or something check for the existence of that value in all the other Lead records and return True or False. That way I can alert the user that the Company already exists BEFORE they save the new record.
Make sense? Am I just TOTALLY missing something here?
Thanks,
Scotty
Microsoft removed this functionality. But you can restore it using one of following articles:
http://a33ik.blogspot.com/2013/10/how-to-turn-on-duplicate-detection-for.html
http://jlattimer.blogspot.com/2013/10/are-you-missing-duplicate-detection-in.html
You can use below function to check duplicate records and set alert/field value depending upon result set :
CheckDuplicate: function (someIdentifier) {
var value = null;
var filter = "?$select=*&$filter=(new_Identifier eq '" + someIdentifier + "') and (new_someGuidField/Id eq guid'" + Xrm.Page.getAttribute("new_someGuidField").getValue()[0].id + "')";
retrieveMultipleSync("new_EntityNameSet", filter, function (data, textStatus, XmlHttpRequest) {
if (data != null && data.length > 0) {
value = data;
}
}, null);
return value;
}

Linq throwing exception when Null is returned to a string - attribute on a class?

I have a Linq query which I am selecting into a string, of course a string can contain null!
So is there a way I can throw an exception within my Linq query, if I detect a null?
Can I decorate my class with an attribute that won't let it allow null?
I would like to wrap my Linq query in a try catch, and as soon as a null is detected then it would enter the catch, and I can handle it.
Edit
Here's my Linq query, it's quite simple currently. I am going to extend it, but this shows the basic shape:
var localText = from t in items select new Items { item = t.name }
Basically item is set to t.name, t.name is a string so it could be empty / null is this perfectly legal as its a string and strings can hold NULL.
So if it returns NULL then I need to throw an exception. Actually it would be handy to be able to throw an exception is NULL or empty.
I seemed to remember some kind of Attributes that can be set on top of properties that says "Don't accept null" etc.?
Edit
I think I found it: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.aspx
This doesn't allow null or strings so I presume it throws an exception, I have used this with MVC but I am not sure if I can use it with a standard class.
As a string being null isn't particularly exceptional, you could do something like:
var items = myStrings.Where(s => !string.IsNullOrEmpty(s)).Select(s => new Item(s));
UPDATE
If you are reading this data from an XML file, then you should look into LINQ to XML, and also use XSD to validate the XML file rather than throwing exceptions on elements or attributes that don't contain strings.
You could try intentionally generating a NullReferenceException:
try
{
//Doesn't change the output, but throws if that string is null.
myStrings.Select(s=>s.ToString());
}
catch(NullReferenceException ex)
{
...
}
You could also create an extension method you could tack on to a String that would throw if null:
public static void ThrowIfNull(this string s, Exception ex)
{
if(s == null) throw ex;
}
...
myString.ThrowIfNull(new NullReferenceException());
Why do you want to throw an exception in this case? This sounds like throwing the baby out with the bath water for something that should not happen in the first place.
If you just want to detect that there are null/empty items:
int nullCount= items.Count( x=> string.IsNullOrEmpty(x.name));
If you want to filter them out:
var localText = from t in items where !string.IsNullOrEmpty(t.name) select new Items { item = t.name };

LINQ Submit Changes not submitting changes

I'm using LINQ to SQL and C#. I have two LINQ classes: User and Network.
User has UserID (primary key) and NetworkID
Network has NetworkID (primary key) and an AdminID (a UserID)
The following code works fine:
user.Network.AdminID = 0;
db.SubmitChanges();
However, if I access the AdminID before making the change, the change never happens to the DB. So the following doesn't work:
if(user.Network.AdminID == user.UserID)
{
user.Network.AdminID = 0;
db.SubmitChanges();
}
It is making it into the if statement and calling submit changes. For some reason, the changes to AdminID never make it to the DB. No error thrown, the change just never 'takes'.
Any idea what could be causing this?
Thanks.
I just ran a quick test and it works fine for me.
I hate to ask this, but are you sure the if statement ever returns true? It could be you're just not hitting the code which changes the value.
Other than that we might need more info. What are the properties of that member? Have you traced into the set statement to ensure the value is getting set before calling SubmitChanges? Does the Linq entity have the new value after SubmitChanges? Or do both the database AND the Linq entity fail to take the new value?
In short, that code should work... so something else somewhere is probably wrong.
Here's the original post.
Here's a setter generated by the LinqToSql designer.
Code Snippet
{
Contact previousValue = this._Contact.Entity;
if (((previousValue != value)
|| (this._Contact.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Contact.Entity = null;
previousValue.ContactEvents.Remove(this);
}
this._Contact.Entity = value;
if ((value != null))
{
value.ContactEvents.Add(this);
this._ContactID = value.ID;
}
else
{
this._ContactID = default(int);
}
this.SendPropertyChanged("Contact");
}
}
This line sets the child's property to the parent.
this._Contact.Entity = value;
This line adds the child to the parent's collection
value.ContactEvents.Add(this);
The setter for the ID does not have this second line.
So, with the autogenerated entities...
This code produces an unexpected behavior:
myContactEvent.ContactID = myContact.ID;
This code is good:
myContactEvent.Contact = myContact;
This code is also good:
myContact.ContactEvents.Add(myContactEvent);
I had this issue. The reason was one dumb line of code:
DBDataContext db { get { return new DBDataContext(); } }
obviously it should be:
DBDataContext db = new DBDataContext();

Resources