GetLoginResultAsync send wrong message to client - aspnetboilerplate

it seems that AccountController (ABP 2.3 standard template version) send wrong message to client browser for instance when:
User type wrong credential ;
Username doesn't exist ;
User market as "inactive" ;
switch (loginResult.Result)
{
case AbpLoginResultType.Success:
return loginResult;
default:
throw CreateExceptionForFailedLoginAttempt(loginResult.Result, usernameOrEmailAddress, tenancyName);
}
For instance, CreateExceptionForFailedLoginAttempt return UserFriendlyException exception when AbpLoginResultType.UserIsNotActive is true (user inactive) but the client recieve a generic "An error has occurred! - Error detail not sent by server" message instead the "friendly message"
private Exception CreateExceptionForFailedLoginAttempt(AbpLoginResultType result, string usernameOrEmailAddress, string tenancyName)
{
switch (result)
{
case AbpLoginResultType.Success:
return new ApplicationException("Don't call this method with a success result!");
case AbpLoginResultType.InvalidUserNameOrEmailAddress:
// Wrong Username/password
return new UserFriendlyException(L("LoginFailed"), L("UnknownUser"));
case AbpLoginResultType.InvalidPassword:
return new UserFriendlyException(L("LoginFailed"), L("InvalidUserNameOrPassword"));
case AbpLoginResultType.InvalidTenancyName:
return new UserFriendlyException(L("LoginFailed"), L("ThereIsNoTenantDefinedWithName{0}", tenancyName));
case AbpLoginResultType.TenantIsNotActive:
return new UserFriendlyException(L("LoginFailed"), L("TenantIsNotActive", tenancyName));
case AbpLoginResultType.UserIsNotActive:
return new UserFriendlyException(L("LoginFailed"), L("UserIsNotActiveAndCanNotLogin", usernameOrEmailAddress));
case AbpLoginResultType.UserEmailIsNotConfirmed:
return new UserFriendlyException(L("LoginFailed"), "UserEmailIsNotConfirmedAndCanNotLogin");
case AbpLoginResultType.LockedOut:
return new UserFriendlyException(L("LoginFailed"), L("UserLockedOutMessage"));
default: //Can not fall to default actually. But other result types can be added in the future and we may forget to handle it
Logger.Warn("Unhandled login fail reason: " + result);
return new UserFriendlyException(L("LoginFailed"));
}
}
i take a look at Log.txt file and found
WARN 2017-09-27 10:51:55,219 [8 ] MPA_EF.Web.Controllers.AccountController - Login failed!
Abp.UI.UserFriendlyException: Login failed!
at BBWP_ABP_MPA_EF.Web.Controllers.AccountController.d__13.MoveNext() in C:_Ambienti\vs2015\Biosic\module-zero-template-2.1.1\src\BBWP_ABP_MPA_EF.Web\Controllers\AccountController.cs:line 130
--- 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.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at BBWP_ABP_MPA_EF.Web.Controllers.AccountController.<Login>d__12.MoveNext() in C:\_Ambienti\vs2015\Biosic\module-zero-template-2.1.1\src\BBWP_ABP_MPA_EF.Web\Controllers\AccountController.cs:line 100
--- 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.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.b__1c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__1e(IAsyncResult asyncResult)
Edit
no customization in Login method
Standard Login method AccountController.cs
Login method inside my project

Looking at the provided log I see no issues with the processing of your code. The only thing I can think of is a configuration issue in your web.config.
Make sure the <customErrors /> tag is set to either <customErrors mode="RemoteOnly" /> or <customErrors mode="On" />.

Related

Exception -"Cannot send a content-body with this verb-type" using httpclient.sendasync

