Code contracts and ASP.Net Validators - asp.net

Imagine I have a method having a contract :
public void Do(string value)
{
Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(value));
MyBusiness.Handle(value);
}
This method is called from an asp.net 2.0 web site, and value is grabbed from a textbox, mandatory :
<asp:TextBox ID="txtValue" runat="server" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtValue" ErrorMessage="boom" />
<asp:Button ID="btnDo" OnClick="btnDo_Click" Text="Do" />
The code behind is classic :
protected void btnDo_Click(object source, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
Do(txtDo.Text);
}
}
This code is working, but throw code contracts warnings : Requires unproven (!string.IsNullOrEmpty(value)), which let me think (not surprisingly though) that the static checker is not smart enough to see the Page.IsValid (this would probably far more complex for the static checker to have such intelligence).
What are my options in this case ?
The option option I see is to help the static check with assume :
protected void btnDo_Click(object source, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
Contract.Assume(!string.IsNullOrEmpty(value));
Do(txtDo.Text);
}
}
This has the merit to works as expected, but the client side is noised by a lot of Contract.Assume on large project.
Any idea/suggestion ?

I think that Contract.Assume() is the right choice here. Yes it's noisy, but I don't know any better way that wouldn't complicate the issue.

Related

ASP:Button tag is onclick method is not calling

Button on click method is not calling
Button code :
<asp:Button ID="personalSub" runat="server" ValidationGroup="personal" Text="Save" CausesValidation="false" OnClick="InsertPersonalDetail" />
C# Code :
protected void InsertPersonalDetail(object sender, EventArgs e)
{
Console.WriteLine("hello");
MessageBox.Show("hello");
}
If you have any problem on the page then you must see a compiler error.
You do NOT have compiler error witch is means that asp.net finds the InsertPersonalDetail function on code behind.
From what I see you call inside the button click two functions that are for desktop programming (not for web page).
Neither one can have any visible effect on your click - there is no console there to see anything, neither user interface to open the MessageBox.
protected void InsertPersonalDetail(object sender, EventArgs e)
{
Console.WriteLine("hello"); // have no effect on web page
MessageBox.Show("hello"); // have no effect on web page
}
So its called but you don't see it by just wait a pop up to appears
To check this out, run it with debuger and add a break point there.
Or add a literal on page and add some text there to verify that is called.
eg, add on page
<asp:Literal runat="server" ID="txtLiteral" />
and on code behind
protected void InsertPersonalDetail(object sender, EventArgs e)
{
txtLiteral.Text += "InsertPersonalDetail called <br />";
}

How can I stop refreshing the page in the else condition

My code:
protected void btnOk_Click(object sender, EventArgs e)
{
if (txtReportFavorite.Text != string.Empty)
{
//..
}
else
{
Response.Write("<script>alert('Enter Favorite name.')</script>");
// I need to prevent page refresh here.
}
}
How can I stop refreshing the page in the else condition. Thanks.
You can't.
The new page has already been requested when that code runs. If you don't do a postback, that code will never run.
If you want to do the validation without doing the postback, you should do it using client code instead.
The fact that you got to the server side means that your page has done a full cycle to the server and refreshed itself.
Unless you are calling this code with an Ajax call.
You can also achieve this by placing an AjaxUpdatePanel around your button that will simulate an Ajax call when your clients will submit your form.
in your code behind on page load put this
btnOk.Attributes.Add("onclick","return validate();");
in your aspx file have this script
function validate()
{
if(document.getElementById("txtReportFavorite").value == "";
{
alert("Enter Favorite name");
return false;
}
}
Your page is already go to the server side and it is in already postback is progressing.
you have to use client side code for preventing postback.
why not to use RequiredFieldValidator if only empty textbox need to validate?
you can do it on client side.
<asp:TextBox runat="server" id="txtReportFavorite" />
<asp:RequiredFieldValidator runat="server" id="txtReportFavorite" controltovalidate="txtName" errormessage="Enter Favorite name!" />
<br />
<asp:Button runat="server" id="btnSubmit" text="Ok" onclick="btn_Click" />
protected void btnSubmitForm_Click(object sender, EventArgs e)
{
if(Page.IsValid) //for secure validation
{
//do something
}
}
Try using RegisterScriptBlock.
ClientScript.RegisterStartupScript(this.GetType),"","$(document).ready(function(){alert('Enter Favorite name.')});",true);
If you want to perform from server-side do it like above.. Otherwise many answers already posted.
The kind of functionality you are showing can be easily achieved by using a Validator so the page won't post back.
As once it reaches the server, its really not possible to stop the refresh. Well, at least as far as I know.
-Milind

server side validation in asp.net?

