Error in processing entity WorkOrder unable to create entity object - infor-eam

I am receiving the following error calling GetAssetEquipmentOp:
"Error in processing entity WorkOrder unable to create entity object"
Here is the code so far:
public stringType getAssetDescription(string equipmentcode)
{
try
{
// Setup Service Objects
MP0302_GetAssetEquipment_001.GetAssetEquipmentService getservice = new MP0302_GetAssetEquipment_001.GetAssetEquipmentService();
MP0302_GetAssetEquipment_001.MP0302_GetAssetEquipment_001 getrequest = new MP0302_GetAssetEquipment_001.MP0302_GetAssetEquipment_001();
MP0302_GetAssetEquipment_001.MP0302_GetAssetEquipment_001_Result getresult = new MP0302_GetAssetEquipment_001.MP0302_GetAssetEquipment_001_Result();
// Setup Return Object
stringType desc = new stringType();
// Setup Service Parameters
getrequest.ASSETID = new MP0302_GetAssetEquipment_001.EQUIPMENTID_Type();
getrequest.ASSETID.EQUIPMENTCODE = equipmentcode;
getrequest.ASSETID.ORGANIZATIONID = new MP0302_GetAssetEquipment_001.ORGANIZATIONID_Type();
getrequest.ASSETID.ORGANIZATIONID.ORGANIZATIONCODE = _orgCodeBody;
// Setup Datastream Object
Datastream.EWS.Session sess = new Datastream.EWS.Session(_userid, _passwd, _orgCodeHead, _url, _tenant, false);
// Prepare Service Request
sess.PrepareServiceRequest(getservice);
// Call Web Service and get result
getresult = getservice.GetAssetEquipmentOp(getrequest);
// Extract Description
desc.stringValue = getresult.ResultData.AssetEquipment.ASSETID.DESCRIPTION;
desc.errorNum = 0;
// Close Up/Dispose
sess.CompleteServiceRequest(getservice);
sess.Dispose();
// Return value
return desc;
}
catch (Exception ex)
{
stringType errorStringType = new stringType();
errorStringType.errorNum = 1;
errorStringType.errorDesc = ex.Message;
return errorStringType;
}
}
I have checked the following:
- User group has interface permissions including BECONN
- User has "Connector" option selected
- User has status authorizations including * to Q for EVNT
Any help would be appreciated.

Problem solved! The problem was that the work order number did not exist. It is a very misleading error but once an existing work order was tested, it fetched the work order with no issues.

Related

CrmServiceClient.GetEntityMetadata returns wrong information

Using the Microsoft.CrmSdk assembly to generate entities in Dynamics 365 for Customer Engagement (version 9), I found out that the method GetEntityMetadata from CrmServiceClient does not get the most uptodate information from entities.
Here the code to show you:
using (var svc = new CrmServiceClient(strConn))
{
EntityMetadata em = svc.GetEntityMetadata(PREFIX + TABLE_NAME_D, EntityFilters.Attributes);
if (em == null)
{
Console.WriteLine($"Create entity [{PREFIX + TABLE_NAME_D}]");
CreateEntityRequest createRequest = new CreateEntityRequest
{
Entity = new EntityMetadata
{
SchemaName = PREFIX + TABLE_NAME_D,
LogicalName = PREFIX + TABLE_NAME_D,
DisplayName = new Label(TABLE_LABEL, 1036),
DisplayCollectionName = new Label(TABLE_LABEL_P, 1036),
OwnershipType = OwnershipTypes.UserOwned,
},
PrimaryAttribute = new StringAttributeMetadata
{
SchemaName = PREFIX + "name",
MaxLength = 30,
FormatName = StringFormatName.Text,
DisplayName = new Label("Residence", 1036),
}
};
CreateEntityResponse resp = (CreateEntityResponse)svc.Execute(createRequest);
em = svc.GetEntityMetadata(PREFIX + TABLE_NAME_D, EntityFilters.All);
// At this point, em is null!!!
}
}
After the createResponse is received, the entity is well created in Dynamics, but still the GetEntityMetadata called just after is still null. If I wait a few seconds and make another call, the response is now correct. But that's horrible!
Is there any way to "force" the refresh of the response?
Thanks.
Ok I found it! It's linked to a caching mechanism.
One must use the function ResetLocalMetadataCache to clean the cache, but there seems to be an issue with this function.
It will only works by passing the entity name in parameter (if you call it without parameter, it is supposed to clean the entire cache but that does not work for me).
EntityMetadata em = svc.GetEntityMetadata(TABLE_NAME_D, EntityFilters.All); // Request sent
em = svc.GetEntityMetadata(TABLE_NAME_D, EntityFilters.All); // Cache used
svc.ResetLocalMetadataCache(); // No effect?!
em = svc.GetEntityMetadata(TABLE_NAME_D, EntityFilters.All); // Cache used
em = svc.GetEntityMetadata(TABLE_NAME_D, EntityFilters.All); // Cache used
svc.ResetLocalMetadataCache(TABLE_NAME_D); // Cache cleaned for this entity
em = svc.GetEntityMetadata(TABLE_NAME_D, EntityFilters.All); // Request sent!

