Search Results

Search found 17503 results on 701 pages for 'bean validation model'.

Page 9/701 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Spring - using static final fields (constants) for bean initialization

    - by lisak
    Hey, is it possible to define a bean with the use of static final fields of CoreProtocolPNames class like this: <bean id="httpParamBean" class="org.apache.http.params.HttpProtocolParamBean"> <constructor-arg ref="httpParams"/> <property name="httpElementCharset" value="CoreProtocolPNames.HTTP_ELEMENT_CHARSET" /> <property name="version" value="CoreProtocolPNames.PROTOCOL_VERSION"> </bean> public interface CoreProtocolPNames { public static final String PROTOCOL_VERSION = "http.protocol.version"; public static final String HTTP_ELEMENT_CHARSET = "http.protocol.element-charset"; } If it is possible, what is the best way of doing this ?

    Read the article

  • ASP.NET MVC 2 Mdel encapsulated within ViewModel Validation

    - by Program.X
    I am trying to get validation to work in ASP.NET MVC 2, but without much success. I have a complex class containing a large number of fields. (Don't ask - this is oneo f those real-world situations best practices can't touch) This would normally be my Model and is a LINQ-to-SQL generated class. Because this is generated code, I have created a MetaData class as per http://davidhayden.com/blog/dave/archive/2009/08/10/AspNetMvc20BuddyClassesMetadataType.aspx. public class ConsultantRegistrationMetadata { [DisplayName("Title")] [Required(ErrorMessage = "Title is required")] [StringLength(10, ErrorMessage = "Title cannot contain more than 10 characters")] string Title { get; set; } [Required(ErrorMessage = "Forename(s) is required")] [StringLength(128, ErrorMessage = "Forename(s) cannot contain more than 128 characters")] [DisplayName("Forename(s)")] string Forenames { get; set; } // ... I've attached this to the partial class of my generated class: [MetadataType(typeof(ConsultantRegistrationMetadata))] public partial class ConsultantRegistration { // ... Because my form is complex, it has a number of dependencies, such as SelectLists, etc. which I have encapsulated in a ViewModel pattern - and included the ConsultantRegistration model as a property: public class ConsultantRegistrationFormViewModel { public Data.ConsultantRegistration ConsultantRegistration { get; private set; } public SelectList Titles { get; private set; } public SelectList Countries { get; private set; } // ... So it is essentially ViewModel=Model My View then has: <p> <%: Html.LabelFor(model => model.ConsultantRegistration.Title) %> <%: Html.DropDownListFor(model => model.ConsultantRegistration.Title, Model.Titles,"(select a Title)") %> <%: Html.ValidationMessage("Title","*") %> </p> <p> <%: Html.LabelFor(model => model.ConsultantRegistration.Forenames) %> <%: Html.TextBoxFor(model => model.ConsultantRegistration.Forenames) %> <%: Html.ValidationMessageFor(model=>model.ConsultantRegistration.Forenames) %> </p> The problem is, the validation attributes on the metadata class are having no effect. I tried doing it via an Interface, but also no effect. I'm beginning to think that the reason is because I am encapsulating my model within a ViewModel. My Controller (Create Action) is as follows: [HttpPost] public ActionResult Create(Data.ConsultantRegistration consultantRegistration) { if (ModelState.IsValid) // this is always true - which is wrong!! { try { consultantRegistration = ConsultantRegistrationRepository.SaveConsultantRegistration(consultantRegistration); return RedirectToAction("Edit", new { id = consultantRegistration.ID, sectionIndex = 2 }); } catch (Exception ex) { ModelState.AddModelError("CreateException",ex); } } return View(new ConsultantRegistrationFormViewModel(consultantRegistration)); } As outlined in the comment, the ModelState.IsValid property always returns true, despite fields with the Validaiton annotations not being valid. (Forenames being a key example). Am I missing something obvious - considering I am an MVC newbie? I'm after the mechanism demoed by Jon Galloway at http://www.asp.net/learn/mvc-videos/video-10082.aspx. (Am aware t is similar to http://stackoverflow.com/questions/1260562/asp-net-mvc-model-viewmodel-validation but that post seems to talk about xVal. I have no idea what that is and suspect it is for MVC 1)

    Read the article

  • ASP.NET MVC 2 Model encapsulated within ViewModel Validation

    - by Program.X
    I am trying to get validation to work in ASP.NET MVC 2, but without much success. I have a complex class containing a large number of fields. (Don't ask - this is oneo f those real-world situations best practices can't touch) This would normally be my Model and is a LINQ-to-SQL generated class. Because this is generated code, I have created a MetaData class as per http://davidhayden.com/blog/dave/archive/2009/08/10/AspNetMvc20BuddyClassesMetadataType.aspx. public class ConsultantRegistrationMetadata { [DisplayName("Title")] [Required(ErrorMessage = "Title is required")] [StringLength(10, ErrorMessage = "Title cannot contain more than 10 characters")] string Title { get; set; } [Required(ErrorMessage = "Forename(s) is required")] [StringLength(128, ErrorMessage = "Forename(s) cannot contain more than 128 characters")] [DisplayName("Forename(s)")] string Forenames { get; set; } // ... I've attached this to the partial class of my generated class: [MetadataType(typeof(ConsultantRegistrationMetadata))] public partial class ConsultantRegistration { // ... Because my form is complex, it has a number of dependencies, such as SelectLists, etc. which I have encapsulated in a ViewModel pattern - and included the ConsultantRegistration model as a property: public class ConsultantRegistrationFormViewModel { public Data.ConsultantRegistration ConsultantRegistration { get; private set; } public SelectList Titles { get; private set; } public SelectList Countries { get; private set; } // ... So it is essentially ViewModel=Model My View then has: <p> <%: Html.LabelFor(model => model.ConsultantRegistration.Title) %> <%: Html.DropDownListFor(model => model.ConsultantRegistration.Title, Model.Titles,"(select a Title)") %> <%: Html.ValidationMessage("Title","*") %> </p> <p> <%: Html.LabelFor(model => model.ConsultantRegistration.Forenames) %> <%: Html.TextBoxFor(model => model.ConsultantRegistration.Forenames) %> <%: Html.ValidationMessageFor(model=>model.ConsultantRegistration.Forenames) %> </p> The problem is, the validation attributes on the metadata class are having no effect. I tried doing it via an Interface, but also no effect. I'm beginning to think that the reason is because I am encapsulating my model within a ViewModel. My Controller (Create Action) is as follows: [HttpPost] public ActionResult Create(Data.ConsultantRegistration consultantRegistration) { if (ModelState.IsValid) // this is always true - which is wrong!! { try { consultantRegistration = ConsultantRegistrationRepository.SaveConsultantRegistration(consultantRegistration); return RedirectToAction("Edit", new { id = consultantRegistration.ID, sectionIndex = 2 }); } catch (Exception ex) { ModelState.AddModelError("CreateException",ex); } } return View(new ConsultantRegistrationFormViewModel(consultantRegistration)); } As outlined in the comment, the ModelState.IsValid property always returns true, despite fields with the Validaiton annotations not being valid. (Forenames being a key example). Am I missing something obvious - considering I am an MVC newbie? I'm after the mechanism demoed by Jon Galloway at http://www.asp.net/learn/mvc-videos/video-10082.aspx. (Am aware t is similar to http://stackoverflow.com/questions/1260562/asp-net-mvc-model-viewmodel-validation but that post seems to talk about xVal. I have no idea what that is and suspect it is for MVC 1)

    Read the article

  • Create Rails model with argument of associated model?

    - by Kyle Carlson
    I have two models, User and PushupReminder, and a method create_a_reminder in my PushupReminder controller (is that the best place to put it?) that I want to have create a new instance of a PushupReminder for a given user when I pass it a user ID. I have the association via the user_id column working correctly in my PushupReminder table and I've tested that I can both create reminders & send the reminder email correctly via the Rails console. Here is a snippet of the model code: class User < ActiveRecord::Base has_many :pushup_reminders end class PushupReminder < ActiveRecord::Base belongs_to :user end And the create_a_reminder method: def create_a_reminder(user) @user = User.find(user) @reminder = PushupReminder.create(:user_id => @user.id, :completed => false, :num_pushups => @user.pushups_per_reminder, :when_sent => Time.now) PushupReminderMailer.reminder_email(@user).deliver end I'm at a loss for how to run that create_a_reminder method in my code for a given user (eventually will be in a cron job for all my users). If someone could help me get my thinking on the right track, I'd really appreciate it. Thanks!

    Read the article

  • OnSelectedIndexChange only fires on second click when using custom page validation script

    - by Kris P
    Okay.. this is hard to explain, so here it goes. I have an update panel which contains a number of controls. The update panel is triggered by the OnSelectedIndexChanged event of a dropdownlist called: ddlUSCitizenshipStatus. It works as expected when I selected a new item. However, if I leave ddlUSCitizenshipStatus with the default value, and then click "submit" button on the page, the requiredfieldvalidators say there is an error on ddlUSCitizenshipStatus (which it should, as I never selected a value). So I then choose a value, the error message goes away on ddlUSCitizenshipStatus, however the updatepanel does not refresh. I've debugged this locally and the OnSelectedIndexChanged event for ddlUSCitizenshipStatus does not fire. If I choose an item in the ddlUSCitizenshipStatus list a second time, the OnSelectedIndexChanged server event fires and the update panel refreshes and works as expected. The issue is, I have to select an item in ddlUSCitizenshipStatus twice, after failed validation, before the updatepanel it's sitting in updates. The submit button on the page looks like this: <asp:LinkButton ID="btnSubmitPage1" runat="server" CssClass="continueButton" OnClick="btnSubmitPage1_Click" CausesValidation="true" OnClientClick="javascript: return ValidatePage();" /> If I remove my custom OnClientClick script, making the submit button look like this: <asp:LinkButton ID="btnSubmitPage1" runat="server" CssClass="continueButton" OnClick="btnSubmitPage1_Click" CausesValidation="true" ValidationGroup="valGrpAdditionalInformation" /> The dropdownlist, update panel, and reguiredfieldvalidator all work as expected. However, I need to run that custom "ValidatePage()" script when the button is clicked. Below is what my ValidatePage script looks like. I've been troubleshooting this for more hours than I can count.... I hope someone is able to help me. Please let me know if you can figure out why ddlUSCitizenshipStatus doesn't update the updatepanel until the second click after a failed validation. function ValidatePage() { var blnDoPostBack = true; if (typeof(Page_ClientValidate) == 'function' ) { //Client side validation can occur, so lets do it. //Validate each validation group. for( var i = 0; i < Page_ValidationSummaries.length; i++ ) Page_ClientValidate( Page_ValidationSummaries[i].validationGroup.toString() ); //Validate every validation control on the page. for (var i = 0; i < Page_Validators.length; i++) ValidatorValidate(Page_Validators[i]); //Figure out which validation groups have errors, store a list of these validation groups in an array. var aryValGrpsWithErrors = []; for( var i = 0; i < Page_Validators.length; i++ ) { if( !Page_Validators[i].isvalid ) { //This particular validator has thrown an error. //Remeber to not do a postback, as we were able to catch this validation error client side. blnDoPostBack = false; //If we haven't already registered the validation group this erroring validation control is a part of, do so now. if( aryValGrpsWithErrors.indexOf( Page_Validators[i].validationGroup.toString() ) == -1 ) aryValGrpsWithErrors[aryValGrpsWithErrors.length++] = Page_Validators[i].validationGroup.toString(); } } //Now display every validation summary that has !isvalid validation controls in it. for( var i = 0; i < Page_ValidationSummaries.length; i++ ) { if( aryValGrpsWithErrors.indexOf( Page_ValidationSummaries[i].validationGroup.toString() ) != -1 ) { Page_ValidationSummaries[i].style.display = ""; document.getElementById( Page_ValidationSummaries[i].id.toString() + "Wrapper" ).style.display = ""; } else { //The current validation summary does not have any error messages in it, so make sure it's hidden. Page_ValidationSummaries[i].style.display = "none"; document.getElementById( Page_ValidationSummaries[i].id.toString() + "Wrapper" ).style.display = "none"; } } } return blnDoPostBack; }

    Read the article

  • MVC3/Razor Client Validation Not firing

    - by Jason Gerstorff
    I am trying to get client validation working in MVC3 using data annotations. I have looked at similar posts including this MVC3 Client side validation not working for the answer. I'm using an EF data model. I created a partial class like this for my validations. [MetadataType(typeof(Post_Validation))] public partial class Post { } public class Post_Validation { [Required(ErrorMessage = "Title is required")] [StringLength(5, ErrorMessage = "Title may not be longer than 5 characters")] public string Title { get; set; } [Required(ErrorMessage = "Text is required")] [DataType(DataType.MultilineText)] public string Text { get; set; } [Required(ErrorMessage = "Publish Date is required")] [DataType(DataType.DateTime)] public DateTime PublishDate { get; set; } } My cshtml page includes the following. <h2>Create</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) Post <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.Text) </div> <div class="editor-field"> @Html.EditorFor(model => model.Text) @Html.ValidationMessageFor(model => model.Text) Web Config: <appSettings> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> Layout: <head> <title>@ViewBag.Title</title> <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script> So, the Multiline Text annotation works and creates a text area. But none of the validations work client side. I don't know what i might be missing. Any ideas?? i can post more information if needed. Thanks!

    Read the article

  • Excel 2010 data validation warning (compatibility mode)

    - by Madmanguruman
    We have some legacy worksheets that were created in Excel 2003, which are used by LabVIEW-based test automation software. The current LabVIEW software can only handle the legacy .xls format, so we're forced to keep these worksheets as-is for the time being. We've migrated to Office 2010 and when working with these worksheets, I see this warning: "The following features in this workbook are not supported by earlier versions of Excel. These features may be lost or degraded when you save this workbook in the currently selected file format. Click Continue to save the workbook anyway. To keep all of your features, click Cancel and then save the file in one of the new file formats." "Significant loss of functionality" "One or more cells in this workbook contain data validation rules which refer to values on other worksheets. These data validation rules will not be saved." When I click 'Find', some cells that do indeed have validation rules are highlighted, but those rules are all on the same worksheet! We're using simple list-based validation, with some cells off to the side containing the valid values (for example, cell B4 has a List with Source "=$D$4:$E$4") This makes no sense to me whatsoever. One, the workbook was created in Excel 2003, so obviously we couldn't implement a feature that doesn't exist. Secondly, the modifications we're making don't involve changing the validation rules at all. Thirdly, the complaint that Excel is making is incorrect! All of the rules are on the same worksheet as the target. As if the story wasn't bizarre enough: I went ahead and saved the worksheet with Excel 2010. I then went to an old computer back in the lab and opened the document with Excel 2003. Guess what - the validations were untouched! My questions are: is this a legitimate bug in Excel 2010, or is this some exotic error in the legacy .xls worksheet that is confusing the heck out of Excel 2010? Has anyone else observed this issue working in compatibility mode?

    Read the article

  • Erfolgreich durchstarten als Partner mit dem Open Market Model

    - by A&C Redaktion
    Wer als Oracle Partner bei dem erfolgreichen Programm OMM (Open Market Model) mitmacht, profitiert vierfach: Projektschutz oder Tipp-Provision, auf der Basis der OMM-Policy "Guter Name" durch kontinuierliche Projektregistrierungen Jedes erfolgreiche OMM-Projekt zählt einen Transaktionspunkt Direkter Ansprechpartner, der OMM Manager als Vermittler zum Oracle Sales Gönnen Sie sich diese 3 Minuten und Sie wissen dann, warum OMM auch für Sie interessant sein kann!

    Read the article

  • Best practice to handle Parent Form Child Form relation using Presentation Model

    - by Rajarshi
    According to Presentation Model notes by Martin Fowler and also on MSDN documentation about Presentation Model, it is explained that the Presentation Model Class should be unaware of the UI class and similarly Business Model Class should be unaware of the Presentation Model class. The UI should databind extensively to the Presentation Model, the Presentation Model in turn will co-ordinate with one or more Domain/Business Model objects to get the job done. The Presentation Model basically presents the Domain Model data in a way to facilitate maximum data binding in UI, allowing the UI take as less decisions as possible and thus increase testability of Presentation behaviours. This also makes the presentation model class generic, i.e. agnostic of any particular UI technology. Now, consider there is a List form (say CustomerList) and there is another Root form (say Customer) and there is a Use Case of allowing to Edit a Customer from the CustomerList form on a button click. For simplicity of discussion, consider that some actions took place when Customer List is opened from menu (i.e. Customer menu clicked) and the Customer List has been shown from the Menu click event. Now as per the above Use Case, I need to open the Customer Root UI (single Customer) from the Customer List. How do I do that? Build necessary objects (BusinessModel, PresentationModel, UI) in click event of Edit button and call CustomerEdit UI from there? Build the CustomerEdit UI from Presentation Model Class and show UI from presentation model? this can be done in any of the two ways below - a. Create objects in the following sequence DomainModel-PresentationModel-UIForm b. Use Unity.Resolve(); Either ways, Presentation Model is violated as the P model now has to the refer the concrete UI assembly, where CustomerEdit is located. Also the P Model has to refer and use a WinForm directly making it less UI technology agnostic. Even though the violations are in theory and can be ignored, I would still seek the community's opinion about whether I am going wrong direction. Please suggest if there's a better way to call the Child Form from the List (Parent) Form. Rajarshi

    Read the article

  • Is it possible to inject a bean into a spring form bean

    - by Mike
    I tried to do it 2 different ways, but neither way worked. @Component public class EmailForm{ ... private QuestionDAO questionDAO; ... @Autowired public void setQuestionDAO(QuestionDAO questionDAO) { this.questionDAO = questionDAO; } ... Another way: @Component public class EmailForm implements ApplicationContextAware { ... public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.questionDAO = (QuestionDAO)applicationContext.getBean("questionDAO"); } ... Neither way results in questionDAO being injected Form bean is populated by spring: @RequestMapping(method = RequestMethod.POST) public String submit(@Valid final EmailForm emailForm, BindingResult result, final Model model) {

    Read the article

  • PHP XML Strategy: Parsing DOM to fill "Bean"

    - by Mike
    I have a question concerning a good strategy on how to fill a data "bean" with data inside an xml file. The bean might look like this: class Person { var $id; var $forename = ""; var $surname = ""; var $bio = new Biography(); } class Biography { var $url = ""; var $id; } the xml subtree containing the info might look like this: <root> <!-- some more parent elements before node(s) of interest --> <person> <name pre="forename"> Foo </name> <name pre="surname"> Bar </name> <id> 1254 </id> <biography> <url> http://www.someurl.com </url> <id> 5488 </id> </biography> </person> </root> At the moment, I have one approach using DOMDocument. A method iterates over the entries and fills the bean by "remembering" the last node. I think thats not a good approach. What I have in mind is something like preconstructing some xpath expression(s) and then iterate over the subtrees/nodeLists. Return an array containing the beans as defined above eventually. However, it seems not to be possible reusing a subtree /DOMNode as DOMXPath constructor parameter. Has anyone of you encountered such a problem?

    Read the article

  • Performing both client side and server side validation using jQuery and CodeIgniter

    - by Vasu
    What is the right way of doing both client side and server side validation using jQuery and CodeIgniter? I am using the jQuery form plugin for form submit. I would like to use jQuery validation plugin (http://docs.jquery.com/Plugins/Validation) for client side validation and CodeIgniter form validation on the server side. However the two don't seem to gel together (or I am unable to get my head around it). Can someone help please? Whether its a client side validation or server side validation, the user should see consistent UI displaying error messages next to the input fields.

    Read the article

  • ASP.NET MVC2 Model Validation Fails with Non-US Date Format

    - by 81bronco
    I have a small MVC2 app that displays in two cultures: en-US and es-MX. One portion contains a user input for a date that is pre-populated with the current date in the Model. When using en-US, the date field is displayed as MM/dd/yyyy and can be changed using the same format without causing any validation errors. When using es-MX, the date field is displayed as dd/MM/yyyy, but when the date is edited in this format, the server-side validation fails with the message: The value '17/05/1991' is not valid for The Date. One of the first things that jumps out at me about that message is that it is not localized. Both the message itself (which I do not think I can control) and the Display Name of the field (which I can control and is localized in my code). Should be displaying in a localized format. I have tried stepping through the code to see exactly where the validation is failing, but it seems to be happening inside some of the compiled MVC or DataAnnotations code that I cannot see. Application details: IIS6, ASP.NET 3.5 (C#), MVC 2 RTM Sample Model Code: public class TestVieModel{ [LocalizedDisplayNameDisplayName("TheDateDisplayName", NameResourceType=typeof(Resources.Model.TestViewModel))] [Required(ErrorMessageResourceName="TheDateValidationMessageRequired", ErrorMessageResourceType=typeof(Resources.Model.TestViewModel))] [DataType(DataType.Date)] public DateTime TheDate { get; set; } } Sample Controller Action Code: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Save(TestViewModel model) { if(ModelState.IsValid) { // <--- Always is false when using es-MX and a date foramtted as dd/MM/yyyy. // Do other stuff return this.View("Complete", model); } // Validation failed, redisplay the form. return this.View("Enter", model); } Sample View Code: <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HispanicSweeps.Web.Model.LosMets.EnterViewModel>" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Test</title> </head> <body> <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div class="editor-label"> <%= Html.LabelFor(model => model.DateOfBirth) %> </div> <div class="editor-field"> <%= Html.EditorFor(model => model.DateOfBirth) %> <%= Html.ValidationMessageFor(model => model.DateOfBirth) %> </div> <p><input type="submit" value="Save" /></p> </fieldset> <% } %> </body> </html>

    Read the article

  • ASP.NET MVC 2 Model object validation

    - by Jimmy
    Hey guys, I'm trying to validate a model object outside of the context of ModelState within a controller, I currently have a parser that creates model objects from an excel file and I want to be able to report how many entries were added to the database and how many failed, is there a way to validate a model object on its data annotations outside of model binding? I'm looking for something similar to the rails model method of model.valid? or a way for me to implement that myself. My current solution is just manually checking if a few key fields are present but this duplicates requirements between my model class and its metadata, there has to be a better way to hook into the model validation checking that is done by mvc 2. Thanks

    Read the article

  • For an ORM supporting data validation, should constraints be enforced in the database as well?

    - by Ramnique Singh
    I have always applied constraints at the database level in addition to my (ActiveRecord) models. But I've been wondering if this is really required? A little background I recently had to unit test a basic automated timestamp generation method for a model. Normally, the test would create an instance of the model and save it without validation. But there are other required fields that aren't nullable at the in the table definition, meaning I cant save the instance even if I skip the ActiveRecord validation. So I'm thinking if I should remove such constraints from the db itself, and let the ORM handle them? Possible advantages if I skip constraints in db, imo - Can modify a validation rule in the model, without having to migrate the database. Can skip validation in testing. Possible disadvantage? If its possible that ORM validation fails or is bypassed, howsoever, the database does not check for constraints. What do you think? EDIT In this case, I'm using the Yii Framework, which generates the model from the database, hence database rules are generated also (though I could always write them post-generation myself too).

    Read the article

  • Play Framework custom validation errors with multiple String parameters

    - by Mark
    I'm trying to set a custom validation error with multiple params in Play!, but it seems like my validation parameters are not rendered correctly. I have defined in messages: validation.customerror=This is first param "%s", and this is the second "%s" The in my code I execute: validation.addError("","validation.customerror", "FIRST", "SECOND"); And I get: This is first param "", and this is the second "FIRST" Thoughts?

    Read the article

  • How to perform duplicate key validation using entlib (or DataAnnotations), MVC, and Repository pattern

    - by olivehour
    I have a set of ASP.NET 4 projects that culminate in an MVC (3 RC2) app. The solution uses Unity and EntLib Validation for cross-cutting dependency injection and validation. Both are working great for injecting repository and service layer implementations. However, I can't figure out how to do duplicate key validation. For example, when a user registers, we want to make sure they don't pick a UserID that someone else is already using. For this type of validation, the validating object must have a repository reference... or some other way to get an IQueryable / IEnumerable reference to check against other rows already in the DB. What I have is a UserMetadata class that has all of the property setters and getters for a user, along with all of the appropriate DataAnnotations and EntLib Validation attributes. There is also a UserEntity class implemented using EF4 POCO Entity Generator templates. The UserEntity depends on UserMetadata, because it has a MetadataTypeAttribute. I also have a UserViewModel class that has the same exact MetadataType attribute. This way, I can apply the same validation rules, via attributes, to both the entity and viewmodel. There are no concrete references to the Repository classes whatsoever. All repositories are injected using Unity. There is also a service layer that gets dependency injection. In the MVC project, service layer implementation classes are injected into the Controller classes (the controller classes only contain service layer interface references). Unity then injects the Repository implementations into the service layer classes (service classes also only contain interface references). I've experimented with the DataAnnotations CustomValidationAttribute in the metadata class. The problem with this is the validation method must be static, and the method cannot instantiate a repository implementation directly. My repository interface is IRepository, and I have only one single repository implementation class defined as EntityRepository for all domain objects. To instantiate a repository explicitly I would need to say new EntityRepository(), which would result in a circular dependency graph: UserMetadata [depends on] DuplicateUserIDValidator [depends on] UserEntity [depends on] UserMetadata. I've also tried creating a custom EntLib Validator along with a custom validation attribute. Here I don't have the same problem with a static method. I think I could get this to work if I could just figure out how to make Unity inject my EntityRepository into the validator class... which I can't. Right now, all of the validation code is in my Metadata class library, since that's where the custom validation attribute would go. Any ideas on how to perform validations that need to check against the current repository state? Can Unity be used to inject a dependency into a lower-layer class library?

    Read the article

  • Effective Data Validation

    - by John Conde
    What's an effective way to handle data validation, say, from a form submission? Originally I had a bunch of if statements that checked each value and collected invalid values in an array for later retrieval (and listing). // Store errors here $errors = array(); // Hypothetical check if a string is alphanumeric if (!preg_match('/^[a-z\d]+$/i', $fieldvalue)) { $errors[$fieldname] = 'Please only use letters and numbers for your street address'; } // etc... What I did next was create a class that handles various data validation scenarios and store the results in an internal array. After data validation was complete I would check to see if any errors occurred and handle accordingly: class Validation { private $errorList = array(); public function isAlphaNumeric($string, $field, $msg = '') { if (!preg_match('/^[a-z\d]+$/i', $string)) { $this->errorList[$field] = $msg; } } // more methods here public function creditCard($cardNumber, $field, $msg = '') { // Validate credit card number } // more methods here public function hasErrors() { return count($this->errorList); } } /* Client code */ $validate = new Validation(); $validate->isAlphaNumeric($fieldvalue1, $fieldname1, 'Please only use letters and numbers for your street address'); $validate->creditCard($fieldvalue2, $fieldname2, 'Please enter a valid credit card number'); if ($validate->hasErrors()) { // Handle as appropriate } Naturally it didn't take long before this class became bloated with the virtually unlimited types of data to be validated. What I'm doing now is using decorators to separate the different types of data into their own classes and call them only when needed leaving generic validations (i.e. isAlphaNumeric()) in the base class: class Validation { private $errorList = array(); public function isAlphaNumeric($string, $field, $msg = '') { if (!preg_match('/^[a-z\d]+$/i', $string)) { $this->errorList[$field] = $msg; } } // more generic methods here public function setError($field, $msg = '') { $this->errorList[$field] = $msg; } public function hasErrors() { return count($this->errorList); } } class ValidationCreditCard { protected $validate; public function __construct(Validation $validate) { $this->validate = $validate; } public function creditCard($cardNumber, $field, $msg = '') { // Do validation // ... // if there is an error $this->validate->setError($field, $msg); } // more methods here } /* Client code */ $validate = new Validation(); $validate->isAlphaNumeric($fieldvalue, $fieldname, 'Please only use letters and numbers for your street address'); $validateCC = new ValidationCreditCard($validate); $validateCC->creditCard($fieldvalue2, $fieldname2, 'Please enter a valid credit card number'); if ($validate->hasErrors()) { // Handle as appropriate } Am I on the right track? Or did I just complicate data validation more then I needed to?

    Read the article

  • JBoss 6 deployment of message-driven bean error

    - by AntonioP
    Hello, I have an java EE application which has one message-driven bean and it runs fine on JBoss 4, however when I configure the project for JBoss 6 and deploy on it, I get this error; WARN [org.jboss.ejb.deployers.EjbDeployer.verifier] EJB spec violation: ... The message driven bean must declare one onMessage() method. ... org.jboss.deployers.spi.DeploymentException: Verification of Enterprise Beans failed, see above for error messages. But my bean HAS the onMessage method! It would not have worked on jboss 4 either then. Why do I get this error!? Edit: The class in question looks like this package ... imports ... public class MyMDB implements MessageDrivenBean, MessageListener { AnotherSessionBean a; OneMoreSessionBean b; public MyMDB() {} public void onMessage(Message message) { if (message instanceof TextMessage) { try { //Lookup sessionBeans by jndi, create them lookupABean(); // check message-type, then invokie a.handle(message); // else b.handle(message); } catch (SomeException e) { //handling it } } } public void lookupABean() { try { // code to lookup session beans and create. } catch (CreateException e) { // handling it and catching NamingException too } } } Edit 2: And this is the jboss.xml relevant parts <message-driven> <ejb-name>MyMDB</ejb-name> <destination-jndi-name>topic/A_Topic</destination-jndi-name> <local-jndi-name>A_Topic</local-jndi-name> <mdb-user>user</mdb-user> <mdb-passwd>pass</mdb-passwd> <mdb-client-id>MyMessageBean</mdb-client-id> <mdb-subscription-id>subid</mdb-subscription-id> <resource-ref> <res-ref-name>jms/TopicFactory</res-ref-name> <jndi-name>jms/TopicFactory</jndi-name> </resource-ref> </message-driven>

    Read the article

  • Mapping between 4+1 architectural view model & UML

    - by Sadeq Dousti
    I'm a bit confused about how the 4+1 architectural view model maps to UML. Wikipedia gives the following mapping: Logical view: Class diagram, Communication diagram, Sequence diagram. Development view: Component diagram, Package diagram Process view: Activity diagram Physical view: Deployment diagram Scenarios: Use-case diagram The paper Role of UML Sequence Diagram Constructs in Object Lifecycle Concept gives the following mapping: Logical view (class diagram (CD), object diagram (OD), sequence diagram (SD), collaboration diagram (COD), state chart diagram (SCD), activity diagram (AD)) Development view (package diagram, component diagram), Process view (use case diagram, CD, OD, SD, COD, SCD, AD), Physical view (deployment diagram), and Use case view (use case diagram, OD, SD, COD, SCD, AD) which combines the four mentioned above. The web page UML 4+1 View Materials presents the following mapping: Finally, the white paper Applying 4+1 View Architecture with UML 2 gives yet another mapping: Logical view class diagrams, object diagrams, state charts, and composite structures Process view sequence diagrams, communication diagrams, activity diagrams, timing diagrams, interaction overview diagrams Development view component diagrams Physical view deployment diagram Use case view use case diagram, activity diagrams I'm sure further search will reveal other mappings as well. While various people usually have different perspectives, I don't see why this is the case here. Specially, each UML diagram describes the system from a particular aspect. So, for instance, why the "sequence diagram" is considered as describing the "logical view" of the system by one author, while another author considers it as describing the "process view"? Could you please help me clarify the confusion?

    Read the article

  • Is Form validation and Business validation too much?

    - by Robert Cabri
    I've got this question about form validation and business validation. I see a lot of frameworks that use some sort of form validation library. You submit some values and the library validates the values from the form. If not ok it will show some errors on you screen. If all goes to plan the values will be set into domain objects. Here the values will be or, better said, should validated (again). Most likely the same validation in the validation library. I know 2 PHP frameworks having this kind of construction Zend/Kohana. When I look at programming and some principles like Don't Repeat Yourself (DRY) and single responsibility principle (SRP) this isn't a good way. As you can see it validates twice. Why not create domain objects that do the actual validation. Example: Form with username and email form is submitted. Values of the username field and the email field will be populated in 2 different Domain objects: Username and Email class Username {} class Email {} These objects validate their data and if not valid throw an exception. Do you agree? What do you think about this aproach? Is there a better way to implement validations? I'm confused about a lot of frameworks/developers handling this stuff. Are they all wrong or am I missing a point? Edit: I know there should also be client side kind of validation. This is a different ballgame in my Opinion. If You have some comments on this and a way to deal with this kind of stuff, please provide.

    Read the article

  • LLBLGen Pro feature highlights: model views

    - by FransBouma
    (This post is part of a series of posts about features of the LLBLGen Pro system) To be able to work with large(r) models, it's key you can view subsets of these models so you can have a better, more focused look at them. For example because you want to display how a subset of entities relate to one another in a different way than the list of entities. LLBLGen Pro offers this in the form of Model Views. Model Views are views on parts of the entity model of a project, and the subsets are displayed in a graphical way. Additionally, one can add documentation to a Model View. As Model Views are displaying parts of the model in a graphical way, they're easier to explain to people who aren't familiar with entity models, e.g. the stakeholders you're interviewing for your project. The documentation can then be used to communicate specifics of the elements on the model view to the developers who have to write the actual code. Below I've included an example. It's a model view on a subset of the entities of AdventureWorks. It displays several entities, their relationships (both relational and inheritance relationships) and also some specifics gathered from the interview with the stakeholder. As the information is inside the actual project the developer will work with, the information doesn't have to be converted back/from e.g .word documents or other intermediate formats, it's the same project. This makes sure there are less errors / misunderstandings. (of course you can hide the docked documentation pane or dock it to another corner). The Model View can contain entities which are placed in different groups. This makes it ideal to group entities together for close examination even though they're stored in different groups. The Model View is a first-class citizen of the code-generator. This means you can write templates which consume Model Views and generate code accordingly. E.g. you can write a template which generates a service per Model View and exposes the entities in the Model View as a single entity graph, fetched through a method. (This template isn't included in the LLBLGen Pro package, but it's easy to write it up yourself with the built-in template editor). Viewing an entity model in different ways is key to fully understand the entity model and Model Views help with that.

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >