.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Using DataAnnotations to verify integer

Posted By:      Posted Date: October 01, 2010    Points: 0   Category :ASP.Net

I am using Entity Framework with partial classes added on so I can use DataAnnotation attributes.  Does anyone know how to add a data annotatin which will verify that a field is a whole number (or a DataType of int or long)?  I'm surprised there is no [DataType(DataType.Integer)] attribute.  I tried to create a custom attribute, but it doesn't work because the value it receives is always null:

[DataTypeWholeNumberAttribute(ErrorMessage = "Zip must be a whole number")]
public object Zip{ get; set; }

public class DataTypeWholeNumberAttribute : ValidationAttribute
    public override bool IsValid(object value)
       long i;

        if (value == null) //value is always null.
            return false;

        return Int64.TryParse(value.ToString(), out i);

Obviously I'm missing the point, but I don't know enough to know what I'm missing.  Can anyone shed some light?

View Complete Post

More Related Resource Links

Integer Validation



I need to make validation for Textbox to allow enter integer stated by 9 or 6 or 5 , and also maximum 8 digits , how to do that ?





How to cast integer values as an array of enum values?


Hello all!

I'm working with VS2010 Beta2, ASP.NET and Dynamic Data. I'm using VB but will certainly be happy to receive a C# example if necessary. Laughing

I used a few of Steve's examples (Writing Attributes and Extension Methods for Dynamic Data and Dynamic Data - Hiding Columns in selected PageTemplates) to create a custom property attribute to be applied to a dynamic data column and want it to accept an array of enum values (each value will represent a dynamic data page template where this column should not be displayed).  My new attribute works fine when I hardcode it like this, meaning the HideColumnIn attribute is properly populated with the array of enum values:

<HideColumnIn(PageTemplate.List, PageTemplate.Edit)> _
Public Property My_DD_Column As Object


However, I want to store the values to be used for the HideColumnIn in the DB as integer values that correspond to the

Which ComponentModel.DataAnnotations attributes are used in the Dynamic Data metadata classes?


This namespace contains a lot of attributes for use in, I'm sure, many different applications. I'm curious to know which subset of the attributes in this namespace can be and are used in the Dynamic Data proxy class system, where the entity class is given an attribute that specifies a metadata type. That type contains properties with the same names as properties in the entity class, and the metadata provider builds MetaColumns using attributes on properties in these 'buddy' (proxy') classes.

So far my list includes, from System.ComponentModel.DataAnnotations:

Required, Range, DisplayFormat, StringLength, UIHint, DataType, Regular Expression, Display Column, Editable, and CustomValidation.

And from System.ComponentModel:

DisplayName, Description, and DefaultValue.

Am I missing any?

This was originally asked by myself on StackOverflow at: http://stackoverflow.com/questions/3537356/which-componentmodel-dataannotations-attributes-are-used-in-the-dynamic-data-meta

Creating an integer only textbox control

Hi all I was wondering on how to create an integer only textbox control. Im close I just cant figure out why its not working. public partial class IntegerTextBox : TextBox { public IntegerTextBox() { } private void OnTextChanged(KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) e.Handled = true; } }

The type 'DataGrid' was not found. Verify that you are not missing an assembly reference and that

Hi; I'm new to WPF and I was going through the ExpenseIt tutorial on MSDN's website. The tutorial was working fine until I added DataGrid. I got the error message: "The type 'DataGrid' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built."     I could not find a clear answer online of which assembly references to fix and how to fix them. Any help would be appreciated. Thanks!     Note: I'm running the following: Windows Vista 32-bit operating system Microsoft Visual Studio 2008 Version 9.0.30729.1 SP Microsoft .NET Framework Version 3.5 SP1

DataContractSerializer do not verify "xml markup name" / "property name" correspondance

Hello, I use the DataContractSerializer o serialize / deserialize a complex class. During deserialisation, if an XML markup does not correspond to any property of my class, or if a property of the class is not present in the XML, there is not a single warning. This is problematic if a user make an invalid modification in the xml, or if a developer make a refactor in the code... How can I change this behavior ?   Thanks for your time.