Automatically map a Contact to an Account

I want to add a field to Accounts which shows the email domain for that account e.g. #BT.com. I then have a spreadsheet which lists all the Accounts and their email domains. What I want to do is when a new Contact is added to Dynamics that it checks the spreadsheet for the same email domain (obviously without the contacts name in the email) and then assigned the Contact to the Account linked to that domain. Any idea how I would do this. Thanks
Probably best chance would be to develop CRM plugin. Register your plugin to be invoked when on after contact is created or updated (so called post-event phase). And in your plugin update the parentaccountid property of the contact entity to point to account of your choice.
Code-wise it goes something like (disclaimer: not tested):
// IPluginExecutionContext context = null;
// IOrganizationService organizationService = null;
var contact = (Entity)context.InputParameters["Target"];
var email = organizationService.Retrieve("contact", contact.Id, new ColumnSet("emailaddress1")).GetAttributeValue<string>("emailaddress1");
string host;
try
{
var address = new MailAddress(email);
host = address.Host;
}
catch
{
return;
}
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
contact["parentaccountid"] = entities[0].ToEntityReference();
}
organizationService.Update(contact);
I took Ondrej's code and cleaned it up a bit, re-factored for pre-operation. I also updated the logic to only match active account records and moved the query inside the try/catch. I am unfamiliar with the MailAddress object, I personally would just use string mapping logic.
var target = (Entity)context.InputParameters["Target"];
try
{
string host = new MailAddress(target.emailaddress1).Host;
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
query.Criteria.AddCondition("statecode", ConditionOperator.Equals, 0); //Active records only
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
target["parentaccountid"] = entities[0].ToEntityReference();
}
}
catch
{
//Log error
}

Modifying Parse.User object before FIRST save

I'm working on an app and I need some changes to be made on new users registering during certain periods.
I've added a variable which I will change manually, and a check if that value is true or false.
This is my current code:
Parse.Cloud.beforeSave(Parse.User, function(request, status)
{
console.log("********************************************");
Parse.Cloud.useMasterKey();
var special = true;
if(special)
{
request.object.set("points", 1000);
request.object.set("role/objectid", "PZHTquGti0");
}else{
request.object.set("points", 0);
request.object.set("role/objectid", "TQyjIY59oL");
}
console.log("********************************************");
status.success("Job finished successfully!");
}); // end of Parse.define
This code errors out with "Uncaught Error: change must be passed a Parse.Object" and I've been looking through the documentation to find out how to change a value of a subclass of the User object, but have found none.
Also, this code will also run when updating a user, which I don't want it to do.
Any help is highly appreciated!
First of all for running the code on first save (insert), you can use request.object.isNew()
As the role column is a pointer, you should set an object & not the id string directly.
So create a new dummy object and assign the id to it.
Parse.Cloud.beforeSave(Parse.User, function(request, status)
{
console.log("********************************************");
Parse.Cloud.useMasterKey();
if(request.object.isNew()){ // Object Insert
var Role = Parse.Object.extend("_Role");
var role = new Role();
var special = true;
if(special)
{
request.object.set("points", 1000);
role.id = "PZHTquGti0";
request.object.set("role", role);
}else{
request.object.set("points", 0);
role.id = "TQyjIY59oL";
request.object.set("role", role);
}
}
else{ // Object Update
//Do nothing
}
console.log("********************************************");
status.success("Job finished successfully!");
}); // end of Parse.define

