<%@ 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.");
}
}
}
Everything seems right with your current codes……So what do you mean
AlAnoud
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……???
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 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
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.
See my blog C# Bits | Twitter @sjnaughton Always seeking an elegant solution.
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
See my blog C# Bits | Twitter @sjnaughton Always seeking an elegant solution.
Marked as answer by sjnaughton on Apr 12, 2012 01:14 PM
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.
See my blog C# Bits | Twitter @sjnaughton Always seeking an elegant solution.
Decker Dong ...
All-Star
118619 Points
18779 Posts
Re: Date Validation
Apr 09, 2012 08:01 AM|LINK
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:
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."); } } }AlAnoud
0 Points
7 Posts
Re: Date Validation
Apr 09, 2012 09:31 AM|LINK
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>
Decker Dong ...
All-Star
118619 Points
18779 Posts
Re: Date Validation
Apr 10, 2012 01:06 AM|LINK
Hello AlAnoud:)
Everything seems right with your current codes……So what do you mean
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……???
AlAnoud
0 Points
7 Posts
Re: Date Validation
Apr 10, 2012 05:10 AM|LINK
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
TimoYang
Contributor
3732 Points
1275 Posts
Re: Date Validation
Apr 10, 2012 05:39 AM|LINK
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……
sjnaughton
All-Star
27330 Points
5459 Posts
MVP
Re: Date Validation
Apr 10, 2012 09:57 AM|LINK
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.
Always seeking an elegant solution.
sjnaughton
All-Star
27330 Points
5459 Posts
MVP
Re: Date Validation
Apr 10, 2012 01:57 PM|LINK
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
Always seeking an elegant solution.
AlAnoud
0 Points
7 Posts
Re: Date Validation
Apr 11, 2012 09:53 AM|LINK
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
sjnaughton
All-Star
27330 Points
5459 Posts
MVP
Re: Date Validation
Apr 11, 2012 11:05 AM|LINK
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.
Always seeking an elegant solution.