Integer Value of 80 being returned as 20480

I'm writing an applicaiton that lists all of the ports of existing processes on the system.  However the system is returning the value of 20480 as the value for port 80.  I've found a couple of articles that would indicate that the discrepancy is because of the "endianess" of the underlying system and that reversing the byte order would resolve the problem.  However when I convert the return value to an array of bytes the values show up as 0,80,0,0.  Even reversing the order of the bytes wouldn't return the appropriate value of 80. Specifically I'm calling into the iphlpapi.dll using the following function [DllImport("iphlpapi.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]         private static extern int GetExtendedTcpTable(IntPtr pTcpTable, ref int dwOutBufLen, bool bOrder, int dwFamily, TCP_TABLE_CLASS dwClass, int dwReserved); Here's some additional code from the listing this.m_TcpTable.Add(new TcpEntry(entry.dwState, entry.dwRemoteAddr, entry.dwRemotePort, entry.dwLocalAddr, entry.dwLocalPort, entry.dwProcessId)); public TcpEntry(TcpState state, UInt32 remoteAddr, int remotePort, UInt32 localAddress, int localPort, int processID)         {             this.m_State = state; &nb

DataAnnotations.Display.Order not working with MVC 2 (using Futures)

Hi All!I have these two classes in my model: public partial class Customer { #region Primitive Properties [Display(Name="Note", Order=10)] public virtual string Notes { get; set; } ... public partial class AdvisoryCentre : Customer { #region Primitive Properties [Display(Name="Denominazione", Order=-10)] public virtual string BusinessName { get; set; } ... In the editor for the AdvisoryCentre model, using Html.EditorForModel, the behavior is not what i expected. When creating a new AdvisoryCentre object, BusinessName and Notes fields are shown in correct order, but when i edit an existing AdvisoryCentre with empty Notes property, the Notes field is always shown before BusinessName field. If Notes property is not empty, the fields order is correct.There is a workaround for this problem?Thankyou

Need help using the integer ID assigned in another field

Hi, My table stores information about files stored in the file system. I need to use the ID assigned by the database (primary key) in the file name. Is there a way to use the ID being assigned in the INSERT statement or will I have to make an INSERT statement, then get SCOPE_IDENTITY(), then do an UPDATE? Table looks something like this: FileID int (PK) FileName varchar(250) Here's an example of what I'm trying to do: INSERT INTO MyFiles (FileName) VALUES (-- ??? Not sure what goes here) Thanks, Sam

The report server is not responding. Verify that the report server is running and can be accessed fr

When I trying to configure Reposrting services in IIS & XP. It hsows me error  "The report server is not responding. Verify that the report server is running and can be accessed from this computer."   I also configure with reposrting configuration tools which show all confuguration is perfect.   but when I try to open through IE http://localhost/Reports/Pages/Folder.aspx   or http://localhost/Reportserver   It shows error. I try all ways still not works ..Help me out   Thanks.

Value changing to integer value when changing top drop down box from cascaded drop downs in Sharepoi

Hi, I have two drop down boxes named Categories and Sub Categories. When I select a category, the sub category populates fine and I can select the values where the category is equal to the category lookup field. But as soon as I then change the Category field again once I have selected both the category and sub category fields, the sub category field changes to an integer value? How can I change this so it just selects the blank value again?

Validating ICollection using DataAnnotations

 What's the best way to validate ICollectionie. sample class: public class BlogPost    {        public BlogPost()        {            this.CreateDate = DateTime.Now;            this.IsPostNow = false;        }        public virtual int BlogPostId { get; set; }        public virtual int AdminId { get; set; }        public virtual ICollection<BlogCategory> BlogCategory { get; set; }    }what's the best way to ensure that at least ONE BlogCategory is selected (if on the edit page BlogCategory is a list of checkboxes)thanks

Convert integer to binary using asp.net

Hi I have an Integer value as 15, i want to convert as binary value. please guide me.   Thanks S.Andrews  

The type 'DropShadowEffect' was not found. Verify that you are not missing an assembly reference a

We created a grid in Expressions Blend but the DropShadowEffect caused an error for a developer who tried to build the solution and did not have Expressions Blend on his machine.  Had to replace with  <Border.BitmapEffect><DropShadowBitMapEffect ... Are there other incompatibilities between Expressions Blend and plain old Visual Studio 2008 development environs? <   UserControl   xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation   xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml   xmlns:d=http://schemas.microsoft.com/expression/blend/2008   xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006   mc:Ignorable="d"   xmlns:igRibbon=http://infragistics.com/Ribbon   x:Class="TestEditor.Ctrl_PR"   x:Name="UserControl"   MaxWidth="450"   d:DesignWidth="450" d:DesignHeight="125">     <Grid x:Name="LayoutRoot" RenderTransformOrigin="0.5,0.5" Width="450" Height="125">   <Border CornerRadius="8" BorderBrush="DarkSlateBlue" BorderThickness="0.5" HorizontalAlignment="Stretch" Grid.ColumnSpan="2">     <Border.Background>       <LinearGradientB

How to cast integer values to an array of enum values?

Hello all! I'm new to VB.NET (and OOP in general) and am struggling a bit...  I'm working with VS2010 Beta2, ASP.NET and Dynamic Data, however I'm thinking this question may be more related to VB so hopefully I've chosen the correct forum. I have a list of integer values stored in the DB and would like to cast them to an array of enum values so that they may be passed to my constructor.  The values in the DB directly correspond to the enum values.  Here is stripped down version of the code that hopefully highlights what I'm attempting to do:Private _pageTemplate() As PageTemplate Public Sub New(ByVal ParamArray pageTemplateArray As PageTemplate()) _pageTemplate = pageTemplateArray End Sub Public Enum PageTemplate Details = 1 Edit = 2 Insert = 3 List = 4 ListDetails = 5 End Enum What I'm having difficulty with is reading integer values from the DB and casting them to an array of PageTemplate() to be passed to the constructor above.  The integer values in the DB will be 1 through 5 to correspond to the enum values listed above.  Here is how I'm trying to build the ParamArray to be passed to the attribute constructor:Dim hideFieldsIn(-1) As PageTemplate Dim rowCount As Integer = -1 If reader.HasRows Then While reader.Read() rowCount += 1 ReDim hideFieldsIn(rowCount)

Security Context Token verification failed. (The security protocol cannot verify the incoming messag

Hello, I would like implement Message Lever security with username/password authentication on HTTP. My environment looks something like this.  Server Side - Message lever security is configured on service.           <security mode="Message">             <message clientCredentialType="UserName" negotiateServiceCredential="True"/>           </security> - CA and self signed certificates are created on server and configured. ServiceCredentials are looks like this <serviceCredentials> <serviceCertificate findValue="CertForIdm" storeLocation="LocalMachine" storeName="My" x509FindType="FindByIssuerName" /> <userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="IfMembershipProvider" /> </serviceCredentials> Client Side (References are generated by VS) - Binding configuration                 <binding name="WSHttpBinding_IWaypoint2" closeTimeout="00:11:00"                     openTimeout="00:11:00" receiveTimeout="00:10:00" sendTimeout="00:11:00"  &nb

Problem in verify data via SQL

I am facing problem in verify a registered user. The program can only read the first row table data. For example, the row 1 username is A, password is a, the row 2 username is B, the password is b, if I login via username A i can enter the system, but if I login via username B, the program cannot verify the username B. Here are my codes....Can anyone tell me what's going on?private bool YourValidationFunction(string UserName, string Password)    {        bool boolReturnValue = false;        string strConnection = @"Data Source=MY-PC;Initial Catalog=myDB.MDF;Integrated Security=True";        SqlConnection sqlConnection = new SqlConnection(strConnection);        String SQLQuery = "SELECT psw, userID, usertype FROM dbo.users_login";        SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);        SqlDataReader Dr;        sqlConnection.Open();        Dr = command.ExecuteReader();        while (Dr.Read())        {            if ((Login1
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend