locked
Date Validation RRS feed

  • Question

  • User1511392911 posted

    Hi all,

    The following is a part of a class that I have created for manual scaffolding

     

    [ScaffoldTable(true)]

        [MetadataType(typeof(PROJECT_INITIATIVEMetaData))]

        [DisplayName("**********")]

        public partial class PROJECT_INITIATIVE

        {  //planned end date must be greated than planned start date

     

            partial void OnPROJECT_PLANNED_END_DATEChanging(Nullable<global::System.DateTime> value)

                 {

                     if (value != null && value < Convert.ToDateTime(this.PROJECT_PLANNED_START_DATE))

                     {

                         throw new ValidationException("Planned end date must be greated than planned start date.");

                     }

                 }

            //***************************************************************************

        }

     

        public class PROJECT_INITIATIVEMetaData

            {

                [ScaffoldColumn(false)] 

                public object PROJECT_ID { get; set; }

     

                [DisplayName("Project Code- رمز المشروع")]

                public object PROJECT_CODE { get; set; }

     

                [DisplayName("**********")]

                public object PROJECT_DESC_ARB{ get; set; }

               

                 // [Display(Name = " Project Name", Order = 3)]

                 [DisplayName("Project Name")]

                 public object PROJECT_DESC_ENG { get; set; }

     

                 [DisplayName("********")]

                 public object PROJECT_BASELINE_ARB { get; set; }

     

                 [DisplayName("******")]

                 public object PROJECT_BASELINE_ENG { get; set; }

     

                 [UIHint("Date")]

                 [DisplayName("Planned Start Date-التاريخ المتوقع للبدء")]

                 public object PROJECT_PLANNED_START_DATE { get; set; }

                 [UIHint("Date")]

                 [DisplayName("*********")]

                 public object PROJECT_PLANNED_END_DATE { get; set; }

                 [UIHint("Date")]

                 [DisplayName("********")]

                 public object PROJECT_ACTUAL_START_DATE { get; set; }

                  [UIHint("Date")]

                 [DisplayName("*********** ")]

                 public object PROJECT_ACTUAL_END_DATE { get; set; }          

             }

     

    In table  PROJECT_INITIATIVE I have “planned start date” and “planned end date”, I have to make sure that the planned end date is greater that the planned start date.

    As mentioned above I wrote the following code for the validation

            partial void OnPROJECT_PLANNED_END_DATEChanging(Nullable<global::System.DateTime> value)

                 {

                     if (value != null && value < Convert.ToDateTime(this.PROJECT_PLANNED_START_DATE))

                     {

                         throw new ValidationException("Planned end date must be greated than planned start date.");

                     }

                 }

    How can I display the error in the list validation errors and avoid getting “ValidationExceptionwas unhandled by user code" error

    • "Date" is a custom field template that was created to display a Calendar control for editing dates.

     

    Thursday, April 5, 2012 5:27 AM

Answers

  • User-330204900 posted

    Sorry I got confused with another post :) try something like this:

    public partial class ProjectsDataModel
    {
        internal const string CANNOT_HAVE_DUPLICATES = "{0} cannot have duplicates.";
    
        partial void OnContextCreated()
        {
            // Register the handler for the SavingChanges event. 
            this.SavingChanges += new EventHandler(context_SavingChanges);
        }
    
        public override int SaveChanges(System.Data.Objects.SaveOptions options)
        {
            try
            {
                return base.SaveChanges(options);
            }
            catch (Exception exception)
            {
                // Find the most innermost exception, unwrap it.
                var message = exception.ExtractExceptionMessage();
    
                //TODO: build logging and notification in here
                throw new ValidationException(message);
            }
        }
    
        private static void context_SavingChanges(object sender, EventArgs e)
        {
            var objects = ((ObjectContext)sender).ObjectStateManager;
    
            #region Inserted objects
            foreach (ObjectStateEntry entry in objects.GetObjectStateEntries(EntityState.Added))
            {
                if (entry.Entity != null)
                {
                    // auto update the EANo
                    if (entry.Entity.GetType() == typeof(PROJECT_INITIATIVE))
                    {
                        var pi = entry.Entity as PROJECT_INITIATIVE;
                        if (OnPROJECT_PLANNED_END_DATE < PROJECT_PLANNED_START_DATE)
                            throw new ValidationException("Planned end date must be greated than planned start date.");
                    }
                }
            }
            #endregion
    
            #region Updated objects
            foreach (ObjectStateEntry entry in objects.GetObjectStateEntries(EntityState.Modified))
            {
                if (entry.Entity != null)
                {
                    if (entry.Entity.GetType() == typeof(PROJECT_INITIATIVE))
                    {
                        //Do tests here
                    }
                }
            }
            #endregion
    
            #region Delete objects
            foreach (ObjectStateEntry entry in objects.GetObjectStateEntries(EntityState.Deleted))
            {
                if (entry.Entity != null)
                {
                    // ================================================================================//
                    //  NOTE: to self remember that during delete entities only have primary key value //
                    // ================================================================================//
    
                    #region EA
                    if (entry.Entity.GetType() == typeof(PROJECT_INITIATIVE))
                    {
                        var id = ((PROJECT_INITIATIVE)entry.Entity).ID;
                        var project_initiative = OC.PROJECT_INITIATIVES.FirstOrDefault(e => e.ID == id);
                        //Do tests here
                    }
                    #endregion
                }
            }
            #endregion
        }
    }
    
    public static class ExceptionExtensionMethods
    {
        public static String ExtractExceptionMessage(this Exception exception)
        {
            while (exception.InnerException != null)
                exception = exception.InnerException;
            return exception.Message;
        }
    }

    see mostly the "Inserted objects region" I have implemented the test there, also NOTE that this is a partial class off of the entity data model it is not  the code behind of the EDMX file.

    Hope that helps

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, April 10, 2012 9:57 AM

