Cannot pass ampersand and hash sign in MVC - ajax

I have this code
#using (Ajax.BeginForm("LoadFilter", "Contact", new { filterType = (int)FilterContactBy.Name }, new AjaxOptions { OnBegin = "ShowProgrees", OnSuccess = "HideProgress" }))
{
#Html.TextBoxFor(m => m.ContactFilter.FilterValue, new { placeholder = "Enter a name" })
<input type="submit" class="link submit green" value="Add Filter" />
}
As quite obvious, the ShowProgress and HideProgress method do nothing but show and hide a loader gif.
The method at backend is
[HttpPost]
public ActionResult LoadFilter(ContactListModel filter, int filterType=0, Boolean isAllFilterApply=true)
{
if (filter != null)
{
// process here
}
}
It works fine if I enter anything, for example
hi
test
me & you
contact #1
contact #1 and me
BUT
When I enter &# together in any from error occurs. The loader gif just keeps moving and the code on Controller is never hit.
Also, in Chrome console, it shows 500 Internal Server Error (and so does Firefox!).
My Solution
I tried escape and enocodeURIComponent but it didn't worked. Here's the method I tried
$.ajaxPrefilter(function(o, org, xhr) {
if (org.url.indexOf('/Contact/LoadFilter?filterType=') > -1) {
// console.log(org.data[0].value);
org.data[0].value = encodeURIComponent(org.data[0].value);
// console.log(org.data[0].value);
}
});
The output (in console)
&#
%26%23
When instead of encodeURIComponent I used escape, the output was same
&#
%26%23
But it still doesn't hit the method on controller. Can anyone please help me to get a solution, and more importantly, tell me why is this occurring in the first place?
ps
Please don't ask me that what is the use of inputting &# in a contact filter, or to remove these and tell client this is not a valid input. I can't do that, so please don't advice that.
Update
Is anyone even reading this fully? I am not asking that how can I decode. NO. Please read the full question before marking it as duplicate or marking it for close.

Okay, I got this.
I created Application_BeginRequest in Global.asax in the code like this..
protected void Application_BeginRequest(Object sender, EventArgs e)
{
var httpApp = (HttpApplication)sender;
Debug.Write(httpApp);
}
I sat a breakpoint of httpApp and then in the watch window, checked for httpApp.Request and found that it was there. It said (something I don't remember right now) threw an exception of type 'System.Web.HttpRequestValidationException'.
So, I got that the error was because of this, so on the method LoadFilter, I just added the attribute ValidateInput(false), and it's working
[HttpPost]
[ValidateInput(false)]
public ActionResult LoadFilter(ContactListModel filter, int filterType=0, Boolean isAllFilterApply=true)
{
// process here
}
Though, I do have to check for sql injection in here because we are building up a dynamic query from the input we receive.

Use
HttpUtility.UrlDecode("url")

Related

OnChange in MudBlazor RadioButtonGroup

I am new to Blazor and MudBlazor. I am using a and I want to call an event when the selection changes. The documentation show there is a EventCallback method but there are no syntax examples. I have been searching a good part of the day but cannot find an example. Can anyone please share some simple code? I know I can bind to a variable, and I initially did that. What I want is to call code and do some different code based on the selected value. Seems to be easier to do in Blazor syntax vs MudBlazor.
I appreciate any help.
Thank you
<MudRadioGroup T="string" SelectedOption="#SelectedOption" SelectedOptionChanged="OnSelectedOptionChanged">
<MudRadio Option="#("Radio 1")" Color="Color.Primary">Primary</MudRadio>
<MudRadio Option="#("Radio 2")" Color="Color.Secondary">Secondary</MudRadio>
<MudRadio Option="#("Radio 3")">Default</MudRadio>
<MudRadio Option="#("Radio 4")" Color="Color.Primary" Disabled="true">Disabled</MudRadio>
</MudRadioGroup>
#code {
public string SelectedOption { get; set; }
private void OnSelectedOptionChanged(string selectedOption)
{
SelectedOption = selectedOption;
// call your stuff
}
}
https://try.mudblazor.com/snippet/mOQGYtGKUpgnQxqe

How to remove tooManyAttempts message in Prompt.Choice? How to accept text in Prompt.Choice that is not in list of options? C#

