Error saving Entity dynamics crm 2011 - c#

I have an error that I can not repair.
Im developing an application that takes a guid as a parameter and "clone" that entity in another. (I know I can do this through javascript, the problem is the CRM server don't have the required rollup and I can't update it).
The projects works fine when I'm debugging in my computer, but when I deploy it to production server it just crash. My first guess was that it was an authentication problem, but I modified the authentication rules in IIS and impersonate any windows user that use the app with mine but didn't worked anyway.
The error it throws is: -2146233088 System.Collections.ListDictionaryInternal An error occured while processing this request. at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChanges(SaveChangesOptions options) at Ambiente.DataAccess.Entities.CRMOrdenDeCompra.CreateOrdenDeCompra(Guid guidSolicitudDeCompra) in c:\Wip\Projects\Dev\CRMINTEGRATION\CRMINTEGRATION.DataAccess\Entities\CRMOrdenDeCompra.cs:line 42 at CRMINTEGRATION.WebApp.Controllers.RequestController.CreateOrdenDeCompra(String guid) in c:\Wip\Projects\Dev\CRMINTEGRATION\CRMINTEGRATION.WebApp\Controllers\RequestController.cs:line 22
The code that insert the entity:
var solicituddecompraContext = new CRMSolicitudDeCompra();
var solicituddecompra = new new_solicituddecompra();
solicituddecompra = context.new_solicituddecompraSet.FirstOrDefault(q => q.new_solicituddecompraId == parameterGuid);
new_ordendecompra ordendecompra = new new_ordendecompra();
ordendecompra.new_ordendecompraId = Guid.NewGuid();
ordendecompra.new_name = string.Format(solicituddecompra.new_name + " ({0})", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"));
ordendecompra.new_FechaRequirida = solicituddecompra.new_Fecharequerida;
ordendecompra.new_Tipodesolicitud = solicituddecompra.new_Tipodesolicitud;
ordendecompra.new_Observaciones = solicituddecompra.new_observaciones;
ordendecompra.new_Numerodesolicitud = solicituddecompra.new_SolicitudNo;
var detallerequisicion = CRMDetalleRequisicion.getDetalleRequisicion(context, guidSolicitudDeCompra);
context.AddObject(ordendecompra);
context.SaveChanges();
I generated the XRM class of CRM with the crmsvcutil.exe. So the name of the classes you see in the code are actually the name of the entities in CRM. All of the above works fine until it reaches the method entidad.SaveChanges().
Ps. As you can see in the code, english is not my native language. Feel free to correct me if I make any mistake. I will apreciate that :).

Related

Show more than 5000 records from CRM in C#

I am trying to understand how FetchXml works (or any other method) because I want to retrieve and process more than the limit of 5000 records that CRM returns on the api call below.
My base url looks like this: http://crm.domain.com:1234/api/data/v8.0/
the resource is: emails
and query options are: $top=50000&$filter=description ne null and not contains(sender, '#not-interesting.com')
I'm trying to copy the code from
https://learn.microsoft.com/en-us/previous-versions/dynamicscrm-2016/developers-guide/gg327917(v=crm.8)?redirectedfrom=MSDN
but I'm having issues with creating the OrganizationServiceProxy object like this:
var creds = new ClientCredentials();
creds.UserName.UserName = CrmApiUsername;
creds.UserName.Password = CrmApiPassword;
using (var _serviceProxy = new OrganizationServiceProxy(
new Uri(CrmApiBaseAddress), null, creds, null))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes(); // ...
I'm getting an error:
Metadata contains a reference that cannot be resolved: 'http://crm.domain.com:1234/data/v8.0/?wsdl&sdkversion=90'.'
WebException: The remote server returned an error: (404) Not Found.
You mixed up these two:
Web API - which was available after v8.0
2011 endpoint - which is deprecated now but was available for really long time
Read more
When you use web api the url will be like: https://yourcrm.crm#.dynamics.com/api/data/v8.0/
In case of Organization Service Proxy still the 2011 endpoint: https://yourcrm.crm.dynamics.com/XRMServices/2011/Organization.svc
For breaking the 5000 records limitation & getting more than 5k records, the pagination concept has to be used. How to fetch more than 5000 entities from CRM
For more ideas, I have answered in this SO thread about other options.