Create a custum Sharepoint list and add items problems

Im new to SharePoint programming, or programming at all for that case. My problem is that I get a error-message when I try to go to my sharepoint site after I debugged this oode (it worked fine in visual studio). I don't know whats wrong? The error message i get is:
"Server Error in '/' Application.
0x80004005Updates are currently disallowed on GET requests. To allow updates on a GET, set the 'AllowUnsafeUpdates' property on SPWeb."
I've read that you got to allow safe updates? but is that the case? I think maybe it is my code that is not right... Please help :)
// choose your site
SPSite site = new SPSite("http://....");
SPWeb web = SPContext.Current.Web;
//Add a list to the choosen site
SPListCollection lists = web.Lists;
// create new Generic list called "OrdersList"
lists.Add("OrdersTest", "All of my testorders will be here", SPListTemplateType.GenericList);
//Add the new list to the website
SPList newList = web.Lists["OrdersTest"];
// create Number type new column called "OrderID"
newList.Fields.Add("OrderID", SPFieldType.Number, true);
// create Number type new column called "OrderNumber"
newList.Fields.Add("OrderNumber", SPFieldType.Number, true);
// create Text type new column called "OrderProducts"
newList.Fields.Add("OrderProducts", SPFieldType.Text, true);
newList.Update();
//Create a object to that list
SPListItem newOrder = newList.AddItem();
//Add a new item
newOrder["OrderID"] = 1;
newOrder["OrderNumber"] = 1;
newOrder["OrderProducts"] = "Icecream";
newOrder.Update();
// create new Generic list called "ProductTest"
lists.Add("ProductTest", "All of my testproducts will be here", SPListTemplateType.GenericList);
//Add the new list to the website
SPList newList2 = web.Lists["ProductTest"];
// create Number type new column called "ProductID"
newList2.Fields.Add("ProductID", SPFieldType.Number, true);
// create Text type new column called "ProductName"
newList2.Fields.Add("ProductName", SPFieldType.Text, true);
// create Number type new column called "OrderID"
newList2.Fields.Add("ProductPrice", SPFieldType.Number, true);
//Create a object to that list
SPListItem nyProduct = newList2.AddItem();
//Add a new item
nyProduct["ProductID"] = 1;
nyProduct["ProductName"] = "Icecream";
nyProduct["ProductPrice"] = 13;
nyProduct.Update();
You need to set AllowUnsafeUpdates to true for updating data in get requests.
using(SPSite site = new SPSite("http://...."))
using (SPWeb web = site.OpenWeb())
{
bool b = web.AllowUnsafeUpdates;
web.AllowUnsafeUpdates = true;
try
{
//your code
//create and update list
}
catch (Exception ex)
{
//handles errors
}
finally
{
web.AllowUnsafeUpdates = b;
}
}

NHib 3 Configuration & Mapping returning empty results?

