ASP.NET file size validator not validating - c#

So I have a few ASP.NET file upload controls in my aspx file -
<asp:FileUpload ID="fulNature" class="form-control summer" runat="server" /><asp:Labe ID="lblNature" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="fulNature" Display="Dynamic"
ErrorMessage="File size should not be greater than 1 MB." ForeColor="#FF3300" OnServerValidate="ValidateFileSize"></asp:CustomValidator>
<asp:FileUpload ID="fulIndustrial" class="form-control summer" runat="server" /><asp:Label ID="lblIndustrial" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="fulIndustrial" Display="Dynamic"
ErrorMessage="File size should not be greater than 1 MB." ForeColor="#FF3300" OnServerValidate="ValidateFileSize"></asp:CustomValidator>
I'm trying to limit file size with one C# validator -
protected void ValidateFileSize(object source, ServerValidateEventArgs args)
{
var validator = (source as CustomValidator);
string controlToValidate = validator.ControlToValidate;
FileUpload SubmittedUpload = validator.NamingContainer.FindControl(controlToValidate) as FileUpload;
if (SubmittedUpload.FileBytes.Length > 1048576) // A little padding added.
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
The issue is that the validator never fires regardless of file size. I have to be missing something simple here, but I'm just not seeing it.

you can directly get the size of uploaded file:
long size=fulNature.FileContent.Length;

Try:
long filesize = SubmittedUpload.FileContent.Length;

Related

How to add custom code to a Text Page type item created in Umbraco

I have recently installed Txt starter kit on Umbraco 7. In content section of admin page, I created a page of type Text Page under Home. For the page I am limited to only selecting a picture and writing a content. On my former ASP.net website, I had the following code getting some input from user and doing a cost approximation:
<div class="costSection" runat="server">
برآورد قیمت ترجمه:
<br />
<asp:Label runat="server" Text="نوع ترجمه "></asp:Label>
<asp:DropDownList ID="ddlTranslationType" runat="server">
<asp:ListItem Value="0">فارسی به انگلیسی</asp:ListItem>
<asp:ListItem Value="1">انگلیسی به فارسی</asp:ListItem>
<asp:ListItem Value="2">فرانسه به فارسی</asp:ListItem>
</asp:DropDownList>
<br />
<asp:Label runat="server" Text="تعداد کلمه "></asp:Label>
<asp:TextBox ID="txtWordsCount" runat="server" CssClass="costSection" ></asp:TextBox><br />
<asp:Button runat="server" ID="btnCalcCost" CssClass="costSection" OnClick="btnCalcCost_Click" Text="محاسبه هزینه"/>
<asp:Label Text="" ID="lblCost" runat="server" CssClass="costSection"> </asp:Label>
</div>
And the C# code was:
protected void btnCalcCost_Click(object sender, EventArgs e)
{
int userChoice;
try{int.TryParse(ddlTranslationType.SelectedValue,out userChoice);}
catch(Exception ex){
lblCost.ForeColor = System.Drawing.Color.Red;
lblCost.Text=ex.Message;
return;
}
int wordsCount;
if (txtWordsCount.Text == null || !int.TryParse(txtWordsCount.Text,out wordsCount))
{
lblCost.ForeColor = System.Drawing.Color.Red;
lblCost.Text = "لطفا تعداد کلمات را وارد کنید";
return;
}
float cost=0;
switch (userChoice)
{
case 0: //Farsi-English
cost = (float)wordsCount / 250 * 13000;
break;
case 1: //English-Farsi
cost = (float)wordsCount / 300 * 8000;
break;
case 2: //French-Farsi
cost = (float)wordsCount / 250 * 20000;
break;
}
long estimatedCost = (long)cost;
lblCost.ForeColor= System.Drawing.Color.Green;
lblCost.Text = estimatedCost.ToString()+" تومان ";
}
In my new Umbraco post, I want to have this code, but I don't know where to add the markup and the C# code for it to work.
You should take a look at Umbraco macros at https://our.umbraco.org/DOCUMENTATION/reference/templating/macros/ - you can create a partial view and put your code in there, then add the macro to either your template or to individual pages via the editor.

Stop DropDownList SelectedIndexChanged Event firing on FormView command

I have a dropdown list inside an editItemTemplate. The Dropdownlist onSelectedIndexChanged event fires on change like I want. However it also will fire when I submit the form.
********UPDATE ************
Per Saechel comment below, I started to investigate further. Here it describes it can be done. http://blog.programmingsolution.net/net-windows-application/selectionchangecommitted-and-selectedindexchanged-events-system-nullreferenceexception-while-closing-windows-form/
BUT, I tried it and it didn't even fire the event.
I checked http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist(v=vs.110).aspx and they don't list the event.
My goal is to let the user enter the values as a % of the Total or actual as actual tons and then toggle back and forth. The end value that will be inserted into the DB will be in tons.
I want to either:
a) not fire the "onSelectedIndexChanged" event
b) Some how determine if I am on the same index and have an if statement to skip everything
c) A better way of going about this that I don't know of.
I tried verifying via the ViewState the Dropdown's current index and skip the code if it was the same but couldn't find the value. Maybe help me figure out how to get that value? Searched around and could not find how do do it.
I tried: `var vs = ViewState["ddl_units"].ToString(); and some other variations as I needed to find the control via FindControl
.aspx:
<asp:Panel ID="pnlRecycledMaterialsReceivedForm" runat="server" Visible="false">
<asp:FormView ID="fvAddRecycledMaterialsReceived" runat="server" SkinID="annualReportFormview" EnableViewState="false"
HeaderText="Selected Recycled Materials Received Detail" DataKeyNames="RecycleDetailId" DefaultMode="Insert"
DataSourceID="odsRecycledMaterialsReceivedDetail" OnDataBound="fvAddRecycledMaterialsReceived_DataBound"
OnItemCommand="fvAddRecycledMaterialsReceived_ItemCommand" OnItemInserted="fvAddRecycledMaterialsReceived_ItemInserted"
OnItemUpdated="fvAddRecycledMaterialsReceived_ItemUpdated" OnItemDeleted="fvAddRecycledMaterialsReceived_ItemDeleted">
<EditItemTemplate>
<asp:TextBox ID="tbxRecycledTotalWasteQuantity" runat="server" Text='<%# Bind("TotalWasteQuantity") %>' Width="64px"></asp:TextBox>
<asp:TextBox ID="tbxRecycledWasteCommercialQuantity" runat="server" Text='<%# Bind("CommercialQuantity") %>' Width="64px"></asp:TextBox>
<asp:TextBox ID="tbxRecycledWasteResidentialQuantity" runat="server" Text='<%# Bind("ResidentialQuantity") %>' Width="64px"></asp:TextBox>
<asp:DropDownList ID="ddl_Units" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_Units_SelectedIndexChanged">
<asp:ListItem Value="" Text="" Enabled="false" />
<asp:ListItem Text="Tons" Value="1" />
<asp:ListItem Text="Percent" Value="9" />
</asp:DropDownList>
<asp:LinkButton ID="lbtnWasteReceivedUpdate" runat="server" Text="Update" CommandName="Update"
ValidationGroup="RecycledWasteReceivedDetail" Font-Bold="True" />
<asp:LinkButton ID="lbtnWasteReceivedInsertCancel" runat="server" Text="Cancel" CausesValidation="False" CommandName="Cancel" />
</EditItemTemplate>
</asp:FormView>
</asp:Panel>
.cs:
protected void ddl_Units_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox tbxRecycledTotalWasteQuantity = (TextBox)fvAddRecycledMaterialsReceived.FindControl("tbxRecycledTotalWasteQuantity");
TextBox tbxRecycledWasteResidentialQuantity = (TextBox)fvAddRecycledMaterialsReceived.FindControl("tbxRecycledWasteResidentialQuantity");
var d_TotalWasteQuantity = Convert.ToDecimal(tbxRecycledTotalWasteQuantity.Text);
ResidentialQuantity = Convert.ToDecimal(tbxRecycledWasteResidentialQuantity.Text);
DropDownList ddl_units = (DropDownList)fvAddRecycledMaterialsReceived.FindControl("ddl_units");
if (ddl_units.SelectedIndex.ToString() == "2")
{
//2 = percent
//Take tb value and convert to percent
//300/700 * 100
tbxRecycledWasteResidentialQuantity.Text = ((ResidentialQuantity / d_TotalWasteQuantity) * 100).ToString();
//ResidentialQuantity = ResidentialQuantity * (d_TotalWasteQuantity / 100);
}
else
{
//Else 'tons' was chosen. Convert value(%) to tons.
//700 * (43/100) = 301
ResidentialQuantity = d_TotalWasteQuantity * (ResidentialQuantity / 100);
tbxRecycledWasteResidentialQuantity.Text = ResidentialQuantity.ToString();
//tbxRecycledWasteResidentialQuantity.Text = "Tons";
}
}
Try using the SelectionChangeCommitted Event.
This will not trigger on form load but triggers on selectionchange

CustomValidation using OnServerValidate and ClientValidationFunction

I have problems in using CustomValidation control, I want to check if year entered in date of birth text field is less than graduation year selected from a drop down list by 20 years. I think using ClientValidationFunction is much better when i tried to use it:
<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="Enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" ClientValidationFunction="GraduationYearValidation"></asp:CustomValidator>
here is the script
<script type="text/javascript">
function GraduationYearValidation(sender, args) {
var brithYear = parseInt(new Date(document.getElementById('<%=txtBirthDate.ClientID%>').value).getFullYear());
var gradeYear = parseInt(document.getElementById('<%=ddlGraduationYear.ClientID%>').options[document.getElementById('<%=ddlGraduationYear.ClientID%>').selectedIndex].text);
if ((brithYear - gradeYear) < 20) {
return args.IsValid = true;
}
else {
return args.IsValid = false;
}
}
I get those errors: document.getElementById(...) is null and GraduationYearValidation is not defined.
so, i tried to make it server side by:
<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" OnServerValidate="BirthYearCustomValidator_ServerValidate"></asp:CustomValidator>
code behind is :
protected void BirthYearCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
int brithYear = Convert.ToDateTime(txtBirthDate.Text).Year;
int gradeYear = Convert.ToInt32(ddlGraduationYear.SelectedValue);
if ((gradeYear - brithYear) < 20)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
it doen't work and i searched for the reason i found it may be because i need to write Page.Validate("SaveEducationStep"); and check if Page.IsValid before save, but it still not working with me
any suggestion on both scenarios will be appreciated. thanks.
client side validation is working, check your code
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:DropDownList ID="dddate" runat="server">
<asp:ListItem Text="2014" Value="2014"></asp:ListItem>
<asp:ListItem Text="2013" Value="2013"></asp:ListItem>
<asp:ListItem Text="2012" Value="2012"></asp:ListItem>
<asp:ListItem Text="2011" Value="2011"></asp:ListItem>
</asp:DropDownList>
<asp:CustomValidator ID="CustomValidator1" ValidateEmptyText="true" EnableClientScript="true" runat="server" ErrorMessage="CustomValidator" ValidationGroup="test" ClientValidationFunction="abc" ControlToValidate="dddate"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" ValidationGroup="test" />
<script type="text/javascript">
function abc(sender, args) {
var birthYear = parseInt(new Date(document.getElementById('<%=txtDate.ClientID%>').value).getFullYear());
var gradeYear = parseInt(document.getElementById('<%=dddate.ClientID%>').options[document.getElementById('<%=dddate.ClientID%>').selectedIndex].text);
if ((gradeYear - birthYear) > 20) {
return args.IsValid = true;
}
else {
return args.IsValid = false;
}
}
</script>

I want the textbox AJAX Mask Edit Extender to change based on a radio button selection

I creating an ASP.net online application with C# background. I am also using AJAX MaskEditExtender. I'm pretty new to AJAX and don't know Javascript. What I need to do is have the textbox AJAX mask change based on the selection of the radio buttons.
In this example they are choosing salary or hourly. I need the salary to be "999,999" and the hourly to be "99.99".
<asp:TextBox ID="finalwage" runat="server" Width="80px">$</asp:TextBox>
<!-- Salary Mask -->
<asp:MaskedEditExtender
ID="MaskedEditExtender1"
runat="server"
TargetControlID="finalwage"
Mask="999,999"
MessageValidatorTip="true"
MaskType="Number"
InputDirection="RightToLeft"
AcceptNegative="None"
ErrorTooltipEnabled="true">
</asp:MaskedEditExtender>
<asp:MaskedEditValidator
ID="MaskedEditValidator1"
runat="server"
ControlExtender="MaskedEditExtender1"
IsValidEmpty="true"
MinimumValue="0"
MaximumValueMessage="Must enter a number"
ControlToValidate="finalwage" >
</asp:MaskedEditValidator>
<!-- Hourly Mask -->
<asp:MaskedEditExtender
ID="MaskedEditExtender2"
runat="server"
TargetControlID="finalwage"
Mask="99.99"
MessageValidatorTip="true"
MaskType="Number"
InputDirection="RightToLeft"
AcceptNegative="None"
ErrorTooltipEnabled="true">
</asp:MaskedEditExtender>
<asp:MaskedEditValidator
ID="MaskedEditValidator2"
runat="server"
ControlExtender="MaskedEditExtender1"
IsValidEmpty="true"
MinimumValue="0"
MaximumValueMessage="Must enter a number"
ControlToValidate="finalwage" >
</asp:MaskedEditValidator>
.......
<asp:RadioButtonList
ID="RadioButtonList1"
runat="server"
AutoPostBack="true"
RepeatDirection="Horizontal"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
<asp:ListItem Text="Hourly" Value="Hourly"
<asp:ListItem Text="Salary" Value="Salary" />
</asp:RadioButtonList>
Heres the C# code that I thought would work:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (RadioButtonList1.SelectedValue = "Hourly")
{
MaskedEditExtender1.Mask = "99.99";
}
if (RadioButtonList1.SelectedValue == "Salary")
{
MaskedEditExtender1.Mask = "999,999";
}
}
Try to move the RadioButtonList1_SelectedIndexChanged code to Page_Init. I believe RadioButtonList1_SelectedIndexChanged is too late in the lifecycle process to change the mask.

Required field validator for User control not working

Hi I have created user control for re-sizable text box.
<asp:Panel ID="PanelText" runat="server" CssClass="frameText">
<asp:TextBox runat="server" ID="TextBoxResizable" CssClass="noborder" Width="100%"
Height="100%" TextMode="MultiLine">
</asp:TextBox>
</asp:Panel>
<cc1:ResizableControlExtender ID="ResizableTextBoxExtender" runat="server" TargetControlID="PanelText"
ResizableCssClass="resizingText" HandleCssClass="handleText" OnClientResizing="OnClientResizeText" />
And have created Validator property for this control like:
[ValidationProperty("Text")]
public partial class ResizableTextBoxControl : System.Web.UI.UserControl
{ public string Validator
{
get { return this.TextBoxResizable.Text; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
In aspx page I am using this control like:
<uc1:ResizableTextBoxControl ID="tbDescription" MinimumHeight="50" MinimumWidth="100"
MaximumHeight="300" MaximumWidth="400" runat="server" onKeyPress="javascript:Count(this,1500);" onKeyUp="javascript:Count(this,1500);" ValidationGroup="vgSubmit" ></uc1:ResizableTextBoxControl>
<asp:RequiredFieldValidator ID="rfvDescription" runat="server" controlToValidate="tbDescription" ValidationGroup="vgSubmit" ErrorMessage="Description" Text="*" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
When I click on submit, "tbDescription" does not appear to be mandatory.
What can be wrong with the code?
EDIT
Ok...I got what was the problem, one control was hidden, and required field validator for that control was not disabled, I did it using jquery and now everything is fine except asterics.. I dont understand why asterics are not visible..
try placing your validator to your controlle especially if you just try to validate one textbox
<asp:Panel ID="PanelText" runat="server" CssClass="frameText">
<asp:TextBox runat="server" ID="TextBoxResizable" CssClass="noborder" Width="100%"
Height="100%" TextMode="MultiLine">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="rfvDescription" runat="server" controlToValidate="TextBoxResizable"
ValidationGroup="vgSubmit"
ErrorMessage="Description" Text="*"
ForeColor="Red" SetFocusOnError="True">
</asp:RequiredFieldValidator
</asp:Panel>
<cc1:ResizableControlExtender ID="ResizableTextBoxExtender"
runat="server" TargetControlID="PanelText"
ResizableCssClass="resizingText" HandleCssClass="handleText OnClientResizing="OnClientResizeText" />
in to the user controller it might not be recognized after the page is rendered.
try using Page.IsValid in your Submit button event.
if (!Page.IsValid) {
return;
}
Sorry for all the trouble,
There was one control on page which was hidden and required field validator for that control was not disabled. I disabled it using jQuery like
$(document).ready(function () {
if (!$("#<%=TextBoxResizable.ClientID %>").is(":visible")) {
ValidatorEnable(<%=rfvTextBoxResizable.ClientID %>, false);
}
})
Asteric is visible after placing required field validator outside Panel.

Categories