Checking if page is valid without firing validations from server side - asp.net

I want to check if current page is valid for a validation group without showing any validation messages. If I call Page.Validate("ValidationGroup") then it shows all the valiation message but I do not want it.
I just to check if page is valid for a particular validation group. And one more constraint, I have to do this on server side can't do it with javascript.

You can loop through the validators in a validation group, like this:
private bool AreAllValidatorsInGroupValid(string validationGroupName)
{
foreach(var theValidator in Page.GetValidators(validationGroupName))
{
var baseValidator = theValidator as BaseValidator;
if(baseValidator != null)
{
if(!baseValidator.IsValid)
{
return false;
}
}
}
return true;
}
Usage:
if(!AreAllValidatorsInGroupValid("ValidationGroup"))
{
// Do something here
}

Related

What is the proper way to handle callback effects and errors in Compose?

I have a main composable that wraps a NavHost to display different screens. Some of these screens need to navigate to other screens based on state changes in a ViewModel that happen as a result of method calls. Here's a trimmed down example of what I have at the moment:
class ExampleViewModel(application: Application) : AndroidViewModel(application) {
// Used by a
var error: String? by mutableStateOf(null)
private set
var user: User? by mutableStateOf(null)
private set
fun onLogin(email: String, password: String) {
viewModelScope.launch {
doLogin(email, password)
.onSuccess { user = it }
.onFailure { error = it.localizedMessage }
}
}
}
#Composable
fun LoginScreen(
navController: NavController,
exampleViewModel: ExampleViewModel,
) {
DisposableEffect(exampleViewModel.user) {
if (exampleViewModel.user != null) {
navController.navigate("somewhere")
}
onDispose {}
}
var email by rememberSaveable { mutableStateOf("") }
var password by rememberSaveable { mutableStateOf("") }
// Email TextField.
// Password TextField.
Button(onClick = { exampleViewModel.onLogin(email, password) }) {
Text("Login")
}
}
The error is handled like this in a composable up above:
LaunchedEffect(exampleViewModel.error) {
exampleViewModel.error?.let { scaffoldState.snackbarHostState.showSnackbar(it) }
}
Using a DisposableEffect in this way seems kind of dirty, and quite error prone. On top of that, this error handling method makes it difficult to, for example, disable the login form while the login is pending. Would it be better to make onLogin() suspend and handle its success and failures, and corresponding local state, in a callback inside of LoginScreen? The downside to that is that the login screen will no longer automatically redirect if it's navigated to while already logged in. snapshotFlow in a LaunchedEffect(true) is another thing I've considered, but that doesn't really seem to have any particular benefits over DisposableEffect.
What's the correct way to do this? Am I on completely the wrong track here?

Changing visibility of Log-out button from serverasp

I'm now building a site including database of users. I want to add "log-out" button on the menu if the session exists. I thought that after checking session exist I would change the visibility property in the css. How can I do that. thanks.
Ok how about something like this:
javascript:
PageMethods.IsSessionActive(isActive, onSuccess, onError);
function onSuccess(result) {
if (result == "true") {
//logic where the logout button is set to visible
} else {
//set to hidden
}
}
C# server side web method:
[WebMethod] public static string IsSessionActive(string isActive) {
//check if session is active //is active set isActive = "true";
return isActive; }

Validating a field based on a different database table / entity

I am writing an MVC 4 application, and using Entity Framework 4.1. I have a validation question which I cannot seem to find the answer to.
Essentially, I have an Entity (object) called "Product" which contains a field "Name", which must follow strict naming conventions which are defined in a separate Entity called "NamingConvention". When the user enters a value, the system needs to check it against the rules established in the NamingConvention entity, and return an error if need be.
Where should this validation be done, and how? I need to check the NamingConvention entity when doing the validation, which means I would need a database context since I'm referencing a different entity. Is there any validation method which won't require me to create a new context? I was thinking of doing the validation in the Controller, since it already creates a data context, but this doesn't seem like the right place to do it.
Thanks for any help!
I have done things like this using a JQuery post (ajax) call from the webpage where the name is being entered. You then post (the value of name) to a method on your controller which can return a JSON value that contains a flag saying if the validation passed and also a message that you want to return to your user. For example :
Javascript in webpage :
$("#name").change(function () {
var nameVal = $(this).val();
$.post(getRoot() + "/NameController/ValidateName", { name: nameVal },
function (data) {
if (data.valid == "true") {
alert("A valid name was chosen");
} else
{
alert(data.message);
}
}, "json");
});
Controller (NameController) Code :
[HttpPost]
public ActionResult ValidateName(string name)
{
// actual validation carried out in a static utility class (Utils.IsNameValid)
// if you are loading the same validation rules from your table each time
// consider caching the data in the application cache or a static List.
bool nameIsValid = Utils.IsNameValid(name, out string ErrorMessage);
JsonResult result = new JsonResult();
result.Data = new { valid = (nameIsValid "true" : "false"), message = ErrorMessage };
return result;
}
I'm using EF 5 but believe you can use this method ... apologies in advance if I'm misleading you with this answer.
You could do the validation within your context (or a context decorator)
public override int SaveChanges()
{
var products = this.GetChangedProducts();
foreach (var product in products)
{
this.ValidateName(product);
}
return base.SaveChanges();
}
private IEnumerable<Product> GetChangedProducts()
{
return (
from entry in _context.ChangeTracker.Entries()
where entry.State != EntityState.Unchanged
select entry.Entity)
.OfType<Product>();
}
private void ValidateName(Product product)
{
//validate here
}

