Search Results

Search found 406 results on 17 pages for 'dry'.

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

  • Announcing Entity Framework Code-First (CTP5 release)

    - by ScottGu
    This week the data team released the CTP5 build of the new Entity Framework Code-First library.  EF Code-First enables a pretty sweet code-centric development workflow for working with data.  It enables you to: Develop without ever having to open a designer or define an XML mapping file Define model objects by simply writing “plain old classes” with no base classes required Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything Optionally override the convention-based persistence and use a fluent code API to fully customize the persistence mapping I’m a big fan of the EF Code-First approach, and wrote several blog posts about it this summer: Code-First Development with Entity Framework 4 (July 16th) EF Code-First: Custom Database Schema Mapping (July 23rd) Using EF Code-First with an Existing Database (August 3rd) Today’s new CTP5 release delivers several nice improvements over the CTP4 build, and will be the last preview build of Code First before the final release of it.  We will ship the final EF Code First release in the first quarter of next year (Q1 of 2011).  It works with all .NET application types (including both ASP.NET Web Forms and ASP.NET MVC projects). Installing EF Code First You can install and use EF Code First CTP5 using one of two ways: Approach 1) By downloading and running a setup program.  Once installed you can reference the EntityFramework.dll assembly it provides within your projects.      or: Approach 2) By using the NuGet Package Manager within Visual Studio to download and install EF Code First within a project.  To do this, simply bring up the NuGet Package Manager Console within Visual Studio (View->Other Windows->Package Manager Console) and type “Install-Package EFCodeFirst”: Typing “Install-Package EFCodeFirst” within the Package Manager Console will cause NuGet to download the EF Code First package, and add it to your current project: Doing this will automatically add a reference to the EntityFramework.dll assembly to your project:   NuGet enables you to have EF Code First setup and ready to use within seconds.  When the final release of EF Code First ships you’ll also be able to just type “Update-Package EFCodeFirst” to update your existing projects to use the final release. EF Code First Assembly and Namespace The CTP5 release of EF Code First has an updated assembly name, and new .NET namespace: Assembly Name: EntityFramework.dll Namespace: System.Data.Entity These names match what we plan to use for the final release of the library. Nice New CTP5 Improvements The new CTP5 release of EF Code First contains a bunch of nice improvements and refinements. Some of the highlights include: Better support for Existing Databases Built-in Model-Level Validation and DataAnnotation Support Fluent API Improvements Pluggable Conventions Support New Change Tracking API Improved Concurrency Conflict Resolution Raw SQL Query/Command Support The rest of this blog post contains some more details about a few of the above changes. Better Support for Existing Databases EF Code First makes it really easy to create model layers that work against existing databases.  CTP5 includes some refinements that further streamline the developer workflow for this scenario. Below are the steps to use EF Code First to create a model layer for the Northwind sample database: Step 1: Create Model Classes and a DbContext class Below is all of the code necessary to implement a simple model layer using EF Code First that goes against the Northwind database: EF Code First enables you to use “POCO” – Plain Old CLR Objects – to represent entities within a database.  This means that you do not need to derive model classes from a base class, nor implement any interfaces or data persistence attributes on them.  This enables the model classes to be kept clean, easily testable, and “persistence ignorant”.  The Product and Category classes above are examples of POCO model classes. EF Code First enables you to easily connect your POCO model classes to a database by creating a “DbContext” class that exposes public properties that map to the tables within a database.  The Northwind class above illustrates how this can be done.  It is mapping our Product and Category classes to the “Products” and “Categories” tables within the database.  The properties within the Product and Category classes in turn map to the columns within the Products and Categories tables – and each instance of a Product/Category object maps to a row within the tables. The above code is all of the code required to create our model and data access layer!  Previous CTPs of EF Code First required an additional step to work against existing databases (a call to Database.Initializer<Northwind>(null) to tell EF Code First to not create the database) – this step is no longer required with the CTP5 release.  Step 2: Configure the Database Connection String We’ve written all of the code we need to write to define our model layer.  Our last step before we use it will be to setup a connection-string that connects it with our database.  To do this we’ll add a “Northwind” connection-string to our web.config file (or App.Config for client apps) like so:   <connectionStrings>          <add name="Northwind"          connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\northwind.mdf;User Instance=true"          providerName="System.Data.SqlClient" />   </connectionStrings> EF “code first” uses a convention where DbContext classes by default look for a connection-string that has the same name as the context class.  Because our DbContext class is called “Northwind” it by default looks for a “Northwind” connection-string to use.  Above our Northwind connection-string is configured to use a local SQL Express database (stored within the \App_Data directory of our project).  You can alternatively point it at a remote SQL Server. Step 3: Using our Northwind Model Layer We can now easily query and update our database using the strongly-typed model layer we just built with EF Code First. The code example below demonstrates how to use LINQ to query for products within a specific product category.  This query returns back a sequence of strongly-typed Product objects that match the search criteria: The code example below demonstrates how we can retrieve a specific Product object, update two of its properties, and then save the changes back to the database: EF Code First handles all of the change-tracking and data persistence work for us, and allows us to focus on our application and business logic as opposed to having to worry about data access plumbing. Built-in Model Validation EF Code First allows you to use any validation approach you want when implementing business rules with your model layer.  This enables a great deal of flexibility and power. Starting with this week’s CTP5 release, EF Code First also now includes built-in support for both the DataAnnotation and IValidatorObject validation support built-into .NET 4.  This enables you to easily implement validation rules on your models, and have these rules automatically be enforced by EF Code First whenever you save your model layer.  It provides a very convenient “out of the box” way to enable validation within your applications. Applying DataAnnotations to our Northwind Model The code example below demonstrates how we could add some declarative validation rules to two of the properties of our “Product” model: We are using the [Required] and [Range] attributes above.  These validation attributes live within the System.ComponentModel.DataAnnotations namespace that is built-into .NET 4, and can be used independently of EF.  The error messages specified on them can either be explicitly defined (like above) – or retrieved from resource files (which makes localizing applications easy). Validation Enforcement on SaveChanges() EF Code-First (starting with CTP5) now automatically applies and enforces DataAnnotation rules when a model object is updated or saved.  You do not need to write any code to enforce this – this support is now enabled by default.  This new support means that the below code – which violates our above rules – will automatically throw an exception when we call the “SaveChanges()” method on our Northwind DbContext: The DbEntityValidationException that is raised when the SaveChanges() method is invoked contains a “EntityValidationErrors” property that you can use to retrieve the list of all validation errors that occurred when the model was trying to save.  This enables you to easily guide the user on how to fix them.  Note that EF Code-First will abort the entire transaction of changes if a validation rule is violated – ensuring that our database is always kept in a valid, consistent state. EF Code First’s validation enforcement works both for the built-in .NET DataAnnotation attributes (like Required, Range, RegularExpression, StringLength, etc), as well as for any custom validation rule you create by sub-classing the System.ComponentModel.DataAnnotations.ValidationAttribute base class. UI Validation Support A lot of our UI frameworks in .NET also provide support for DataAnnotation-based validation rules. For example, ASP.NET MVC, ASP.NET Dynamic Data, and Silverlight (via WCF RIA Services) all provide support for displaying client-side validation UI that honor the DataAnnotation rules applied to model objects. The screen-shot below demonstrates how using the default “Add-View” scaffold template within an ASP.NET MVC 3 application will cause appropriate validation error messages to be displayed if appropriate values are not provided: ASP.NET MVC 3 supports both client-side and server-side enforcement of these validation rules.  The error messages displayed are automatically picked up from the declarative validation attributes – eliminating the need for you to write any custom code to display them. Keeping things DRY The “DRY Principle” stands for “Do Not Repeat Yourself”, and is a best practice that recommends that you avoid duplicating logic/configuration/code in multiple places across your application, and instead specify it only once and have it apply everywhere. EF Code First CTP5 now enables you to apply declarative DataAnnotation validations on your model classes (and specify them only once) and then have the validation logic be enforced (and corresponding error messages displayed) across all applications scenarios – including within controllers, views, client-side scripts, and for any custom code that updates and manipulates model classes. This makes it much easier to build good applications with clean code, and to build applications that can rapidly iterate and evolve. Other EF Code First Improvements New to CTP5 EF Code First CTP5 includes a bunch of other improvements as well.  Below are a few short descriptions of some of them: Fluent API Improvements EF Code First allows you to override an “OnModelCreating()” method on the DbContext class to further refine/override the schema mapping rules used to map model classes to underlying database schema.  CTP5 includes some refinements to the ModelBuilder class that is passed to this method which can make defining mapping rules cleaner and more concise.  The ADO.NET Team blogged some samples of how to do this here. Pluggable Conventions Support EF Code First CTP5 provides new support that allows you to override the “default conventions” that EF Code First honors, and optionally replace them with your own set of conventions. New Change Tracking API EF Code First CTP5 exposes a new set of change tracking information that enables you to access Original, Current & Stored values, and State (e.g. Added, Unchanged, Modified, Deleted).  This support is useful in a variety of scenarios. Improved Concurrency Conflict Resolution EF Code First CTP5 provides better exception messages that allow access to the affected object instance and the ability to resolve conflicts using current, original and database values.  Raw SQL Query/Command Support EF Code First CTP5 now allows raw SQL queries and commands (including SPROCs) to be executed via the SqlQuery and SqlCommand methods exposed off of the DbContext.Database property.  The results of these method calls can be materialized into object instances that can be optionally change-tracked by the DbContext.  This is useful for a variety of advanced scenarios. Full Data Annotations Support EF Code First CTP5 now supports all standard DataAnnotations within .NET, and can use them both to perform validation as well as to automatically create the appropriate database schema when EF Code First is used in a database creation scenario.  Summary EF Code First provides an elegant and powerful way to work with data.  I really like it because it is extremely clean and supports best practices, while also enabling solutions to be implemented very, very rapidly.  The code-only approach of the library means that model layers end up being flexible and easy to customize. This week’s CTP5 release further refines EF Code First and helps ensure that it will be really sweet when it ships early next year.  I recommend using NuGet to install and give it a try today.  I think you’ll be pleasantly surprised by how awesome it is. Hope this helps, Scott

    Read the article

  • ASP.NET MVC 3: Layouts and Sections with Razor

    - by ScottGu
    This is another in a series of posts I’m doing that cover some of the new ASP.NET MVC 3 features: Introducing Razor (July 2nd) New @model keyword in Razor (Oct 19th) Layouts with Razor (Oct 22nd) Server-Side Comments with Razor (Nov 12th) Razor’s @: and <text> syntax (Dec 15th) Implicit and Explicit code nuggets with Razor (Dec 16th) Layouts and Sections with Razor (Today) In today’s post I’m going to go into more details about how Layout pages work with Razor.  In particular, I’m going to cover how you can have multiple, non-contiguous, replaceable “sections” within a layout file – and enable views based on layouts to optionally “fill in” these different sections at runtime.  The Razor syntax for doing this is clean and concise. I’ll also show how you can dynamically check at runtime whether a particular layout section has been defined, and how you can provide alternate content (or even an alternate layout) in the event that a section isn’t specified within a view template.  This provides a powerful and easy way to customize the UI of your site and make it clean and DRY from an implementation perspective. What are Layouts? You typically want to maintain a consistent look and feel across all of the pages within your web-site/application.  ASP.NET 2.0 introduced the concept of “master pages” which helps enable this when using .aspx based pages or templates.  Razor also supports this concept with a feature called “layouts” – which allow you to define a common site template, and then inherit its look and feel across all the views/pages on your site. I previously discussed the basics of how layout files work with Razor in my ASP.NET MVC 3: Layouts with Razor blog post.  Today’s post will go deeper and discuss how you can define multiple, non-contiguous, replaceable regions within a layout file that you can then optionally “fill in” at runtime. Site Layout Scenario Let’s look at how we can implement a common site layout scenario with ASP.NET MVC 3 and Razor.  Specifically, we’ll implement some site UI where we have a common header and footer on all of our pages.  We’ll also add a “sidebar” section to the right of our common site layout.  On some pages we’ll customize the SideBar to contain content specific to the page it is included on: And on other pages (that do not have custom sidebar content) we will fall back and provide some “default content” to the sidebar: We’ll use ASP.NET MVC 3 and Razor to enable this customization in a nice, clean way.  Below are some step-by-step tutorial instructions on how to build the above site with ASP.NET MVC 3 and Razor. Part 1: Create a New Project with a Layout for the “Body” section We’ll begin by using the “File->New Project” menu command within Visual Studio to create a new ASP.NET MVC 3 Project.  We’ll create the new project using the “Empty” template option: This will create a new project that has no default controllers in it: Creating a HomeController We will then right-click on the “Controllers” folder of our newly created project and choose the “Add->Controller” context menu command.  This will bring up the “Add Controller” dialog: We’ll name the new controller we create “HomeController”.  When we click the “Add” button Visual Studio will add a HomeController class to our project with a default “Index” action method that returns a view: We won’t need to write any Controller logic to implement this sample – so we’ll leave the default code as-is.  Creating a View Template Our next step will be to implement the view template associated with the HomeController’s Index action method.  To implement the view template, we will right-click within the “HomeController.Index()” method and select the “Add View” command to create a view template for our home page: This will bring up the “Add View” dialog within Visual Studio.  We do not need to change any of the default settings within the above dialog (the name of the template was auto-populated to Index because we invoked the “Add View” context menu command within the Index method).  When we click the “Add” Button within the dialog, a Razor-based “Index.cshtml” view template will be added to the \Views\Home\ folder within our project.  Let’s add some simple default static content to it: Notice above how we don’t have an <html> or <body> section defined within our view template.  This is because we are going to rely on a layout template to supply these elements and use it to define the common site layout and structure for our site (ensuring that it is consistent across all pages and URLs within the site).  Customizing our Layout File Let’s open and customize the default “_Layout.cshtml” file that was automatically added to the \Views\Shared folder when we created our new project: The default layout file (shown above) is pretty basic and simply outputs a title (if specified in either the Controller or the View template) and adds links to a stylesheet and jQuery.  The call to “RenderBody()” indicates where the main body content of our Index.cshtml file will merged into the output sent back to the browser. Let’s modify the Layout template to add a common header, footer and sidebar to the site: We’ll then edit the “Site.css” file within the \Content folder of our project and add 4 CSS rules to it: And now when we run the project and browse to the home “/” URL of our project we’ll see a page like below: Notice how the content of the HomeController’s Index view template and the site’s Shared Layout template have been merged together into a single HTML response.  Below is what the HTML sent back from the server looks like: Part 2: Adding a “SideBar” Section Our site so far has a layout template that has only one “section” in it – what we call the main “body” section of the response.  Razor also supports the ability to add additional "named sections” to layout templates as well.  These sections can be defined anywhere in the layout file (including within the <head> section of the HTML), and allow you to output dynamic content to multiple, non-contiguous, regions of the final response. Defining the “SideBar” section in our Layout Let’s update our Layout template to define an additional “SideBar” section of content that will be rendered within the <div id=”sidebar”> region of our HTML.  We can do this by calling the RenderSection(string sectionName, bool required) helper method within our Layout.cshtml file like below:   The first parameter to the “RenderSection()” helper method specifies the name of the section we want to render at that location in the layout template.  The second parameter is optional, and allows us to define whether the section we are rendering is required or not.  If a section is “required”, then Razor will throw an error at runtime if that section is not implemented within a view template that is based on the layout file (which can make it easier to track down content errors).  If a section is not required, then its presence within a view template is optional, and the above RenderSection() code will render nothing at runtime if it isn’t defined. Now that we’ve made the above change to our layout file, let’s hit refresh in our browser and see what our Home page now looks like: Notice how we currently have no content within our SideBar <div> – that is because the Index.cshtml view template doesn’t implement our new “SideBar” section yet. Implementing the “SideBar” Section in our View Template Let’s change our home-page so that it has a SideBar section that outputs some custom content.  We can do that by opening up the Index.cshtml view template, and by adding a new “SiderBar” section to it.  We’ll do this using Razor’s @section SectionName { } syntax: We could have put our SideBar @section declaration anywhere within the view template.  I think it looks cleaner when defined at the top or bottom of the file – but that is simply personal preference.  You can include any content or code you want within @section declarations.  Notice above how I have a C# code nugget that outputs the current time at the bottom of the SideBar section.  I could have also written code that used ASP.NET MVC’s HTML/AJAX helper methods and/or accessed any strongly-typed model objects passed to the Index.cshtml view template. Now that we’ve made the above template changes, when we hit refresh in our browser again we’ll see that our SideBar content – that is specific to the Home Page of our site – is now included in the page response sent back from the server: The SideBar section content has been merged into the proper location of the HTML response : Part 3: Conditionally Detecting if a Layout Section Has Been Implemented Razor provides the ability for you to conditionally check (from within a layout file) whether a section has been defined within a view template, and enables you to output an alternative response in the event that the section has not been defined.  This provides a convenient way to specify default UI for optional layout sections.  Let’s modify our Layout file to take advantage of this capability.  Below we are conditionally checking whether the “SideBar” section has been defined without the view template being rendered (using the IsSectionDefined() method), and if so we render the section.  If the section has not been defined, then we now instead render some default content for the SideBar:  Note: You want to make sure you prefix calls to the RenderSection() helper method with a @ character – which will tell Razor to execute the HelperResult it returns and merge in the section content in the appropriate place of the output.  Notice how we wrote @RenderSection(“SideBar”) above instead of just RenderSection(“SideBar”).  Otherwise you’ll get an error. Above we are simply rendering an inline static string (<p>Default SideBar Content</p>) if the section is not defined.  A real-world site would more likely refactor this default content to be stored within a separate partial template (which we’d render using the Html.RenderPartial() helper method within the else block) or alternatively use the Html.Action() helper method within the else block to encapsulate both the logic and rendering of the default sidebar. When we hit refresh on our home-page, we will still see the same custom SideBar content we had before.  This is because we implemented the SideBar section within our Index.cshtml view template (and so our Layout rendered it): Let’s now implement a “/Home/About” URL for our site by adding a new “About” action method to our HomeController: The About() action method above simply renders a view back to the client when invoked.  We can implement the corresponding view template for this action by right-clicking within the “About()” method and using the “Add View” menu command (like before) to create a new About.cshtml view template.  We’ll implement the About.cshtml view template like below. Notice that we are not defining a “SideBar” section within it: When we browse the /Home/About URL we’ll see the content we supplied above in the main body section of our response, and the default SideBar content will rendered: The layout file determined at runtime that a custom SideBar section wasn’t present in the About.cshtml view template, and instead rendered the default sidebar content. One Last Tweak… Let’s suppose that at a later point we decide that instead of rendering default side-bar content, we just want to hide the side-bar entirely from pages that don’t have any custom sidebar content defined.  We could implement this change simply by making a small modification to our layout so that the sidebar content (and its surrounding HTML chrome) is only rendered if the SideBar section is defined.  The code to do this is below: Razor is flexible enough so that we can make changes like this and not have to modify any of our view templates (nor make change any Controller logic changes) to accommodate this.  We can instead make just this one modification to our Layout file and the rest happens cleanly.  This type of flexibility makes Razor incredibly powerful and productive. Summary Razor’s layout capability enables you to define a common site template, and then inherit its look and feel across all the views/pages on your site. Razor enables you to define multiple, non-contiguous, “sections” within layout templates that can be “filled-in” by view templates.  The @section {} syntax for doing this is clean and concise.  Razor also supports the ability to dynamically check at runtime whether a particular section has been defined, and to provide alternate content (or even an alternate layout) in the event that it isn’t specified.  This provides a powerful and easy way to customize the UI of your site - and make it clean and DRY from an implementation perspective. Hope this helps, Scott P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

    Read the article

  • ASP.NET MVC: shortcut for Response.Write and String.Format

    - by pcampbell
    I've found a pattern in my Views like this: <% if (someCondition) { Response.Write(string.Format("Hello {0}, Visitor {1} on {2}.", userName, someCounter, someDate)); } else { Response.Write(string.Format("Foo is {0}.", bar)); } %> The question here is around DRY and Response.Write(string.Format()). Are there better, or more concise ways to . Consider that HTML encoding would be a nice feature to include, perhaps as a boolean to a method call of some kind (extension method on Html?. Is there an obvious extension method that I'm missing? Do you have an extension method that you rely on to achieve this functionality?

    Read the article

  • is there any easy way to auto generated code like this?

    - by Kevin Yang
    i have a file which will be used across many app projects. the only difference of these files is the webserice referrence name. code like this: public void Test(){ Kevin.ServiceReference1.Service1Client client = new Kevin.ServiceReference1.Service1Client(); // do something.... } like code above, the 'Kevin.ServiceReference1' will be replace by specified app project namespace. so, according to DRY(dont repeat yourself), i shouldn't just copy the file to many projects and rename the specified part manually. is there any way i can easily replace some parts of my template file to something related to the project?

    Read the article

  • Ruby on Rails: having two xmlbuilder templates per action , one for errors one for regular output

    - by randombits
    What's the best way to handle having two templates (or should it be one, DRY?) for xml builder templates? I'm building a web api with Rails and wanted to see an example of how to have a view that does regular output vs one that does error output. I've been using @obj.to_xml for a while, but my requirements have changed and require me building my own error templates. do you typically have both views in one with a condition above for errors such as app/views/myresource/create.xml.builder unless @myobj.errors.empty? // xml for errors here? end // regular xml view

    Read the article

  • Programming pattern to flatten deeply nested ajax callbacks?

    - by chiborg
    I've inherited JavaScript code where the success callback of an Ajax handler initiates another Ajax call where the success callback may or may not initiate another Ajax call. This leads to deeply nested anonymous functions. Maybe there is a clever programming pattern that avoids the deep-nesting and is more DRY. jQuery.extend(Application.Model.prototype, { process: function() { jQuery.ajax({ url:myurl1, dataType:'json', success:function(data) { // process data, then send it back jQuery.ajax({ url:myurl2, dataType:'json', success:function(data) { if(!data.ok) { jQuery.ajax({ url:myurl2, dataType:'json', success:mycallback }); } else { mycallback(data); } } }); } }); } });

    Read the article

  • Merge items in nanoc

    - by Gordon Potter
    I have been trying to use nanoc for generating a static website. I need to organize a complex arrangement pages I want to keep my content DRY. How does the concept of includes or merges work within the nanoc system? I have read the docs but I can't seem to find what I want. For example: how can I take two partial content items and merge them together into a new content item. In staticmatic you can do some like the following inside your page. = partial('partials/shared/navigation') How would a similar convention work within nanoc?

    Read the article

  • Django: reverse lookup URL of feeds?

    - by Santa
    I am having trouble doing a reverse URL lookup for Django-generated feeds. I have the following setup in urls.py: feeds = { 'latest': LatestEntries, } urlpatterns = patterns('', # ... # enable feeds (RSS) url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}, name='feeds_view'), ) I have tried using the following template tag: <a href="{% url feeds_view latest %}">RSS feeds</a> But the resulting link is not what want (http://my.domain.com/feeds//). It should be http://my.domain.com/feeds/latest/. For now, I am using a hack to generate the URL for the template: <a href="http://{{ request.META.HTTP_HOST }}/feeds/latest">RSS feeds</a> But, as you can see, it clearly is not DRY. Is there something I am missing?

    Read the article

  • Refactoring a custom User model to user UserProfile: Should I create a custom UserManager or add use

    - by BryanWheelock
    I have been refactoring an app that had customized the standard User model from django.contrib.auth.models by creating a UserProfile and defining it with AUTH_PROFILE_MODULE. The problem is the attributes in UserProfile are used throughout the project to determine the User sees. I had been creating tests and putting in this type of statement repeatedly: user = User.objects.get(pk=1) user_profile = user.get_profile() if user_profile.karma > 10: do_some_stuff() This is tedious and I'm now wondering if I'm violating the DRY principle. Would it make more sense to create a custom UserManager that automatically loads the UserProfile data when the user is requested. I could even iterate over the UserProfile attributes and append them to the User model. This would save me having to update all the references to the custom model attributes that litter the code. Of course, I'd have to reverse to process for to allow the User and UserProfile models to be updated correctly. Which approach is more Django-esque?

    Read the article

  • Trying to extend ActionView::Helpers::FormBuilder

    - by nibbo
    Hello I am trying to DRY up some code by moving some logic into the FormBuilder. After reading the documentation about how to select and alternative form builder the logical solution for me seemed to be something like this. In the view <% form_for @event, :builder => TestFormBuilder do |f| %> <%= f.test %> <%= f.submit 'Update' %> <% end %> and then in app/helpers/application_helper.rb module ApplicationHelper class TestFormBuilder < ActionView::Helpers::FormBuilder def test puts 'apa' end end end This, however, gives me an error at the "form_for" uninitialized constant ActionView::Base::CompiledTemplates::TestFormBuilder Where am I doing it wrong?

    Read the article

  • How to Create a Temporary Function in Emacs Lisp

    - by Cristian
    I'm making some tedious calls to a bunch of functions, but the parameters will be determined at runtime. I wrote a simple function to keep my code DRY but giving it a name is unnecessary. I don't use this function anywhere else. I'm trying to do it the way I would in Scheme, but I get a void-function error: (let ((do-work (lambda (x y z) (do-x x) (do-y y) ;; etc ))) (cond (test-1 (do-work 'a 'b 'c)) (test-2 (do-work 'i 'j 'k)))) I could stick it all into an apply (e.g., (apply (lambda ...) (cond ...))) but that isn't very readable. Is there a better way?

    Read the article

  • Why a very good PHP framework - Qcodo (or Qcubed - its branch) - is so unpopular?

    - by Pawel
    I am wondering why this framework (QCodo) is almost forgotten and totally unpopular. I've started using it a few years ago and it is the only thing that keeps me with PHP. Yeah ... its development is stuck (that's why there is now more active branch Qcubed) but it is still very good piece of software. Its main advantages: Event driven (something like asp.net) no spaghetti code Powerful code generation good ORM follows DRY very simple AJAX support is fun to write Since then I wanted to be trendy and checked Django but I cannot write normal request-based web application (it just doesn't feel right). Don't believe? chess.com is written with it and surely there are plenty others. My 2 questions are: Have you heard of it (PHP people)? If you are using it what is your opinion about it (show us examples of your work) Thanks

    Read the article

  • To subclass or not to subclass

    - by poulenc
    I have three objects; Action, Issue and Risk. These all contain a nunber of common variables/attributes (for example: Description, title, Due date, Raised by etc.) and some specific fields (risk has probability). The question is: Should I create 3 separate classes Action, Risk and Issue each containing the repeat fields. Create a parent class "Abstract_Item" containing these fields and operations on them and then have Action, Risk and Issue subclass Abstract_Item. This would adhere to DRY principal.

    Read the article

  • Can a CouchDB document update handler get an update conflict?

    - by jhs
    How likely is a revision conflict when using an update handler? Should I concern myself with conflict-handling code when writing a robust update function? As described in Document Update Handlers, CouchDB 0.10 and later allows on-demand server-side document modification. Update handlers can process non-JSON formats; but the other major features are these: An HTTP front-end to arbitrarily complex document modification code Similar code needn't be written for all possible clients—a DRY architecture Execution is faster and less likely to hit a revision conflict I am unclear about the third point. Executing locally, the update handler will run much faster and with lower latency. But in situations with high contention, that does not guarantee a successful update. Or does the update handler guarantee a successful update?

    Read the article

  • Capistrano configuration

    - by Eli
    I'm having some issues with variable scope with the capistrano-ext gem's multistage module. I currently have, in config/deploy/staging.rb. set(:settings) { YAML.load_file("config/deploy.yml")['staging'] } set :repository, settings["repository"] set :deploy_to, settings["deploy_to"] set :branch, settings["branch"] set :domain, settings["domain"] set :user, settings["user"] role :app, domain role :web, domain role :db, domain, :primary => true My config/deploy/production.rb file is similar. This doesn't seem very DRY. Ideally, I think I'd like everything to be in the deploy.rb file. If there were a variable set with the current stage, everything would be really clean. UPDATE: I found a solution. I defined this function in deploy.rb: def set_settings(params) params.each_pair do |k,v| set k.to_sym, v end if exists? :domain role :app, domain role :web, domain role :db, domain, :primary => true end end Then my staging.rb file is just set_settings(YAML.load_file("config/deploy.yml")['staging'])

    Read the article

  • Circular Dependency Solution

    - by gfoley
    Our current project has ran into a circular dependency issue. Our business logic assembly is using classes and static methods from our SharedLibrary assembly. The SharedLibrary contains a whole bunch of helper functions, such as a SQL Reader class, Enumerators, Global Variables, Error Handling, Logging and Validation. The SharedLibrary needs access to the Business objects, but the Business objects need access to SharedLibrary. The old developers solved this obvious code smell by replicating the functionality of the business objects in the shared library (very anti-DRY). I've spent a day now trying to read about my options to solve this but i'm hitting a dead end. I'm open to the idea of architecture redesign, but only as a last resort. So how can i have a Shared Helper Library which can access the business objects, with the business objects still accessing the Shared Helper Library?

    Read the article

  • Supporting different locale regions using Rails i18n

    - by Olly
    I'm using the standard Rails I18n API to localise some of our views. This is working really well, but we now have a few use cases for regional changes to the en locale. The API guide mentions that this isn't supported directly, and other plugins should be used. However, I'm wondering whether there's a simpler way to do this. I already have en.yml, so in theory I could just create en-AU.yml and en-US.yml which are effectively clones of en.yml but with a few regional changes applied. I could then add additional English - American and English - Australian options to our configuration which would map to the new region-specific locales and allow users to use a region-specific locale. The only problem I can think of with this is that it isn't DRY -- I would have duplicate translations for all common English words. I can't see a way around this. Are there any other disadvantages to this approach, or should I just bite the bullet and dive into one of the plug-ins such as Globalize2 instead?

    Read the article

  • Drying repeated specs in RSpec

    - by snl
    In the test below, the Bar and Baz blocks contain identical specs. Leaving aside why such repetition was necessary in the first place, I'm wondering how one could dry this up. I tried turning the blocks into objects and calling them under Bar and Baz, but possibly because I did not get the scopes right, I have not been able to make it work. describe Foo do describe Bar do before(:each) do prepare end it "should do something" do true end it "should do something else" do true end end describe Baz do before(:each) do prepare_something_else end it "should do something" do true end it "should do something else" do true end end end

    Read the article

  • Windows Phone 7, MVVM, Silverlight and navigation best practice / patterns and strategies

    - by Matt F
    Whilst building a Windows Phone 7 app. using the MVVM pattern we've struggled to get to grips with a pattern or technique to centralise navigation logic that will fit with MVVM. To give an example, everytime the app. calls our web service we check that the logon token we've assigned the app. earlier hasn't expired. We always return some status to the phone from the web service and one of those might be Enum.AuthenticationExpired. If we receive that I'd imagine we'd alert the user and navigate back to the login screen. (this is one of many examples of status we might receive) Now, wanting to keep things DRY, that sort of logic feels like it should be in one place. Therein lies my question. How should I go about modelling navigation that relies on (essentially) switch or if statements to tell us where to navigate to next without repeating that in every view. Are there recognised patterns or techniques that someone could recommend? Thanks

    Read the article

  • DRYing Search Logic in Rails

    - by Kevin Sylvestre
    I am using search logic to filter results on company listing page. The user is able to specify any number of parameters using a variety of named URLs. For example: /location/mexico /sector/technology /sector/financial/location/argentina Results in the following respectively: params[:location] == 'mexico' params[:sector] == 'technology' params[:sector] == 'financial' and params[:location] == 'argentina' I am now trying to cleanup or 'DRY' my model code. Currently I have: def self.search(params) ... if params[:location] results = results.location_permalink_equals params[:location] if results results = Company.location_permalink_equals params[:location] unless results end if params[:sector] results = results.location_permalink_equals params[:sector] if results results = Company.location_permalink_equals params[:sector] unless results end ... end I don't like repeating the searchs. Any suggestions? Thanks.

    Read the article

  • Testing complex entities

    - by Carlos
    I've got a C# form, with various controls on it. The form controls an ongoing process, and there are many, many aspects that need to be right for the program to run correctly. Each part can be unit tested (for instance, loading some coefficients, drawing some diagnostics) but I often run into problems that are best described with an example: "If I click here, then here, then change this, then re-open the form, then click here, it crashes or produces an error" I've tried my best to use common code organisational ideas (inheritance, DRY, separation of concerns) but there never seems to be a way to test every single path, and inevitably, a form with several controls will have a huge number of ways to execute. What can I read (preferably online) that addresses this kind of issue, and is there a (non-generic) term for it. This isn't a specific problem I'm having, but one that creeps up on me, especially with WinForms.

    Read the article

  • Added tagging to existing model, now how does its admin work?

    - by Oli
    I wanted to add a StackOverflow-style tag input to a blog model of mine. This is a model that has a lot of data already in it. class BlogPost(models.Model): # my blog fields try: tagging.register(BlogPost) except tagging.AlreadyRegistered: pass I thought that was all I needed so I went through my old database of blog posts (this is a newly ported blog) and copied the tags in. It worked and I could display tags and filter by tag. However, I just wrote a new BlogPost and realise there's no tag field there. Reading the documentation (coincidentally, dry enough to be used as an antiperspirant), I found the TagField. Thinking this would just be a manager-style layer over the existing tagging register, I added it. It complained about there not being a Tag column. I'd rather not denormalise on tags just to satisfy create an interface for inputting them. Is there a TagManager class that I can just set on the model? tags = TagManager() # or somesuch

    Read the article

  • What's so bad about in-line CSS?

    - by ChessWhiz
    When I see website starter code and examples, the CSS is always in a separate file, named something like "main.css", "default.css", or "Site.css". However, when I'm coding up a page, I'm often tempted to throw the CSS in-line with a DOM element, such as by setting "float: right" on an image. I get the feeling that this is "bad coding", since it's so rarely done in examples. I understand that if the style will be applied to multiple objects, it's wise to follow "Don't Repeat Yourself" (DRY) and assign it to a CSS class to be referenced by each element. However, if I won't be repeating the CSS on another element, why not in-line the CSS as I write the HTML? The question: Is using in-line CSS considered bad, even if it will only be used on that element? If so, why? Example (is this bad?): <img src="myimage.gif" style="float:right" />

    Read the article

  • How to render the properties of the view model's base class first when using ViewData.ModelMetadata.

    - by Martin R-L
    When I use the ViewData.ModelMetadata.Properties in order to loop the properties (with an additional Where(modelMetadata => modelMetadata.ShowForEdit && !ViewData.TemplateInfo.Visited(modelMetadata))), and thereby create a generic edit view, the properties of the view model's base class are rendered last. Is it possible to use a clever OrderBy() or is there another way to first get the properties of the base class, and then the sub class'? Reverse won't do the trick since the ordering of each class' properties is perfectly fine. A workaround would of course be composition + delegation, but since we don't have mixins, it's too un-DRY IMHO, why I seek a better solution if possible.

    Read the article

  • How to handle similar items in rails MVC?

    - by mocker
    I'm working on building a pretty simple site mainly as an exercise in learning more about rails. You can see my rough progress at statific.com. It's working pretty much as I wanted it for keeping track of server information, but now I'd like to expand it to other things, next on the list being firewalls. I can pretty easily duplicate all the models, views, etc.. that I have for my servers. The problem I see with that is that it isn't very DRY since most of the code would look the same, the only difference would be the attributes I have setup for firewalls would be different than for servers. I know in plain ruby this is pretty simple, you can have a 'Product' w/ common attributes ('manufacturer', 'model') and then have children with more specific attributes. Does the same type of concept exist for rails, or am I just over thinking this?

    Read the article

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