Handling 'Sequence has no elements' exception dup - sql

I just finished my ASP.NET hospital management app, everything works fine, but if I try to add a doctor I get this error:
System.InvalidOperationException HResult=0x80131509
Message=Sequence contains no elements
Source=Hospital Management System
StackTrace:
at Hospital_Management_System.Controllers.DoctorController.Index(String message) in C:\Users\mouha\OneDrive\Bureau\Hospital Management System\Hospital Management System\Controllers\DoctorController.cs:line 37
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f()
The code:
public ActionResult Index(string message)
{
var date = DateTime.Now.Date;
ViewBag.Messege = message;
var user = User.Identity.GetUserId();
// The exception is being thrown here
var doctor = db.Doctors.Single(c => c.ApplicationUserId == user);
var model = new CollectionOfAll
{
Ambulances = db.Ambulances.ToList(),
Departments = db.Department.ToList(),
Doctors = db.Doctors.ToList(),
Patients = db.Patients.ToList(),
Medicines = db.Medicines.ToList(),
ActiveAppointments = db.Appointments.Where(c => c.DoctorId == doctor.Id).Where(c => c.Status).Where(c => c.AppointmentDate >= date).ToList(),
PendingAppointments = db.Appointments.Where(c => c.DoctorId == doctor.Id).Where(c => c.Status == false).Where(c => c.AppointmentDate >= date).ToList(),
AmbulanceDrivers = db.AmbulanceDrivers.ToList(),
Announcements = db.Announcements.Where(c => c.AnnouncementFor == "Doctor").ToList()
};
return View(model);
}

Related

Error uploading a document to SQL Server in .Net Core 3.1 Web API