Already tried searching SO for similar issues but those didn't help to resolve.
Scenario:
Have a Web Client app which has a Web API app as a backend. There is no issue when calling the same URI if it's from this Client - Web API but the exception happens when I'm trying to trigger the API request from another WebAPI Services application ( say its a separate project for accessing reports which run as a service using Telerik Reporting).
Code:
private async Task<HttpStatusCode> AccessService()
{
HttpResponseMessage response = null;
try
{
using (HttpRequestMessage request = new HttpRequestMessage()
{
Content = new System.Net.Http.StringContent(JSONValues, System.Text.Encoding.UTF8, "application/json"),
RequestUri = new Uri(UriString),
Method = CallMethod
})
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Utils.Token) ;
response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
string httpResponse = await response.Content.ReadAsStringAsync();
httpString = JsonConvert.DeserializeObject<string[]>(httpResponse);
}
ErrorCode = response.StatusCode;
response.Dispose();
}
}
catch (Exception ex)
{
Misc.Error= ex.Message;
}
finally
{
response.Dispose();
}
return ErrorCode;
}
Exception:
Cannot send a content-body with this verb-type.
at System.Net.HttpWebRequest.CheckProtocol(Boolean onRequestStream)
at System.Net.HttpWebRequest.BeginGetRequestStream(AsyncCallback callback, Object state)
at System.Net.Http.HttpClientHandler.StartGettingRequestStream(RequestState state)
at System.Net.Http.HttpClientHandler.PrepareAndStartContentUpload(RequestState state)
--- 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.Net.Http.HttpClient.<FinishSendAsyncBuffered>d__58.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.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
This works fine when I access the same from the Client app ( asp.net mvc ) and issue happens when I call this from the Report Services API app. Is this has something to with it.
Edit:
The Web client Project is asp.net mvc core 2.1, so I think it works while using content in GET method of HttpClient.SendAsync but the Reports Services App where this issue happens are targets .net 461 .
I strongly doubt this might be the cause since .net framework doesn't allow content for GET operations? Any work arounds?
Link
TIA
Based on the description provided, if you use get method you usually don't have a body in the get request. For more details, please refer to the solutions below:
http://stackoverflow.com/questions/3981564/cannot-send-a-content-body-with-this-verb-type

How disable location in Xamarin.Forms UI Test

How can I disable location while single UI test in xamarin forms (I am using Android 8.1 simulator)? In one test case I want cancel location permission, and in other simulate that the GPS can not find user location.
I thought about backdors, but I did not found nothing useful or up to date on msdn and stack (some links pasted bellow).
I have tried something like this (and much more similar 'mutations'):
Droid.MainActivity:
[Export("GpsBackdoor")]
public void GpsBackdoor()
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.PutExtra("enabled", Java.Lang.Boolean.False);
SendBroadcast(intent);
}
UITests.Test:
[Test]
public void SetCurrentUserLocation_WhenGPSisOff_ShouldShowAlert()
{
app.WaitForElement(x => x.Text("Nearest stops"));
app.Invoke("GpsBackdoor");
app.Tap(x => x.Text("Nearest stops"));
var result = app.WaitForElement("Could not obtain position");
}
After running test I am getting message:
System.Exception : Error while performing Invoke("GpsBackdoor", null)
----> System.Net.Http.HttpRequestException : An error occurred while sending
the request.
----> System.Net.WebException : The underlying connection was closed: The
connection was closed unexpectedly.
at Xamarin.UITest.Utils.ErrorReporting.With[T](Func`1 func, Object[] args,
String memberName)
at Xamarin.UITest.Android.AndroidApp.Invoke(String methodName, Object
argument)
at BusMap.Mobile.UITests.NearestStopsMapPageTests.
SetCurrentUserLocation_WhenGPSisOff_ShouldShowAlert() in
<source>\NearestStopsMapPageTests.cs:line 40
--HttpRequestException
at Xamarin.UITest.Shared.Http.HttpClient.SendData(String endpoint, String
method, HttpContent content, ExceptionPolicy exceptionPolicy, Nullable`1
timeOut)
at Xamarin.UITest.Shared.Http.HttpClient.Post(String endpoint, String
arguments, ExceptionPolicy exceptionPolicy, Nullable`1 timeOut)
at Xamarin.UITest.Android.AndroidGestures.Invoke(String methodName, Object[]
arguments)
at Xamarin.UITest.Utils.ErrorReporting.With[T](Func`1 func, Object[] args,
String memberName)
--WebException
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
I've also tried turn off Wifi or cellular data, which gave me the same error.
I will be grateful for any help.
P.S. Some links which I've found:
Enable/Disable wifi using Xamarin UiTest
How to start GPS ON and OFF programatically in Android

Upload a text file as attachment using Bot framework not working in Skype channel

