This question already has answers here:
"Specified cast is not valid" error in C# windows forms program
(9 answers)
Closed 6 years ago.
I got the following code:
var model = new List<LogModels>();
while (reader.Read())
{
var logContent = new LogModels(
(int)reader["id"],
(string)reader["response"],
(string)reader["language"],
(string)reader["country"],
(string)reader["location"],
(string)reader["os"],
(string)reader["browser"],
(string)reader["type"],
(DateTime)reader["date"]
);
model.Add(logContent);
}
But I get the following error:
An exception of type 'System.InvalidCastException' occurred in Speed Services.dll but was not handled in user code
Additional information: Specified cast is not valid.
Image: https://i.gyazo.com/adf04b8e271bb53c93303d5774a48f80.png
My model (LogModels) looks like this:
public int id { get; set; }
public string response { get; set; }
public string language { get; set; }
public string country { get; set; }
public string location { get; set; }
public string os { get; set; }
public string browser { get; set; }
public string type { get; set; }
public DateTime date { get; set; }
Does someone know what the issue could be since I can't seem to find the problem?
var model = new List<LogModels>();
while (reader.Read())
{
var logContent = new LogModels(
Convert.ToInt32(reader["id"].Tostring()),
(string)reader["response"],
(string)reader["language"],
(string)reader["country"],
(string)reader["location"],
(string)reader["os"],
(string)reader["browser"],
(string)reader["type"],
Convert.ToDateTime(reader["date"].Tostring())
);
model.Add(logContent);
}
casting problem because of integer or datetime value.
(int)reader["Id"] instead of Convert.ToInt32(reader["Id"].Tostring())
(DateTime)reader["date"] instead of Convert.ToDateTime(reader["date"].Tostring())
Related
Hi I am using PuppeteerSharp for the first time and am wondering if EvaulateExpressionAsync supports a way to convert to a complex c# object. So when i try to do something like this:
var allResultsSelector = ".sortableTable.resultTable tr.studyResultRow";
var jsSelectAllAnchors = $"Array.from(document.querySelectorAll('{allResultsSelector}')).map(f=>f.innerText);";
await frmSearch.WaitForSelectorAsync(allResultsSelector);
var urls = await frmSearch.EvaluateExpressionAsync<InteleStudyResult[]>(jsSelectAllAnchors);
c# type for now
public class InteleStudyResult
{
public string PatientName { get; set; }
//public string PatientId { get; set; }
//public DateTime DOB { get; set; }
//public string Sex { get; set; }
//public string Accession { get; set; }
//public DateTime StudyDate { get; set; }
//public string Modality { get; set; }
//public int? Series { get; set; }
//public string StudyDescription { get; set; }
}
exception occurs on the Eval call
Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Message=Error converting value " my string here " to type 'InteleradWebAccessor.InteleStudyResult'. Path '[0]'.
Source=Newtonsoft.Json
Inner Exception 1:
ArgumentException: Could not cast or convert from System.String to InteleradWebAccessor.InteleStudyResult.
If this is not supported I'd greatly appreciate a suggestion on best way to handle getting what is a html table row into a c# complex type using PuppeteerSharp
You should an object in your map
Array.from(document.querySelectorAll('{allResultsSelector}'))
.map(f =>{ return { patientName: f.innerText} });
This question already has answers here:
The model item passed into the dictionary is of type .. but this dictionary requires a model item of type
(7 answers)
Closed 3 years ago.
The details are being fetched in the controller correctly but value passed in the view is incorrect. Therefore I am getting the following error:
The model item passed into the dictionary is of type 'System.Int64', but this >dictionary requires a model item of type >'estatebranch.ViewModels.RentRegisterViewModel'
My controller has following action method
public ActionResult RentRegister(int propertyId)
{
try
{
using (estatebranchEntities db = new estatebranchEntities())
{
RentRegisterViewModel objRentRegister = new RentRegisterViewModel();
objRentRegister.balance = db.PropertyDetails.Where(m => m.propertyid == propertyId).Select(m => m.balance).SingleOrDefault();
return View(objRentRegister.balance);
}
}
catch (Exception)
{
throw;
}
}
My View model is as follow:
public class RentRegisterViewModel
{
public int recordid { get; set; }
public int propertyid { get; set; }
public int month { get; set; }
public int year { get; set; }
public long amountpaid { get; set; }
public System.DateTime paymentdate { get; set; }
public long interest { get; set; }
public Nullable<long> balance { get; set; }
public virtual PropertyDetail PropertyDetail { get; set; }
}
try changing this line:
return View(objRentRegister);
This question already has answers here:
Easiest way to parse JSON response
(4 answers)
Closed 4 years ago.
string sample = "{\"warnings\":[{\"code\":3,\"message\":\"Invalid number\"}],\"errors\":[{\"code\":4,\"message\":\"No recipients specified\"}],\"status\":\"failure\"}";
JavaScriptSerializer js = new JavaScriptSerializer();
List<Status> liststatus = (List<Status>)js.Deserialize(sample, typeof(List<Status>));
string success = "";
foreach (Status status in liststatus)
{
success = status.code;
}
Response.Write("success");
public class Status
{
public string status { get; set; }
public string[] warnings { get; set; }
public string balance { get; set; }
public string message { get; set; }
public string recipient { get; set; }
public string content { get; set; }
public string num_messages { get; set; }
public string num_parts { get; set; }
}
i trying to convert json object to c# , but i didn't. what wrong with my code???
Your JSON string is not a list, its a object which has the properties of Warnings (List),
Create a model that matches it
JavaScriptSerializer js = new JavaScriptSerializer();
Status x = (Status)js.Deserialize(sample, typeof(Status);
Apparently, status.code is not to any code attribute in json.
It should be status.warnings[0].code or status.errors[0].code
This question already has answers here:
A specified Include path is not valid. The EntityType does not declare a navigation property with the name *
(5 answers)
Closed 3 years ago.
I am encountering an error to the effect of "A specified Include path is not valid. The EntityType 'MyCMS.DAL.SiteSettings' does not declare a navigation property with the name 'SiteSettingOptions'."
I have read quite a few posts about this issue but all of the research I have done pertains to ICollections and not for properties that are classes.
Here is where I am and could use your help resolving the issues.
[Table("SiteSettingsBridge")]
[DataContract]
public partial class SiteSettings
{
[Key]
[DataMember]
public int SiteSettingsBridgeID { get; set; }
[DataMember]
public int SiteID { get; set; }
[DataMember]
public int SiteSettingOptionID { get; set; }
[DataMember]
public virtual SiteSettingOptions SiteSettingOption { get; set; }
[DataMember]
[StringLength(500)]
public string Value { get; set; }
public SiteSettings()
{
SiteSettingsBridgeID = 0;
SiteID = 0;
SiteSettingOptionID = 0;
Value = "";
}
}
[DataContract]
public partial class SiteSettingOptions
{
[Key]
[DataMember]
public int SiteSettingOptionID { get; set; }
[DataMember]
public string SettingsGroup { get; set; }
[DataMember]
[StringLength(100)]
public string Name { get; set; }
[DataMember]
[StringLength(500)]
public string DefaultValue { get; set; }
[DataMember]
public SettingType Type { get; set; }
public enum SettingType
{
String = 1,
Bool = 2,
Integer = 3
}
public SiteSettingOptions()
{
SiteSettingOptionID = 0;
SettingsGroup = string.Empty;
Name = string.Empty;
DefaultValue = string.Empty;
Type = SiteSettingOptions.SettingType.String;
}
}
and then in my DAL project, I am attempting to add an Include to the context query like this
public static List<Contracts.Sites.SiteSettings> GetBySiteID(int SiteID)
{
using (CMSContext cntx = new CMSContext())
{
///OMITTED FOR BREVITY
return cntx.SiteSettings.Include("SiteSettingOptions").Where(i => i.SiteID == SiteID).ToList();
}
}
When I compile and run, I am receiving the above error.
To answer a few questions up front, I am not using LazyLoading and I am not doing anything on model create.
Yes, I am brand new to EF. This is my first app.
Thanks Ben...
Your property is called SiteSettingOption (no s) but you are trying to Include("SiteSettingOptions") (notice the final s). Remove the last s. You can avoid this by using the Include extension that uses lambdas rather than strings this would be something like Include(x => x.SiteSettingOption)
Background
I am working on a trading ActiveX API in visual studio 2010 on C#. Since it is an ActiveX API, I simply added the ActiveX as my reference. The api provides three group of things: Method you could use to call API, the Event with which the API updates information for you and some socalled ActiveX COM object.
ISSUE
I asked a related question here: C# boolean int conversion issue Finally, after viewing the exception has been thrown, I know that it is about casting. Here is the description of exception:
*System.InvalidCastException was unhandled Message=Unable to cast object of type
InteractiveBrokersTradingSystem.Forex' to type 'TWSLib.IContract'.
*
And here is my definition for Forex Class:
namespace InteractiveBrokersTradingSystem
{
class Forex:TWSLib.IContract
{
public int conId { get; set; }
public string symbol { get; set; }
public string secType { get; set; }
public string expiry { get; set; }
public double strike { get; set; }
public string right { get; set; }
public string multiplier { get; set; }
public string exchange { get; set; }
public string primaryExchange { get; set; }
public string currency { get; set; }
public string localSymbol { get; set; }
public int includeExpired { get; set; }
public object comboLegs { get; set; }
public object underComp { get; set; }
public string comboLegsDescrip { get;set; }
public string secIdType { get; set; }
public string secId { get; set; }
public Forex(string preCurrency,string baseCurrency)
{
//conId = 0;
//symbol = preCurrency;
//secType = "CASH";
//expiry = null;
//strike = double.Parse("0");
//right = null;
//multiplier = null;
//exchange = "IDEALPRO";
//primaryExchange = "IDEALPRO";
//currency = baseCurrency;
//localSymbol = null;
//includeExpired = 0;
// comboLegs = null;
//underComp = null;
//comboLegsDescrip = null;
//secType = null;
//secId = null;
}
}
}
You could see that I did not assign any value to the properties of the class and the exception is always the same no matter what kind of value I assign or not assign or null.
In the description of the api below as image we can see that some property with () like strike() as doulble and some not with () like secType as string; someone told me that it might be problem. Please, give me any hint related to this COM casting issue:
(source: minus.com)
(source: minus.com)
(source: minus.com)
Can you post some code that actually fails?
I think what's happening is that you're trying to cast a COM object to a plain .NET type and that will not work because the COM object needs to explicitly be mapped to a .NET type either by the Runtime Callable Wrapper or by manual mapping.
One suggestion I would have is to skip explicit casting and use the dynamic type in .NET 4.0 to access the properties of your COM object, then map it to whatever properties/objects you need it to. That way you'll be able to see exactly which part of the object doesn't want to map.