I have write a code base on other code.
It is a plugin for Dynamic CRM 2011.
Anyways, I wanna replace this plugin with existing Plugin.
It is almost a mirror of another .dll Plugin.
Anyways, In customization of CRM, I have disabled All steps of previous Plugin and want to insert new Plugin via Plugin Registration.
I build my class library via VS, VS makes a .dll file in /bin/Debug folder of project.
I select insert that .dll as Register new assembly.
I chose Sandbox as Isolation mode.
And then database as location ( Not Disk or GAC ).
It successfully updated my selected Plugin.
After that, I insert my steps( Just like the previous Plugin I wanna replace with ).
But in one the create methods, I get this Error :
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault,
Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]:
Unexpected exception from plug-in (Execute): OrderReceiptStepPlugin: System.MethodAccessException:
Attempt by method 'Microsoft.Xrm.Sdk.Entity.ToEntity<System.__Canon>()' to access method 'StepType..ctor()' failed.Detail:
<OrganizationServiceFault xmlns:i="www.w3.org/.../XMLSchema-instance"
xmlns="schemas.microsoft.com/.../Contracts">
<ErrorCode>-2147220956</ErrorCode>
<ErrorDetails xmlns:d2p1="schemas.datacontract.org/.../System.Collections.Generic" />
<Message>Unexpected exception from plug-in (Execute): OrderReceiptStepPlugin: System.MethodAccessException:
Attempt by method 'Microsoft.Xrm.Sdk.Entity.ToEntity<System.__Canon>()' to access method 'StepType..ctor()' failed.</Message>
<Timestamp>xxxxxxxxxx.4628797Z</Timestamp>
<InnerFault i:nil="true" />
<TraceText>
[OrderReceiptStep: OrderReceiptStepPlugin]
[xxxxxx-xxxx-xxxx11-xxx-xxxxxxxxxxxx: OrderReceiptStepPlugin: Create of bmsd_orderreceiptstep]
Entered .Execute(), Correlation Id: 47c5ddcb-9290-4945-9ac0-fd88925480b1, Initiating User: 5b6b27be-ca0f-e811-bebe-000c2964dd77
is firing for Entity: bmsd_orderreceiptstep, Message: Create, Correlation Id: 47c5ddcb-9290-4945-9ac0-fd88925480b1, Initiating User: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx
Exiting .Execute(), Correlation Id: xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, Initiating User: xxxxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxx
</TraceText>
</OrganizationServiceFault>
I googled about MethodAccessException Find out that this method occurs because of .Net version 4 and later,
And some code you can add in your Assebmly.cs to avoid this exception, according to this thread.
But in my case no success.
I added the code below to my assembly.cs but no success :
[assembly: SecurityTransparent()]
[assembly: AllowPartiallyTrustedCallersAttribute]
Here is the code that cause the error, It is in pre-Create of custom entity :
private void OrderReceiptStepPreCreateEventHandler(LocalPluginContext context)
{
SalesOrderReceiptStepRepository salesOrderReceiptStepRepository = new SalesOrderReceiptStepRepository(context);
SalesOrderReceiptStep salesOrderReceiptStep = salesOrderReceiptStepRepository.CreateInstance();
salesOrderReceiptStep.TotalAmountWithoutTax = new Money(salesOrderReceiptStep.TotalAmountWithoutTax.Value + salesOrderReceiptStep.FreightAmount.Value);
salesOrderReceiptStep.TotalAmountWithoutTax = new Money(salesOrderReceiptStep.TotalAmountWithoutTax.Value - salesOrderReceiptStep.DiscountAmount.Value);
switch (salesOrderReceiptStep.ReceiptStepType)
{
case ReceiptStepType.TimeOriented:
case ReceiptStepType.PrePayment:
case ReceiptStepType.Others:
salesOrderReceiptStep.TotalAmountWithoutTax = new Money(salesOrderReceiptStep.TotalDetailAmount.Value + salesOrderReceiptStep.FreightAmount.Value - salesOrderReceiptStep.DiscountAmount.Value);
salesOrderReceiptStep.TotalAmount = new Money(salesOrderReceiptStep.TotalAmountWithoutTax.Value + salesOrderReceiptStep.TotalTax.Value);
break;
}
OrderReceiptStepCalculationPlugin orderReceiptStepCalculationPlugin = new OrderReceiptStepCalculationPlugin();
orderReceiptStepCalculationPlugin.CreateORderReceiptStep(context, salesOrderReceiptStep);
if (salesOrderReceiptStep.Contains("bmsd_totallineitemamount") && salesOrderReceiptStep.Contains("bmsd_orderid"))
{
EntityReference attributeValue = salesOrderReceiptStep.GetAttributeValue<EntityReference>("bmsd_orderid");
if (attributeValue != null)
{
SalesOrderAdapter salesOrderAdapter = new SalesOrderAdapter();
OrganizationServiceContext context2 = new OrganizationServiceContext(context.OrganizationService);
Entity ordersById = salesOrderAdapter.GetOrdersById(context2, attributeValue.Id);
if (ordersById != null)
{
CalculationHelper calculationHelper = new CalculationHelper();
Entity entity = calculationHelper.CalculateOrdersAndReturnEntity(context, ordersById, ordersById);
entity.Attributes["statuscode"] = null;
entity.Attributes["statecode"] = null;
context.OrganizationService.Update(entity);
}
}
}
if (salesOrderReceiptStep.Contains("bmsd_invoiceid") || salesOrderReceiptStep.Contains("statuscode") || salesOrderReceiptStep.Contains("statecode") || salesOrderReceiptStep.Contains("bmsd_totallineitemamount"))
{
EntityReference attributeValue2 = salesOrderReceiptStep.GetAttributeValue<EntityReference>("bmsd_invoiceid");
if (attributeValue2 != null)
{
OrganizationServiceContext context2 = new OrganizationServiceContext(context.OrganizationService);
OrderReceiptItemAdapter orderReceiptItemAdapter = new OrderReceiptItemAdapter();
Entity invoiceById = orderReceiptItemAdapter.GetInvoiceById(context2, attributeValue2.Id);
if (invoiceById != null)
{
CalculationHelper calculationHelper = new CalculationHelper();
Entity entity2 = calculationHelper.CalculateInvoiceAndReturnEntity(context, invoiceById, invoiceById);
entity2.Attributes["statuscode"] = null;
entity2.Attributes["statecode"] = null;
context.OrganizationService.Update(entity2);
}
}
}
}
I know this is not a syntax or logical error in development ( Cause the mirror is working correctly).
What other reasons can make this error?
Also here is the Class that Exception throw from that, It also contains the Execute medthod :
public void Execute(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
LocalPluginContext localcontext = new LocalPluginContext(serviceProvider);
localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", new object[1]
{
ChildClassName
}));
try
{
Action<LocalPluginContext> action = (from a in RegisteredEvents
where a.Item1 == localcontext.PluginExecutionContext.Stage && a.Item2 == localcontext.PluginExecutionContext.MessageName &&
(string.IsNullOrWhiteSpace(a.Item3) || a.Item3 == localcontext.PluginExecutionContext.PrimaryEntityName)
select a.Item4).FirstOrDefault();
if (action != null)
{
localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "{0} is firing for Entity: {1}, Message: {2}", new object[3]
{
ChildClassName,
localcontext.PluginExecutionContext.PrimaryEntityName,
localcontext.PluginExecutionContext.MessageName
}));
action(localcontext);
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", new object[1]
{
ex.ToString()
}));
throw;
}
finally
{
localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", new object[1]
{
ChildClassName
}));
}
}
Related
I tried to make a remove method of an object on a table of my database for a WPF project using C#, EF6 and XAML. I tried several different variation of it my last one. The error that VS throw me is the following one:
System.InvalidOperationException: 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker.'
Code:
private void btnSupprimer_Click(object sender, RoutedEventArgs e)
{
var empASupprimer = ListViewEmployes.SelectedItems[0] as Employe;
if (empASupprimer == null)
{
return;
}
else
{
using (var x = new ScriptBDEntity())
{
x.Employes.Attach(empASupprimer);
x.Employes.Remove(empASupprimer);
x.SaveChanges();
loadlistview();
MessageBox.Show("Vous avez supprimer l'employé:" + empASupprimer);
}
}
}
Are you try to get employe by Id instead use attach ?
Like
var employe = x.Employes.Single(e => e.Id == empASupprimer.Id),
X.Employes.Remove(employe);
X.SaveChanges();
I'm creating a Revit plugin that reads and writes modelinformation to a database, and it all works fine in debug mode, but when I release the project and run Revit with the plugin outside visual studio, I'm getting an error when the plugin tries to read data from the database.
The code runs on DocumenetOpened event and looks like this:
public void application_DocumentOpenedEvent(object sender, DocumentOpenedEventArgs e)
{
UIApplication uiapp = new UIApplication(sender as Autodesk.Revit.ApplicationServices.Application);
Document doc = uiapp.ActiveUIDocument.Document;
//ModelGUID COMMAND
var command = new ModelCheckerCommandExec();
command.Execute(uiapp);
}
It then fails on the following line:
ModelsList = (DatabaseHelper.ReadNonAsync<RevitModel>())
.Where(m => m.ModelGUID == DataStores.ModelData.ModelGUID).ToList();
In this code block that gets executed:
public class ModelCheckerCommandExec : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
return Execute(commandData.Application);
}
public Result Execute(UIApplication uiapp)
{
Document doc = uiapp.ActiveUIDocument.Document;
Transaction trans = new Transaction(doc);
try
{
trans.Start("ModelGUID");
ModelGUIDCommand.GetAndSetGUID(doc);
trans.Commit();
var ModelsList = new List<RevitModel>();
ModelsList = (DatabaseHelper.ReadNonAsync<RevitModel>()).ToList();//.Where(m => m.ModelGUID == DataStores.ModelData.ModelGUID).ToList(); // Read method only finds models the are similar to the DataStore.ModelDate.DBId;
if (ModelsList.Count == 1)
{
trans.Start("DataFromDB");
doc.ProjectInformation.Name = ModelsList[0].ProjectName;
doc.ProjectInformation.Number = ModelsList[0].ModelNumber;
doc.ProjectInformation.Status = ModelsList[0].ModelStatus;
doc.ProjectInformation.IssueDate = ModelsList[0].ProjectIssueDate;
doc.ProjectInformation.ClientName = ModelsList[0].ClientName;
doc.ProjectInformation.Address = ModelsList[0].ProjectAddress;
doc.ProjectInformation.LookupParameter("Cadastral Data").Set(ModelsList[0].ProjectIssueDate);
doc.ProjectInformation.LookupParameter("Current Version").Set(ModelsList[0].CurrentVersion);
doc.ProjectInformation.BuildingName = ModelsList[0].BuildingName;
DataStores.ModelData.ModelManager1 = ModelsList[0].ModelManagerOne;
DataStores.ModelData.ModelManager1Id = ModelsList[0].ModelManagerOneId;
DataStores.ModelData.ModelManager2 = ModelsList[0].ModelManagerTwo;
DataStores.ModelData.ModelManager2Id = ModelsList[0].ModelManagerTwoId;
trans.Commit();
}
return Result.Succeeded;
}
catch (Exception ex)
{
TaskDialog.Show("Error", ex.Message);
return Result.Failed;
}
}
}
The "ReadNonAsync" method is as follows:
public static List<T> ReadNonAsync<T>() where T : IHasId
{
using (var client = new HttpClient())
{
var result = client.GetAsync($"{dbPath}{Properties.Settings.Default.CompanyName}_{typeof(T).Name.ToLower()}.json?access_token={DataStores.IdToken.UserIdToken}").GetAwaiter().GetResult();
var jsonResult = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
if (result.IsSuccessStatusCode)
{
var objects = JsonConvert.DeserializeObject<Dictionary<string, T>>(jsonResult);
List<T> list = new List<T>();
if (objects != null)
{
foreach (var o in objects)
{
o.Value.Id = o.Key;
list.Add(o.Value);
}
}
return list;
}
else
{
return null;
}
}
}
In the rest of my code I use a async Read method which works, so I'm wondering wether or not that's the issue, but Revit wont let me use an async method inside an Execute method.
How do I debug this issue correctly, and why could there be code working in debug that doesn't work in "live" versions?
I found a solution!
The issue:
The reason for the error was that when I run the software in debug-mode, a file path of "xxx.txt" finds files in the solution folder, but when I run the software "xxx.txt" points to the folder of the software and not the .dll -
So in my case it pointed to "c:\Program Files\Autodesk\Revit\2021".
The fix:
Hard coding the path, or by getting the path of the executing .dll
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
Debugging/Troubleshooting:
I found the issue by inserting dialogboxes with errormessages in all my try/catch statements.
In am new in elasticsearch and i am trying to do update operation with elasticsearch but for that when am trying to filter and select that particular code i am getting execption and the exception is:
An exception of type 'ElasticsearchCRUD.ElasticsearchCrudException' occurred in ElasticsearchCRUD.dll but was not handled in user code,
Additional information: ElasticSearchContextGet: HttpStatusCode.BadRequestNo handler found for uri [//skillwithlistofdetailss/skillwithlistofdetails/1] and method [GET]
and my method is below:
public void UpdateSkill(long updateId, string updateName, string updateDescription, List<SkillDetail> updateSkillDetailsList)
{
using (var context = new ElasticsearchContext(ConnectionString, _elasticSearchMappingResolver))
{
//var addressItem = _elasticsearchContext.SearchById<SkillWithListOfDetails>(updateId);
//var entityAddress = _entityFrameworkContext.Address.First(t => t.Id == addressItem.Id);
try
{
var skill = context.GetDocument<SkillWithListOfDetails>(updateId);
skill.Updated = DateTime.UtcNow;
skill.Name = updateName;
skill.Description = updateDescription;
skill.SkillDetails = updateSkillDetailsList;
foreach (var item in skill.SkillDetails)
{
item.Updated = DateTime.UtcNow;
}
context.AddUpdateDocument(skill, skill.Id);
context.SaveChanges();
}
catch(Exception e)
{
throw e;
}
}
}
and i am getting exception in this line of code:--
var skill = context.GetDocument(updateId);
There seems to be a problem with index/type name somewhere? The error message says: "ElasticSearchContextGet: HttpStatusCode.BadRequestNo handler found for uri [//skillwithlistofdetailss/skillwithlistofdetails/1] and method [GET]:".
Check your index and type are correct or not.
Index: skillwithlistofdetailss
Type: skillwithlistofdetails
Trying to go to a page on my site, got a blank screen and decided to try again with Visual Studio 2012 loaded and debugging it, now I get this error when the page loads:
An exception of type 'System.ArgumentException' occurred in cms.dll but was not handled in user code and points to the following code in HeaderControl.ascx.cs:
else if(new umbraco.cms.businesslogic.template.Template((Context.GetContent()).template).Alias == "TemplateLanguage")
This code is inside the following method:
public void LoadData()
{
_Location = HttpContext.Current.GetLocation();
if (Context.GetContent().NodeTypeAlias == "Home")
{
TheHomeHeaderPH.Visible = true;
ThePhonePH.Visible = true;
_MenuStyle = "var-nav nav-large";
LoadMenuTopControl();
LoadMenuMainControl();
}
else if(new umbraco.cms.businesslogic.template.Template((Context.GetContent()).template).Alias == "TemplateLanguage")
{
TheContentHeaderPH.Visible = true;
_MenuStyle = "nav-small";
LoadContentMenuTopControl();
LoadMenuLanguageControl();
}
else
{
MMG.BusinessLayer.Content theContent = MMG.BusinessLayer.Content.GetCached(Context.GetContent());
if (theContent.TemplateColor == "168C9C")
{
TheHomeHeaderPH.Visible = true;
_MenuStyle = "nav-small";
LoadMenuTopControl();
LoadMenuMainControl();
}
else
{
TheContentHeaderPH.Visible = true;
LoadContentMenuTopControl();
LoadContentMenuMainControl();
}
}
}
How can I fix this problem? System.ArgumentException says this: {"No node exists with id '0'"}
I would guess it's the (Context.GetContent()).template that breaks somehow and I assume GetContent is a custom extension method.
The exception {"No node exists with id '0'"} usually means that you couldn't fetch the node you requested.
Instead try
else if(new umbraco.cms.businesslogic.template.Template(umbraco.uQuery.GetCurrentNode().template).Alias == "TemplateLanguage")
If that doesn't work it means you are running the code in a context where the CurrentNode is unavailable. In that case you must extend your LoadData method with a nodeId parameter.
I am using EISK (Employee Info Starter Kit) to develop an application. My entity diagram looks like this I try to update the application table via this code.
int apId = Convert.ToInt32(Request.QueryString["ApplicationID"]);
ApplicationBLL objGetApplication = new ApplicationBLL();
Appdec.YEP.BusinessEntities.Application objApplication =
objGetApplication.GetApplicationByApplicationID(apId);
objApplication.Status = (ddlStatus.SelectedValue == "0" ? false : true);
new ApplicationBLL(new Appdec.YEP.DataAccessLayer.DatabaseContext()).UpdateApplication(objApplication);
now the update method at bussiness logic is
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
public void UpdateApplication(Application updatedApplication)
{
// Validate Parameters
if (updatedApplication == null)
throw (new ArgumentNullException("updatedApplication"));
// Validate Primary key value
if (updatedApplication.ApplicationID.IsInvalidKey())
BusinessLayerHelper.ThrowErrorForInvalidDataKey("ApplicationID");
// Apply business rules
OnApplicationSaving(updatedApplication);
OnApplicationUpdating(updatedApplication);
//attaching and making ready for parsistance
if (updatedApplication.EntityState == EntityState.Detached)
_DatabaseContext.Applications.Attach(updatedApplication);
_DatabaseContext.ObjectStateManager.ChangeObjectState(updatedApplication, System.Data.EntityState.Modified);//this line throws the error
//ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type
int numberOfAffectedRows = _DatabaseContext.SaveChanges();
if (numberOfAffectedRows == 0)
throw new DataNotUpdatedException("No application updated!");
//Apply business workflow
OnApplicationUpdated(updatedApplication);
OnApplicationSaved(updatedApplication);
}
Can somebody tell me how to fix this error and update the tables.
the same error ocurres when i try to update other tables also. The insert works fine.
Hoping not to bother you. Best Regards.
So it already belongs to a context,and you should update that context.
It can't be attached to new context,
You can create a new instance of updatedApplication and copy all properties of updatedApplication to this new one and attach new entity to application.
Also change
if (newApp .EntityState == EntityState.Detached)
_DatabaseContext.Applications.Attach(newApp );
to
var newApp = Application ();
//Copy all propery of updatedApplication to newApp here
if (newApp .EntityKey == null || newApp .EntityKey.IsTemporary)
{
_DatabaseContext.Applications.AddObject(newApp );
}
else
{
_DatabaseContext.Applications.Attach(newApp );
}
_DatabaseContext.ObjectStateManager.ChangeObjectState(newApp , System.Data.EntityState.Modified);