C# ASP.Net Errors on form submission - c#

I was hoping to get some insight on the error that are produced by the system. I am using a already built message system that I got some time ago and it works but sometimes on the forms I will get errors that I do not understand. For instance on a Create I have a try / catch block that produces a message if it has successfully Executed. I have tried to search for these errors in my project and it does not come up with anything. Even if it was in meta data a search should find it.
I use System.Text.StringBuilder sb = new System.Text.StringBuilder(); for the message and the code looks like this:
public ActionResult Create(Vendors model)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
try
{
if (ModelState.IsValid)
{
var userId = User.Identity.GetUserId();
//var getdata = ExtendedViewModels.VendorToEntity(model);
model.VendorId = Guid.NewGuid();
model.CreatedDate = System.DateTime.Now;
model.CreatedBy = User.Identity.Name;
model.Status = true;
db.Vendors.Add(model);
db.SaveChanges();
sb.Append("Submitted");
return Content(sb.ToString());
}
else
{
foreach (var key in this.ViewData.ModelState.Keys)
{
foreach (var err in this.ViewData.ModelState[key].Errors)
{
sb.Append(err.ErrorMessage + "<br/>");
}
}
}
}
catch (Exception ex)
{
sb.Append("Error :" + ex.Message);
}
return Content(sb.ToString());
}
When this returns or closes the Modal it produces a message or if there is an error it will produce that so you can fix it like a Required field. If everything is okay it will produce from this:
#Html.StarkAjaxFormSubmiter("frmVendors", "tbVendors", true, "Action Successfully Executed")
This is a green box that shows up as "Action Successfully Executed". If something is wrong a red box shows up and you get a message. In my case I am getting a red box that says Submitted Read Warnings Alerts This is how it is spelled. I doubt this is a error that comes from ASP.Net it looks more like a custom message, I dont know what it means and I cannot find it anywhere. Regardless, it does create the record in the db. The other error I have gotten shows Something is went wrong [object, object] Not only do I want to find out what these mean, I also want to clean them up and give a proper message that makes sense. Does anyone have any ideas as to how to correct this? Could they be encypted in the custom package that was written for this? That is why I cannot find them. I have also viewed the package and did not find anything for this.
This is from Meta data:
//
// Parameters:
// stark:
//
// FormId:
// Enter Here Form ID LIKE So you have to pass = frmCreate
//
// DataTableId:
// Which DataTable You have update after submit provide that ID
//
// IsCloseAfterSubmit:
// Do you want to opened popup close after submit , So pass=true or false any
//
// SuccessMessage:
// Give any Success message
public static MvcHtmlString StarkAjaxFormSubmiter(this HtmlHelper stark, string FormId, string DataTableId, bool IsCloseAfterSubmit, string SuccessMessage);
//
// Parameters:
// stark:
//
// FormId:
// Enter Here Form ID LIKE So you have to pass = frmCreate
//
// DataTableId:
// Which DataTable You have update after submit provide that ID
//
// IsCloseAfterSubmit:
// Do you want to opened popup close after submit , So pass=true or false any
//
// SuccessMessage:
// Give any Success message
//
// AfterSuccessCode:
// Add other JQuery code if you want
public static MvcHtmlString StarkAjaxFormSubmiter(this HtmlHelper stark, string FormId, string DataTableId, bool IsCloseAfterSubmit, string SuccessMessage, string AfterSuccessCode);
Thanks for our help
UPDATE:
I did some searching on the web and found a program called JetBrains dotPeek. I decompiled the dll and sure enough the messages are in there. So I should be able to change them and recompile it and add if I want, to it.

I was not able to edit the decompiled dll. So I decided to just create a class in the main project and copy the the code to that class. Changing what I needed. Where my trouble was, was with misspellings. The dll used Sumitted as the sb.Append("Sumitted") I changed that in the controller to be Submitted. So the dll did not find "Sumitted" in the action, and in the dll class there is an If statement that faults to error if not found - which was listed as Read Warnings Error. I changed that and fixed all the misspellings. I also got rid of the Something is went wrong and changed it to something more meaningful. I will continue to add to this to give more meaningful messages. It helps to know what the error is, instead of [object], [object]. I dont know if this will help others, maybe if they have downloaded the same code I have and have issues.

Related

RedirettoAction() doesn't takes object

