.NET MVC Controller Exception - c#

[HttpPost]
public JsonResult CreateUser(UserCreateDTO dto)
{
Entity.User Us = new User();
Us.Name = dto.Name;
Us.Surname = dto.Surname;
Us.Username = dto.Username;
Us.Password = dto.Password;
container.Users.Add(Us);
container.SaveChanges();
UserCreateList UsList = new UserCreateList
{
Id = Us.Id,
Name = Us.Name,
Surname = Us.Surname,
Username = Us.Username,
Email = Us.Email,
Password = Us.Password
};
return Json(UsList);
}
It's an ajax New Member Form.
When it comes to this controller from ajax submit, it's throwing an internal network server error. I debugged the code and its crashed at the line container.users.add(us); and the line below..
According to my examples it must be Users.AddObject but there's no AddObject selection..
It can be a problem for giving error or how can I fix it.
www.muratkamci.com/exception.jpg
This is the pic of ex.

That error "conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value." can occur when you fail to set a datetime value on a field that does not accept nulls. Since you aren't defining any DateTime properties on your User object, this is a likely scenario. Look at your model, and see if you can find a non-nullable datetime field.

Related

The type of member in type is not compatible with of member in type in EF

In my ASP.NET MVC 5 application, I have an ActionResult in one of my controllers that takes parameters from the client and returns a JSON string.
The problem is, I get the error below when I have null values in one or more of the database records. I can clear this error by casting all the null values to an empty string in the view table itself, but I'd rather not keep that as a long-term solution.
System.Data.Entity.Core.MappingException: 'Schema specified is not valid. Errors:
EFA.msl(16,12) : error 2019: Member Mapping specified is not valid. The type 'Edm.String[Nullable=False,DefaultValue=,MaxLength=,Unicode=,FixedLength=]' of member 'ScheduledStartTime' in type 'EFAModel.v_DemandList' is not compatible with 'SqlServer.datetime[Nullable=False,DefaultValue=,Precision=3]' of member 'ScheduledStartTime' in type 'EFAModel.Store.v_DemandList'.'
Any recommendations on how should be approaching this scenario?
[HttpPost]
public ActionResult GetDemandData()
{
//get basic parameters from DataTables
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
//Find Order Column
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
//find search parameters
var searchParam = Request.Form.GetValues("search[value]")[0];
//build return dataset
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
//materialize dataset using serch parameters
EFAEntities efa = new EFAEntities();
//*** throws error when database table contains null values ***
var dataSet = (from a in efa.v_DemandList
where a.ScheduledStartTime.Contains(searchParam)
select a
).Distinct().OrderBy(sortColumn + " " + sortColumnDir);
recordsTotal = dataSet.Count();
var data = dataSet.Skip(skip).Take(pageSize).ToList();
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }, JsonRequestBehavior.AllowGet);
}
Sample from View Table:
Error message is clear! Its clearly saying that ScheduledStartTime type in efa.v_DemandList is not the same type for ScheduledStartTime in database table. In your model class ScheduledStartTime is string type but in your database table its datatime type.
So change your ScheduledStartTime type from string to DateTime in your DemandList model class.
Then update your query as follows:
var dataSet = (from a in efa.v_DemandList
where a.ScheduledStartTime.ToString().Contains(searchParam)
select a
).Distinct().OrderBy(sortColumn + " " + sortColumnDir);
Here I am using .ToString() with ScheduledStartTime otherwise you cannot use Contains() because its a DateTime type.
Give default values in your action method. If it's in fact null, you'll get the default value. For ints, you need to provide a nullable type.
[HttpPost]
public ActionResult GetDemandData(int? start=0, int? length=0, etc)
{

How do i convert Context.User.Identity.GetUserId() to int with c# in asp.net vs2015

How do I convert Context.User.Identity.GetUserId() to an int.
code:
string clientId = Context.User.Identity.GetUserId();
if (clientId != null) {
cart NewInCart = new cart();
NewInCart.ClientId = Convert.ToInt32(clientId);
}
Above code gives error stating:
when converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object.
I think what you want is:
NewInCart.ClientId = Int32.Parse(clientId);
Sorted for now.
I have decided to change the data type of ClientID in the dbo to nvarchar(50); that way I save like this:
string clientId = Context.User.Identity.GetUserId() ;
.......
cart.ClientId = clientId;
where cart.ClientId is now expecting a string. This sorted my problem and I no longer need to convert Context.User.Identity.GetUserId() to int.

How to Add Custom Fields on JoeBlogs Wordpress Wrapper

I'm trying to complete fields with JoeBlogs WordPress Wrapper.
My code is:
private void postToWordpress(string title, string postContent,string tags, string aioTitle)
{
string link = this.maskedTextBox1.Text;
string username = this.maskedTextBox2.Text;
string password = this.maskedTextBox3.Text;
var wp = new WordPressWrapper(link + "/xmlrpc.php", username, password);
var post = new Post();
post.Title = title;
post.Body = postContent;
post.Tags = tags.Split(',');
string[] cf = new CustomField(); //{ ID = "name", Key = "aiosp_title", Value = "All in One SEO Title" };
cf.ID = "name";
cf.Key = "aiosp_title";
cf.Value = "All in One SEO Title";
post.CustomFields[0] = cf;
wp.NewPost(post, false);
}
The error is at this line:
post.CustomFields[0] = cf;
And it is:
An unhandled exception of type 'System.NullReferenceException'
occurred in JoeBlogsWordpressWrapperTests.exe
Additional information: Object reference not set to an instance of an
object.
So, how to use/add correctly custom fields on WordPress from C# Application using JoeBlogs WordPress Wrapper?
The following code fixes your NullReferenceException and also successfully saves the custom fields into the Post in Wordpress.
private void postToWordpress(string title, string postContent,string tags, string aioTitle)
{
string link = this.maskedTextBox1.Text;
string username = this.maskedTextBox2.Text;
string password = this.maskedTextBox3.Text;
var wp = new WordPressWrapper(link + "/xmlrpc.php", username, password);
var post = new Post();
post.Title = title;
post.Body = postContent;
post.Tags = tags.Split(',');
var cfs = new CustomField[]
{
new CustomField()
{
// Don't pass in ID. It's auto assigned for new custom fields.
// ID = "name",
Key = "aiosp_title",
Value = "All in One SEO Title"
}
};
post.CustomFields = cfs;
wp.NewPost(post, false);
}
You were getting the NullReferenceException error because you were creating a string array and trying to assign it the CustomFields property of the Post object, which is an array of CustomField i.e. CustomField[].
Also, in order to save the CustomFields to the Post in the database, you should pass in only the Key and Value fields of the CustomField struct and skip the ID field all together. Reason being Wordpress auto-generates the ID fields (also it's an integer / numeric field in the database). I think that was what was causing the XmlRpc call to fail, but we did not get any errors as to why.
Try the above code and it should work (I have it working on my localhost WAMP Wordpress installation).
One final note. Although the CustomField's name property is called Key, it doesn't have to be unique, and uniqueness is not enforced. So for instance, if you are populating a custom dropdown box with a list of cities for a Post, you could have the list of cities as a set of custom fields as follows.
var cfs = new CustomField[]
{
new CustomField()
{
Key = "aiosp_title",
Value = "All in One SEO Title"
} ,
new CustomField()
{
Key = "this is another custom field with HTML",
Value = "All in One SEO Title <br/> Keyword 1 <br/><p>This is some more text and html</p>"
} ,
new CustomField()
{
Key = "list_of_cities",
Value = "San Francisco"
} ,
new CustomField()
{
Key = "list_of_cities",
Value = "New York"
}
};
This will also get saved to the post, with 2 custom fields with the same Key value and different text in the Value field's value.
And last but not least, you can store HTML also in the custom fields (as shown above).

How does the asp.net mvc framework deals with Null values

I have some problem in understanding how does the asp.net mvc deal with Null values .
In the first scenario i have the following action method:-
[HttpPost]
public ActionResult Delete(int labtestid, int visitid)
{
try
{
var vlr = repository.GetVisitLabResult(labtestid,visitid);
string desc = vlr.LabTest.Description;
repository.DeleteVisitLabResult(vlr);
repository.Save();
return Json(new { IsSuccess = "True", id = labtestid, description = desc }, JsonRequestBehavior.AllowGet);
}
Incase the repository method var vlr = repository.GetVisitLabResult(labtestid,visitid); does not return any result (var vlr is null) then the following exception will be raised on the string desc = vlr.LabTest.Description; NullReferenceException was unhandled by user code. So why did the framework raise an exception instead of just assigning a null value to the string desc !!!
BR
It looks like the actual object itself is null. You have a null object and you're trying to access properties on it, hence the runtime will throw a NullReferenceException. You're best off checking if the object is null first before trying to access it's members :)

Error creating an Entity in CRM 2011 - CRM doesn't like OptionSetValue

I'm trying to create an entity in CRM 2011 (not an out of the box kind, but what in CRM 4 would have been called a DynamicEntity... one with my custom attributes). The code below gives me this error and I'm not sure why. This exact same code works if I remove the new_accounttype attribute and try to use another custom attribute.
CRM seems to have taken issue with the "OptionSetValue" being set as the value for that key value pair. new_accounttype is a picklist (or OptionSet in CRM 2011) and that value of 100000003 was pulled from the front end so it's a valid value.
Error: A validation error occurred. The value of 'new_accounttype' on
record of type 'account' is outside the valid range.
What am I doing wrong?
public static void CreateAccount(string accountName, string accountType)
{
//Create properties
KeyValuePairOfstringanyType[] attributes = new KeyValuePairOfstringanyType[2];
attributes[0] = new KeyValuePairOfstringanyType() { key = "name", value = accountName ?? "" };
attributes[1] = new KeyValuePairOfstringanyType() { key = "new_accounttype", value = new OptionSetValue() { Value = 100000003 } };
////Create DynamicEntity
Entity accountToCreate = new Entity();
accountToCreate.LogicalName = "account";
accountToCreate.Attributes = attributes;
try
{
service.Create(accountToCreate);
}
}
I agree that what you have should work fine. This can only mean that the value isn't published or is incorrect. As #glosrob mentions, check that the changes are actually published. Confirm these values by looking at the published form and seeing if your new value is present (and perhaps double check by using IE Developer Tools - hit F12 - and confirm that the value in the select>option object in the HTML contains the integer you expect).
As an aside, your code looks more complex than necessary (IMHO!). I believe this is easier to read an no less efficient:
Try this:
public static void CreateAccount(string accountName, string accountType)
{
////Create DynamicEntity
Entity accountToCreate = new Entity();
accountToCreate.LogicalName = "account";
accountToCreate.Attributes = attributes;
//Append properties
accountToCreate.Attributes.Add("name", accountName ?? "" );
accountToCreate.Attributes.Add("new_accounttype", new OptionSetValue(100000003);
try
{
service.Create(accountToCreate);
}
}
Give this a shot: key = "new_accounttype", value = new OptionSetValue(100000003)

Categories