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

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

Related

Handling 'Sequence has no elements' exception dup

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);
}

ArgumentException While connecting win phone 8.1 to wcf

While building win phone 8.1 Silverlight,
Added service reference to WCF, some method for reference:
[OperationContract]
Task<GetPlayListResponse> GetPlayList(GetPlayListRequest request);
And using it like this:
private void Button_Click(object sender, RoutedEventArgs e)
{
var service = new MediaServiceClient();
service.GetPlayListCompleted += service_GetPlayListCompleted;
GetPlayListRequest request = new GetPlayListRequest { BusinessId = 41 };
service.GetPlayListAsync(request);
}
void service_GetPlayListCompleted(object sender, MediaService.GetPlayListCompletedEventArgs e)
{
var response = e.Result;
if (response.Result.ResultCode == eRequestResultCode.Success)
{
lb_RequestList.ItemsSource = response.Songs;
}
}
Getting the following error message:
[System.ArgumentException] {System.ArgumentException: Value does not fall within the expected range. at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState) at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)} System.ArgumentException
The exception is accruing here :
public WinPhone.Silverlight_Client.MediaService.GetPlayListResponse EndGetPlayList(System.IAsyncResult result) {
object[] _args = new object[0];
WinPhone.Silverlight_Client.MediaService.GetPlayListResponse _result = ((WinPhone.Silverlight_Client.MediaService.GetPlayListResponse)(base.EndInvoke("GetPlayList", _args, result)));
return _result;
}

System.ServiceModel.FaultException - The process cannot access the file 'xxx' because it is being used by another process

I have a webservice WCF which log requests at the end of the process :
public void xxxxx(string sXmlIn, out string sXmlOut)
{
[...]
// log
log.PrintDatas = bPrintDatas;
log.sXmlIn = sXmlIn;
log.sXmlOut = sXmlOut;
log.error = error;
log.toFile();
}
Here is my Log class :
public class LogFile
{
public String sXmlIn;
public String sXmlOut;
public Error error;
private bool bPrintDatas;
public bool PrintDatas
{
set { bPrintDatas = value; }
}
private bool bInitWs;
public bool InitWs
{
get { return bInitWs; }
set { bInitWs = value; }
}
private string sMethodName;
public string MethodName
{
get { return sMethodName; }
set { sMethodName = value; }
}
private bool bCallWs;
public bool CallWs
{
get { return bCallWs; }
set { bCallWs = value; }
}
private DateTime dtDebutSession;
private DateTime dtEndSession;
private DateTime dtDebutWS;
private DateTime dtEndWS;
public void startWScall()
{
dtDebutWS = DateTime.Now;
}
public void stopWScall()
{
dtEndWS = DateTime.Now;
}
public LogFile()
{
dtDebutSession = DateTime.Now;
}
public void toFile()
{
dtEndSession = DateTime.Now;
Uri pathUri = new Uri(Path.GetDirectoryName(Assembly.GetAssembly(typeof(xxxxx)).CodeBase));
string path = pathUri.AbsolutePath + "/logs/";
path = System.Web.HttpUtility.UrlDecode(path);
System.IO.Directory.CreateDirectory(path);
string name = DateTime.Now.ToString("yyyyMMdd") + ".txt";
// create a StreamWriter and open the file
StreamWriter logFile = new StreamWriter(path + name, true, System.Text.Encoding.GetEncoding("iso-8859-1"));
logFile.Write(ToString());
logFile.Close();
}
override
public String ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Session begin : " + dtDebutSession);
sb.AppendLine("Method : " + sMethodName);
sb.AppendLine("Init WS : " + bInitWs);
sb.AppendLine("Calling WS : " + bCallWs);
sb.AppendLine("Callins WS Duration : " + (dtEndWS - dtDebutWS).TotalSeconds);
sb.AppendLine("Duration : " + (dtEndSession - dtDebutSession).TotalSeconds);
sb.AppendLine("Session end : " + dtEndSession);
sb.AppendLine("Result : " + Enum.GetName(typeof(ErrorCodes), error.RC));
if (error.RC != ErrorCodes.OK)
{
sb.AppendLine("Exception Name : " + error.ExceptionType);
sb.AppendLine("Exception Message : " + error.ErrorMsg);
}
if (error.RC != ErrorCodes.OK || bPrintDatas == true)
{
sb.AppendLine("--------------------");
sb.AppendLine(sXmlIn);
sb.AppendLine("--------------------");
sb.AppendLine(sXmlOut);
}
sb.AppendLine("----------------------------------------");
return sb.ToString();
}
public void toXML()
{
}
}
The problem is, sometimes (I can't redo the problem), an exception appears :
Date : 11/02/2014 20:19:49
Exception :
System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]
- The process cannot access the file 'C:\xxx\xxxt\xxx\bin\logs\20140211.txt' because it is being
used by another process.
Stack Trace : Server stack trace: at
System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message
reply, MessageFault fault, String action, MessageVersion version,
FaultConverter faultConverter) at
System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime
operation, ProxyRpc& rpc) at
System.ServiceModel.Channels.ServiceChannel.Call(String action,
Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
Object[] outs, TimeSpan timeout) at
System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
methodCall, ProxyOperationRuntime operation) at
System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
message) Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg) at
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type) at xxxxxxxx at xxxxxxxx in
c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
Files\root\24b8742a\5648f098\App_WebReferences.b9kkgfpv.0.cs:line 811
at xxxxxxxx in xxxxxxxx\tools.cs:line 547 at xxxxxxxx() in
xxxxxxxx.cs:line 48 at xxxxxxxx.Page_Load(Object sender, EventArgs e)
in xxxxxxxx.aspx.cs:line 41 at
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object
o, Object t, EventArgs e) at System.Web.UI.Control.LoadRecursive() at
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
I don't understand why because WCF manage concurrency between each instance of WCF entry.
EDIT :
This is the code with the Mutex added in LogFile class
private readonly Mutex mutex = new Mutex();
[...]
mutex.WaitOne();
StreamWriter logFile = new StreamWriter(path + name, true, System.Text.Encoding.GetEncoding("iso-8859-1"));
logFile.Write(ToString());
logFile.Close();
mutex.ReleaseMutex();
At first you should wrap your mutex usage in a try finally block
private readonly Mutex mutex = new Mutex();
[...]
try
{
mutex.WaitOne();
StreamWriter logFile = new StreamWriter(path + name, true, System.Text.Encoding.GetEncoding("iso-8859-1"));
logFile.Write(ToString());
logFile.Close();
}
catch(Exception e)
{
// trace your exception somewhere useful here!
throw;
}
finally
{
mutex.ReleaseMutex();
}
You are also using the Mutex wrong, have a look at the very good example here:
What is a good pattern for using a Global Mutex in C#?