I have the following method
public ActionResult APLogin(int userId, int courseId, string authToken)
{
try
{
// // To be varified from Assessment platform, will be implemented later.
// //Make sure user/course exist in User/Course table
// //User should be enrolled in this course.
// //If anyone missing from all thee ..return false
// //Otherwise redirect to StaffHome page
CourseRolesBOFilters courseRole = new CourseRolesBOFilters();
courseRole.CourseId = courseId;
courseRole.UserId = userId;
return RedirectToAction("SelectCourse", courseRole, FormMethod.Post);
}
catch (Exception ex)
{
string errorMessage = string.Format("Error loading LMS page. Please try again or contact support.");
Trace.WriteLine(errorMessage);
Trace.WriteLine(ex.ToString());
ModelState.AddModelError("", String.Format("System failed to load LMS page. {0}", ex.Message));
return View();
}
}
I am getting an error at line
return RedirectToAction("SelectCourse", courseRole, FormMethod.Post);
The error is:
Argument 2: cannot convert from 'BrightScribeDAL.NonDBBO.CourseRolesBOFilters' to 'string'screenshot
Can anyone please help
Please take a look at Microsoft documentation about RedirectToAction found here: https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.redirecttoaction(v=vs.118).aspx
You are sending three parameters to the function, and by looking at the documentation, the only two signatures that has 3 parameters are:
RedirectToAction(String, String, Object)
RedirectToAction(String, String, RouteValueDictionary)
Both requires second parameter to be string, hence your error shown in the image you posted Cannot convert from 'xyz' to 'string'
Make sure to send the correct parameters, and you'll be okay.
Hi I hope the below table itself will solve all your problem and doubts.
For your current problem , fifth row in table will be helpful that is,
RedirectToAction(string actionName,string controllerName,object routeValue)
Your Ex:
return RedirectToAction("SelectCourse", "AnycontrollerName", new{CourseID = courseId,...(you can pass anyno of route values) });
Useful Link:http://www.dotnetfunda.com/articles/show/3116/to-understand-various-types-of-redirecttoaction-override-methods-in-as
Hope above information was helpful
Thanks
Karthik

Posting a tweet C#

I am trying to post a tweet with TweetSharp library but a StackOverflowException is thrown. I couldn't solve this problem. What should I do? The error occurs in this line:
servis.SendTweet(new SendTweetOptions { Status = textBox1.Text });
Break it down and step through in the debugger (put a break-point on the string status = ... line):
// if you don't get this far, the problem is elsewhere
// if it fails here, the problem is accessing the textbox value
string status = textBox1.Text;
// if it fails here, the problem is inside the tweetsharp library,
// and should be referred to the library authors, but indicating which
// step fails (constructor vs Status property vs Send method)
var msg = new SendTweetOptions();
msg.Status = status;
servis.SendTweet(msg);

IsolatedStorage and navigation

I can't sort this weird issue out and I have tried anything and everything I can think of.
I got 5 pages, everyone of them passing variables with navigation this way:
Pass:
NavigationSerice.Navigate(new Uri("/myPage.xaml?key=" + myVariable, UriKind.Relative));
Retrieve:
If (NavigationContext.QueryString.ContainsKey(myKey))
{
String retrievedVariable = NavigationContext.QueryString["myKey"].toString();
}
I open a list on many pages and one of the pages automatically deletes an item from the list actualProject (actualProject is a variable for a string list). Then, when I go so far back that I reach a specific page - the app throws an exception. Why? I have no idea.
The code that deletes the item:
// Remove the active subject from the availible subjects
unlinkedSubjects.Remove(actualSubject);
unlinkedsubjectsListBox.ItemsSource = null;
unlinkedsubjectsListBox.ItemsSource = unlinkedSubjects;
Then the page that throws the exception's OnNavigatedTo event:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.ContainsKey("key"))
{
actualProject = NavigationContext.QueryString["key"];
try
{
//Read subjectList from IsolatedStorage
subjectList = readSetting(actualProject) != null ? (List<String>)readSetting(actualProject) : new List<String>();
//Put the subjectList into the subjectListBox
subjectListBox.ItemsSource = subjectList;
//Set the subjectsPageTitle to the "actualProject" value, to display the name of the current open project at the top of the screen
subjectsPageTitle.Text = actualProject;
}
catch (Exception)
{
if (language.Equals("en."))
{
// Language is set to english
MessageBox.Show("Couldn't open the project, please try again or please report the error to Accelerated Code - details on the about page");
}
else if (language.Equals("no."))
{
// Language is set to norwegian
MessageBox.Show("Kunne ikke åpne prosjektet, vennligst prøv igjen eller rapporter problemet til Accelerated Code - du finner detaljer på om-siden");
}
}
}
}
Exception:
_exception {System.ArgumentException: Value does not fall within the expected range.} System.Exception {System.ArgumentException}
My theory:
The app kind of loads the currently opened and modified List. Is that possible? No idea.
So there are a number of ways to pass data between pages.
The way you have chosen is the least suggested.
You can use the PhoneApplicationService.Current dictionary but this is messy also if you have a ton of variables, doesn't persist after app shut down and could be simplified.
I wrote a free DLL that kept this exact scenario in mind called EZ_iso.
You can find it here
Basically what you would do to use it is this.
[DataContractAttribute]
public class YourPageVars{
[DataMember]
public Boolean Value1 = false;
[DataMember]
public String Value2 = "And so on";
[DataMember]
public List<String> MultipleValues;
}
Once you have your class setup you can pass it easily between pages
YourPageVars vars = new YourPageVars { /*Set all your values*/ };
//Now we save it
EZ_iso.IsolatedStorageAccess.SaveFile("PageVars",vars);
That's it! Now you can navigate and retrieve the file.
YourPageVars vars = (YourPageVars)EZ_iso.IsolatedStorageAccess.GetFile("PageVars",typeof(YorPageVars));
This is nice because you can use it for more than navigation. You can use it for anything that would require Isolated storage. This data is serialized to the device now so even if the app shuts down it will remain. You can of course always delete the file if you choose as well.
Please make sure to refer to the documentation for any exceptions you have. If you still need help feel free to hit me up on twitter #Anth0nyRussell or amr#AnthonyRussell.info