I am unable to upload a text file as an attachment using the Bot framework (Bot.Builder v3.11.0), when trying in the Skype channel. It worked in the Bot framework emulator though. Following is the code which uploads a file and to returns the activity with the uploaded file URL in the attachment. It throws an exception when using the Skype channel. Alternatively is there any other way to achieve uploading/attaching a text file in the Skype channel which the user can then download from within the client?
public static async Task<Activity> GetTextAttachmentAsync(Activity message)
{
var reply = message.CreateReply("Here is a text attachment");
var serviceUrl = reply.ServiceUrl;
var conversationId = reply.Conversation.Id;
byte[] fileData = null;
using (var wc = new System.Net.WebClient())
fileData = wc.DownloadData("https://textfiles.com/100/adventur.txt");
using (var connector = new ConnectorClient(new Uri(serviceUrl)))
{
var attachments = new Attachments(connector);
var token = await (connector.Credentials as MicrosoftAppCredentials).GetTokenAsync();
connector.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await attachments.Client.Conversations.UploadAttachmentAsync(
conversationId,
new AttachmentData
{
Name = "transcript.html",
OriginalBase64 = fileData,
Type = "text/html"
});
reply.Attachments = new List<Attachment>
{
new Attachment
{
Name = "transcript.html",
ContentType = "text/html",
ContentUrl = attachments.GetAttachmentUri(response.Id)
}
};
return reply;
}
}
Exception thrown from the UploadAttachmentAsync() function above:
Microsoft.Rest.HttpOperationException: Not Found
at Microsoft.Bot.Connector.ErrorHandling.<HandleErrorAsync>d__2`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Connector.ConversationsExtensions.<UploadAttachmentAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Support.Services.Bot.Core.Utilities.AdaptiveCardsHelper.<GetTextAttachmentAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Support.Services.Bot.Core.Dialogs.BotDialog.<HandleMessageAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Support.Services.Bot.Core.Dialogs.DialogBase`1.<MessageReceivedAsync>d__8.MoveNext()
When running your code with Common Language Runtime Errors enabled in Visual Studio. I got the following error:
It seems that the site address https://textfiles.com/100/adventur.txt does not have a trusted certificate and that makes .NET unhappy. When I went to investigate, I found this Stack Overflow answer that suggested using this code below to overcome this but is strongly recommended not to use this in production.
ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
This was going to be my original suggestion before I ran your code: many channels (Skype included), limit the types of files you are able to send from a bot when using base64 and/or local files. For example, I know that you cannot send PDF files as Base64 in Skype. If memory serves correctly, you can only send image and video files (maybe audio too) using the base64 method in Skype. So even if you resolve this error you may run into this afterward. The workaround for this is using hosted files. I'm not exactly sure what you are trying to do with your bot, so I'm not sure if this is an option for you specifically, but it is an option.
So if you find this code not working after resolving the certificate issue, try sending an image file and see if that works, if it does but your HTML file still fails, you will know this is why.

handle some errors in Global.asax

I have a web application on .NET4 and MVC3 (razor) .
I want to handle my application errors in Global.asax. I have created application_error function.
I have noticed and found some errors.
one of them returns this string in Application_Error when I am trying to add break point on line Response.Clear(); and that error is generic.
how can I find which codes or part of my codes makes it?
my code:
protected void Application_Error()
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
}
error on httpException:
{System.Web.HttpException (0x80004005): File does not exist.
at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String
physicalPath, HttpResponse response)
at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context, String
overrideVirtualPath)
at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context,
AsyncCallback callback, Object state) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionSt
ep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously)}
i found the solution
string errorLocation = Request.Path;
this syntax in Application_Error() tel you where is the problem :)
Just to state my experience with this exception, in my case the reason was that there was no webpage specified as the start page for the site.

Handling WCF web config errors with MVC?

I was about to use the following Application_Error() handling in my Global.asax:
protected void Application_Error()
{
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
string action;
switch (httpException.GetHttpCode())
{
case 404:
// page not found
action = "HttpError404";
break;
case 500:
// server error
action = "HttpError500";
break;
default:
action = "General";
break;
}
// clear error on server
Server.ClearError();
Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
}
}
However, the issue was that I couldn't trap this error:
The maximum message size quota for incoming messages (100000) has been
exceeded. To increase the quota, use the MaxReceivedMessageSize
property on the appropriate binding element.
When I had the web.config value set to low, as when it got to the Response.Clear(); call, I get an HTTP exception:
Response is not available in this context.
How can I get around this to handle all exceptions?
Thanks.

Resources