Conversion to Parallel/TPL for this Async code

I'm wondering as to how I'd go aroung converting this Begin-End-Async approach to the newer TPL syntax:
public override IAsyncResult BeginRegisterClaimant(ClaimantSex claimantSex, AgeGroup ageGroup, AsyncCallback callback, object state)
{
AsyncResult<string> asyncResult = new AsyncResult<string>(callback, state);
InitManagementProxy();
m_management.RegisterClaimantCompleted += RegisterClaimantCallbackInternal;
m_management.RegisterClaimantAsync(m_configurationID, (PowWow.Service.ClaimantSex)claimantSex, (PowWow.Service.AgeGroup)ageGroup, new object[]
{ this, asyncResult
});
return asyncResult;
}
public override string EndRegisterClaimant(IAsyncResult asyncResult)
{
if (!(asyncResult is AsyncResult<string>))
{
throw new Exception("Invalid IAsyncResult object");
}
return ((AsyncResult<string>)asyncResult).Close();
}
private void InitManagementProxy()
{
WSHttpBinding binding;
if (m_management != null)
{
return;
}
binding = new WSHttpBinding(SecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
m_management = new PowWow.Service.VerifierContractClient(binding, new EndpointAddress(m_managementUri));
m_management.ClientCredentials.UserName.UserName = m_userName;
m_management.ClientCredentials.UserName.Password = m_password;
}
private static void RegisterClaimantCallbackInternal(object senderObject, PowWow.Service.RegisterClaimantCompletedEventArgs eventArgs)
{
PowWowVerifier powWowVerifier = (PowWowVerifier)((Object[])eventArgs.UserState)[0];
powWowVerifier.m_management.RegisterClaimantCompleted -= RegisterClaimantCallbackInternal;
powWowVerifier.m_management.Close();
powWowVerifier.m_management = null;
if (eventArgs.Error != null)
{
((AsyncResult<string>)((Object[])eventArgs.UserState)[1]).OnException(eventArgs.Error);
}
else
{
((AsyncResult<string>)((Object[])eventArgs.UserState)[1]).OnExecuted(eventArgs.Result);
}
}
Thanks!
EDIT
ATM, cancellation is not required. Progress reporting maybe required but not a priority.
The simplest way would be to wrap your existing code in a TaskCompletionSource and return it's Task - this will then fit in with the new async/await model coming in C# 5

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.