Note: I'm specifically not using Fluent NHibernate but am using 3.x's built-in mapping style. However, I am getting a blank recordset when I think I should be getting records returned.
I'm sure I'm doing something wrong and it's driving me up a wall. :)
Background / Setup
I have an Oracle 11g database for a product by IBM called Maximo
This product has a table called workorder which lists workorders; that table has a field called "wonum" which represents a unique work order number.
I have a "reporting" user which can access the table via the maximo schema
e.g. "select * from maximo.workorder"
I am using Oracle's Managed ODP.NET DLL to accomplish data tasks, and using it for the first time.
Things I've Tried
I created a basic console application to test this
I added the OracleManagedClientDriver.cs from the NHibernate.Driver on the master branch (it is not officially in the release I'm using).
I created a POCO called WorkorderBriefBrief, which only has a WorkorderNumber field.
I created a class map, WorkorderBriefBriefMap, which maps only that value as a read-only value.
I created a console application with console output to attempt to write the lines of work orders.
The session and transaction appear to open correct,
I tested a standard ODP.NET OracleConnection to my connection string
The Code
POCO: WorkorderBriefBrief.cs
namespace PEApps.Model.WorkorderQuery
{
public class WorkorderBriefBrief
{
public virtual string WorkorderNumber { get; set; }
}
}
Mapping: WorkorderBriefBriefMap.cs
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;
using PEApps.Model.WorkorderQuery;
namespace ConsoleTests
{
public class WorkorderBriefBriefMap : ClassMapping<WorkorderBriefBrief>
{
public WorkorderBriefBriefMap()
{
Schema("MAXIMO");
Table("WORKORDER");
Property(x=>x.WorkorderNumber, m =>
{
m.Access(Accessor.ReadOnly);
m.Column("WONUM");
});
}
}
}
Putting it Together: Program.cs
namespace ConsoleTests
{
class Program
{
static void Main(string[] args)
{
NHibernateProfiler.Initialize();
try
{
var cfg = new Configuration();
cfg
.DataBaseIntegration(db =>
{
db.ConnectionString = "[Redacted]";
db.Dialect<Oracle10gDialect>();
db.Driver<OracleManagedDataClientDriver>();
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
db.BatchSize = 500;
db.LogSqlInConsole = true;
})
.AddAssembly(typeof(WorkorderBriefBriefMap).Assembly)
.SessionFactory().GenerateStatistics();
var factory = cfg.BuildSessionFactory();
List<WorkorderBriefBrief> query;
using (var session = factory.OpenSession())
{
Console.WriteLine("session opened");
Console.ReadLine();
using (var transaction = session.BeginTransaction())
{
Console.WriteLine("transaction opened");
Console.ReadLine();
query =
(from workorderbriefbrief in session.Query<WorkorderBriefBrief>() select workorderbriefbrief)
.ToList();
transaction.Commit();
Console.WriteLine("Transaction Committed");
}
}
Console.WriteLine("result length is {0}", query.Count);
Console.WriteLine("about to write WOs");
foreach (WorkorderBriefBrief wo in query)
{
Console.WriteLine("{0}", wo.WorkorderNumber);
}
Console.WriteLine("DONE!");
Console.ReadLine();
// Test a standard connection below
string constr = "[Redacted]";
OracleConnection con = new OracleConnection(constr);
con.Open();
Console.WriteLine("Connected to Oracle Database {0}, {1}", con.ServerVersion, con.DatabaseName.ToString());
con.Dispose();
Console.WriteLine("Press RETURN to exit.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error : {0}", ex);
Console.ReadLine();
}
}
}
}
Thanks in advance for any help you can give!
Update
The following code (standard ADO.NET with OracleDataReader) works fine, returning the 16 workorder numbers that it should. To me, this points to my use of NHibernate more than the Oracle Managed ODP.NET. So I'm hoping it's just something stupid that I did above in the mapping or configuration.
// Test a standard connection below
string constr = "[Redacted]";
OracleConnection con = new Oracle.ManagedDataAccess.Client.OracleConnection(constr);
con.Open();
Console.WriteLine("Connected to Oracle Database {0}, {1}", con.ServerVersion, con.DatabaseName);
var cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "select wonum from maximo.workorder where upper(reportedby) = 'MAXADMIN'";
cmd.CommandType = CommandType.Text;
Oracle.ManagedDataAccess.Client.OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
con.Dispose();
When configuring NHibernate, you need to tell it about your mappings.
I found the answer -- thanks to Oskar's initial suggestion, I realized it wasn't just that I hadn't added the assembly, I also needed to create a new mapper.
to do this, I added the following code to the configuration before building my session factory:
var mapper = new ModelMapper();
//define mappingType(s) -- could be an array; in my case it was just 1
var mappingType = typeof (WorkorderBriefBriefMap);
//use AddMappings instead if you're mapping an array
mapper.AddMapping(mappingType);
//add the compiled results of the mapper to the configuration
cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
var factory = cfg.BuildSessionFactory();

Resources