I have a SQL Server stored procedure that is used for uploading a document and returns an ID upon success.
I am storing the parameter file_data into a byte[] type in the Customer_Document_ADD class.
public byte[] file_data { get; set; }
The following is my repository code.
public async Task<int> InsertCustomer_Document_ADDResult(Customer_Document_ADD customer_Document_ADDED)
{
await using(SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
// define SqlParameters for the other two params to be passed
var company_idParam = new SqlParameter("#company_id", customer_Document_ADDED.company_id);
var customer_idParam = new SqlParameter("#customer_id", customer_Document_ADDED.customer_id);
var customer_site_idParam = new SqlParameter("#customer_site_id", customer_Document_ADDED.customer_site_id);
var customer_system_idParam = new SqlParameter("#customer_system_id", customer_Document_ADDED.customer_system_id);
var job_idParam = new SqlParameter("#job_id", customer_Document_ADDED.job_id);
var security_levelParam = new SqlParameter("#security_level", customer_Document_ADDED.security_level);
var file_nameParam = new SqlParameter("#file_name", customer_Document_ADDED.file_name);
var file_sizeParam = new SqlParameter("#file_size", customer_Document_ADDED.file_size);
var upload_dateParam = new SqlParameter("#upload_date", customer_Document_ADDED.upload_date);
var document_extParam = new SqlParameter("#document_ext", customer_Document_ADDED.document_ext);
var user_codeParam = new SqlParameter("#user_code", customer_Document_ADDED.user_code);
var user_descriptionParam = new SqlParameter("#user_description", customer_Document_ADDED.user_description);
var reference1Param = new SqlParameter("#reference1", customer_Document_ADDED.reference1);
var reference2Param = new SqlParameter("#reference2", customer_Document_ADDED.reference2);
var reference3Param = new SqlParameter("#reference3", customer_Document_ADDED.reference3);
var reference4Param = new SqlParameter("#reference4", customer_Document_ADDED.reference4);
var file_dataParam = new SqlParameter("#file_data", customer_Document_ADDED.file_data);
//if (file_dataParam.Value == null)
//{
// file_dataParam.Value = "";
//}
file_dataParam.SqlDbType = SqlDbType.Image;
// define the output parameter that needs to be retained
// for the Id created when the Stored Procedure executes
// the INSERT command
var document_idParam = new SqlParameter("#document_id", SqlDbType.Int);
// the direction defines what kind of parameter we're passing
// it can be one of:
// Input
// Output
// InputOutput -- which does pass a value to Stored Procedure and retains a new state
document_idParam.Direction = ParameterDirection.Output;
// we can also use context.Database.ExecuteSqlCommand() or awaitable ExecuteSqlCommandAsync()
// which also produces the same result - but the method is now marked obselete
// so we use ExecuteSqlRawAsync() instead
// we're using the awaitable version since GetOrCreateUserAsync() method is marked async
await context.Database.ExecuteSqlRawAsync(
"EXECUTE [dbo].[Customer_Document_ADD_incentive] #company_id, #customer_id, #customer_site_id, #customer_system_id, #job_id, #security_level, #file_name, #file_size, #upload_date, #document_ext, #user_code, #user_description, #reference1, #reference2, #reference3, #reference4, #file_data, #document_id out",
company_idParam,
customer_idParam,
customer_site_idParam,
customer_system_idParam,
job_idParam,
security_levelParam,
file_nameParam,
file_sizeParam,
upload_dateParam,
document_extParam,
user_codeParam,
user_descriptionParam,
reference1Param,
reference2Param,
reference3Param,
reference4Param,
file_dataParam,
document_idParam);
// the userIdParam which represents the Output param
// now holds the Id of the new user and is an Object type
// so we convert it to an Integer and send
return Convert.ToInt32(document_idParam.Value);
}
}
I'm getting the following error in Postman.
Microsoft.Data.SqlClient.SqlException (0x80131904): The parameterized query '(#company_id int,#customer_id int,#customer_site_id int,#custome' expects the parameter '#file_data', which was not supplied.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at Microsoft.Data.SqlClient.SqlCommand.CompleteAsyncExecuteReader(Boolean isInternal, Boolean forDescribeParameterEncryption)
at Microsoft.Data.SqlClient.SqlCommand.InternalEndExecuteNonQuery(IAsyncResult asyncResult, Boolean isInternal, String endMethod)
at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryInternal(IAsyncResult asyncResult)
at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryAsync(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlRawAsync(DatabaseFacade databaseFacade, String sql, IEnumerable`1 parameters, CancellationToken cancellationToken)
at WebAPI.Repository.Customer_Document_ADDRepository.InsertCustomer_Document_ADDResult(Customer_Document_ADD customer_Document_ADDED) in C:\Users\CStith\source\code\project\WebAPI\WebAPI\Repository\Customer_Document_ADDRepository.cs:line 73
at WebAPI.Repository.Customer_Document_ADDRepository.InsertCustomer_Document_ADDResult(Customer_Document_ADD customer_Document_ADDED) in C:\Users\CStith\source\code\project\WebAPI\WebAPI\Repository\Customer_Document_ADDRepository.cs:line 97
at WebAPI.Controllers.Customer_Document_ADDController.InsertCustomer_Document_ADDResult(Customer_Document_ADD customer_Document_ADDED) in C:\Users\CStith\source\code\project\WebAPI\WebAPI\Controllers\Customer_Document_ADDController.cs:line 38
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
ClientConnectionId:e8f735f0-1ab5-4d53-9ead-01df3ee63c2e
Error Number:8178,State:1,Class:16
All other values are captured except the file. I am getting a null value in the debugger. Why am I unable to upload a file into the database? Thanks in advance.
Firstly,default model binding system cannot bind file to byte[] properties.If you want to bind file to btye[],you can use ByteArrayModelBinder,here is an official link.
Also,if you don't mind to change the type of file_data,you can use
public IFormFile file_data { get; set; }
and then you can convert it to byte[] type with MemoryStream.Here is an official link about upload files in .net core.

The translation of String.IndexOf to SQL does not support versions with a StringComparison argument occurs

i have build one predicate for filter grid view record filter :
public static IQueryable<T> FilterForColumn<T>(this IQueryable<T> queryable, string colName, string searchText)
{
if (colName != null && searchText != null)
{
var parameter = Expression.Parameter(typeof(T), "m");
var propertyExpression = Expression.Property(parameter, colName);
System.Linq.Expressions.ConstantExpression searchExpression = null;
System.Reflection.MethodInfo containsMethod = null;
// this must be of type Expression to accept different type of expressions
// i.e. BinaryExpression, MethodCallExpression, ...
System.Linq.Expressions.Expression body = null;
Expression ex1 = null;
Expression ex2 = null;
Expression converted = null;
propertyExpression = Expression.Property(parameter, colName);
searchExpression = Expression.Constant(searchText);
containsMethod = typeof(string).GetMethod("IndexOf", new[] { typeof(string), typeof(StringComparison) });
ConstantExpression compareExpression = Expression.Constant(StringComparison.OrdinalIgnoreCase);
ex1 = Expression.Call(propertyExpression, containsMethod, searchExpression, compareExpression);
body = Expression.NotEqual(ex1, Expression.Constant(-1));
var predicate = Expression.Lambda<Func<T, bool>>(body, new[] { parameter });
return queryable.Where(predicate);
}
}
this not working with this queries :
post = db.Posts.Where(p => (p.ToUser_id.Equals(user_id) || p.ToUser_id.Equals(null)) && p.User_id != user_id).OrderByDescending(p => p.Sent_Datetime).Select(p => new
{
Id = p.Id,
Title = p.Title,
Publisher = db.Users.Where(u => u.Id.Equals(p.User_id)).Select(u => u.First_name + ' ' + u.Last_name).FirstOrDefault(),
ToUser = db.Users.Where(u => u.Id.Equals(p.ToUser_id)).Select(u => u.First_name + ' ' + u.Last_name).FirstOrDefault(),
PublishDate = p.Sent_Datetime,
IsFile = p.IsFileAttached,
CategoryName = db.Categories.Where(c => c.Id.Equals(p.Category_id)).Select(c => c.Category_name).FirstOrDefault(),
status_name = db.Status.Where(s => s.Id.Equals(p.status_id)).Select(s => s.status_name).FirstOrDefault(),
Group_name = db.Groups.Where(g => g.Id.Equals(p.group_id)).Select(g => g.Group_name).FirstOrDefault(),
FileSize = p.TotalFileSize
}).FilterForColumn(ColumnName, SearchText).ToList();
i have found this error like :
The translation of String.IndexOf to SQL does not support versions with a StringComparison argument.
what this error saying i don't understand....
Update
as per comment suggested i modify my code :
default:
searchExpression = Expression.Constant(searchText);
containsMethod = typeof(string).GetMethod("SqlMethods.Like", new[] { typeof(string) });
body = Expression.Call(propertyExpression, containsMethod, searchExpression);
break;
but now it's give me error like :
Value cannot be null.
Parameter name: method
Update
i have found new error like :
Server Error in '/CRM' Application.
Static method requires null instance, non-static method requires non-null instance.
Parameter name: instance
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.ArgumentException: Static method requires null instance, non-static method requires non-null instance.
Parameter name: instance
Source Error:
Line 75: searchExpression = Expression.Constant(searchText);
Line 76: containsMethod = typeof(System.Data.Linq.SqlClient.SqlMethods).GetMethod("Like", new[] { typeof(string), typeof(string) });
Line 77: body = Expression.Call(propertyExpression, containsMethod, searchExpression);
Line 78: break;
Line 79: }
Source File: f:\CRM\App_Code\Helper.cs Line: 77
Stack Trace:
[ArgumentException: Static method requires null instance, non-static method requires non-null instance.
Parameter name: instance]
System.Linq.Expressions.Expression.ValidateStaticOrInstanceMethod(Expression instance, MethodInfo method) +4189320
System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments) +55
System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, Expression[] arguments) +29
Helper.FilterForColumn(IQueryable`1 queryable, String colName, String searchText) in f:\CRM\App_Code\Helper.cs:77
Staff_Raise_Ticket.FillGrid(String StartAlpha, Int32 GroupByENTYPE, String ColumnName, String SearchText) in f:\CRM\Staff\Raise_Ticket.aspx.cs:625
Staff_Raise_Ticket.btnsearch_Click(Object sender, EventArgs e) in f:\CRM\Staff\Raise_Ticket.aspx.cs:1918
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +176
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1

Operation is not valid due to the current state of the object.( SPWebApplication.Update)

I get this error when trying to add user policy whithin sharepoint 2010 web application programmatically:
Operation is not valid due to the current state of the object.
Here's a code sample:
public Boolean AddUser(SoftwareUser user)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (site = new SPSite(siteUrl))
{
using (web = site.RootWeb)
{
web.AllowUnsafeUpdates = true;
SPUser spUser = web.EnsureUser(user.UserShortname);
web.Groups["MySolution Members"].AddUser(spUser);
if (spUser != null)
{
if (user.Email != null)
{
spUser.Email = user.Email;
}
spUser.Update();
SPWebApplication webApp = site.WebApplication;
SPPolicy policy = webApp.Policies.Add(spUser.Name, "deny");
policy.PolicyRoleBindings.Add(webApp.PolicyRoles["deny"]);
webApp.Update();
}
web.AllowUnsafeUpdates = false;
}
}
});
return true;
}
Thank you in advance.
Find below the stacktrace:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
System.InvalidOperationException: Operation is not valid due to the current state of the object.
at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context)
at Microsoft.SharePoint.Utilities.SPUtility.ValidateFormDigest()
at Microsoft.SharePoint.Administration.SPPersistedObject.BaseUpdate()
at Microsoft.SharePoint.Administration.SPWebApplication.Update()
at WcfServices.WFService.<>c__DisplayClass2c.<AddUser>b__2b() in C:\SourceCode\DEV-_V5.2.5\WCFServices\SP2010\WcfServices\WcfServices\WFService.svc.cs:line 980
at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.<RunWithElevatedPrivileges>b__2()
at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)
at WcfServices.WFService.AddUser(SoftwareUser user) in C:\SourceCode\DEV-_V5.2.5\WCFServices\SP2010\WcfServices\WcfServices\WFService.svc.cs:line 959
at SyncInvokeAddUser(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
Do NOT call .Update() inside Evelvated Permission’s delegate
Just do it below SPSecurity.RunWithElevatedPrivileges

Error in creating a dynamic jqGrid , ASP.net MVC 4

First, I would like to tell that i am new on the .net development (MVC 4)
and I am trying to follow this tutorial with entity framework 5 but I keep getting this error " exception of type 'System.NullReferenceException' occurred in jqGridMVC2.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
, even though i tried to cheeck the value for null before.
if(propInfo.GetValue(this, null) != null) {
}
private static object GetPropertyValue(object obj, string property)
{
System.Reflection.PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
// if (obj != null)
// if (propertyInfo.GetValue(obj, null) != null)
return propertyInfo.GetValue(obj, null);
// return 0;
}
at jqGridMVC2.Extensions.GridExtension.GetPropertyValue(Object obj, String property) in c:\Users\aal\Documents\Visual Studio 2013\Projects\jqGridMVC2\jqGridMVC2\Extensions\Grid\GridExtension.cs:line 70
at jqGridMVC2.Extensions.GridExtension.<>c__DisplayClass4`1.<AsJqGridResult>b__2(T item) in c:\Users\aal\Documents\Visual Studio 2013\Projects\jqGridMVC2\jqGridMVC2\Extensions\Grid\GridExtension.cs:line 38
at System.Linq.EnumerableSorter`2.ComputeKeys(TElement[] elements, Int32 count)
at System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count)
at System.Linq.OrderedEnumerable`1.<GetEnumerator>d__0.MoveNext()
at System.Linq.Enumerable.<SkipIterator>d__4d`1.MoveNext()
at System.Linq.Enumerable.<TakeIterator>d__3a`1.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at jqGridMVC2.Extensions.GridExtension.AsJqGridResult[T](IQueryable`1 source, String column, String sortOrder, Int32 page, Int32 pageSize) in c:\Users\aal\Documents\Visual Studio 2013\Projects\jqGridMVC2\jqGridMVC2\Extensions\Grid\GridExtension.cs:line 41
at jqGridMVC2.Controllers.HomeController.DynamicGridData(String sidx, String sord, Int32 page, Int32 rows) in c:\Users\aal\Documents\Visual Studio 2013\Projects\jqGridMVC2\jqGridMVC2\Controllers\HomeController.cs:line 30
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
Please help me in solving this problem
Thank you in advance.
I just solve the error by this
private static object GetPropertyValue(object obj, string property)
{
foreach (var property1 in obj.GetType().GetProperties()) {
return property1.GetValue(obj, null); //throws exception TargetParameterCountException for String type
}
return 0;
}

