I was following this Mohsen Esmailpour's answer, to build a sample project to load views and controllers from a class library using custom view engine.
Here's what I did,
Add a Asp.Net MVC project
Add a class library. Add references to
Microsoft.AspNet.Razor
Microsoft.AspNet.WebPages
Microsoft.Web.Infrastructure
Microsoft.AspNet.Mvc"
Reference class library in MVC project.
3. Add a "Controllers" folder and added "MyViewController.cs" class
public class MyViewController : Controller
{
public ActionResult Index()
{
return View();
}
}
View engine (which should be causing the problem), I am not entirely sure what's happening here,
public class CustomViewEngine : RazorViewEngine
{
public CustomViewEngine()
{
MasterLocationFormats = new string[]
{
"~/bin/Views/{1}/{0}.cshtml",
"~/bin/Views/Shared/{0}.cshtml"
};
ViewLocationFormats = new string[]
{
"~/bin/Areas/{2}/Views/{1}/{0}.cshtml",
"~/bin/Areas/{2}/Views/Shared/{0}.cshtml"
};
}
}
Route.config for the Mvc project,
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(name: "Route2", url: "{controller}/{action}/{id}",
namespaces: new[] { "Custom.Views.Controllers" },
defaults: new { controller = "MyView", action = "Index", id = UrlParameter.Optional });
}
}
Add Views folder and added "MyView.cshtml" (Views/MyView/Index.cshtml), also I set the Properties of this cshtml to "Copy to Output Directory" as "Copy Always" so that it appears in web project / bin/MyView/Index.cshtml.
When I run the project, http://localhost:/MyView, it hits the "MyView" controller, but not finding the "MyView" view.
Server Error in '/' Application.
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
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.FormatException: Index (zero based) must be
greater than or equal to zero and less than the size of the argument
list.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[FormatException: Index (zero based) must be greater than or equal to
zero and less than the size of the argument list.]
System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider,
String format, ParamsArray args) +1876
System.String.FormatHelper(IFormatProvider provider, String format,
ParamsArray args) +58 System.String.Format(IFormatProvider
provider, String format, Object[] args) +80
System.Web.Mvc.ViewLocation.Format(String viewName, String
controllerName, String areaName) +70
System.Web.Mvc.VirtualPathProviderViewEngine.GetPathFromGeneralName(ControllerContext
controllerContext, List1 locations, String name, String
controllerName, String areaName, String cacheKey, String[]&
searchedLocations) +166
System.Web.Mvc.VirtualPathProviderViewEngine.GetPath(ControllerContext
controllerContext, String[] locations, String[] areaLocations, String
locationsPropertyName, String name, String controllerName, String
cacheKeyPrefix, Boolean useCache, String[]& searchedLocations) +626
System.Web.Mvc.VirtualPathProviderViewEngine.FindView(ControllerContext
controllerContext, String viewName, String masterName, Boolean
useCache) +130
System.Web.Mvc.<>c__DisplayClass14_0.<FindView>b__1(IViewEngine e) +24
System.Web.Mvc.ViewEngineCollection.Find(Func2 lookup, Boolean
trackSearchedPaths) +85
System.Web.Mvc.ViewEngineCollection.FindView(ControllerContext
controllerContext, String viewName, String masterName) +183
System.Web.Mvc.ViewResult.FindView(ControllerContext context) +84
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
+126 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext
controllerContext, ActionResult actionResult) +13
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList1
filters, Int32 filterIndex, ResultExecutingContext preContext,
ControllerContext controllerContext, ActionResult actionResult) +56
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList1
filters, Int32 filterIndex, ResultExecutingContext preContext,
ControllerContext controllerContext, ActionResult actionResult) +420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext
controllerContext, IList1 filters, ActionResult actionResult) +52
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3()
+198 System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult
asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult
asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult
asyncResult) +27
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult
asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult,
Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult
asyncResult) +10
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult
asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
+28 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+583 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +132 System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously) +173
Seems like I am missing something.
not sure what ""~/bin/Views/{1}/{0}.cshtml" configurations doing and it seems failing in CustomViewEngine.
I had a typo in the folder's name, the folder in which my view was located.
So here's the rub, I am actually doing this in Sitecore, but got so frustrated, I broke out a new boilerplate WebApi project, just to find my problem.
My assertion is that given the following request,
/api/Simple/AspNetJsonDeserializing?instance={%20"$type":%20"SimpleWebApi.Controllers.ConcreteTestInstance,%20SimpleWebApi",%20"hostName":%20"google.com"%20}
I should get a non-null parameter value of ConcreteTestInstance for ITestInstance Instance in my AspNetJsonDeserializing Action Method.
However, Instead I am receiving the following exception:
Cannot create an instance of an interface.
Instead, though if I use my NewtonsoftJsonDeserializing Action Method, and pass it a jsonString and explicitly deserialize it using the Newtonsoft JsonConvert, it will deserialize fine.
What am I doing Wrong?
Here's all the code
The Json
{
"$type": "SimpleWebApi.Controllers.ConcreteTestInstance, SimpleWebApi",
"hostName": "google.com"
}
Controller/Action
[JsonInterfaceBindingAndNonDefaultConstructors]
public class SimpleController : ApiController
{
[System.Web.Http.HttpGet]
public JsonResult<string> NewtonsoftJsonDeserializing(string jsonString) // [FromUri] ITestInstance instance) //
{
JsonSerializerSettings jsonSerializerSettingForTypeHandling = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor };
ITestInstance instance = JsonConvert.DeserializeObject<ITestInstance>(jsonString, jsonSerializerSettingForTypeHandling);
return Json("OK");
}
[System.Web.Http.HttpGet]
public JsonResult<string> AspNetJsonDeserializing([FromUri] ITestInstance instance)
{
return Json($"Uri:{((ConcreteTestInstance)instance)._instanceUri}");
}
}
Attribute for modifying SerializerSettings
[AttributeUsage(AttributeTargets.Class)]
public class JsonInterfaceBindingAndNonDefaultConstructors : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
{
IEnumerable<JsonMediaTypeFormatter> jsonFormatters = controllerSettings.Formatters.OfType<JsonMediaTypeFormatter>();
foreach (var jsonFormatter in jsonFormatters)
{
jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver(); //new JsonContractResolver(new JsonMediaTypeFormatter() {});
jsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.All;
jsonFormatter.SerializerSettings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
}
}
}
Interface
public interface ITestInstance
{
}
Concrete Subclass
public class ConcreteTestInstance : ITestInstance
{
private const string SCHEME = "http://";
private const int PORT = 80;
private const string API_PATH = "/";
private const string QUERYSTRING = "";
public readonly Uri _instanceUri;
public ConcreteTestInstance(string hostName)
{
_instanceUri = new UriBuilder(SCHEME, hostName, PORT, API_PATH, QUERYSTRING).Uri;
}
}
Exception: Cannot create an instance of an interface.
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>Cannot create an instance of an interface.</ExceptionMessage>
<ExceptionType>System.MissingMethodException</ExceptionType>
<StackTrace>
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.Activator.CreateInstance(Type type) at System.Web.Http.ModelBinding.Binders.MutableObjectModelBinder.CreateModel(HttpActionContext actionContext, ModelBindingContext bindingContext) at System.Web.Http.ModelBinding.Binders.MutableObjectModelBinder.EnsureModel(HttpActionContext actionContext, ModelBindingContext bindingContext) at System.Web.Http.ModelBinding.Binders.MutableObjectModelBinder.BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) at System.Web.Http.Controllers.HttpActionContextExtensions.Bind(HttpActionContext actionContext, ModelBindingContext bindingContext, IEnumerable`1 binders) at System.Web.Http.ModelBinding.Binders.CompositeModelBinder.BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) at System.Web.Http.ModelBinding.ModelBinderParameterBinding.ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) at System.Web.Http.Controllers.HttpActionBinding.<ExecuteBindingAsyncCore>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
</StackTrace>
</Error>
Just a quick update.
I have changed a few things, which have provided some new results.
First I have switched the AspNetJsonDeserializing attribute to HttpPost.
I have also switched the AspNetJsonDeserializing parameter ITestInstance instance attribute to [FromBody]
Obviously now, this if forcing me to call it via PostMan.
All of this has now removed the exception, but the instance is null. No breakpoints are hit on the ConcreteTestInstance constructors (I added another zero-parameter constructor to validate it both ways).
Here are the changes all together.
[System.Web.Http.HttpPost]
public JsonResult<string> AspNetJsonDeserializing([FromBody] ITestInstance instance)
{
ConcreteTestInstance myConcreteTestInstance = ((ConcreteTestInstance) instance);
return Json($"Uri:{myConcreteTestInstance._instanceUri}");
}
So short story, I am still on the hunt, for why instance is null
Another update.
I have got the code working now with a HttpPost. The problem was the json formatting :FACEPALM:
In PostMan I was using the format
{instance: {
"$type": "SimpleWebApi.Controllers.ConcreteTestInstance, SimpleWebApi",
"hostName": "google.com"
}}
When I removed the instance variable, it corrected the issue.
Also, I tested, and the [FromBody] attribute on the ITestInstance parameter, was irrelevant.
So the issue still remains as to how do I enable this functionality as an HttpGet.
At the moment, when I switch the attribute from HttpPost to HttpGet, I start recieving the exceptions mentioned in the first post.
I'm stuck on why this is is erroring out.
If i remove the div tag that holds the Comp Plan:, it works just fine.
<div id="tabs-1">
<form id="importForm">
<div id="required">
<div>
<label class="OptionLabel">Comp Plan:</label>
#*// TODO: suspect this next line is causing problems*#
#Html.DropDownListFor(model => model.CompPlanTypeId, (IEnumerable<SelectListItem>)ViewBag.CompPlanList)
</div>
<div>
<label class="OptionLabel">System:</label>
#Html.DropDownListFor(model => model.SystemId, (IEnumerable<SelectListItem>)ViewBag.SystemList)
</div>
<div>
<label class="OptionLabel">Month:</label>
#Html.DropDownListFor(model => model.Month, (SelectList)ViewBag.MonthList)
</div>
<div>
<label class="OptionLabel">Year:</label>
#Html.DropDownListFor(model => model.Year, (SelectList)ViewBag.YearList)
</div>
</div>
in here:
public ActionResult Index()
{
ViewBag.Title = Text.Import;
ViewBag.MonthList = MonthList;
ViewBag.YearList = YearList;
ViewBag.SystemList = GetSystemList();
ViewBag.CompPlanList = GetCompPlanList();
ViewBag.Message = "";
ViewBag.MessageType = "";
return View();
}
ViewBag.CompPlanList is set to 2 items. One containing a blank string, one containing a drop down value.
Here's the stack trace.
[InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'CompPlanTypeId'.]
System.Web.Mvc.Html.SelectExtensions.GetSelectData(HtmlHelper htmlHelper, String name) +392896
System.Web.Mvc.Html.SelectExtensions.SelectInternal(HtmlHelper htmlHelper, String optionLabel, String name, IEnumerable1 selectList, Boolean allowMultiple, IDictionary2 htmlAttributes) +137
System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper1 htmlHelper, Expression1 expression, IEnumerable1 selectList, String optionLabel, IDictionary2 htmlAttributes) +35
System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper1 htmlHelper, Expression1 expression, IEnumerable`1 selectList) +60
ASP._Page_Views_Import_Index_cshtml.Execute() in c:\WIP\CompensationAudit\src\WebLibrary\Views\Import\Index.cshtml:28
I am getting an error trying to move a DataSourceResult from one web service to another... the client calls web service A which resides on our web server. We then make a call to web service B which resides on our db server. The intent is that web service A adds certain sensitive data to the call, that we want hidden behind our firewall... then the call gets handled by web service B, gets a DataSourceResult, and seems to serialize it just fine... note I am using the same set of serilization properties to bot serialize and deserialize, I am just not showing the call to serilize here for brevity. When I go to deserialize this, I get a System.AggregateException - thrown on line "return formatter.ReadFromStreamAsync(typeof(T), stream, null, null).Result as T;" of my deserialization code... any ideas? anything would be much appreciated :)
Serilize code:
string Serialize<T>(MediaTypeFormatter formatter, T value)
{
// Create a dummy HTTP Content.
Stream stream = new MemoryStream();
var content = new StreamContent(stream);
/// Serialize the object.
formatter.WriteToStreamAsync(typeof(T), value, stream, content, null).Wait();
// Read the serialized string.
stream.Position = 0;
return content.ReadAsStringAsync().Result;
}
Deserialize code:
T Deserialize<T>(MediaTypeFormatter formatter, string str) where T : class
{
// Write the serialized string to a memory stream.
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(str);
writer.Flush();
stream.Position = 0;
// Deserialize to an object of type T
return formatter.ReadFromStreamAsync(typeof(T), stream, null, null).Result as T;
}
Json Object / settings being passed into methods:
var json = GlobalConfiguration.Configuration.Formatters.OfType<System.Net.Http.Formatting.JsonMediaTypeFormatter>().FirstOrDefault();
json.SerializerSettings.Formatting = Formatting.None;
json.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
json.SerializerSettings.NullValueHandling = NullValueHandling.Include;
json.UseDataContractJsonSerializer = false;
DataSourceResult result = Deserialize<DataSourceResult>(json, loansJson);
I have this string I try to deserialize and it throws this
error:
`System.AggregateException was unhandled by user code
HResult=-2146233088
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at Cavatica35.Web.Api.Controllers.RelationshipsGridController.Deserialize[T](MediaTypeFormatter formatter, String str) in c:\dev\Cavatica35\Code\MarginMaximizerInteractive\Cavatica35.Web\Api\Controllers\RelationshipsGridController.cs:line 54
at Cavatica35.Web.Api.Controllers.RelationshipsGridController.Get(RelationshipDataSourceRequest request) in c:\dev\Cavatica35\Code\MarginMaximizerInteractive\Cavatica35.Web\Api\Controllers\RelationshipsGridController.cs:line 96
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
InnerException: Newtonsoft.Json.JsonSerializationException
HResult=-2146233088
System.AggregateException was unhandled by user code
HResult=-2146233088
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at Cavatica35.Web.Api.Controllers.RelationshipsGridController.Deserialize[T](MediaTypeFormatter formatter, String str) in c:\dev\Cavatica35\Code\MarginMaximizerInteractive\Cavatica35.Web\Api\Controllers\RelationshipsGridController.cs:line 54
at Cavatica35.Web.Api.Controllers.RelationshipsGridController.Get(RelationshipDataSourceRequest request) in c:\dev\Cavatica35\Code\MarginMaximizerInteractive\Cavatica35.Web\Api\Controllers\RelationshipsGridController.cs:line 96
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
InnerException: Newtonsoft.Json.JsonSerializationException
HResult=-2146233088
Message=Error converting value "{"$id":"1","Data":[{"$id":"2","Relationship_loanOfficerName":"Deva MMi Admin","guidID":"c4327c4a-7aa5-4503-b738-59a9241a5a1c","name":"New Deva","briefDescription":null,"fullDescription":"","autoRenewLOC":0,"numOfLoans":1,"loanBalance":1000000.0,"numOfDeposits":0,"Relationship_depositbalance":0.0,"numOfOtherRels":0,"otherRelBalance":0.0,"targetROE":0.0,"yearsRemaining":5,"ownedBy":"21973a46-c06e-4ddc-8a94-05bb53c949e6","modBy":"00000000-0000-0000-0000-000000000000","createdBy":"00000000-0000-0000-0000-000000000000","modDate":"12/18/2014","createdDate":"1/1/0001","Relationship_netincome":16955.0,"Relationship_relationshiproe":26.48,"Relationship_avgbalance":1000000.0,"monthsUntilFirstRenewal":"1/1/0001","requiresReview":false,"deleted":false,"extIDList":"","overrideOfficer":false,"selected":false,"ni":16954.908394431,"niOverROE":64028.495587965743,"tag":""}],"Total":1,"AggregateResults":[{"$id":"3","Value":1,"Member":"name","FormattedValue":1,"ItemCount":0,"Caption":null,"FunctionName":"Count_name_28477829","AggregateMethodName":"Count"},{"$id":"4","Value":16955.0,"Member":"Relationship_netincome","FormattedValue":16955.0,"ItemCount":0,"Caption":null,"FunctionName":"Sum_Relationship_netincome_244267","AggregateMethodName":"Sum"},{"$id":"5","Value":26.48,"Member":"Relationship_relationshiproe","FormattedValue":26.48,"ItemCount":0,"Caption":null,"FunctionName":"Sum_Relationship_relationshiproe_8060817","AggregateMethodName":"Sum"},{"$id":"6","Value":1000000.0,"Member":"Relationship_avgbalance","FormattedValue":1000000.0,"ItemCount":0,"Caption":null,"FunctionName":"Sum_Relationship_avgbalance_64680392","AggregateMethodName":"Sum"},{"$id":"7","Value":1,"Member":"numOfLoans","FormattedValue":1,"ItemCount":0,"Caption":null,"FunctionName":"Sum_numOfLoans_54078176","AggregateMethodName":"Sum"},{"$id":"8","Value":1000000.0,"Member":"loanBalance","FormattedValue":1000000.0,"ItemCount":0,"Caption":null,"FunctionName":"Sum_loanBalance_39749352","AggregateMethodName":"Sum"},{"$id":"9","Value":0,"Member":"numOfDeposits","FormattedValue":0,"ItemCount":0,"Caption":null,"FunctionName":"Sum_numOfDeposits_36660208","AggregateMethodName":"Sum"},{"$id":"10","Value":0.0,"Member":"Relationship_depositbalance","FormattedValue":0.0,"ItemCount":0,"Caption":null,"FunctionName":"Sum_Relationship_depositbalance_1827337","AggregateMethodName":"Sum"},{"$id":"11","Value":16954.908394431,"Member":"ni","FormattedValue":16954.908394431,"ItemCount":0,"Caption":null,"FunctionName":"Sum_ni_60302147","AggregateMethodName":"Sum"},{"$id":"12","Value":64028.495587965743,"Member":"niOverROE","FormattedValue":64028.495587965743,"ItemCount":0,"Caption":null,"FunctionName":"Sum_niOverROE_43813805","AggregateMethodName":"Sum"}],"Errors":null}" to type 'Kendo.Mvc.UI.DataSourceResult'. Path '', line 1, position 3087.
Source=Newtonsoft.Json
StackTrace:
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)
at System.Net.Http.Formatting.JsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
InnerException: System.ArgumentException
HResult=-2147024809
Message=Could not cast or convert from System.String to Kendo.Mvc.UI.DataSourceResult.
Source=Newtonsoft.Json
StackTrace:
at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, Type initialType, Type targetType)
at Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, CultureInfo culture, Type targetType)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
InnerException: `
I'm working with mysql .net connector 6.4.4 at win7 x64 platform. While reading data from MySqlDataReader Object, it throws exception after 18th row. But in another application I could take 40 rows without errors.
The error is just here:
MySqlDataReader.Read()
Any helps would be very appreciated.
Exception details:
System.ArgumentOutOfRangeException was unhandled
Message=Non-negative number required.
Parameter name: count
Source=mscorlib
ParamName=count
StackTrace:
at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at MySql.Data.MySqlClient.MySqlPacket.Read(Byte[] byteBuffer, Int32 offset, Int32 count)
at MySql.Data.MySqlClient.MySqlPacket.ReadString(Int64 length)
at MySql.Data.Types.MySqlString.MySql.Data.Types.IMySqlValue.ReadValue(MySqlPacket packet, Int64 length, Boolean nullVal)
at MySql.Data.MySqlClient.NativeDriver.ReadColumnValue(Int32 index, MySqlField field, IMySqlValue valObject)
at MySql.Data.MySqlClient.Driver.ReadColumnValue(Int32 index, MySqlField field, IMySqlValue value)
at MySql.Data.MySqlClient.ResultSet.ReadColumnData(Boolean outputParms)
at MySql.Data.MySqlClient.ResultSet.NextRow(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlDataReader.Read()
at VeriTasima.Form1..ctor() in E:\Projeler\VeriTasima\VeriTasima\Form1.cs:line 42
at VeriTasima.Program.Main() in E:\Projeler\VeriTasima\VeriTasima\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Updated:
// test
string commandString = "SELECT * FROM haber LIMIT 50";
MySqlConnection connection = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString);
MySqlCommand command = new MySqlCommand(commandString, connection);
connection.Open();
MySqlDataReader sdr = command.ExecuteReader();
int count = 0;
while (sdr.Read())
{
count++;
}
sdr.Close();
sdr.Dispose();
command.Dispose();
connection.Close();
connection.Dispose();
MessageBox.Show(count.ToString());
Updated:
I fixed this problem by setting target platfrom from x86 to Any CPU. Now works properly.