All replies

  • User-330204900 posted

    Is this Entity Framework or Linq to SQL?

     

    Friday, April 6, 2012 7:29 AM
  • User436389104 posted

    Would you please give more explaination, you said:

    How can I display the error in the list validation errors and avoid getting “ValidationExceptionwas unhandled by user code" error


    As you threw an specific exception, naturally you'll get the mentioned exception, what do you mean by " display the error in the list "?

    Friday, April 6, 2012 7:36 AM
  • User-330204900 posted

    Hi Amin.Mirzapour, this is the Dynamic Data forum which is a framework that sits on WebForms is uses templates ans scaffolding to give you a RAD development experience and one of the things it does is display errors in a validation list at the top of all pages when editing.

    Friday, April 6, 2012 7:38 AM
  • User436389104 posted

    Thanks stive.Smile

    Friday, April 6, 2012 8:53 AM
  • User3866881 posted

    value != null

    Hello:)

    Since value is nullable,I think you can use value.HasValue to check whether it's really having a real value of DateTime instead of checking whether it belongs to null or not。

    As for customizing checking……If you are using LINQ-TO-SQL,you can have a look at this(Point is that you should use DynamicValidator)

    http://msdn.microsoft.com/en-us/library/cc488527.aspx

    Friday, April 6, 2012 9:35 PM
  • User1511392911 posted

    It is Entity Framework

    Monday, April 9, 2012 2:50 AM
  • User1511392911 posted

    Hi all,

    I think the problem is in Date_Edit.ascx

    <%

    @ Control Language="C#" CodeBehind="Date_Edit.ascx.cs" Inherits="GSDP_MES.DynamicData.FieldTemplates.Date_EditField"

    %>

    <

    asp:Calendar ID="DateCalendar" runat="server"></asp:Calendar

    >

     

    How can I add dynamic validator to the previous code?

    Please recommend

    Monday, April 9, 2012 3:20 AM
  • User3866881 posted

    Hello again:)

    How can I add dynamic validator to the previous code?

    I don't think it a good idea to dynamically bind a DynamicValidator to the Calendar,maybe you can just specify the control into the aspx and assign the ControlToValidate property to deal with the problem……

    Monday, April 9, 2012 3:31 AM
  • User1511392911 posted

     

    Hello again:)

    I don't think it a good idea to dynamically bind a DynamicValidator to the Calendar,maybe you can just specify the control into the aspx and assign the ControlToValidate property to deal with the problem……

    Hi,

    unfortunately I'm an Oracle developer, and this is a new and very complicated technology for me :(

    1. how can I specify the control?

    2. which aspx ?

    3. how and where I assign the controlTovalidate property?

    Thanks, 

    Monday, April 9, 2012 3:44 AM
  • User3866881 posted

    unfortunately I'm an Oracle developer, and this is a new and very complicated technology for me :(

    Oops……Don't worry and it shouldn't be so complicated……

    Just drag and drop the DynamicValidator onto the same page to the control that you want to valrify……Sample looks like this:

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <cc1:dynamicvalidator runat="server" ID="dynamicValidator"
       ControlToValidate="TextBox1"></cc1:dynamicvalidator>
    Full sample:
    <%@ Page Language="C#" 
    AutoEventWireup="true" CodeFile="CustomValidation.aspx.cs" 
    Inherits="CustomValidation" %>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title></title>
        <link href="~/Site.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
         <h2>Example: <%=Title%></h2>
    
         <!-- Enable dynamic behavior. The GridView must be 
         registered with the manager. See code-behind file. -->
        <asp:DynamicDataManager ID="DynamicDataManager1" runat="server"
            AutoLoadForeignKeys="true" />
    
    
        <form id="form1" runat="server">
    
            <!-- Capture validation exceptions -->
            <asp:DynamicValidator ID="ValidatorID" ControlToValidate="GridView1" 
                runat="server" /> 
            <asp:DynamicValidator ID="DynamicValidator1" ControlToValidate="GridView2" 
                runat="server" /> 
            <table>
                <tr>
                    <td align="left" valign="top" style="font-weight:bold">
                        Customize Validation Using the Table OnValidate 
                    </td>
                    <td>
                        <asp:GridView ID="GridView1" 
                            runat="server" 
                            DataSourceID="GridDataSource" 
                            AutoGenerateColumns="false"  
                            AutoGenerateEditButton="true"
                            AllowPaging="true" 
                            PageSize="5"
                            AllowSorting="true">
                            <Columns>
                                <asp:DynamicField DataField="Title" />
                                <asp:DynamicField DataField="FirstName" />
                                <asp:DynamicField DataField="LastName" />
                            </Columns>
                            <EmptyDataTemplate>
                                There are currently no items inthis table.
                            </EmptyDataTemplate>
                        </asp:GridView>
                    </td>
                </tr>
                <tr>
                    <td align="left" valign="top" style="font-weight:bold">
                        Customize Validation Using OnOrderQtyChanging
                    </td>
                    <td>
                        <asp:GridView ID="GridView2" 
                            runat="server" 
                            DataSourceID="GridDataSource2" 
                            AutoGenerateColumns="false"  
                            AutoGenerateEditButton="true"
                            AllowPaging="true" 
                            PageSize="5"
                            AllowSorting="true">
                            <Columns>
                                <asp:DynamicField DataField="OrderQty" />
                            </Columns>
                            <EmptyDataTemplate>
                                There are currently no items inthis table.
                            </EmptyDataTemplate>
                        </asp:GridView>
                    </td>
                </tr>
            </table>
    
        </form>
    
        <!-- Connect to the database -->
        <asp:LinqDataSource ID="GridDataSource" runat="server"  
             TableName="Customers" EnableUpdate="true"
            ContextTypeName="AdventureWorksLTDataContext">
    
        </asp:LinqDataSource>
    
         <!-- Connect to the database -->
        <asp:LinqDataSource ID="GridDataSource2" runat="server"  
             TableName="SalesOrderDetails" EnableUpdate="true"
            ContextTypeName="AdventureWorksLTDataContext">
        </asp:LinqDataSource>
    </body>
    </html>
    using System;
    using System.Collections;
    using System.Configuration;
    using System.Web.DynamicData;
    
    publicpartialclass CustomValidation : System.Web.UI.Page
    {
        protected MetaTable _table1, _table2;
    
        protectedvoid Page_Init(object sender, EventArgs e)
        {
            // Register data controls with the data manager.
            DynamicDataManager1.RegisterControl(GridView1);
            DynamicDataManager1.RegisterControl(GridView2);
        }
    
        protectedvoid Page_Load(object sender, EventArgs e)
        {
            // Get the table entities.
            _table1 = GridDataSource.GetTable();
            _table2 = GridDataSource2.GetTable();
    
            // Assign title dynamically.
            Title = string.Concat("Customize Validation of the ",
                _table1.Name, " and ",  _table2.Name, " Tables");
    
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.DynamicData;
    using System.ComponentModel.DataAnnotations;
    
    [MetadataType(typeof(CustomerMetadata))]
    public partial class Customer
    {
    
    
        partialvoid OnValidate(System.Data.Linq.ChangeAction action)
        {
            if (!char.IsUpper(this._LastName[0]) ||
                !char.IsUpper(this._FirstName[0])  ||
                !char.IsUpper(this._Title[0]))
                thrownew ValidationException(
                   "Data value must start with an uppercase letter.");
        }
    
    
    }
    
    public class CustomerMetadata
    {
        [Required()]
        publicobject Title;
    
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.DynamicData;
    using System.ComponentModel.DataAnnotations;
    
    public partial class SalesOrderDetail
    {
        partial void OnOrderQtyChanging(short value)
        {
            if (value < 100)
            {
                thrownew ValidationException(
                    "Quantity is less than the allowed minimum of 100.");
            }
        }
    }




    Monday, April 9, 2012 4:01 AM
  • User1511392911 posted

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  <cc1:dynamicvalidator runat="server" ID="dynamicValidator"     ControlToValidate="TextBox1"></cc1:dynamicvalidator>

     

    I have modified Date_Edit.ascx as recommended to the following

    <%@ Control Language="C#" CodeBehind="Date_Edit.ascx.cs" Inherits="GSDP_MES.DynamicData.FieldTemplates.Date_EditField"%>

    <asp:Calendar ID="DateCalendar" runat="server"></asp:Calendar>

    <asp:dynamicvalidator runat="server" ID="dynamicValidator" CssClass="DDControl DDValidator"

    ControlToValidate="DateCalendar" Display="Dynamic" ></asp:dynamicvalidator>

    Next, what should I include into Edit.aspx ?

    <%@ Page Language="C#" MasterPageFile="~/Site.master" CodeBehind="Edit.aspx.cs" Inherits="GSDP_MES.Edit"

    %>

     <asp:Content ID="headContent" ContentPlaceHolderID="head" Runat="Server">

    </asp:Content>

    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

    <asp:DynamicDataManager ID="DynamicDataManager1" runat="server" AutoLoadForeignKeys="true">

    <DataControls>

    <asp:DataControlReference ControlID="FormView1" />

    </DataControls>

    </asp:DynamicDataManager>

    <h2 class="DDSubHeader">Edit entry from table <%= table.DisplayName %></h2>

     

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">

    <ContentTemplate>

    <asp:ValidationSummary ID="ValidationSummary1" runat="server" EnableClientScript="true"

    HeaderText="List of validation errors" CssClass="DDValidator" />

    <asp:DynamicValidator runat="server" ID="DetailsViewValidator" ControlToValidate="FormView1" Display="None" CssClass="DDValidator" />

    <asp:FormView runat="server" ID="FormView1" DataSourceID="DetailsDataSource" DefaultMode="Edit"

    OnItemCommand="FormView1_ItemCommand" OnItemUpdated="FormView1_ItemUpdated" RenderOuterTable="false">

    <EditItemTemplate>

    <table id="detailsTable" class="DDDetailsTable" cellpadding="6">

    <asp:DynamicEntity runat="server" Mode="Edit" />

    <tr class="td">

    <td colspan="2">

    <asp:LinkButton runat="server" CommandName="Update" Text="Update" />

    <asp:LinkButton runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" />

    </td>

    </tr>

    </table>

    </EditItemTemplate>

    <EmptyDataTemplate>

    <div class="DDNoItem">No such item.</div>

    </EmptyDataTemplate>

    </asp:FormView>

    <asp:EntityDataSource ID="DetailsDataSource" runat="server" EnableUpdate="true" />

    <asp:QueryExtender TargetControlID="DetailsDataSource" ID="DetailsQueryExtender" runat="server">

    <asp:DynamicRouteExpression />

    </asp:QueryExtender>

    </ContentTemplate>

    </asp:UpdatePanel>

    </asp:Content>

     

    Monday, April 9, 2012 5:31 AM
  • User3866881 posted

    Hello AlAnoud:)

    Everything seems right with your current codes……So what do you mean

    Next, what should I include into Edit.aspx ?

    In fact you can tell us what you really want to achieve and what you really want to gain?I couldn't understand what you really want……Last time you told me that you wanted a Dynamic Validator,but now your Dynamic Validator is finished……So……???

    Monday, April 9, 2012 9:06 PM
  • User1511392911 posted

    Hi,

    what I want is when user enters the planned_end_date  less than the planned_start_date, the error must appeared in the edit page under "Listed of validation errors", which is not the case currently

    what I get now is the following warning

     

    Tuesday, April 10, 2012 1:10 AM
  • User-1488931086 posted

    Hi,

    what I want is when user enters the planned_end_date  less than the planned_start_date, the error must appeared in the edit page under "Listed of validation errors", which is not the case currently

    what I get now is the following warning

    http://postimage.org/image/6vtbzthtj/

    This means that you haven't handled the customized exception!Plz see this full sample at:

    http://msdn.microsoft.com/en-us/library/cc488527.aspx

    Plz use your brain first before asking questions……

    Tuesday, April 10, 2012 1:39 AM
  • User-330204900 posted

    Hi AlAnoud, the easyest way for me is to use a date picker then that voids the need to date validate, send me a direct mail and I will reply with my e-mail and I can sen you a working field template.

    Tuesday, April 10, 2012 5:57 AM
  • User-330204900 posted

    Sorry I got confused with another post :) try something like this:

    public partial class ProjectsDataModel
    {
        internal const string CANNOT_HAVE_DUPLICATES = "{0} cannot have duplicates.";
    
        partial void OnContextCreated()
        {
            // Register the handler for the SavingChanges event. 
            this.SavingChanges += new EventHandler(context_SavingChanges);
        }
    
        public override int SaveChanges(System.Data.Objects.SaveOptions options)
        {
            try
            {
                return base.SaveChanges(options);
            }
            catch (Exception exception)
            {
                // Find the most innermost exception, unwrap it.
                var message = exception.ExtractExceptionMessage();
    
                //TODO: build logging and notification in here
                throw new ValidationException(message);
            }
        }
    
        private static void context_SavingChanges(object sender, EventArgs e)
        {
            var objects = ((ObjectContext)sender).ObjectStateManager;
    
            #region Inserted objects
            foreach (ObjectStateEntry entry in objects.GetObjectStateEntries(EntityState.Added))
            {
                if (entry.Entity != null)
                {
                    // auto update the EANo
                    if (entry.Entity.GetType() == typeof(PROJECT_INITIATIVE))
                    {
                        var pi = entry.Entity as PROJECT_INITIATIVE;
                        if (OnPROJECT_PLANNED_END_DATE < PROJECT_PLANNED_START_DATE)
                            throw new ValidationException("Planned end date must be greated than planned start date.");
                    }
                }
            }
            #endregion
    
            #region Updated objects
            foreach (ObjectStateEntry entry in objects.GetObjectStateEntries(EntityState.Modified))
            {
                if (entry.Entity != null)
                {
                    if (entry.Entity.GetType() == typeof(PROJECT_INITIATIVE))
                    {
                        //Do tests here
                    }
                }
            }
            #endregion
    
            #region Delete objects
            foreach (ObjectStateEntry entry in objects.GetObjectStateEntries(EntityState.Deleted))
            {
                if (entry.Entity != null)
                {
                    // ================================================================================//
                    //  NOTE: to self remember that during delete entities only have primary key value //
                    // ================================================================================//
    
                    #region EA
                    if (entry.Entity.GetType() == typeof(PROJECT_INITIATIVE))
                    {
                        var id = ((PROJECT_INITIATIVE)entry.Entity).ID;
                        var project_initiative = OC.PROJECT_INITIATIVES.FirstOrDefault(e => e.ID == id);
                        //Do tests here
                    }
                    #endregion
                }
            }
            #endregion
        }
    }
    
    public static class ExceptionExtensionMethods
    {
        public static String ExtractExceptionMessage(this Exception exception)
        {
            while (exception.InnerException != null)
                exception = exception.InnerException;
            return exception.Message;
        }
    }

    see mostly the "Inserted objects region" I have implemented the test there, also NOTE that this is a partial class off of the entity data model it is not  the code behind of the EDMX file.

    Hope that helps

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, April 10, 2012 9:57 AM
  • User1511392911 posted

    Dear Steve,

    I really would like to thank you for the big help you have given me with this issue. your last post was invaluable to me.

    the problem was partially solved, now when I run the project first I get the warning "validationexception was unhandled by user code"

     after I continue debugging the error message is displayed under the list of validation errors.

    how can I prevent getting the previous warning?

    Again, thank you for your help, I really appreciate it

    Wednesday, April 11, 2012 5:53 AM
  • User-330204900 posted

    Hi Al, have a look at this thread http://forums.asp.net/t/1367801.aspx/2/10 it's old but it may be that you are running .Net 3.5 SP1 or you project is based on an old .Net 3.5 SP1 Project.

    Wednesday, April 11, 2012 7:05 AM