Search Results

Search found 13135 results on 526 pages for 'actor model'.

Page 68/526 | < Previous Page | 64 65 66 67 68 69 70 71 72 73 74 75  | Next Page >

  • Combining Two Models in Rails for a Form

    - by matsko
    Hey Guys. I'm very new with rails and I've been building a CMS application backend. All is going well, but I would like to know if this is possible? Basically I have two models: @page { id, name, number } @extended_page { id, page_id, description, image } The idea is that there are bunch of pages but NOT ALL pages have extended_content. In the event that there is a page with extended content then I want to be able to have a form that allows for editing both of them. In the controller: @page = Page.find(params[:id]) @extended= Extended.find(:first, :conditions = ["page_id = ?",@page.id]) @combined = ... #merge the two somehow So in the view: <%- form_for @combined do |f| % <%= f.label :name % <%= f.text_field :name % ... <%= f.label :description % <%= f.text_field :description % <%- end This way in the controller, there only has to be one model that will be updated (which will update to both). Is this possible?

    Read the article

  • ibatis domain modelling

    - by josh
    Hi team; I am working on the domain model for a project. I have a class named user that has a class named UserType as one of the properties. I know when i want to select all users, i will use joins to pick up all corresponding usertypes. How do i do inserts? Do i have to write a handler for userType? or can i do something like INSERT INTO users(... usertype_id ...) VALUES(... #{usertype.usertype_id}...) Please help; I have spent the whole day trying to figure this out. Am using ibatis 3.0 and am new to ibatis. Regards Josh

    Read the article

  • MVC2 IModelBinder and parsing a string to an object - How do I do it?

    - by burnt_hand
    I have an object called Time public class Time{ public int Hour {get;set;} public int Minute {get;set;} public static Time Parse(string timeString){ //reads the ToString()'s previous output and returns a Time object } override protected string ToString(){ //puts out something like 14:50 (as in 2:50PM) } } So what I want is for the automatic model binding on the Edit or Create action to set this Time instance up from a string (i.e. feed the Parse method with the string and return the result). The reason I am doing this is that I will have a DropDownList with selectable times. The value of each option will be the parser readable string. Can anyone provide an example BindModel method from the IModelBinder interface?

    Read the article

  • Typed DefaultListModel to avoid casting

    - by Thomas R.
    Is there a way in java to have a ListModel that only accepts a certain type? What I'm looking for is something like DefaultListModel<String> oder TypedListModel<String>, because the DefaultListModel only implements addElement(Object obj) and get(int index) which returns Object of course. That way I always have to cast from Object to e.g. String and there is no guarantee that there are only strings in my model, even though I'd like to enforce that. Is this a flaw or am I using list models the wrong way?

    Read the article

  • Of Models / Entities and N-tier applications

    - by Jonn
    I've only discovered a month ago the folly of directly accessing entities / models from the data access layer of an n-tier app. After reading about ViewModels while studying ASP.NET MVC, I've come to understand that to make a truly extensible application the model that the UI layer interacts with must be different from the one that the Data Access layer has access to. But what about the Business layer? Should I have a different set of models for my business layer as well? For true separation of concern, should I have a specific set of models that are relevant only to my business layer so as not to mess around with any entities (possibly generated by for example, the entity framework, or EJB) in the DAL or would that be overkill?

    Read the article

  • Zend without Database

    - by dbemerlin
    Hi, i googled for an hour now but maybe my Google-Fu is just too weak, i couldn't find a solution. I want to create an application that queries a service via JSON requests (all data and backend/business logic is stored in the service). With plain PHP it's simple enough since i just make a curl request, json_decode the result and get what i need. This already works quite well. A request might look like this: Call http://service-host/userlist with body: {"logintoken": "123456-1234-5678-901234"} Get Result: { "status": "Ok", "userlist":[ {"name": "foo", "id": 1}, {"name": "bar", "id": 2} ] } Now we want to get that into the Zend Framework since it's a hobby project and we want to learn about Zend. The problem is that all information i could find use a Database. Is there even a way to create a Zend Project that does not use a Database? And how can i write a model that represents the actions instead of objects and object-relations?

    Read the article

  • MySQL Count If using 4 tables or Perl

    - by user1726133
    Hi I have a relatively convoluted query that relies on 4 different tables, unfortunately I do not have control of this data, but I do have to query it. I ran this simpler query and it works using just table 1 and table 2 SELECT actor, receiver, count(IF(t2.group1 = "anxiety behavior", 1,0)) AS 'anxiety' FROM ethogram_edited_obs_behaviors t1 JOIN ethogram_behaviors t2 on t1.behavior = t2.behavior_code GROUP BY actor; Below are the 4 tables I need and the query I tried that didn't work Table 1 | Table 2 | Table 3 | Table 4 Actor | Behavior | Behavior | type of Behavior | subject | sex | subject |subject_code er frown | frown anxiety behavior | Eric M | Eric | er Here is the query that is failing SELECT actor, count(IF(t2.group1 = "anxiety behavior", 1,0) AND(t3.sex = "M", 1,0)) AS 'anxiety', FROM ethogram_edited_obs_behaviors t1 JOIN ethogram_behaviors t2 on t1.behavior = t2.behavior_code JOIN subject_code t3 on t1.actor = t3.behavior_code1 JOIN subjects t4 on t3.subject = t4.yerkes_code GROUP BY actor; Any help would be much appreciated!! Thanks :) P.S. if this is easier to do in Perl tips also much appreciated

    Read the article

  • Controlling CodeModel's code output formatting: putting lines between namespace declarations

    - by devoured elysium
    I'm making some experiments with Visual Studio's CodeModel. I tried creating a file with two namespaces in there through VS's Code Model: CodeModel codeModel = projItem.ContainingProject.CodeModel; codeModel.AddNamespace("Namespaces.FirstNamespace", "namespacestest.cs"); codeModel.AddNamespace("Namespaces.SecondNamespace", "namespacestest.cs"); the output of such code is: //file namespacestest.cs namespace Namespaces.FirstNamespace { } namespace Namespaces.SecondNamespace { } Which is almost what I'm looking for. The only catch here is that I'd like to control the spacing: having at least one line between the first and the second namespace. Does by chance anyone know of a way of achieving this? This is what I want: //file namespacestest.cs namespace Namespaces.FirstNamespace { } namespace Namespaces.SecondNamespace { } Thanks

    Read the article

  • Django complex queries

    - by Josh K
    I need to craft a filter for an object that checks date ranges. Right now I'm performing a very inefficient loop which checks all the objects. I would like to simplify this to a database call. The logic is you have a start and an end date objects. I need to check if the start OR the end is within the range of an appointment. if (start >= appointment.start && start < appointment.end) || (end > appointment.start && end <= appointment.end) I could do this in SQL, but I'm not as familiar with the Django model structure for more complex queries.

    Read the article

  • Can I add columns in a QListView in Qt ??

    - by Vic.
    Can I add columns in a QListView object?? here's something I found here: model->setHeaderData( 0, Qt::Horizontal, "numéro" ); model->setHeaderData( 1, Qt::Horizontal, "prénom" ); model->setHeaderData( 2, Qt::Horizontal, "nom" ); //... model->setData( model->index( line, 0 ), contact->num(), Qt::DisplayRole ); model->setData( model->index( line, 1 ), contact->prenom(), Qt::DisplayRole ); model->setData( model->index( line, 2 ), contact->nom(), Qt::DisplayRole ); Since I'm using Qt Creator 2.0.1, I figured my model would be: ui->ObjectName->model() The application builds successfully but I get a: "The program has unexpectedly finished." at runtime. Any Ideas ? Thanks.

    Read the article

  • How to properly reserve identity values for usage in a database?

    - by esac
    We have some code in which we need to maintain our own identity (PK) column in SQL. We have a table in which we bulk insert data, but we add data to related tables before the bulk insert is done, thus we can not use an IDENTITY column and find out the value up front. The current code is selecting the MAX value of the field and incrementing it by 1. Although there is a highly unlikely chance that two instances of our application will be running at the same time, it is still not thread-safe (not to mention that it goes to the database everytime). I am using the ADO.net entity model. How would I go about 'reserving' a range of id's to use, and when that range runs out, grab a new block to use, and guarantee that the same range will not be used.

    Read the article

  • Rails: How do I run a before_save only if certain conditions are met?

    - by Shpigford
    I have a before_save method that I call that renames an uploaded image. before_save :randomize_file_name def randomize_file_name extension = File.extname(screen_file_name).downcase key = ActiveSupport::SecureRandom.hex(8) self.screen.instance_write(:file_name, "#{key}#{extension}") end That method is part of my Item model. That works great when I create a new item or need to update the image associated with an item...but the problem is that if I need to update an item but NOT the image, the randomize_file_name method still gets run and renames the file in the database (though not the file itself, obviously). So, I'm thinking I need to figure out a way to only run randomize_file_name if a file is included in the form submission...but I'm not sure how to pull that off.

    Read the article

  • General approach for posting business logic status messages to UI?

    - by generalt
    Hello all. I have been struggling with this question for awhile now, and I haven't reached a conclusion. I'm not typically a UI programmer, so forgive the noobishness. I'm writing a typical application with a UI layer (WPF) and a business layer. I want to post status messages to the UI from the business layer (perhaps deep within the business layer), but I don't want the business layer to have any knowledge of the UI. Is there a generally accepted pattern for this? I was thinking to have a message queue of some sort to which the business layer posts status messages, and have the view model of the UI subscribe to that queue and intercept messages from the queue and route them to the UI. Is that a good approach? Is there somewhere else I should start? Thank you.

    Read the article

  • Rails architecture questions

    - by justinbach
    I'm building a Rails site that, among other things, allows users to build their own recipe repository. Recipes are entered either manually or via a link to another site (think epicurious, cooks.com, etc). I'm writing scripts that will scrape a recipe from these sites given a link from a user, and so far (legal issues notwithstanding) that part isn't giving me any trouble. However, I'm not sure where to put the code that I'm writing for these scraper scripts. My first thought was to put it in the recipes model, but it seems a bit too involved to go there; would a library or a helper be more appropriate? Also, as I mentioned, I'm building several different scrapers for different food websites. It seems to me that the elegant way to do this would be to define an interface (or abstract base class) that determines a set of methods for constructing a recipe object given a link, but I'm not sure what the best approach would be here, either. How might I build out these OO relationships, and where should the code go?

    Read the article

  • reading variable from xml file in flex

    - by m0j1
    hi , I'm trying to read the address of a flv file from an xml file and then put it in the "source" property of a videodisplay tag . here's my code : //in decleration tags <fx:Model id="myModel" source="myXML.xml"/> <s:ArrayList id="myArrList" source="{myModel.main}"/> //in the main code <mx:VideoDisplay id="videoDisplay" source="{myArrList.getItemAt(0)}" /> and the xml file is: <main> <myFile>"g:\myflv.flv"</myFile> </main> anyone knows what's wrong? tnx

    Read the article

  • Recommendation for tool/framework that follows the naked objects pattern?

    - by Marcus Munzert
    I am searching for a tool/framework that follows the naked objects pattern and is written in Java. I know about tools like for instance JMatter, Naked Objects and Domain Object Explorer. That's not exactly what I am searching for, though. Open source would be great, but doesn't need to be. My intention is to use that tool/framework for the purpose of model-driven software development to do the modeling part. Ideally, such a tool/framework would provide the option to use JPA to store/load objects.

    Read the article

  • Adding a Categorylist to all pages with MVC4

    - by Sidriel
    I'm new with MVC4 and just MVC. I have a homecontroller and a categorycontroller. The categorycontroller sends data from the model to the categoryIndex view. That's works fine. But now I want to add the categorylist on all the available controllers. I already fixed this to add in all classes return view(db.categorys.ToList()); and add categoryIndex to the shared folder. In _layout.cshtml I'm adding a@RenderPage("~/")` and this works. But when I have to pass more than only the (db.categorys.ToList()) in the return it goes wrong. How can I fixed this problem. How do I add the categorylist too every controller and page properly?

    Read the article

  • Conditional value for ActiveRecord create method only

    - by Steve Wright
    I have a form where I have an administrator creating new users. The form uses the User model I created (login, password, first_name, etc...). For the last field on the form, I want to have a checkbox that doesn't need to be stored as part of the User record, but it is needed for the controller. This will control whether or not the newly created user will receive a welcome email or not. def create @user = User.new(params[:user]) if @user.save if @user.send_welcome_email UserMailer.welcome_email(@user).deliver end redirect_to(admin_users_url, :notice => "User #{@user.name} was successfully created.") else render :action => "new" end end In my view (haml) I am trying to access it like this: %p Send Welcome Email? = f.check_box :send_welcome_email I tried to make this an attr_accessible: :send_welcome_email but the controller does not recognize it. I get an undefined method 'send_welcome_email' for #&lt;User:0x00000100d080a8&gt; I would like it to look like this: What is the best way to get this working:

    Read the article

  • Navigating by foreign keys in ADO.NET Entity Framework/MySQL

    - by Werg38
    I am using ASP.NET MVC2 on top of a MySQL database in VS2008. I am using the MySQL ADO.NET connector 6.2.3 to provide the connection for the ADO.NET Entity Data Model. This is mostly working ok, however navigating via foreign keys is causing me a real headache! Here is a simplified example.. Car (Table) CarID PK Colour Doors ManufacturerID FK Manufacturer (Table) ManufacturerID PK Name In the edmx file I can see the 1-many relationship shown as a navigation property in the both the Car and Manufacturer tables. I create a Models.CarRepository that allows me to returns a IQueryable. At the View I want to be able to display the Manufacturer.Name for each car. This is not accessible via the object I get returned. What is best way to implement this? Have I encountered a limitation of the Entity Framework/MySQL combination?

    Read the article

  • What's causing "NoMethodError: undefined method `include?' for nil:NilClass"

    - by NudeCanalTroll
    I have a Book model in my Rails application, with various properties (aka columns in the book db table). One of these properties is "ranking". Recently, may app has started to throw NoMethodError: undefined method 'include?' for nil:NilClass for the following code: def some_method(book, another_arg) return book.ranking unless book.ranking.blank? ... end However, it's not consistent. The vast majority of the time, accessing book.ranking works -- the error is thrown maybe 2-4% of the time. If I change the code to book[:ranking] or book['ranking'] instead of book.ranking, it works 100% of the time. Any ideas?

    Read the article

  • How do you preserve the updated_at date field when saving the the database in Symfony?

    - by Failpunk
    This has to be simple... I'm trying to preserve the current date that is already stored in an updated_at field in the DB. I'm updating a single field value in the same row and then saving but I don't want it to update the updated_at field. I want to preserve the existing updated_at value. I only want to do this in one, maybe two situations so I don't need to overwrite the model for every other action in the program. I've tried this: $originalDate = $this->getUpdatedAt(); $this->setUpdatedAt($originalDate); $this->save(); This seems like it should work but still it seems to update the field.

    Read the article

  • NoMethodError when using .where (eager fetching)

    - by Ethan Leroy
    I have the following model classes... class Image < ActiveRecord::Base attr_accessible :description, :title has_many :imageTags has_many :tags, :through => :imageTags end class Tag < ActiveRecord::Base attr_accessible :name has_many :imageTags has_many :images, :through => :imageTags end class ImageTag < ActiveRecord::Base attr_accessible :position belongs_to :image belongs_to :tag end And when I use find for getting the Tag with the id 1 t = Tag.find(1); @images = t.images; But when I do the same with where, I get a NoMethodError, with the description undefined method 'images': t = Tag.where(:name => "foo"); @images = t.images; I also tried adding .includes(:images) before the .where statement, but that doesn't work too. So, how can I get all Images that belong to a Tag?

    Read the article

  • Developing web apps using ASP.NET MVC 3, Razor and EF Code First - Part 1

    - by shiju
    In this post, I will demonstrate web application development using ASP. NET MVC 3, Razor and EF code First. This post will also cover Dependency Injection using Unity 2.0 and generic Repository and Unit of Work for EF Code First. The following frameworks will be used for this step by step tutorial. ASP.NET MVC 3 EF Code First CTP 5 Unity 2.0 Define Domain Model Let’s create domain model for our simple web application Category class public class Category {     public int CategoryId { get; set; }     [Required(ErrorMessage = "Name Required")]     [StringLength(25, ErrorMessage = "Must be less than 25 characters")]     public string Name { get; set;}     public string Description { get; set; }     public virtual ICollection<Expense> Expenses { get; set; } }   Expense class public class Expense {             public int ExpenseId { get; set; }            public string  Transaction { get; set; }     public DateTime Date { get; set; }     public double Amount { get; set; }     public int CategoryId { get; set; }     public virtual Category Category { get; set; } } We have two domain entities - Category and Expense. A single category contains a list of expense transactions and every expense transaction should have a Category. In this post, we will be focusing on CRUD operations for the entity Category and will be working on the Expense entity with a View Model object in the later post. And the source code for this application will be refactored over time. The above entities are very simple POCO (Plain Old CLR Object) classes and the entity Category is decorated with validation attributes in the System.ComponentModel.DataAnnotations namespace. Now we want to use these entities for defining model objects for the Entity Framework 4. Using the Code First approach of Entity Framework, we can first define the entities by simply writing POCO classes without any coupling with any API or database library. This approach lets you focus on domain model which will enable Domain-Driven Development for applications. EF code first support is currently enabled with a separate API that is runs on top of the Entity Framework 4. EF Code First is reached CTP 5 when I am writing this article. Creating Context Class for Entity Framework We have created our domain model and let’s create a class in order to working with Entity Framework Code First. For this, you have to download EF Code First CTP 5 and add reference to the assembly EntitFramework.dll. You can also use NuGet to download add reference to EEF Code First.    public class MyFinanceContext : DbContext {     public MyFinanceContext() : base("MyFinance") { }     public DbSet<Category> Categories { get; set; }     public DbSet<Expense> Expenses { get; set; }         }   The above class MyFinanceContext is derived from DbContext that can connect your model classes to a database. The MyFinanceContext class is mapping our Category and Expense class into database tables Categories and Expenses using DbSet<TEntity> where TEntity is any POCO class. When we are running the application at first time, it will automatically create the database. EF code-first look for a connection string in web.config or app.config that has the same name as the dbcontext class. If it is not find any connection string with the convention, it will automatically create database in local SQL Express database by default and the name of the database will be same name as the dbcontext class. You can also define the name of database in constructor of the the dbcontext class. Unlike NHibernate, we don’t have to use any XML based mapping files or Fluent interface for mapping between our model and database. The model classes of Code First are working on the basis of conventions and we can also use a fluent API to refine our model. The convention for primary key is ‘Id’ or ‘<class name>Id’.  If primary key properties are detected with type ‘int’, ‘long’ or ‘short’, they will automatically registered as identity columns in the database by default. Primary key detection is not case sensitive. We can define our model classes with validation attributes in the System.ComponentModel.DataAnnotations namespace and it automatically enforces validation rules when a model object is updated or saved. Generic Repository for EF Code First We have created model classes and dbcontext class. Now we have to create generic repository pattern for data persistence with EF code first. If you don’t know about the repository pattern, checkout Martin Fowler’s article on Repository Let’s create a generic repository to working with DbContext and DbSet generics. public interface IRepository<T> where T : class     {         void Add(T entity);         void Delete(T entity);         T GetById(long Id);         IEnumerable<T> All();     }   RepositoryBasse – Generic Repository class public abstract class RepositoryBase<T> where T : class { private MyFinanceContext database; private readonly IDbSet<T> dbset; protected RepositoryBase(IDatabaseFactory databaseFactory) {     DatabaseFactory = databaseFactory;     dbset = Database.Set<T>(); }   protected IDatabaseFactory DatabaseFactory {     get; private set; }   protected MyFinanceContext Database {     get { return database ?? (database = DatabaseFactory.Get()); } } public virtual void Add(T entity) {     dbset.Add(entity);            }        public virtual void Delete(T entity) {     dbset.Remove(entity); }   public virtual T GetById(long id) {     return dbset.Find(id); }   public virtual IEnumerable<T> All() {     return dbset.ToList(); } }   DatabaseFactory class public class DatabaseFactory : Disposable, IDatabaseFactory {     private MyFinanceContext database;     public MyFinanceContext Get()     {         return database ?? (database = new MyFinanceContext());     }     protected override void DisposeCore()     {         if (database != null)             database.Dispose();     } } Unit of Work If you are new to Unit of Work pattern, checkout Fowler’s article on Unit of Work . According to Martin Fowler, the Unit of Work pattern "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." Let’s create a class for handling Unit of Work   public interface IUnitOfWork {     void Commit(); }   UniOfWork class public class UnitOfWork : IUnitOfWork {     private readonly IDatabaseFactory databaseFactory;     private MyFinanceContext dataContext;       public UnitOfWork(IDatabaseFactory databaseFactory)     {         this.databaseFactory = databaseFactory;     }       protected MyFinanceContext DataContext     {         get { return dataContext ?? (dataContext = databaseFactory.Get()); }     }       public void Commit()     {         DataContext.Commit();     } }   The Commit method of the UnitOfWork will call the commit method of MyFinanceContext class and it will execute the SaveChanges method of DbContext class.   Repository class for Category In this post, we will be focusing on the persistence against Category entity and will working on other entities in later post. Let’s create a repository for handling CRUD operations for Category using derive from a generic Repository RepositoryBase<T>.   public class CategoryRepository: RepositoryBase<Category>, ICategoryRepository     {     public CategoryRepository(IDatabaseFactory databaseFactory)         : base(databaseFactory)         {         }                } public interface ICategoryRepository : IRepository<Category> { } If we need additional methods than generic repository for the Category, we can define in the CategoryRepository. Dependency Injection using Unity 2.0 If you are new to Inversion of Control/ Dependency Injection or Unity, please have a look on my articles at http://weblogs.asp.net/shijuvarghese/archive/tags/IoC/default.aspx. I want to create a custom lifetime manager for Unity to store container in the current HttpContext.   public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable {     public override object GetValue()     {         return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];     }     public override void RemoveValue()     {         HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);     }     public override void SetValue(object newValue)     {         HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;     }     public void Dispose()     {         RemoveValue();     } }   Let’s create controller factory for Unity in the ASP.NET MVC 3 application. public class UnityControllerFactory : DefaultControllerFactory { IUnityContainer container; public UnityControllerFactory(IUnityContainer container) {     this.container = container; } protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType) {     IController controller;     if (controllerType == null)         throw new HttpException(                 404, String.Format(                     "The controller for path '{0}' could not be found" +     "or it does not implement IController.",                 reqContext.HttpContext.Request.Path));       if (!typeof(IController).IsAssignableFrom(controllerType))         throw new ArgumentException(                 string.Format(                     "Type requested is not a controller: {0}",                     controllerType.Name),                     "controllerType");     try     {         controller= container.Resolve(controllerType) as IController;     }     catch (Exception ex)     {         throw new InvalidOperationException(String.Format(                                 "Error resolving controller {0}",                                 controllerType.Name), ex);     }     return controller; }   }   Configure contract and concrete types in Unity Let’s configure our contract and concrete types in Unity for resolving our dependencies.   private void ConfigureUnity() {     //Create UnityContainer               IUnityContainer container = new UnityContainer()                 .RegisterType<IDatabaseFactory, DatabaseFactory>(new HttpContextLifetimeManager<IDatabaseFactory>())     .RegisterType<IUnitOfWork, UnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>())     .RegisterType<ICategoryRepository, CategoryRepository>(new HttpContextLifetimeManager<ICategoryRepository>());                 //Set container for Controller Factory                ControllerBuilder.Current.SetControllerFactory(             new UnityControllerFactory(container)); }   In the above ConfigureUnity method, we are registering our types onto Unity container with custom lifetime manager HttpContextLifetimeManager. Let’s call ConfigureUnity method in the Global.asax.cs for set controller factory for Unity and configuring the types with Unity.   protected void Application_Start() {     AreaRegistration.RegisterAllAreas();     RegisterGlobalFilters(GlobalFilters.Filters);     RegisterRoutes(RouteTable.Routes);     ConfigureUnity(); }   Developing web application using ASP.NET MVC 3 We have created our domain model for our web application and also have created repositories and configured dependencies with Unity container. Now we have to create controller classes and views for doing CRUD operations against the Category entity. Let’s create controller class for Category Category Controller   public class CategoryController : Controller {     private readonly ICategoryRepository categoryRepository;     private readonly IUnitOfWork unitOfWork;           public CategoryController(ICategoryRepository categoryRepository, IUnitOfWork unitOfWork)     {         this.categoryRepository = categoryRepository;         this.unitOfWork = unitOfWork;     }       public ActionResult Index()     {         var categories = categoryRepository.All();         return View(categories);     }     [HttpGet]     public ActionResult Edit(int id)     {         var category = categoryRepository.GetById(id);         return View(category);     }       [HttpPost]     public ActionResult Edit(int id, FormCollection collection)     {         var category = categoryRepository.GetById(id);         if (TryUpdateModel(category))         {             unitOfWork.Commit();             return RedirectToAction("Index");         }         else return View(category);                 }       [HttpGet]     public ActionResult Create()     {         var category = new Category();         return View(category);     }           [HttpPost]     public ActionResult Create(Category category)     {         if (!ModelState.IsValid)         {             return View("Create", category);         }                     categoryRepository.Add(category);         unitOfWork.Commit();         return RedirectToAction("Index");     }       [HttpPost]     public ActionResult Delete(int  id)     {         var category = categoryRepository.GetById(id);         categoryRepository.Delete(category);         unitOfWork.Commit();         var categories = categoryRepository.All();         return PartialView("CategoryList", categories);       }        }   Creating Views in Razor Now we are going to create views in Razor for our ASP.NET MVC 3 application.  Let’s create a partial view CategoryList.cshtml for listing category information and providing link for Edit and Delete operations. CategoryList.cshtml @using MyFinance.Helpers; @using MyFinance.Domain; @model IEnumerable<Category>      <table>         <tr>         <th>Actions</th>         <th>Name</th>          <th>Description</th>         </tr>     @foreach (var item in Model) {             <tr>             <td>                 @Html.ActionLink("Edit", "Edit",new { id = item.CategoryId })                 @Ajax.ActionLink("Delete", "Delete", new { id = item.CategoryId }, new AjaxOptions { Confirm = "Delete Expense?", HttpMethod = "Post", UpdateTargetId = "divCategoryList" })                           </td>             <td>                 @item.Name             </td>             <td>                 @item.Description             </td>         </tr>          }       </table>     <p>         @Html.ActionLink("Create New", "Create")     </p> The delete link is providing Ajax functionality using the Ajax.ActionLink. This will call an Ajax request for Delete action method in the CategoryCotroller class. In the Delete action method, it will return Partial View CategoryList after deleting the record. We are using CategoryList view for the Ajax functionality and also for Index view using for displaying list of category information. Let’s create Index view using partial view CategoryList  Index.chtml @model IEnumerable<MyFinance.Domain.Category> @{     ViewBag.Title = "Index"; }    <h2>Category List</h2>    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>    <div id="divCategoryList">               @Html.Partial("CategoryList", Model) </div>   We can call the partial views using Html.Partial helper method. Now we are going to create View pages for insert and update functionality for the Category. Both view pages are sharing common user interface for entering the category information. So I want to create an EditorTemplate for the Category information. We have to create the EditorTemplate with the same name of entity object so that we can refer it on view pages using @Html.EditorFor(model => model) . So let’s create template with name Category. Let’s create view page for insert Category information   @model MyFinance.Domain.Category   @{     ViewBag.Title = "Save"; }   <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)     <fieldset>         <legend>Category</legend>                @Html.EditorFor(model => model)               <p>             <input type="submit" value="Create" />         </p>     </fieldset> }   <div>     @Html.ActionLink("Back to List", "Index") </div> ViewStart file In Razor views, we can add a file named _viewstart.cshtml in the views directory  and this will be shared among the all views with in the Views directory. The below code in the _viewstart.cshtml, sets the Layout page for every Views in the Views folder.      @{     Layout = "~/Views/Shared/_Layout.cshtml"; }   Source Code You can download the source code from http://efmvc.codeplex.com/ . The source will be refactored on over time.   Summary In this post, we have created a simple web application using ASP.NET MVC 3 and EF Code First. We have discussed on technologies and practices such as ASP.NET MVC 3, Razor, EF Code First, Unity 2, generic Repository and Unit of Work. In my later posts, I will modify the application and will be discussed on more things. Stay tuned to my blog  for more posts on step by step application building.

    Read the article

  • Core data migration failing with "Can't find model for source store" but managedObjectModel for source is present

    - by Ira Cooke
    I have a cocoa application using core-data, which is now at the 4th version of its managed object model. My managed object model contains abstract entities but so far I have managed to get migration working by creating appropriate mapping models and creating my persistent store using addPersistentStoreWithType:configuration:options:error and with the NSMigratePersistentStoresAutomaticallyOption set to YES. NSDictionary *optionsDictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption]; NSURL *url = [NSURL fileURLWithPath: [applicationSupportFolder stringByAppendingPathComponent: @"MyApp.xml"]]; NSError *error=nil; [theCoordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:url options:optionsDictionary error:&error] This works fine when I migrate from model version 3 to 4, which is a migration that involves adding attributes to several entities. Now when I try to add a new model version (version 5), the call to addPersistentStoreWithType returns nil and the error remains empty. The migration from 4 to 5 involves adding a single attribute. I am struggling to debug the problem and have checked all the following; The source database is in fact at version 4 and the persistentStoreCoordinator's managed object model is at version 5. The 4-5 mapping model as well as managed object models for versions 4 and 5 are present in the resources folder of my built application. I've tried various model upgrade paths. Strangely I find that upgrading from an early version 3 - 5 works .. but upgrading from 4 - 5 fails. I've tried adding a custom entity migration policy for migration of the entity whose attributes are changing ... in this case I overrode the method beginEntityMapping:manager:error: . Interestingly this method does get called when migration works (ie when I migrate from 3 to 4, or from 3 to 5 ), but it does not get called in the case that fails ( 4 to 5 ). I'm pretty much at a loss as to where to proceed. Any ideas to help debug this problem would be much appreciated.

    Read the article

  • ASP.NET MVC: How do I validate a model wrapped in a ViewModel?

    - by Deniz Dogan
    For the login page of my website I would like to list the latest news for my site and also display a few fields to let the user log in. So I figured I should make a login view model - I call this LoginVM. LoginVM contains a Login model for the login fields and a List<NewsItem> for the news listing. This is the Login model: public class Login { [Required(ErrorMessage="Enter a username.")] [DisplayName("Username")] public string Username { get; set; } [Required(ErrorMessage="Enter a password.")] [DataType(DataType.Password)] [DisplayName("Password")] public string Password { get; set; } } This is the LoginVM view model: public class LoginVM { public Login login { get; set; } public List<NewsItem> newsItems { get; set; } } This is where I get stuck. In my login controller, I get passed a LoginVM. [HttpPost] public ActionResult Login(LoginVM model, FormCollection form) { if (ModelState.IsValid) { // What? In the code I'm checking whether ModelState is valid and this would work fine if the view model was actually the Login model, but now it's LoginVM which has no validation attributes at all. How do I make LoginVM "traverse" through its members to validate them all? Am I doing something fundamentally wrong using ModelState in this manner?

    Read the article

< Previous Page | 64 65 66 67 68 69 70 71 72 73 74 75  | Next Page >