Overriding validation in Breezejs

Here is an interesting requirement. How would I solve this with Breezejs?
(note, using a SPA design based on and extremely similar to the one in John Papa's Angular + Breezejs Pluralsight course)
We have a business rule that says that when I add or edit customer phone number, I need to check the phone number to see if there is a different customer with the same number (can happen due to phone number reassignment, etc).
If I find that it is a dup, I need to prompt the user. The user has the option to say "yah, that's fine", and then the phone number will save anyway.
So, I get how to do a basic validation with BeforeSaveEntity, and to fail if I find the dup, but suppose the user checks the "save anyway" option. How do I include this "out of band", non-data row information in my save set so that I can override the server-side validation rule?
And also, I don't want this validation to look like a "normal" error to the user on save -- I want to detect that it was the phone number clash thing, so I can display the view that prompts them to override.
Out of band data can be passed either by using the SaveOptions.tag property or by going to a separate named endpoint in your save call. i.e.
var so = new SaveOptions({ tag: "Special kind of save with extra data" });
return myEntityManager.saveChanges(null, so);
or
var so = new SaveOptions({ resourceName: "SaveWithSpecialValidation", tag: "any special data" });
return em.saveChanges(null, so);
In terms of how to return a special server side save validation
[HttpPost]
public SaveResult SaveWithSpecialValidation(JObject saveBundle) {
// custom tag passed from the client
var theTag = ContextProvider.SaveOptions.Tag;
ContextProvider.BeforeSaveEntitiesDelegate = BeforeSaveWithException;
return ContextProvider.SaveChanges(saveBundle);
}
private Dictionary<Type, List<EntityInfo>> BeforeSaveWithException(Dictionary<Type, List<EntityInfo>> saveMap) {
List<EntityInfo> orderInfos;
if (saveMap.TryGetValue(typeof(Order), out orderInfos)) {
if (YourErrorCheckHere(orderInfos)) {
var errors = orderInfos.Select(oi => {
return new EFEntityError(oi, "WrongMethod", "My custom exception message", "OrderID");
});
// This is a special exception that will be forwarded correctly back to the client.
var ex = new EntityErrorsException("test of custom exception message", errors);
// if you want to see a different error status code use this.
// ex.StatusCode = HttpStatusCode.Conflict; // Conflict = 409 ; default is Forbidden (403).
throw ex;
}
}
return saveMap;
}
Hope this makes sense. :)

Recursion limit exceeded

I am using a jQuery Ajax control from this site http://abeautifulsite.net/2008/03/jquery-file-tree/
I have it all working. I tried to ask a support question but never heard back, thinking maybe someone on here can shed some light on the situation.
Basically what I am trying to do, is on a file selection run an action that returns a JsonResult, that gives more details about the file and then show them to the screen in a container. While I debug, the method gets hit, returns the correct data. After the return in the ajax call i get a error in firebug say the recursionlimit exceeded. I am not sure how to get around this...I thought I could use the callback of the fileTree(options, callback) method provided but that is not fired on selection of the file only the initialization of the file tree. Any ideas?
Heres what I did via JavaScript
function initFileTree() {
$('#fileTree').fileTree({ root: '/', script: '/Scripts/filetree/jqueryFileTree.aspx', multiFolder: false, expandEasing: 'easeOutBounce', collapseEasing: 'easeOutBounce' }, function(file) {
getFileDetails(file);
});
}
function getFileDetails(file) {
// alert(file);
$.getJSON('/Files.mvc/GetFileDetails', { Data: file }, function(data) {
$('#fileDetail').html('<h6>Selected File: ' + data.Length + '</h6>');
}, 'json');
}
Here is my action that take the data and returns a JsonResult
public virtual JsonResult GetFileDetails(string data)
{
string pageMessage = null;
FileInfo fileInfo = null;
try
{
fileInfo = new FileInfo(data);
}
catch (Exception e)
{
pageMessage = e.Message;
}
return Json(fileInfo);
}
Apparently returning a FileInfo obj is not acceptable for a JsonResult. Simplifying the return, I changed it to:
return Json("helloWorld");
and all my problems went away. Not sure why it cares that I was attempting to return a FileInfo type but either way problem solved when I changed it to return a string. So now I just create a small wrapper class to hold the data I want to pass back and life is good.
Thanks! Hope this helps someone else.

Categories

Resources