Strange error message when using SaveChanges in EF with MVC - database

I have a dropdownlistfor with values that is not from my database, and when a user select values that does not exist in my database, I want to save it to the database(and if it already exist, I just use the existing data).
This work fine with some of my data(see code for where it does not work)
This is my repository:
public void newPerson(Person addperson)
{
db.Person.AddObject(addperson);
db.SaveChanges(); //This wont work
}
here is my controller:
[HttpPost]
public ActionResult Create(CreateNKIphase1ViewModel model)
{
if (ModelState.IsValid)
{
var goalcard = new GoalCard();
var companyChecker = "";
var dbCompanies = createNKIRep.GetCustomerByName();
var addcustomer = new Customer();
foreach (var existingcustomer in dbCompanies)
{
companyChecker = existingcustomer.CompanyName;
if (existingcustomer.CompanyName == model.CompanyName)
{
var customerId = existingcustomer.Id;
var selectedCustomerID = createNKIRep.GetByCustomerID(customerId);
goalcard.Customer = selectedCustomerID;
break;
}
}
if (companyChecker != model.CompanyName)
{
addcustomer.CompanyName = model.CompanyName;
createNKIRep.newCustomer(addcustomer); //This works!
goalcard.Customer = addcustomer;
}
if (model.PersonName != null)
{
var Personchecker = "";
var dbPersons = createNKIRep.GetPersonsByName();
foreach (var existingPerson in dbPersons)
{
Personchecker = existingPerson.Name;
if (existingPerson.Name == model.PersonName)
{
var personId = existingPerson.Id;
var selectedPersonID = createNKIRep.GetByPersonID(personId);
goalcard.Person = selectedPersonID;
break;
}
}
if (Personchecker != model.PersonName)
{
Person newPerson = new Person();
newPerson.Name = model.PersonName;
createNKIRep.newPerson(newPerson);//Where repository is called
goalcard.Person = newPerson;
}
}
But when I try to save a new Person I get the following error message:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
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.
Even though Person only have Id and name as attributes in my database.
Is there anything wrong in my code, or is it any setting in my database that has to be changed?
Thanks in advance.

It's because I use db.SaveChanges(); multiple times in one post. Reducing numbers of time I use db.SaveChanges helped me get rid of the error.

Related

Message.Payload is always null for all messages. How do I get this data?

It is returning the correct number of message, but the only fields that are populated are Id and ThreadId. Everything else is null
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
ListMessagesResponse response = service.Users.Messages.List(emailAddress).Execute();
IList<Google.Apis.Gmail.v1.Data.Message> messages = response.Messages;
Console.WriteLine("Messages:");
if (messages != null && messages.Count > 0)
{
foreach (var message in messages)
{
Console.WriteLine("{0}", message.Payload.Body);
Console.WriteLine();
}
}
else
{
Console.WriteLine("No Messages found.");
}
Messages.List() only returns message and thread ids. To retrieve message contents, you need to invoke Get() for each message you are interested in. Updated version of your foreach loop example:
foreach (var message in messages)
{
Message m = service.Users.Messages.Get("me", message.Id).Execute();
// m.Payload is populated now.
foreach (var part in m.Payload.Parts)
{
byte[] data = Convert.FromBase64String(part.Body.Data);
string decodedString = Encoding.UTF8.GetString(data);
Console.WriteLine(decodedString);
}
}
Note: You may need to run a string replace on the part.Body.Data string. See this post for instructions.

How to unit test Soap service access from Crm 2011 Silverlight application?

In a Silverlight 5 application in Dynamics CRM 2011 I access the Organization Service of the CRM to query for entity Metadata. I wrote a service that takes an entity name and returns a list of all its fields.
How can I test this service method automatically? The main problem is how to obtain a reference to the organization service from a Silverlight app that does not run in the context of the CRM.
My Service method looks like this:
public IOrganizationService OrganizationService
{
get
{
if (_organizationService == null)
_organizationService = SilverlightUtility.GetSoapService();
return _organizationService;
}
set { _organizationService = value; }
}
public async Task<List<string>> GetAttributeNamesOfEntity(string entityName)
{
// build request
OrganizationRequest request = new OrganizationRequest
{
RequestName = "RetrieveEntity",
Parameters = new ParameterCollection
{
new XrmSoap.KeyValuePair<string, object>()
{
Key = "EntityFilters",
Value = EntityFilters.Attributes
},
new XrmSoap.KeyValuePair<string, object>()
{
Key = "RetrieveAsIfPublished",
Value = true
},
new XrmSoap.KeyValuePair<string, object>()
{
Key = "LogicalName",
Value = "avobase_tradeorder"
},
new XrmSoap.KeyValuePair<string, object>()
{
Key = "MetadataId",
Value = new Guid("00000000-0000-0000-0000-000000000000")
}
}
};
// fire request
IAsyncResult result = OrganizationService.BeginExecute(request, null, OrganizationService);
// wait for response
TaskFactory<OrganizationResponse> tf = new TaskFactory<OrganizationResponse>();
OrganizationResponse response = await tf.FromAsync(
OrganizationService.BeginExecute(request, null, null), iar => OrganizationService.EndExecute(result));
// parse response
EntityMetadata entities = (EntityMetadata)response["EntityMetadata"];
return entities.Attributes.Select(attr => attr.LogicalName).ToList();
}
Edit:
I can create and execute unit tests with Resharper and AgUnit. Thus, the problem is not how to write a unit test in general.
I have tweaked the GetSoapService from the standard Microsoft SDK to accept a fall back value. This means no codes changes are needed when debugging in visual studio and running in CRM. Anyway here it is
public static IOrganizationService GetSoapService(string FallbackValue = null)
{
Uri serviceUrl = new Uri(GetServerBaseUrl(FallbackValue)+ "/XRMServices/2011/Organization.svc/web");
BasicHttpBinding binding = new BasicHttpBinding(Uri.UriSchemeHttps == serviceUrl.Scheme
? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.TransportCredentialOnly);
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;
binding.SendTimeout = TimeSpan.FromMinutes(20);
IOrganizationService ser =new OrganizationServiceClient(binding, new EndpointAddress(serviceUrl));
return ser;
}
public static string GetServerBaseUrl(string FallbackValue = null)
{
try
{
string serverUrl = (string)GetContext().Invoke("getClientUrl");
//Remove the trailing forwards slash returned by CRM Online
//So that it is always consistent with CRM On Premises
if (serverUrl.EndsWith("/"))
{
serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);
}
return serverUrl;
}
catch
{
//Try the old getServerUrl
try
{
string serverUrl = (string)GetContext().Invoke("getServerUrl");
//Remove the trailing forwards slash returned by CRM Online
//So that it is always consistent with CRM On Premises
if (serverUrl.EndsWith("/"))
{
serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);
}
return serverUrl;
}
catch
{
return FallbackValue;
}
}

OptionSetValue does not contain constructor which takes one argument

I am creating a silverlight application as a web resource for CRM 2011. Now i am creating a ServiceAppointment record in DB and after creating it i want to change its Status to "reserved" instead of requested.
I googled about this and come across the examples like Close a Service Activity Through Code and Microsoft.Crm.Sdk.Messages.SetStateRequest
They all suggesting to use "SetStateRequest" and for using this i have to set the OptionSetValue like
request["State"] = new OptionSetValue(4);
But above line gives me error saying "OptionSetValue does not contain constructor which takes one argument"
BTW i am using SOAP end point of CRM 2011 service in silverlight application
Any ideas friends?
EDIT
Following is my code
var request = new OrganizationRequest { RequestName = "SetStateRequest" };
request["State"] = 3;
request["Status"] = 4;
request["EntityMoniker"] = new EntityReference() { Id = createdActivityId, LogicalName = "serviceappointment" };
crmService.BeginExecute(request,ChangeActivityStatusCallback,crmService);
And my callback function is
private void ChangeActivityStatusCallback(IAsyncResult result) {
OrganizationResponse response;
try
{
response = ((IOrganizationService)result.AsyncState).EndExecute(result);
}
catch (Exception ex)
{
_syncContext.Send(ShowError, ex);
return;
}
}
You must some how be referencing some other OptionSetValue class that is not the Microsoft.Xrm.Sdk one. Try appending the namespace to see if that resolves your issue:
request["State"] = new Microsoft.Xrm.Sdk.OptionSetValue(4);
Also, why are you using late bound on the SetStateRequest? Just use the SetStateRequest class:
public static Microsoft.Crm.Sdk.Messages.SetStateResponse SetState(this IOrganizationService service,
Entity entity, int state, int? status)
{
var setStateReq = new Microsoft.Crm.Sdk.Messages.SetStateRequest();
setStateReq.EntityMoniker = entity.ToEntityReference();
setStateReq.State = new OptionSetValue(state);
setStateReq.Status = new OptionSetValue(status ?? -1);
return (Microsoft.Crm.Sdk.Messages.SetStateResponse)service.Execute(setStateReq);
}
Thanks Daryl for you time and effort. I have solved my problem with the way u have suggested.
I am posting my code that worked for me.
var request = new OrganizationRequest { RequestName = "SetState" };
request["State"] = new OptionSetValue { Value = 3 };
request["Status"] = new OptionSetValue { Value = 4 };
request["EntityMoniker"] = new EntityReference() { Id = createdActivityId, LogicalName = "serviceappointment" };
crmService.BeginExecute(request,ChangeActivityStatusCallback,crmService);
private void ChangeActivityStatusCallback(IAsyncResult result) {
OrganizationResponse response;
try
{
response = ((IOrganizationService)result.AsyncState).EndExecute(result);
}
catch (Exception ex)
{
_syncContext.Send(ShowError, ex);
return;
}
}

context.SaveChanges() not persisting data in database

Im working on a MVC app.
When I call context.SaveChanges to update a specific records. The update is not registered in the database. I do not get any runtime error either. All in notice is that my Records is not updated. I still see the same values. Insert Functionality work Perfectly.
enter code here
public Admission Update(int stuid){
VDData.VidyaDaanEntities context = new VDData.VidyaDaanEntities();
VDData.Student_Master studentmaster = new VDData.Student_Master();
studentmaster.Student_ID = stuid;
studentmaster.Student_First_Name = this.FirstName;
studentmaster.Student_Middle_Name = this.MiddleName;
studentmaster.Student_Last_Name = this.LastName;
studentmaster.Student_Address_1 = this.Address;
studentmaster.Student_Address_2 = this.Address2;
studentmaster.Student_City = this.City;
studentmaster.Student_State = this.State;
studentmaster.Student_Pin_Code = this.Pincode;
context.SaveChanges(); // here it wont give any kind of error. it runs sucessfully. }
First get the entity you are going to update:
var entity = obj.GetEntity(id);
entity.col1 = "value";
context.SaveChanges(entity);
hope this will help.
It seems like you want to update, so your code should be
VDData.Student_Master studentmaster = context.Student_Masters.Single(p=>p.Student_ID == stuid);
And you should not change the Student_ID if it is the primary key.
public Admission Update(int stuid){
VDData.VidyaDaanEntities context = new VDData.VidyaDaanEntities();
//VDData.Student_Master studentmaster = new VDData.Student_Master();
//REPLACE WITH
VDData.Student_Master studentmaster = context.Student_Masters.Where(p=>p.Student_ID == stuid);
studentmaster.Student_ID = stuid;
studentmaster.Student_First_Name = this.FirstName;
studentmaster.Student_Middle_Name = this.MiddleName;
studentmaster.Student_Last_Name = this.LastName;
studentmaster.Student_Address_1 = this.Address;
studentmaster.Student_Address_2 = this.Address2;
studentmaster.Student_City = this.City;
studentmaster.Student_State = this.State;
studentmaster.Student_Pin_Code = this.Pincode;
context.SaveChanges();
Before
context.SaveChanges();
You need to call this
context.Student_Masters.Add(studentmaster );
Edit: introduce Abstraction to your Context class and Create a method in your context class like below, then you can call it whenever you want to create or update your objects.
public void SaveStudent_Master(Student_Master studentmaster)
{
using (var context = new VDData.VidyaDaanEntities())
{
if (studentmaster.Student_ID == 0)
{
context.Student_Masters.Add(studentmaster);
}
else if (studentmaster.Student_ID > 0)
{
//This Updates N-Level deep Object grapgh
//This is important for Updates
var currentStudent_Master = context.Student_Masters
.Single(s => s.Student_ID == studentmaster.Student_ID );
context.Entry(currentStudent_Master ).CurrentValues.SetValues(studentmaster);
}
context.SaveChanges();
}
Then in your Controller replace context.SaveChanges(); with _context.SaveStudent_Master(studentmaster);

what is wrong with my test class in apex force.com code?

I have written a working class in Apex. It is an Email service extender, that processes incoming emails.
It is working perfect on my sandbox enviroment.
I have created a test class, so I can also deploy it to my production, but when validating the code, I get the only 72% of my code is tested.
This is my main class
global class inboundEmail implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
Lead lead;
String [] mFromUserParams;
String [] sourceText;
String mCaseObject;
try{
sourceText = email.toAddresses[0].split('#');
String [] mParams = sourceText[0].split('\\.');
**// FROM THIS LINE TO THE END - NOT COVERED**
mFromUserParams = email.fromAddress.split('#');
mCaseObject = mParams[0];
if (mCaseObject == 'lead'){
lead = new Lead();
lead.LastName = mFromUserParams[0];
lead.Company = email.fromAddress;
lead.OwnerId = mParams[1];
lead.LeadSource = mParams[2];
lead.Email = email.fromAddress;
lead.RequirementsDescription__c = email.subject + email.plainTextBody;
insert lead;
result.success = true;
} else if (mCaseObject == 'case'){
result.success = true;
} else {
result.success = false;
}
}catch(Exception e){
result.success = false;
result.message = 'Oops, I failed.';
}
return result;
}
}
This is my test class
#isTest
private class inboundEmailTest {
public static testMethod void inboundEmail(){
// Create a new email, envelope object and Header
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
envelope.toAddress = 'lead.owner.new#cpeneac.cl.apex.sandbox.salesforce.com';
envelope.fromAddress = 'user#acme.com';
email.subject = 'Please contact me';
email.fromName = 'Test From Name';
email.plainTextBody = 'Hello, this a test email body. for testing Bye';
// setup controller object
inboundEmail catcher = new inboundEmail();
Messaging.InboundEmailResult result = catcher.handleInboundEmail(email, envelope);
}
}
According to the error message, ALL lines in the Try/Catch block from the 3rd line are not covered. (marked in the code).
in your test method you're setting envelope.toAddress but in your email service you're splitting the first element of the actual InboundEmail objects toAddresses. this probably causes either an ArrayIndexOutOfBoundsException or a NPE because the element 0 does not exist. so the code coverage will be poor because your test always jumps into the exception handling and leaves the rest of you code uncovered. just set the emails toAddresses and you should have a better coverage.
h9nry
In your test code, can you add a scenario that causes the lead insert to fail? This will cause the code in your catch block to execute and provide you the needed code test coverage.
The email.fromAddress is not a list by default, so just setting that to a string and not a list solved this.

Resources