Output Caching using BOTH varybyparam and varybycustom

I'm trying to do something which should be very simple...I have a site with a dropdown from which the user selects a group. Thereafter, the user navigates through the site using querystring arguments from menus. So I want the caching to be dependent on the querystring - this seems to work. I also want the cache to be dependent on the group that they selected.
But when the querystring is empty, neither cache element seems to work - the page is just whatever the version was for the last selected group. My cache directive looks like this:
<%# OutputCache Duration="300" VaryByCustom="currentAtomId" VaryByParam="documentId;folderId;sectionId;renderMode;typeId" %>
My varyByCustom code looks like this:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
switch (custom)
{
case "currentAtomId":
var currentAtomId = SecurityManifold.Create().CurrentAtomId;
var returnString = currentAtomId == null ? Guid.NewGuid().ToString() : currentAtomId.ToString();
return returnString;
default:
throw new ArgumentException(string.Format("Argument '{0}' is not a valid cache argument.", custom));
}
}
The call to CurrentAtomId boils down to this:
public static int? GetCurrentAtomIdFromContext(HttpContext context)
{
int entityId;
if (context.Session == null)
{
throw new InvalidOperationException("Session is null");
}
var sessionEntityId = context.Session["CurrentEntityId"];
if (sessionEntityId == null || string.IsNullOrEmpty(sessionEntityId.ToString()))
{
return null;
}
if (!int.TryParse(sessionEntityId.ToString(), out entityId))
{
return null;
}
return entityId;
}
Finally, the code which specifies the CurrentEntityId is this:
var selectedEntityId = this.lstSecurityEntities.SelectedValue;
if (string.IsNullOrEmpty(selectedEntityId))
{
return;
}
Session["CurrentEntityId"] = selectedEntityId;
var possibleQueryString = Request.QueryString.ToString();
if (!string.IsNullOrEmpty(possibleQueryString))
{
possibleQueryString = "?" + possibleQueryString;
}
Response.Redirect("default.aspx" + possibleQueryString);
I'm baffled. Any thoughts would be appreciated.
I eventually determined the problem - when output caching is placed at a PAGE level (as opposed to a control level), the session is not available, and throws an exception. Because this exception is occurring in Global ABOVE the global error handler, it fails silently. I eventually figured this out by wrapping a try-catch block around the cache key generation code in VaryByCustomString and Response.Write-ing it out.
What a beatdown...at any rate, the solution is to implement caching at the control level, which unfortunately is a lot more work because the pieces of the page work together...but it's better than no caching. I hope this helps save somebody else some time.
Bottom Line: for varyByCustomString in global.asax - SESSION IS NOT AVAILABLE WHEN CACHING AT THE PAGE LEVEL.

How to check for a null object reference when validating forms in MVC

I'm experimenting with validating forms in the asp.net MVC framework.
I'm focusing on server side validation for the time being. I've come across an error that I'm not sure how to rectify.
System.NullReferenceException: Object reference not set to an instance of an object.
The code that throws the error is:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="ID")] MembersCreate mc )
{
mc.Modules = ModuleListDataContext.GetModuleList();
ViewData.Model = mc;
//Validation using ModelState
//
//
//line below errors when form field is empty
//
if ((string)mc.Member.Username.Trim() == "")
ModelState.AddModelError("Member.Username", "Username is required.");
if (!ModelState.IsValid)
return View();
try
{
// TODO: Add insert logic here
return RedirectToAction("Index","Home");
}
catch
{
return View();
}
}
When I put spaces in the field it performs exactly as i want, but if I leave the field blank and press submit I get the error.
What's the best way to avoid this error and still validate blank form fields?
Thanks all -
if (string.IsNullOrEmpty(mc.Member.Username) || (mc.Member.Username.Trim()==string.Empty))
{
ModelState.AddModelError("Member.Username", "Username is required.");
}

Resources