MonoTouch Parameter Array Length does not match the number of message body parts exception

I am writing a MonoTouch app for iPhone and i am getting the following exception when calling a WCF web service.
Parameter array length does not match the number of message body parts at System.ServiceModel.Dispatcher.WebMessageFormatter+WebClientMessageFormatter.SerializeRequest (System.ServiceModel.Channels.MessageVersion messageVersion, System.Object[] parameters) [0x0003e] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/WebMessageFormatter.cs:310
at System.ServiceModel.Description.WebHttpBehavior+ClientPairFormatter.SerializeRequest (System.ServiceModel.Channels.MessageVersion messageVersion, System.Object[] parameters) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/WebHttpBehavior.cs:142
at System.ServiceModel.MonoInternal.ClientRuntimeChannel.CreateRequest (System.ServiceModel.Dispatcher.ClientOperation op, System.Object[] parameters) [0x0001e] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:611
at System.ServiceModel.MonoInternal.ClientRuntimeChannel.Request (System.ServiceModel.Description.OperationDescription od, System.Object[] parameters) [0x0002d] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:512
at System.ServiceModel.MonoInternal.ClientRuntimeChannel.DoProcess (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters) [0x00038] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:482
at System.ServiceModel.MonoInternal.ClientRuntimeChannel.Process (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:462
I am calling the service with the following methods (Some namespaces have been removed for readability):
public void Begin ()
{
try
{
WebHttpBinding bnd = new WebHttpBinding (WebHttpSecurityMode.Transport);
bnd.MaxBufferSize=2147483647;
bnd.MaxReceivedMessageSize=2147483647;
EndpointAddress addr = new EndpointAddress (new Uri(this.Url));
ServiceClient service = new ServiceClient (bnd, addr);
service.Endpoint.Behaviors.Add(new WebHttpBehavior());
Login login = new Login()
{
InstitutionId=this.InstitutionNumber.ToString ("D4"),
CompanyNumber = (int)this.CompanyId,
Password = this.Password,
UserName = this.Username
};
LoginRequest loginRequest = new LoginRequest{} (GetClientLoginData(), login);
service.LoginCompleted += HandleServiceLoginCompleted;
service.LoginAsync(loginRequest);
}
catch (Exception e)
{
if(failed != null)
{
failed(new ErrorInformation(e));
}
}
}
void HandleServiceLoginCompleted (object sender, LoginCompletedEventArgs e)
{
if(e.Cancelled)
{
if (failed != null)
{
failed (new ErrorInformation ("Request was cancelled"));
}
}
else if(e.Error != null)
{
if (failed != null)
{
failed (new ErrorInformation (e.Error));
}
}
else
{
ServiceClient service = sender as ServiceClient;
LoginResponse response = e.Result;
if (response.LoginResult)
{
if (success != null)
success ();
}
else
{
if (failed != null)
failed (new ErrorInformation (response.errmsg));
}
}
}
When I run this e.Error in HandleServiceLoginCompleted is not null (it is the above exception). I ran wireshark and no packets are sent to the server at all. The service works correctly when called by other means (such as ASP.NET web pages.) I generated the service reference using silverlight's slsvcutil.exe.
Set bnd.ReaderQuotas.MaxArrayLength = int.MaxValue
There are also some other limits that you can increase in ReaderQuotas.