I'm using bot-Framework SDK3 C#.
I want to allow user input anything which is not in "PromptDialog.Choice"'s options. Any better ways to recommend?
This is my code.
private async Task SelectCategory(IDialogContext context)
{
List<string> options = new List<string>();
options = category.Keys.ToList();
options.Add("Category1");
options.Add("Category2");
options.Add("Category3");
PromptOptions<string> promptOptions = new PromptOptions<string>(
prompt: "which one do you prefer?",
tooManyAttempts: "",
options: options,
attempts: 0);
PromptDialog.Choice(context: context, resume: ResumeAfterSelectCategory, promptOptions: promptOptions);
await Task.FromResult<object>(null);
}
private async Task ResumeAfterSelectCategory(IDialogContext context, IAwaitable<string> result)
{
try
{
selected = await result;
}
catch (Exception)
{
// if the user's input is not in the select options, it will come here
}
}
But the problem is it always send the message "tooManyAttempts". If I set it to empty, I will send me "0".
I suppose you are using NodeJS. You can use the simple builder.Prompts.choice with maxRetries set to 0. Here is a sample snippet. It asks user to choose some option from a list, or they can enter something which is not in the list.
If you are using C# SDK, you can find some similar option for the list.
bot.dialog("optionalList", [
function(session){
builder.Prompts.choice(
session,
"Click any button or type something",
["option1", "option2", "option3"],
{maxRetries: 0} // setting maxRetries to zero causes no implicit checking
)
},
function(session, result){
// something from the list has been clicked
if(result.response && result.response.entity){
console.log(result.response.entity); // use the clicked button
} else {
console.log(session.message.text) // if user entered something which is not in the list
}
}
]);
EDIT 1:
Hi, Saw that you are using C# SDK. I am not that proficient with that but I can give you some suggestion.
The list which you generate in the async task SelectCategory you can generate in some other place, which is also accessible to the second async task ResumeAfterSelectCategory, (like making it a class variable or getting from database).
Now that the list is accessible in the 2nd task, you can compare what user has typed against the list to determine if the message is from the list or not.
If message is something from the list, then take action accordingly, otherwise user has entered something which is not in the list, and then take action accordingly.
Your 2nd problem is
And if user typed, it will show a message "you tried to many times"
What is meant by that? Does bot sends "you tried to many times" to the bot visitor. In which case it could be the behavior of library. You will be able to control that only if library provides some option. Else I don't know. Hope, that helps
EDIT 2:
I came across this SO question Can I add custom logic to a Bot Framework PromptDialog for handling invalid answers?
You can use that questions answer. Basically extending PromptDialog.PromptChoice<T>.Here is an example.
Override TryParse method like this
protected override bool TryParse(IMessageActivity message, out T result)
{
bool fromList = base.TryParse(message, out result);
if (fromList)
{
return true;
} else {
// do something here
return true; // signal that parsing was correct
}
}
I used node.js and to get message which user entered. use this code snippet.
(session, args) => {
builder.Prompts.text(session, "Please Enter your name.");
},
(session, args) => {
session.dialogData.username = args.response;
session.send(`Your user name is `${session.dialogData.username}`);
}

Data Fetching Crashes in Xamarin Forms

I am trying to fetch Customer data to parse them into customer object to display on TableView. The following code sometimes works, sometimes not. Whenever it does crash, it shows Customer data is empty in the foreach loop even though I run the same code every time. I do not have clue what could be wrong in this circumstances. I am quite new on this platform. If I am missing anything/ extra information, please let me know.
namespace TableViewExample
{
public partial class MyDataServices : ContentPage
{
private ODataClient mODataClient;
private IEnumerable <IDictionary<string,object>> Customers;
public MyDataServices ()
{
InitializeComponent ();
InitializeDataService ();
GetDataFromOdataService ();
TableView tableView = new TableView{ };
var section = new TableSection ("Customer");
foreach (var customers in Customers) {
//System.Diagnostics.Debug.WriteLine ((string)customers ["ContactName"]);
var name = (string)customers ["ContactName"];
var cell = new TextCell{ Text = name };
section.Add (cell);
}
tableView.Root.Add (section);
Padding = new Thickness (10, 20, 10, 10);
Content = new StackLayout () {
Children = { tableView }
};
}
private void InitializeDataService(){
try {
mODataClient = new ODataClient ("myURL is here");
}
catch {
System.Diagnostics.Debug.WriteLine("ERROR!");
}
}
private void GetDataFromOdataService (){
try {
Customers = mODataClient.For ("Customers").FindEntries ();
}
catch {
System.Diagnostics.Debug.WriteLine("ERROR!");
}
}
}
}
Its hard helping out here, however here are some things to consider:-
It sounds like the dataservice could either be not contactable / offline; too busy or it could even be throwing an exception itself and returning a data response that you are not expecting to receive, that then triggers an exception and crash in your application as your always expecting an exact response without catering for any abnormal responses / events.
If you are contacting an external service over the internet it may just be your internet connection is slow / faulty and not returning the information fast enough as other possibilities.
In your code you are assuming that you always get a response from the server - and that this response will always be of an anticipated structure that your expecting to decode - without factoring in any possibility of abnormal responses returned by the dataservice. I have not used ODataClient personally, so not sure how it behaves in the event of maybe no data received / timeout or in your case the dataservice and how it behaves internally in the response to a bad-request etc.
I am assuming an exception would get thrown, and you do get your debug line executed indicating a failure.
You may want to also adjust this statement so that you write out the exception as well, i.e.:-
private void GetDataFromOdataService ()
{
try
{
Customers = mODataClient.For ("Customers").FindEntries ();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("ERROR!" + ex.ToString());
}
}
If there was a bad response, then the line at Customers = ..... would throw the exception as there may be no Customers returned or some other information packaged in the response from the dataservice.
The Customers variable would also be null at this point I am assuming due to this failing.
So when you get back to your code at foreach (var customers in Customers) { it will then throw a null reference exception as Customers is infact null.
As all your current code executes in the constructor without any try and catch block around this, it will also crash your application at this point as well.
Also you are doing all of this work in the constructor. Try seperating this out. I haven't investigated exactly where the constructor gets called in an iOS page life-cycle, however, if it is in the viewDidLoad, then you have something like 10 seconds for everything to complete, otherwise it will exit automatically. I imagine in your case, this isn't applicable however.
Going forward also try putting your layout controls in the constructor, and move your data task to maybe the OnAppearing override instead.
Using async would definitely be advisable as well, but remember you need to inspect the response from your dataservice, as the error could be embedded within the response also and you will need to detect when it is OK to process the data.

Execute multiple webrequests in WP7?

I have a list of addresses that i want to visit using httpWebRequest.
All i need is the statuscode returned by the server.
I have tried to foreach through them and begin a httpWebRequest on each of them, but then i only receive the callback from the last one.
It seems like only one webrequest is allowed at a time.
I'm having quite a hard time understanding how to do this without the GetResponse, which is not allowed in silverlight.
The code is running in a backgroundworker.
And i am using Mango - WP7.1
How do i solve that?
foreach (var current in Addresses)
{
var request = HttpWebRequest.Create(current);
request.BeginGetResponse(r =>
{
try
{
var response = (HttpWebResponse)request.EndGetResponse(r);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//BOOM RECEIVED
});
}
catch (Exception)
{
Debug.WriteLine("Error in EndGetResponse");
}
}, null);
}
Thanks in advance =)
Your problem of a single response is most likely being caused by your use of anonymous methods and the the way scoping works when you put these inside loops. You are throwing away the earlier request references on each step through the loop.
See my blogpost on the topic here http://csainty.blogspot.com/2010/10/windows-phone-7asynchronous-programming.html
The simplest way to illustrate this is to rewrite your code with full methods, this forces you to consider the scope instead of just blindly referening external variables in your delegates.
foreach (var current in Addresses)
{
var request = HttpWebRequest.Create(current);
request.BeginGetResponse(EndGetResponse, new RequestState { Request = request, Address = current });
}
private void EndGetResponse(IAsyncResult result) {
try {
var state = (RequestState)result.AsyncState;
var response = (HttpWebResponse)state.Request.EndGetResponse(result);
Deployment.Current.Dispatcher.BeginInvoke(GotResponse, state.Address, response.StatusCode);
} catch (Exception) {
Debug.WriteLine("Error in EndGetResponse");
}
}
private void GotResponse(Address address, HttpStatusCode code) {
//BOOM RECEIVED
}
public class RequestState {
HttpWebRequest Request { get; set; }
Address Address { get; set; }
}
Once you solve the scoping issues you can rewrite back into anonymos methods for stylistic reasons if you like.
This will only solve your first problem of getting all the responses back however, I assume you also need to run some code when all the requests are complete to check the status of the whole batch?
That is a different problem altogether.
You can not use WaitOne() or anything like that, it will lock your thread and stop the requests from actually running at all. You will probably want to call off to another method in you BOOM code that stores away the result and checks if all the results are in yet.

A simple RequiredField validator really this complex?

Using the INotifyDataErrorInfo I have validation methods in my setters of my properties, this works fine if I change the field value and then leave the control (change focus) the setter gets fired and validation occurs and the UI is notified, but using that interface, if the user just presses submit how can I do something similar to RequiredField like in asp.net, I can't seem to find a clear cut example on any forum or blog :(
I'm using Silverlight 4 WCF RIA and the mvvm-light toolkit, thats it. I hope im not over complexing this, because it seems like it should be so simple but can't seem to figure out a solution.
Thank you for all your help, suggestions and pointers!!!
Finally found a simple solution... Please let me know if anyone has a more efficient way of doing this :)
private void Validate()
{
ValidationContext validationContext = new ValidationContext(this, null, null);
ICollection vr = new List();
Validator.TryValidateObject(this, validationContext, vr, true);
if (vr.Count >= 1)
{
foreach (var item in vr)
{
ManageErrors(((string[])item.MemberNames)[0], new List() { item.ErrorMessage }, true);
}
}
}
The Manage Errors method is the simple implementation of the INotifyDataErrorInfo that Jesse Liberty did here
any ways now when my submit method gets called (using mvvm-light) in my viewModel i call this and bam all properties validated using simple dataAnnotations
ie
[Required(ErrorMessage = "Is Required", AllowEmptyStrings = false)]
public string SelectedStatus
{
get { return _selectedStatus; }
set
{
_selectedStatus = value;
RaisePropertyChanged("SelectedStatus");
}
}
Not the most elegant way of doing it but... by god I could not find anyone validating on a submit!?!?

Resources