hi all as i know that asp.net provide server side validation control which has there own built-in logic, so i want to ask here can we extend built-in logic, i means suppose we use compare validator for comparing two file at this point it will validate according to there built-in logic, but i want to add some code for compare validator, is this possible.
According to my knowledge in asp.net every control treated as class which has data and code so according to inheritance or extend can we add some code in validation control ?
It looks like you need to use
CustomValidator
You can use a custom function to define when your control passes your validation. In this case could be something like this.
void ServerValidation (object source, ServerValidateEventArgs args)
{
args.IsValid = //Define your validation here
}
CustomValidator is one option. If you rather going to implement validator similar to existing one, you can simply derive from it and override all necessary methods. But the most important method you should look for is the EvaluateIsValid.
A CustomValidator is better in situations when your logic is more likely unique. In case you want to use the logic in multiple places, I would recommend to use inheritance. It allows you to encapsulate the logic in class library if you want, CustomValidator doesn't.
In your markup:
<asp:TextBox id="Text1" runat="server" />
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Names="verdana"
Font-Size="10pt"
OnServerValidate="ServerValidation"
runat="server"/>
<asp:Button id="Button1"
Text="Validate"
OnClick="ValidateBtn_OnClick"
runat="server"/>
In the server side code:
void ValidateBtn_OnClick(object sender, EventArgs e)
{
// Display whether the page passed validation.
if (Page.IsValid)
{
Message.Text = "Page is valid.";
}
else
{
Message.Text = "Page is not valid!";
}
}
void ServerValidation(object source, ServerValidateEventArgs args)
{
try
{
// Test whether the value entered into the text box is even.
int i = int.Parse(args.Value);
args.IsValid = ((i%2) == 0);
}
catch(Exception ex)
{
args.IsValid = false;
}
}
This example is a shortened version of the one found at the documentation page for CustomValidator:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx
Yes you can. Like Carlos's answer link will tell you. You can put the code in the code behind.(.cs file)

sending data from script to .cs page

i am getting values from .cs to script but i want to send data from script to .cs page
i have tried this,but it is not working.
<script type="text/javascript">
$(document).ready(function() {
$("hfServerValue").val("From ClientSide!");
});
</script>
<asp:HiddenField ID="hfServerValue" runat="server" />
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(hfServerValue.Value.ToString ());
}
You can't directly invoke the Page_Load method from script. There are several ways to send data to server.
Try using an XMLHttpReqest
http://www.jibbering.com/2002/4/httprequest.html
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
If you're using jQuery, you may also try $.ajax(), $.load() etc.
Do remember that unlike a submit action which internally creates a request, you're trying to create the request yourself so you might need to deal with stuff like request headers (content-type, content-length etc.), content etc. So, there's a bit of work to do here even though you're trying to do a simple thing. But once you get it running it comes naturally.
You first need to add a control that get the data from javascript and post them back:
<asp:HiddenField ID="hfServerValue" runat="server" />
Then you place data on that control by getting the cliendID.
$(document).ready(function() { $("<%=hfServerValue.ClientID%>").val("From ClientSide!"); });
And then on post back you get them
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
var YourReturn = hfServerValue.Text;
}
}
This is an answer to a question. Of course ajax is a different way.
Update
Now I see the hidden field, this is also a better way the hidden field. The only error is that you did not use the CliendID !. Also I do not know if you use prototype or jquery or just microsoft.

asp.NET how to change Session Language?

I am new to this and would like to create a few simple hyperlinks that change the session language parameter.
Then I will test against this parameter to show dynamically different page elements.
I have not been able to find any sort of tutorial discussing a simple solution for this, only full blown tutorials that are in depth with databases and everything.
I was hoping someone here might be able to simply lead me to a beginners tutorial on how to alter the Session language parameter?
Any help appreciated!
thanks in advance
Something along this line?
Thread.CurrentThread.CurrentCulture = new CultureInfo( "pt-BR", false );
You can learn more about it here:
Globalization and localization demystified in ASP.NET 2.0
Edit:
Based on your comment bellow I now understand better what you want to do.
For the link part you can use LinkButton in your .aspx page as:
<asp:LinkButton id="linkButton1"
runat="server"
OnCommand="LinkButton1_Click"
CommandArgument="pt-BR">Click Me for Portuguese from Brazil
</asp:LinkButton>
Now in your code-behind file .cs:
private void LinkButton1_Click(object sender, System.EventArgs e)
{
string language = e.CommandArgument.ToString();
if(language.Equals("pt-BR"))
{
// Place your logic here for Portuguese-Brazil... Show or hide DIV...
}
}
If you wanna use Session, do this:
To store the value in Session:
private void LinkButton1_Click(object sender, System.EventArgs e)
{
string language = e.CommandArgument.ToString();
Session["lang"] = language;
}
To read the value from Session:
if (Session["lang"] != null)
{
if(Session["lang"].ToString().Equals("pt-BR"))
{
// Place your logic here for Portuguese-Brazil... Show or hide DIV...
}
}

Resources