MySqlDataReader.Read() throws ArgumentOutOfRangeException - mysql

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.

Related

SciChart 3.1 exception

A bit of a long-shot given that I'm using such an old version (3.1.0.4759). Users have recently started reporting the exception below when zooming on one of my application's charts. It's a bit of a pain as it can't be handled, so the whole app crashes.
It's very, very intermittent, and I've not been able to repro. The chart series does get cleared down and repopulated once a second, so the intermittent nature could be explained by (say) zooming at that specific moment in time. Having said this, I have a lot of charts throughout my app, many of which are continuously plotting, and all using the same chart modifiers, but have never noticed this problem before.
Just wondering if any of the ABT guys can shed any light on this! TIA.
System.NullReferenceException: Object reference not set to an instance of an object.
at Abt.Controls.SciChart.RangeFactory.NewWithMinMax(IRange originalRange, IComparable min, IComparable max)
at Abt.Controls.SciChart.Wpf.PcitureHelper.Zoom(IRange initialRange, Double fromCoord, Double toCoord)
at Abt.Controls.SciChart.ChartModifiers.RubberBandXyZoomModifier.UpdateOutline(IAxis firstFont, Double currentValues, Double currentId)
at Abt.Controls.SciChart.ChartModifiers.RubberBandXyZoomModifier.UpdateOutline(IAxis firstFont, Rect currentValues)
at Abt.Controls.SciChart.ChartModifiers.RubberBandXyZoomModifier.OpenDatabase(Point firstFont, Point currentValues)
at Abt.Controls.SciChart.ChartModifiers.RubberBandXyZoomModifier.OnModifierMouseUp(ModifierMouseArgs e)
at Abt.Controls.SciChart.ChartModifiers.ModifierGroup.UpdateOutline(Action2 firstFont, ModifierEventArgsBase currentValues)
at Abt.Controls.SciChart.Common.Extensions.EnumerableExtensions.CopyBuilder[firstFont](IEnumerable`1 firstFont, Action1 currentValues)
at Abt.Controls.SciChart.Utility.Mouse.MouseManager.QueueInvoker.JoinControl(Object firstFont, MouseButtonEventArgs currentValues)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
It looks like you got a NullReferenceException inside RangeFactory.NewWithMinMax
and also looks like you've customised the source-code, as the methods
at Abt.Controls.SciChart.Wpf.PcitureHelper.Zoom(IRange initialRange, Double fromCoord, Double toCoord)
at Abt.Controls.SciChart.ChartModifiers.RubberBandXyZoomModifier.UpdateOutline(IAxis firstFont, Double currentValues, Double currentId)
at Abt.Controls.SciChart.ChartModifiers.RubberBandXyZoomModifier.UpdateOutline(IAxis firstFont, Rect currentValues).
at Abt.Controls.SciChart.ChartModifiers.RubberBandXyZoomModifier.OpenDatabase
are not part of the SciChart codebase.
So I'd guess that the problem lies in those methods passing invalid values to RangeFactory.
BTW the SciChart team would also tell you that v3 is pretty out of date and to ensure stability, to get up to date. That and if you get problems like this in an old version, especially in customised source-code, they can't help!

MySqlException: Fatal error encountered during command execution . Asp.net Core

When trying to register a new user in the project, an error is occurring on these lines:
WebApplication3.MyClass.ConDB.GetData(string _sqlCommand) in ConDB.cs:
adapter.Fill(dt);
AND
WebApplication3.Controllers.AccountController.Register(
string username, string phone, string email,
string password, string confirmPassword)
in AccountController.cs:
DataTable dt = conDB.GetData($"INSERT INTO
`user`(`Email`, `UserName`, `Phone`, `Password`, `ProfilePath`) VALUES
('{email}','{username}','{phone}','{encode_password}', '{userDataPath}');");
This is the error:
An unhandled exception occurred while processing the request.
EndOfStreamException: Attempted to read past the end of the stream.
MySql.Data.MySqlClient.MySqlStream.ReadFully(Stream stream, byte[] buffer, int offset, int count)
MySqlException: Reading from the stream has failed.
MySql.Data.MySqlClient.MySqlStream.LoadPacket()
MySqlException: Fatal error encountered attempting to read the resultset.
MySql.Data.MySqlClient.MySqlDataReader.NextResult()
MySqlException: Fatal error encountered during command execution.
MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
EndOfStreamException: Attempted to read past the end of the stream.
MySql.Data.MySqlClient.MySqlStream.ReadFully(Stream stream, byte[] buffer, int offset, int count)
MySql.Data.MySqlClient.MySqlStream.LoadPacket()
This is the code:
WebApplication3.MyClass.ConDB.GetData(string _sqlCommand) in ConDB.cs
public DataTable GetData(string _sqlCommand)
{
MySqlCommand command = new MySqlCommand(_sqlCommand, myConnection);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
public void ExecuteQuery(string _sqlCommand)
{
MySqlCommand command = new MySqlCommand("", myConnection);
WebApplication3.Controllers.AccountController.Register(string username, string phone, string email, string password, string confirmPassword) in AccountController.cs
string userDataPath = profile_path + email.Split('#')[0] + "_" + email.Split('#')[1].Split('.')[0];
Helper.DirectoryCopy(default_profile_path, userDataPath, true);
initDriver(userDataPath);
driver.Navigate().GoToUrl(homeURL);
DataTable dt = conDB.GetData($"INSERT INTO `user`(`Email`, `UserName`, `Phone`, `Password`, `ProfilePath`) VALUES ('{email}','{username}','{phone}','{encode_password}', '{userDataPath}');");
HttpContext.Session.SetString("login", "1");
HttpContext.Session.SetString("email", email);
return RedirectToAction("Index", "Home");
}
else
Can anyone help me in this problem?
Use ExecuteNonQuery() instead because you are not looking for a datatable in return while inserting a record. ExecuteNonQuery() would return you the number of rows affected.
It is possible to achieve the same using MySqlDataAdapter, but for inserting one record it is not worth the effort
Reference: https://dev.mysql.com/doc/dev/connector-net/8.0/html/M_MySql_Data_MySqlClient_MySqlCommand_ExecuteNonQuery.htm

i'm trying to update data in Access

when I use this
con.Open();
OleDbCommand conup = new OleDbCommand(#"UPDATE [user1],
SET name = '" + textBox1.Text + "' , password ='" + textBox2.Text + "', <br>remember ='" + remember + "' WHERE (name='" + textBox1.Text + "')", con);
conup.ExecuteNonQuery();
con.Close();
it shows me an exception
System.Data.OleDb.OleDbException was unhandled,
HResult=-2147217900
Message=Syntax error in UPDATE statement.
Source=Microsoft Office Access Database Engine
ErrorCode=-2147217900
StackTrace:
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at Sober_TAILORING.login.button1_Click(Object sender, EventArgs e) in E:\Desktop\vs project\Sober TAILORING\Sober TAILORING\login.cs:line 86
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Sober_TAILORING.Program.Main() in E:\Desktop\vs project\Sober TAILORING\Sober TAILORING\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.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
And password is reserved word in Access, and it makes no sense to update name, thus:
OleDbCommand conup = new OleDbCommand(#"UPDATE [user1] SET [password] = '" + textBox2.Text + "', remember = '" + remember + "' WHERE ([name] = '" + textBox1.Text + "')", con);

Json deserialize error AggregateException c#

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: `

WinForms ReportViewer cannot connecto to remote Report Server (SQL Express)

Introduction:
I have SQL Server Express 2008 R2 installed with Advanced Services. I have created few reports using BI Design Studio and deployed them to the Server. If I access the reporting server using IE (http://Ser2008/Reports/) it works fine (I have to put in User Name/Password). I can view reports or fool around with the settings.
Problem:
On my local machine I created a winforms application with one form containing a ReportViewer control. On form load I'm running following code:
reportViewer1.ProcessingMode = ProcessingMode.Remote;
reportViewer1.ServerReport.ReportServerCredentials.NetworkCredentials =
new CustomCredentials("secret#123") {
UserName = "administrator",
Domain = "ser2008"
}.NetworkCredentials;
reportViewer1.ServerReport.ReportServerUrl = new Uri("http://ser2008/Reports/");
reportViewer1.ServerReport.ReportPath = "/Students/Attendance";
var l = new List<ReportParameter>();
l.Add(CreateParameter("UserId", "144"));
l.Add(CreateParameter("Class", "8"));
l.Add(CreateParameter("date_from", "2011-09-04"));
l.Add(CreateParameter("date_to", "2011-12-31"));
reportViewer1.ServerReport.SetParameters(l); //EXCEPTION THROWN HERE
reportViewer1.RefreshReport();
I get following exception:
The attempt to connect to the report server failed. Check your connection
information and that the report server is a compatible version. The request
failed with HTTP status 404: Not Found.
The stack trace is as follows:
at Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005
.Execution.RSExecutionConnection.MissingEndpointException
.ThrowIfEndpointMissing(WebException e)
at Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005
.Execution.RSExecutionConnection.ProxyMethodInvocation.Execute[TReturn]
(RSExecutionConnection connection, ProxyMethod`1 initialMethod, ProxyMethod`1 retryMethod)
at Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.
Execution.RSExecutionConnection.LogonUser(String userName, String password, String authority)
at Microsoft.Reporting.WinForms.ServerReport.get_Service()
at Microsoft.Reporting.WinForms.ServerReport.EnsureExecutionSession()
at Microsoft.Reporting.WinForms.ServerReport.SetParameters(IEnumerable`1 parameters)
at GridEditor.ReportViewerForm.btnRefresh_Click(Object sender, EventArgs e)
in D:\TestApp\ReportViewerForm.cs:line 79
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager
.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at GridEditor.Program.Main() in D:\TestApp\Program.cs:line 16
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()
CustomCredentials:
public class CustomCredentials : IReportServerCredentials
{
public string UserName { get; set; }
public SecureString Password { get; set; }
public string Domain { get; set; }
#region ctor
public CustomCredentials(string password)
{
Password = new SecureString();
foreach (char c in password.ToCharArray())
Password.AppendChar(c);
}
#endregion
#region IReportServerCredentials Members
public bool GetFormsCredentials(out Cookie authCookie, out string userName
, out string password, out string authority)
{
throw new NotImplementedException();
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get { throw new NotImplementedException(); }
}
public System.Net.ICredentials NetworkCredentials
{
get { return new NetworkCredential(UserName, Password, Domain); }
}
#endregion
}
UPDATE:
I have found following exception also in some place in my log file:
System.Web.Services.Protocols.SoapException: The path of the item
'/Students/Attendance/_vti_bin/ListData.svc/$metadata' is not valid. The full
path must be less than 260 characters long; other restrictions apply. If the
report server is in native mode, the path must start with slash. --->
Microsoft.ReportingServices.Diagnostics.Utilities.InvalidItemPathException:
The path of the item '/Students/Attendance/_vti_bin/ListData.svc/$metadata' is
not valid. The full path must be less than 260 characters long; other
restrictions apply. If the report server is in native mode, the path must
start with slash.
at Microsoft.ReportingServices.WebServer.ReportingService2005Impl
.GetPermissions(String Item, String[]& Permissions)
In the end it was all trivial detail 8-)
I was using Report Manager url (http://ser2008/Reports/) where I was to use Report Server url (http://ser2008/ReportServerXp/).
Well, you should implement IReportServerCredential, and code example as follow :
public class CustomReportCredentials : Microsoft.Reporting.WebForms.IReportServerCredentials
{
// local variable for network credential.
private string _UserName;
private string _PassWord;
private string _DomainName;
public CustomReportCredentials(string UserName, string PassWord, string DomainName)
{
_UserName = UserName;
_PassWord = PassWord;
_DomainName = DomainName;
}
public WindowsIdentity ImpersonationUser
{
get
{
return null; // not use ImpersonationUser
}
}
public ICredentials NetworkCredentials
{
get
{
// use NetworkCredentials
return new NetworkCredential(_UserName,_PassWord,_DomainName);
}
}
public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
{
// not use FormsCredentials unless you have implements a custom autentication.
authCookie = null;
user = password = authority = null;
return false;
}
}
then use this as follows:
IReportServerCredentials irsc = new CustomReportCredentials(userid,password, domain);
ReportViewer1.ServerReport.ReportServerCredentials = irsc;
the other code to set ServerReport property omit. hope you have a good day.