No ViewData localhost versus localhost in debug

I'm stumped. When I run my solution in debug mode, the entire website works. It comes up with home page and everything. I can add, delete and update data to my database. The website was built with MVC, using SQLExpress (built in).
The issue is when I try to access the site either through localhost or from the outside world. The site worked last year before I had to reinstall windows. I upgraded from windows 7 to windows 8.1.
There's some kind of authentication that I'm missing. Could someone point it out to me?
Permissions set
IIS_USRS, and IUSR have modify, read & execute, list folder contents, read, and write
My physical path credentials is set to "Application User (pass-through authentication).
Application pool is using DefaultAppPool
.NET CLR Version v4.030319
Managed pipeline mode = Integrated
I had this issue before with windows 7, I thought I changed the DefaultAppPool process model identity to LocalService, or one of the other options. None of them are working now. Even tried to use a custom account.
Is there any more information I can provide?
Server Error in '/' Application.
There is no ViewData item of type 'IEnumerable' that
has the key 'YearID'.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: There is no
ViewData item of type 'IEnumerable' that has the key
'YearID'.
Source Error:
Line 53: Line 54: Year: Line 55: <%=
Html.DropDownList("YearID", ViewData["years"] as SelectList) %> Line
56: Line 57: League:
Source File:
e:\FantasyFootball\FantasyFootball\mvcFantasyFootball\FantasyFootball\Views\Home\Index.aspx
FFBallEntities _db = new FFBallEntities();
public ActionResult Navigation()
{
return View();
}
public ActionResult Index(int? id, int? leagueid, int? teamid)
{
try
{
bool ImMobile = DisplayModeProvider.MobileDisplayModeId.ToString() == "Mobile";
if (!ImMobile)
{
ViewData["Message"] = "Welcome To Fantasy Football Fantasy Edition!";
}
List<FanYear> years = _db.FanYearSet.OrderByDescending(m => m.FantasyYear).ToList();
List<League> leagues = _db.LeagueSet.ToList();
if (leagueid == null) leagueid = leagues[0].LeagueID;
if (id == null)
{
id = _db.TeamSet.OrderByDescending(m => m.FanYear.YearID).Select(m => m.FanYear.YearID).First();
}
ViewData["years"] = new SelectList(years, "YearID", "FantasyYear", id);
ViewData["leagues"] = new SelectList(leagues, "LeagueID", "League_Name", leagueid);
ViewData["selectedyear"] = id.ToString();
ViewData["selectedleague"] = leagueid.ToString();
ViewData["selectedteam"] = "0";
if (teamid != null)
ViewData["selectedteam"] = teamid.ToString();
int scoringid = _db.LeagueHistorySet.Include("FanYear").Include("Leagues").Include("Scoring").First(m => m.FanYear.YearID == id && m.Leagues.LeagueID == leagueid).Scoring.ScoringID;
ViewData["selectedscore"] = scoringid.ToString();
return View(_db.TeamScoreSet.Where(m => m.LeagueID == leagueid && m.YearID == id && (m.ScoringID == scoringid || m.ScoringID == 0)).OrderByDescending(m => m.PointsEarned).ToList());
}
catch
{
return View();
}
}
Me being an experienced web programmer, I should have known... (yet novice with .net and SQL server on windows platform).
The issue wasn't with the code, however, the code was preventing me from seeing the real error. My try... catch threw out a message I wasn't expecting.
I was having difficulty getting passed the fact that the code worked when I run it on my laptop in debug mode.
The solution is stored and compiled on my server, however, I use the laptop to modify the code.
When I started it in debug, I figured it was still running off the server. But at last I was not. I was using the SQL Express install on the laptop.
I have installed SQL Express 2012 on the server (which wasn't done when I reloaded the server), named the instance as I needed for the website. The website is now communicating with the database. I have other issues to resolve but I should be able to figure those out. My javascript and css isn't getting pulled in. I'll post a new question if I have trouble getting it working.
Thank you for the help.

Impersonation EPM using PSI or CSOM

For a project I have to sync hours from an external program to EPM. There is no requirement to use the Client Side Object Model of EPM 2013 or the PSI. But because Microsoft recommends the CSOM on their website for all new applications I tried to implement it with the CSOM. The first thing I wanted to test is to get all the hours, with the following code: (It isn't the most beautiful code because it is for testing purposes)
private static void GetTimesheets()
{
ProjectContext projContext = new ProjectContext("http://tfspsdemo/PWA/");
projContext.Load(projContext.TimeSheetPeriods);
projContext.ExecuteQuery();
foreach (var period in projContext.TimeSheetPeriods)
{
projContext.Load(period.TimeSheet);
projContext.ExecuteQuery();
Console.WriteLine(period.Name);
try
{
string tempName = period.TimeSheet.Name;
projContext.Load(period.TimeSheet.Lines);
projContext.ExecuteQuery();
Console.WriteLine(period.TimeSheet.Name);
foreach (var line in period.TimeSheet.Lines)
{
try
{
projContext.Load(line);
projContext.Load(line.Work);
projContext.ExecuteQuery();
foreach (var workLine in line.Work)
{
Console.WriteLine(workLine.ActualWork);
}
}
catch (Exception) { }
Console.WriteLine("Total: {0}", line.TotalWork);
}
}
catch (ServerObjectNullReferenceException) { }
}
}
But with above code I get only the code for the current user that is logged in, even if it is a person with rights to see other users hours. But what I want is to see all the hours of all the persons that have booked hours in EPM for a specific project plan. So I can later use this information to sync the hours from an external program to EPM. I thought I can solve this with impersonation but:
ProjectContext projContext = new ProjectContext("http://tfspsdemo/PWA/");
projContext.Credentials = new NetworkCredentials("username", "password");
But this isn't what I want because I have to do this for each user. And also I can't get the passwords of all users.
Does anyone now a solution to solve this problem and/or any suggestions? Solutions with the EPM PSI are also appreciated!
Thanks in advance!
Impersonation is not yet implemented in Project Sever 2016/Project Online. Please vote here: https://microsoftproject.uservoice.com/forums/218133-microsoft-project/suggestions/32981722-impersonation-support-for-csom-to-read-other-user
Thanks,
Werner
There are two modes in Proect server 2013. Proect server and SharePoint mode. I was able to get the above working in SharePoint mode, but alas I cannot read even Timesheet Periods as it says CSOMUnkownUser in Project server mode even after passing in the credentials. What mode are you running in currently on the server
This is probably a little late, but to access that kind of data in a provider/auto hosted app you need to access the sharepoint server through OData. CSOM is only intended to provide data from the current user context.

CrmService.Update method does not work for certain attribute

This is my problem:
all I want to do is update a "contact" entity in Crm 4 using the webservice.
This is my code:
CrmService eatupCrmService = CrmInteraction.InitializeCrmService();
contact updatedDelegate = new contact();
CeatupCrmService.Key contactPrimaryKey = new CeatupCrmService.Key();
contactPrimaryKey.Value = delegateId;
updatedDelegate.contactid = contactPrimaryKey;
updatedDelegate.address2_postalcode = delegateDetails.ContactDetailsPhysicalAddressCode;
eatupCrmService.Update(updatedDelegate);
I use the InitializeCrmService() to also retrieve and it works.
When updating the address2_postalcode attribute, I get the following error:
"Server was unable to process request."
with the exception Detail\InnerText :
"0x80040216 An unexpected error occurred. Platform".
If I change the code to update another attribute, say I try to update the mobilephone attribute
instead of address2_postalcode it works without any exceptions thrown.
As soon as I try to update address2_postalcode then I get that error. The address2_postalcode data type in Crm is nvarchar, and the value it is being assigned (delegateDetails.ContactDetailsPhysicalAddressCode) is of c#'s string type.
Anyone have any idea why this could be happening?
This same error and situation happened to me because I did an SSIS dts to load contacts in CRM from a flat file, in unsopported way, and I forgot to fill the CustomerAddressBase table. After filling this table "correctly" (two rows for each contact) the attributes of the View CustomerAddress(address1_addressid and address2_addressid) became not null. If you don't know how to fill this table (CustomerAddressBase) just create one new contact directly with address fields filled in CRM and then go to SQL Server management studio and by query you can see and know how the fields are filled.
Hope it helps somebody,
Alex
After many attempts at trying to understand why this error was occurring, I finally succeeded.
When I started working on this project, the client instructed me to test using only a specific contact, because we were working directly on the production environment. (the client does not have a development environment yet)
After doing some database queries to compare this contact to others (updates were failing only for the test contact) I noticed that my contact's address2_addressid attribute was NULL.
I then went to CRM under Customization\Customize Entities and opened up the contact entity. Under attributes, I ordered by type and saw that the contact has 3 primarykey attributes: contactid, address1_addressid and address2_addressid.
The test contact's address1_addressid and address2_addressid fields were NULL and this caused the CRM web service to throw the 0x80040216 An unexpected error occurred. Platform error upon me trying to update any of the address fields.
I don't know why this contact had those IDs set to NULL, I asked and the person that created the contact had no explanation of how this could have happened. I guess this will remain a mystery, but at least I now have an answer to the error I was getting and I can cater for this in my code.
I don´t know ho it can work...
I think you have to do CrmService.Create(contact) and then with the returned Guid you can perform updates...
Update is not going to work since the record with the Id you are setting on your contact entity doesn´t exist in the db...
contact updatedDelegate = new contact();
CeatupCrmService.Key contactPrimaryKey = new CeatupCrmService.Key();
You could do something like:
crmService eatupCrmService = CrmInteraction.InitializeCrmService();
contact updatedDelegate = new contact();
updatedDelegate.address2_postalcode = delegateDetails.ContactDetailsPhysicalAddressCode;
Guid cId = eatupCrmService.Create(updatedDelegate);
updatedDelegate.contactid = new Key(cId);
//set more fields if you want
eatupCrmService.Update(updatedDelegate);//update record
Wish I have helped you.

Using SMO.Agent to retrieve SQL job execution status - security issue

I've got a C# program that fires off SQL Server Agent jobs using the SQL Server Management Objects (SMO) interfaces. It looks something like:
Server ssis_server = new Server(
new ServerConnection(SERVER_NAME, SERVER_USERNAME, SERVER_PASSWORD)
);
var agent = ssis_server.JobServer;
var ssis_job = agent.Jobs[job_name];
var current_status = ssis_job.CurrentRunStatus;
if (current_status == JobExecutionStatus.Idle)
{
ssis_job.Start();
OnSuccess("Job started: " + job_name);
}
else
{
OnError("Job is already running or is not ready.");
}
I'm using SQL Server Authentication at this point to simplfy things whilst I work this out.
Now, my problem is that unless the SERVER_USERNAME is part of the 'sysadmin' dbo role, ssis_job.CurrentRunStatus is always 'Idle' - even when I know the job is running. It doesn't error out, just always reports idle.
If the user is an administrator, then the status is returned as expected.
Role membership you say?
Well, I added the SERVER_USERNAME SQL Server login to the msdb Role SQLAgentOperatorRole, that didn't seem to help.
The job's owner is a system administrator account - if that's the issue I'm not sure how to work around it.
Any ideas?
You need to refresh the job by calling the Refresh() method on ssis_job before checking the status, then you will get the correct information.

Categories