Search Results

Search found 11138 results on 446 pages for 'spring mvc'.

Page 16/446 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • How do I create a Spring 3 + Tiles 2 webapp using REST-ful URLs?

    - by Ichiro Furusato
    I'm having a heck of a time resolving URLs with Spring 3.0 MVC. I'm just building a HelloWorld to try out how to build a RESTful webapp in Spring, nothing theoretically complicated. All of the examples I've been able to find are based on configurations that pay attention to file extensions ("*.htm" or "*.do"), include an artificial directory name prefix ("/foo") or even prefix paths with a dot (ugly), all approaches that use some artificial regex pattern as a signal to the resolver. For a REST approach I want to avoid all that muck and use only the natural URL patterns of my application. I would assume (perhaps incorrectly) that in web.xml I'd set a url-pattern of "/*" and pass everything to the DispatcherServlet for resolution, then just rely on URL patterns in my controller. I can't reliably get my resolver(s) to catch the URL patterns, and in all my trials this results in a resource not found error, a stack overflow (loop), or some kind of opaque Spring 3 ServletException stack trace — one of my ongoing frustrations with Spring generally is that the error messages are not often very helpful. I want to work with a Tiles 2 resolver. I've located my *.jsp files in WEB-INF/views/ and have a single line index.jsp file at the application root redirecting to the index file set by my layout.xml (the Tiles 2 Configurer). I do all the normal Spring 3 high-level configuration: <mvc:annotation-driven /> <mvc:view-controller path="/" view-name="index"/> <context:component-scan base-package="com.acme.web.controller" /> ...followed by all sorts of combinations and configurations of UrlBasedViewResolver, InternalResourceViewResolver, UrlFilenameViewController, etc. with all manner of variantions in my Tiles 2 configuration file. Then in my controller I've trying to pick up my URL patterns. Problem is, I can't reliably even get the resolver(s) to catch the patterns to send to my controller. This has now stretched to multiple days with no real progress on something I thought would be very simple to implement. I'm perhaps trying to do too much at once, though I would think this should be a simple (almost a default) configuration. I'm just trying to create a simple HelloWorld-type application, I wouldn't expect this is rocket science. Rather than me post my own configurations (which have ranged all over the map), does anyone know of an online example that: shows a simple Spring 3 MVC + Tiles 2 web application that uses REST-ful URLs (i.e., avoiding forced URL patterns such as file extensions, added directory names or dots) and relies solely on Spring 3 code/annotations (i.e., nothing outside of Spring MVC itself) to accomplish this? Is there an easy way to do this? Thanks very much for any help.

    Read the article

  • How to access/use custom attribute in spring security based CAS client

    - by Bill Li
    I need send certain attributes(say, human readable user name) from server to client after a successful authentication. Server part was done. Now attribute was sent to client. From log, I can see: 2010-03-28 23:48:56,669 DEBUG Cas20ServiceTicketValidator:185 - Server response: [email protected] <cas:proxyGrantingTicket>PGTIOU-1-QZgcN61oAZcunsC9aKxj-cas</cas:proxyGrantingTicket> <cas:attributes> <cas:FullName>Test account 1</cas:FullName> </cas:attributes> </cas:authenticationSuccess> </cas:serviceResponse> Yet, I don't know how to access the attribute in client(I am using Spring security 2.0.5). In authenticationProvider, a userDetailsService is configured to read db for authenticated principal. <bean id="casAuthenticationProvider" class="org.springframework.security.providers.cas.CasAuthenticationProvider"> <sec:custom-authentication-provider /> <property name="userDetailsService" ref="clerkManager"/> <!-- other stuff goes here --> </bean> Now in my controller, I can easily do this: Clerk currentClerk = (Clerk)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Ideally, I can fill the attribute to this Clerk object as another property in some way. How to do this? Or what is recommended approach to share attributes across all apps under CAS's centralized nature?

    Read the article

  • ASP.NET MVC 4 async child action

    - by ShadowChaser
    I have an ASP.NET MVC 4 application targeting .NET 4.5. One of our child actions makes a call out to a web service using HttpClient. Since we're blocking on IO waiting for the HttpClient response, it makes a great deal of sense to convert the code to the async/await pattern. However, when MVC 4 attempts to execute the child action, we get the following error message: HttpServerUtility.Execute blocked while waiting for an asynchronous operation to complete. At first glance, it appears as though MVC 4 does not support async/await within a child action. The only remaining option is to run using synchronous code and force a "Wait" on the async task. As we all know, touching .Result or .Wait() on an async task in an ASP.NET context will cause an immediate deadlock. My async logic is wrapped in a class library, so I can't use the "await blah.ConfigureAwait(false)" trick. Remember, tagging "async" on the child action and using await causes an error, and that prevents me from configuring the await. I'm painted into a corner at this point. Is there any way to consume async methods in an MVC 4 child action? Seems like a flat out bug with no workarounds.

    Read the article

  • Spring MVC and Weblogic integration

    - by Jeune
    I get this error whenever I try to view my tutorial app in the browser WARNING: No mapping found for HTTP request with URI [/HelloWorld.Web] in DispatcherServlet with name 'dispatcher' That just means the request is being received by the dispatcher servlet but it can't forward it to a controller. But I can't seem to know where the problem is. I think I've mapped this correctly: <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/HelloWorld.Web">indexController</prop> </props> </property> </bean> <bean id="indexController" class="com.helloworld.controller.IndexController"> <property name="artistDao" ref="artistDao"/> <property name="methodNameResolver"> <bean class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver"> <property name="alwaysUseFullPath" value="true"/> <property name="mappings"> <props> <prop key="/HelloWorld.Web">getAllArtists</prop> </props> </property> </bean> </property> </bean> I am using Spring 2.5.6 and Bea Weblogic Server 9.2

    Read the article

  • Intercepting method with Spring AOP using only annotations

    - by fish
    In my Spring context file I have something like this: <bean id="userCheck" class="a.b.c.UserExistsCheck"/> <aop:config> <aop:aspect ref="userCheck"> <aop:pointcut id="checkUser" expression="execution(* a.b.c.d.*.*(..)) &amp;&amp; args(a.b.c.d.RequestObject)"/> <aop:around pointcut-ref="checkUser" method="checkUser"/> </aop:aspect> </aop:config> a.b.c.UserExistsCheck looks like this: @Aspect public class UserExistsCheck { @Autowired private UserInformation userInformation; public Object checkUser(ProceedingJoinPoint pjp) throws Throwable { int userId = ... //get it from the RequestObject passed as a parameter if (userExists(userId)) { return pjp.proceed(); } else { return new ResponseObject("Invalid user); } } And the class that is being intercepted with this stuff looks like this: public class Klazz { public ResponseObject doSomething(RequestObject request) {...} } This works. UserExistCheck is executed as desired before the call is passed to Klazz. The problem is that this is the only way I got it working. To get this working by using annotations instead of the context file seems to be just too much for my small brain. So... how exactly should I annotate the methods in UserExistsCheck and Klazz? And do I still need something else too? Another class? Still something in the context file?

    Read the article

  • Extending spring based app

    - by pitr
    I have a spring-based Web Service. I now want to build a sort of plugin for it that extends it with beans. What I have now in web.xml is: <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/*-configuration.xml</param-value> </context-param> My core app has main-configuration.xml which declares its beans. My plugin app has plugin-configuration.xml which declares additional beans. Now when I deploy, my build deploys plugin.jar into /WEB-INF/lib/ and copies plugin-configuration.xml into /WEB-INF/classes/ all under main.war. This is all fine (although I think there could be a better solution), but when I develop the plugin, I don't want to have two projects in Eclipse with dependencies. I wish to have main.jar that I include as a library. However, web.xml from main.jar isn't automatically discovered. How can I do this? Bean injection? Bean discovery of some sort? Something else? Note: I expect to have multiple different plugins in production, but development of each of them will be against pure main.jar Thank you.

    Read the article

  • Newbie question about controllers in ASP.Net MVC.

    - by Sergio Tapia
    I'm following a tutorial on creating the NerdDinner using ASP.Net MVC. However, I'm using Visual Studio 2010 Ultimate edition and there was only MVC2 to choose from. So I've following the tutorial so far, and everything is really clicking and being really well explained, until this little hitch. The guide is asking me to create new methods on a Controller file like so: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace NerdDinner.Controllers { public class DinnersController : Controller { public void Index(){ Response.Write("<h1>Coming Soon: Dinners</h1>"); } public void Details(int id) { Response.Write("<h1>Details DinnerID: " + id + "</h1>"); } } } However, when I created the Controllers file, Visual Studio created an Index method already, but it looks vastly different to what the tutorial shows. Maybe this is the new way to do things using MVC2? using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace NerdDinner.Controllers { public class DinnersController : Controller { // // GET: /Dinners/ public ActionResult Index() { return View(); } } } My question is, how can I reproduce the Details and Index method (they're in MVC) to the MVC2 way? Is this even relevant? Thank you!

    Read the article

  • application-context.xml problem for Spring ActionScript

    - by jiri
    content of The application-content.xml is <?xml version="1.0" encoding="utf-8"?> <objects xmlns="http://www.springactionscript.org/schema/objects" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springactionscript.org/schema/objects http://www.springactionscript.org/schema/objects/spring-actionscript-objects-1.0.xsd"> <property file="strings.properties" /> <object id="string1" class="String"/> <object id="string2" class="String"/> <object id="nlslzf" class="com.sgb.model.MyClass"/> </objects> content of strings.properties is: s1=Firststring s2=Secondstring but error: Main Thread (Suspended: Error: An object definition for 'string1' was not found.) org.springextensions.actionscript.ioc.factory.support::AbstractObjectFactory/getObject SpringActionScript/test SpringActionScript/onCreationComplete SpringActionScript/___SpringActionScript_Application1_creationComplete flash.events::EventDispatcher/dispatchEventFunction [no source] mx.core::UIComponent/dispatchEvent mx.core::UIComponent/set initialized mx.managers::LayoutManager/doPhasedInstantiation Function/http://adobe.com/AS3/2006/builtin::apply [no source] mx.core::UIComponent/callLaterDispatcher2 mx.core::UIComponent/callLaterDispatcher2 mx.core::UIComponent/callLaterDispatcher i can run normal if removed the '' why it is? springactionscript bug?

    Read the article

  • Strage character encoding problem with Eclipse / Spring / Tomcat 6

    - by Czar
    Hi, I have been trying things all da but can't get a proper solution. My problem is: I am developing a Spring MVC based app in my local Tomcat. My MYSQl database has UTF-8 encoding set, all content in there displays properly when using phpMyAdmin. Also the output in LOG files using log4j in catalina.out works fine. My JSP pages are configured by <!-- encoding --> <%@ page contentType="text/html; charset=UTF-8" %> <%@ page pageEncoding="UTF-8" %> Also showing data on my JSP works fine. I can also send data from my Controller without any DB intereference using special chars, e.g. String str = "UTF-8 Test: Ä Ö Ü ß è é â"; logger.debug(str); mav.addObject("utftest", str); That displays correctly in log and on jsp page in browser. BUT: When having special chars directly in my JSP file, e.g. for text in headers, this does not work. FF and Google Chrome display strange chars but report the page to be UTF-8. When switching to Latin, the chars just get more and more strange. Same problem when showing text tokens from my messages.properties file, although Eclipse says when right-clicking that UTF-8 will be used. I am a little it lost and don't know where to check now. Summary: DB storage is fine DB output on JSP is fine Output on JSP directly form controller is fine even reading in form forms is fine .properties files and JSP text is not fine !!! Any ideas? I really appreciate and tips.

    Read the article

  • Spring security with GAE

    - by xybrek
    I'm trying to implement Spring security for my GAE application however I'm getting this error: No bean named 'springSecurityFilterChain' is defined I added this configuration on my application web.xml: <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> And in the servlet-context: <!-- Configure security --> <security:http auto-config="true"> <security:intercept-url pattern="/**" access="ROLE_USER" /> </security:http> <security:authentication-manager alias="authenticationManager"> <security:authentication-provider> <security:user-service> <security:user name="jimi" password="jimi" authorities="ROLE_USER, ROLE_ADMIN" /> <security:user name="bob" password="bob" authorities="ROLE_USER" /> </security:user-service> </security:authentication-provider> </security:authentication-manager> What could be causing the error?

    Read the article

  • Spring security and authentication provider

    - by Pascal
    I'm trying to implement Spring 3 Security in a project, but I can not get rid of the following error: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_authenticationManager': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No authentication providers were found in the application context This seems weird, as I did provide an authentication provider! I've added these lines to web. <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> And this is my applicationContext-security.xml: <http auto-config="false"> <intercept-url pattern="/**" access="ROLE_USER" /> <http-basic /> </http> <authentication-manager alias="authenticationManager"> <authentication-provider> <user-service> <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN"/> <user name="bob" password="bobspassword" authorities="ROLE_USER"/> </user-service> </authentication-provider> </authentication-manager> Google couldn't help me much further, nor could the official documentation.

    Read the article

  • Spring MVC + Hibernate encoding problem

    - by Bar
    I work on Spring MVC + Hibernate application, use MySQL (ver. 5.0.51a) with the InnoDB engine. The problem appears when I am sending a form with cyrillic characters. As the result, database contains senseless chars in unknown encoding. All the JSP pages, database (+ tables and fields) created using UTF-8. Hibernate config also contains property which sets encoding to UTF-8. I had solved this by creating filter which encodes request content with UTF-8. Exemplary code: … encoding = "UTF-8"; request.setCharacterEncoding(encoding); chain.doFilter(request, response); … But it visibly slows down the app. The interesting thing is that executing insert query directly from the app (i.e. running from Eclipse as Java Application) works perfect. Any suggestions are welcome. TIA, Michael.

    Read the article

  • Spring URL mapping question

    - by es11
    I am using Java with Spring framework. Given the following url: www.mydomain.com/contentitem/234 I need to map all requests that come to /contentitem/{numeric value} mapped to a given controller with the "numeric value" passed as a parameter to the controller. Right now in my servlet container xml I have simple mappings similar to the following: ... <entry key="/index.html"> <ref bean="homeController" /> </entry> ... I am just wondering what I need to add to the mapping in order to achieve what I described? Edit: I unaccepted the answer temporarily because I can't seem to figure out how to do the mapping in my web.xml (I am using annotations as described in axtavt's answer below). How do I add a proper <url-pattern>..</url-pattern> in my <servlet-mapping> so that the request for "/contentitem/{numeric_value}" gets properly picked up? Thanks!

    Read the article

  • Componentizing complex functionality in an MVC web app

    - by NXT
    Hi Everyone, This is question about MVC web-app architecture, and how it can be extended to handle componentizing moderately complex units of functionality. I have an MVC style web-app with a customer facing credit card charge page. I've been asked to allow the admins to enter credit card payments as well, for times when credit cards are taken over the phone. The customer facing credit card charge section of the website is currently it's own controller, with approximately 3 pages and a login. That controller is responsible for: Customer login credential authentication Credit card data collection Calling a library to do the actual charge. reporting the results to the user. I would like to extract the card data collection pages into a component of some kind so that I can easily reuse the code on the admin side of the app. Right now my components are limited to single "view" pages with PHP style embedded Perl code. This is a simple, custom MVC framework written in Perl. Right now, controllers are called directly from the framework to service web requests. My idea is to allow controllers to be called from other controllers, so that I can componentize more complex functionality. For simplicity I think I prefer composition over inheritance, even though it will require writing a bunch of pass-through methods (actions). Being Perl, I could in theory do multiple inheritance. I'm wondering if anyone with experience in other MVC web frameworks can comment on how this sort of thing is usually done. Thank you.

    Read the article

  • How to manually set an authenticated user in Spring Security / SpringMVC

    - by David Parks
    After a new user submits a 'New account' form, I want to manually log that user in so they don't have to login on the subsequent page. The normal form login page going through the spring security interceptor works just fine. In the new-account-form controller I am creating a UsernamePasswordAuthenticationToken and setting it in the SecurityContext manually: SecurityContextHolder.getContext().setAuthentication(authentication); On that same page I later check that the user is logged in with: SecurityContextHolder.getContext().getAuthentication().getAuthorities(); This returns the authorities I set earlier in the authentication. All is well. But when this same code is called on the very next page I load, the authentication token is just UserAnonymous. I'm not clear why it did not keep the authentication I set on the previous request. Any thoughts? Could it have to do with session ID's not being set up correctly? Is there something that is possibly overwriting my authentication somehow? Perhaps I just need another step to save the authentication? Or is there something I need to do to declare the authentication across the whole session rather than a single request somehow? Just looking for some thoughts that might help me see what's happening here.

    Read the article

  • upgrading to spring 3.0 problem with interceptorNames

    - by mkoryak
    I am trying to upgrade to Spring 3.0 and i have the following issues: Finding the dependencies. People recommend using maven, but id rather not try to learn how to use maven/install it if the jars are available somewhere for download. The following bean declaration is now longer valid but i dont know how to fix it: <bean id="service" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces" value="com.service.SomeService" /> <property name="target"> <bean class="com.service.SomeServiceImpl"> </bean> </property> <property name="interceptorNames"> <list> <value>hibernateInterceptor</value> </list> </property> </bean> The complaint is that <property name="interceptorNames"> is no longer supported and should be done some other way

    Read the article

  • How to collect and inject all beans of a given type in Spring XML configuration

    - by GrzegorzOledzki
    One of the strongest accents of the Spring framework is the Dependency Injection concept. I understand one of the advices behind that is to separate general high-level mechanism from low-level details (as announced by Dependency Inversion Principle). Technically, that boils down to having a bean implementation to know as little as possible about a bean being injected as a dependency, e.g. public class PrintOutBean { private LogicBean logicBean; public void action() { System.out.println(logicBean.humanReadableDetails()); } //... } <bean class="PrintOutBean"> <property name="loginBean" ref="ShoppingCartBean"/> </bean> But what if I wanted to a have a high-level mechanism operating on multiple dependent beans? public class MenuManagementBean { private Collection<Option> options; public void printOut() { for (Option option:options) { // do something for option } //... } } I know one solution would be to use @Autowired annotation in the singleton bean, that is... @Autowired private Collection<Option> options; But doesn't it violate the separation principle? Why do I have to specify what dependents to take in the very same place I use them (i.e. MenuManagementBean class in my example)? Is there a way to inject collections of beans in the XML configuration like this (without any annotation in the MMB class)? <bean class="MenuManagementBean"> <property name="options"> <xxx:autowire by-type="MyOptionImpl"/> </property> </bean>

    Read the article

  • Why doesn't the spring @Autowire work with java generics

    - by testing123
    Inspired by spring data awesomeness I wanted to create a abstract RESTController that I could extend for a lot of my controllers. I created the following class: @Controller public abstract class RESTController<E, PK extends Serializable, R extends PagingAndSortingRepository<E, PK>> { @Autowired private R repository; @RequestMapping(method=RequestMethod.GET, params={"id"}) @ResponseBody public E getEntity(@RequestParam PK id) { return repository.findOne(id); } ... } I was hoping that the generics would allow me to @Autowire in the repository but I get the following error: SEVERE: Allocate exception for servlet appServlet org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.springframework.data.repository.PagingAndSortingRepository] is defined: expected single matching bean but found 3: [groupRepository, externalCourseRepository, managedCourseRepository] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:800) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) I understand what the error is telling me, there is more than one match for the @Autowire. I am confused because I thought by creating the following controller it would work: @Controller @RequestMapping(value="/managedCourse") public class ManagedCourseController extends RESTController<ManagedCourse, Long, ManagedCourseRepository> { ... } This is easy enough to work around by doing having a method like this in the RESTController: protected abstract R getRepository(); and then doing this in your implementing class: @Autowired private ManagedCourseRepository repository; @Override protected ManagedCourseRepository getRepository() { return repository; } I was just wondering if someone had any thoughts of how I could get this to work.

    Read the article

  • Strange behavior while returning csv file from spring controller

    - by Fanooos
    I working in a spring application which have an action method that returns a CSV file. This action works fine but in some cases it throws a predefined exception (MyAppException). I have another method that is annotated @ExceptionHandler(MyAppException.class) In the exception handler method I return another csv file but with different contents. The code that returns the csv file is almost the same in the two methods. List<String[]> list= new ArrayList<String[]>(); list.add(new String[]{ integrationRequestErrorLog.getErrorMessage(), Long.toString(integrationRequestErrorLog.getId()), Integer.toString(integrationRequestErrorLog.getErrorCode()) }); CSVWriter writer = new CSVWriter(response.getWriter(), ','); writer.writeAll(list); writer.close(); the difference between the two method is the list of contents. In the first method the file is returned normally while in the exception handler method I have a strange behavior. The exception handler method works fine with Opera browser while it gives me a 404 with FireFox. Opera browser give me 404 also but it download the file while firefox does not? Really I do not understand what is the difference here.

    Read the article

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

    - by shiju
    In my previous post Developing web apps using ASP.NET MVC 3, Razor and EF Code First - Part 1, we have discussed on how to work with ASP.NET MVC 3 and EF Code First for developing web apps. We have created generic repository and unit of work with EF Code First for our ASP.NET MVC 3 application and did basic CRUD operations against a simple domain entity. In this post, I will demonstrate on working with domain entity with deep object graph, Service Layer and View Models and will also complete the rest of the demo application. In the previous post, we have done CRUD operations against Category entity and this post will be focus on Expense entity those have an association with Category entity. You can download the source code from http://efmvc.codeplex.com . The following frameworks will be used for this step by step tutorial.    1. ASP.NET MVC 3 RTM    2. EF Code First CTP 5    3. Unity 2.0 Domain Model Category Entity 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 Entity 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. Repository class for Expense Transaction Let’s create repository class for handling CRUD operations for Expense entity public class ExpenseRepository : RepositoryBase<Expense>, IExpenseRepository     {     public ExpenseRepository(IDatabaseFactory databaseFactory)         : base(databaseFactory)         {         }                } public interface IExpenseRepository : IRepository<Expense> { } Service Layer If you are new to Service Layer, checkout Martin Fowler's article Service Layer . According to Martin Fowler, Service Layer defines an application's boundary and its set of available operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coordinating responses in the implementation of its operations. Controller classes should be lightweight and do not put much of business logic onto it. We can use the service layer as the business logic layer and can encapsulate the rules of the application. Let’s create a Service class for coordinates the transaction for Expense public interface IExpenseService {     IEnumerable<Expense> GetExpenses(DateTime startDate, DateTime ednDate);     Expense GetExpense(int id);             void CreateExpense(Expense expense);     void DeleteExpense(int id);     void SaveExpense(); } public class ExpenseService : IExpenseService {     private readonly IExpenseRepository expenseRepository;            private readonly IUnitOfWork unitOfWork;     public ExpenseService(IExpenseRepository expenseRepository, IUnitOfWork unitOfWork)     {                  this.expenseRepository = expenseRepository;         this.unitOfWork = unitOfWork;     }     public IEnumerable<Expense> GetExpenses(DateTime startDate, DateTime endDate)     {         var expenses = expenseRepository.GetMany(exp => exp.Date >= startDate && exp.Date <= endDate);         return expenses;     }     public void CreateExpense(Expense expense)     {         expenseRepository.Add(expense);         unitOfWork.Commit();     }     public Expense GetExpense(int id)     {         var expense = expenseRepository.GetById(id);         return expense;     }     public void DeleteExpense(int id)     {         var expense = expenseRepository.GetById(id);         expenseRepository.Delete(expense);         unitOfWork.Commit();     }     public void SaveExpense()     {         unitOfWork.Commit();     } }   View Model for Expense Transactions In real world ASP.NET MVC applications, we need to design model objects especially for our views. Our domain objects are mainly designed for the needs for domain model and it is representing the domain of our applications. On the other hand, View Model objects are designed for our needs for views. We have an Expense domain entity that has an association with Category. While we are creating a new Expense, we have to specify that in which Category belongs with the new Expense transaction. The user interface for Expense transaction will have form fields for representing the Expense entity and a CategoryId for representing the Category. So let's create view model for representing the need for Expense transactions. public class ExpenseViewModel {     public int ExpenseId { get; set; }       [Required(ErrorMessage = "Category Required")]     public int CategoryId { get; set; }       [Required(ErrorMessage = "Transaction Required")]     public string Transaction { get; set; }       [Required(ErrorMessage = "Date Required")]     public DateTime Date { get; set; }       [Required(ErrorMessage = "Amount Required")]     public double Amount { get; set; }       public IEnumerable<SelectListItem> Category { get; set; } } The ExpenseViewModel is designed for the purpose of View template and contains the all validation rules. It has properties for mapping values to Expense entity and a property Category for binding values to a drop-down for list values of Category. Create Expense transaction Let’s create action methods in the ExpenseController for creating expense transactions public ActionResult Create() {     var expenseModel = new ExpenseViewModel();     var categories = categoryService.GetCategories();     expenseModel.Category = categories.ToSelectListItems(-1);     expenseModel.Date = DateTime.Today;     return View(expenseModel); } [HttpPost] public ActionResult Create(ExpenseViewModel expenseViewModel) {                      if (!ModelState.IsValid)         {             var categories = categoryService.GetCategories();             expenseViewModel.Category = categories.ToSelectListItems(expenseViewModel.CategoryId);             return View("Save", expenseViewModel);         }         Expense expense=new Expense();         ModelCopier.CopyModel(expenseViewModel,expense);         expenseService.CreateExpense(expense);         return RedirectToAction("Index");              } In the Create action method for HttpGet request, we have created an instance of our View Model ExpenseViewModel with Category information for the drop-down list and passing the Model object to View template. The extension method ToSelectListItems is shown below   public static IEnumerable<SelectListItem> ToSelectListItems(         this IEnumerable<Category> categories, int  selectedId) {     return           categories.OrderBy(category => category.Name)                 .Select(category =>                     new SelectListItem                     {                         Selected = (category.CategoryId == selectedId),                         Text = category.Name,                         Value = category.CategoryId.ToString()                     }); } In the Create action method for HttpPost, our view model object ExpenseViewModel will map with posted form input values. We need to create an instance of Expense for the persistence purpose. So we need to copy values from ExpenseViewModel object to Expense object. ASP.NET MVC futures assembly provides a static class ModelCopier that can use for copying values between Model objects. ModelCopier class has two static methods - CopyCollection and CopyModel.CopyCollection method will copy values between two collection objects and CopyModel will copy values between two model objects. We have used CopyModel method of ModelCopier class for copying values from expenseViewModel object to expense object. Finally we did a call to CreateExpense method of ExpenseService class for persisting new expense transaction. List Expense Transactions We want to list expense transactions based on a date range. So let’s create action method for filtering expense transactions with a specified date range. public ActionResult Index(DateTime? startDate, DateTime? endDate) {     //If date is not passed, take current month's first and last dte     DateTime dtNow;     dtNow = DateTime.Today;     if (!startDate.HasValue)     {         startDate = new DateTime(dtNow.Year, dtNow.Month, 1);         endDate = startDate.Value.AddMonths(1).AddDays(-1);     }     //take last date of start date's month, if end date is not passed     if (startDate.HasValue && !endDate.HasValue)     {         endDate = (new DateTime(startDate.Value.Year, startDate.Value.Month, 1)).AddMonths(1).AddDays(-1);     }     var expenses = expenseService.GetExpenses(startDate.Value ,endDate.Value);     //if request is Ajax will return partial view     if (Request.IsAjaxRequest())     {         return PartialView("ExpenseList", expenses);     }     //set start date and end date to ViewBag dictionary     ViewBag.StartDate = startDate.Value.ToShortDateString();     ViewBag.EndDate = endDate.Value.ToShortDateString();     //if request is not ajax     return View(expenses); } We are using the above Index Action method for both Ajax requests and normal requests. If there is a request for Ajax, we will call the PartialView ExpenseList. Razor Views for listing Expense information Let’s create view templates in Razor for showing list of Expense information ExpenseList.cshtml @model IEnumerable<MyFinance.Domain.Expense>   <table>         <tr>             <th>Actions</th>             <th>Category</th>             <th>                 Transaction             </th>             <th>                 Date             </th>             <th>                 Amount             </th>         </tr>       @foreach (var item in Model) {              <tr>             <td>                 @Html.ActionLink("Edit", "Edit",new { id = item.ExpenseId })                 @Ajax.ActionLink("Delete", "Delete", new { id = item.ExpenseId }, new AjaxOptions { Confirm = "Delete Expense?", HttpMethod = "Post", UpdateTargetId = "divExpenseList" })             </td>              <td>                 @item.Category.Name             </td>             <td>                 @item.Transaction             </td>             <td>                 @String.Format("{0:d}", item.Date)             </td>             <td>                 @String.Format("{0:F}", item.Amount)             </td>         </tr>          }       </table>     <p>         @Html.ActionLink("Create New Expense", "Create") |         @Html.ActionLink("Create New Category", "Create","Category")     </p> Index.cshtml @using MyFinance.Helpers; @model IEnumerable<MyFinance.Domain.Expense> @{     ViewBag.Title = "Index"; }    <h2>Expense List</h2>    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery-ui.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.ui.datepicker.js")" type="text/javascript"></script> <link href="@Url.Content("~/Content/jquery-ui-1.8.6.custom.css")" rel="stylesheet" type="text/css" />      @using (Ajax.BeginForm(new AjaxOptions{ UpdateTargetId="divExpenseList", HttpMethod="Get"})) {     <table>         <tr>         <td>         <div>           Start Date: @Html.TextBox("StartDate", Html.Encode(String.Format("{0:mm/dd/yyyy}", ViewData["StartDate"].ToString())), new { @class = "ui-datepicker" })         </div>         </td>         <td><div>            End Date: @Html.TextBox("EndDate", Html.Encode(String.Format("{0:mm/dd/yyyy}", ViewData["EndDate"].ToString())), new { @class = "ui-datepicker" })          </div></td>          <td> <input type="submit" value="Search By TransactionDate" /></td>         </tr>     </table>         }   <div id="divExpenseList">             @Html.Partial("ExpenseList", Model)     </div> <script type="text/javascript">     $().ready(function () {         $('.ui-datepicker').datepicker({             dateFormat: 'mm/dd/yy',             buttonImage: '@Url.Content("~/Content/calendar.gif")',             buttonImageOnly: true,             showOn: "button"         });     }); </script> Ajax search functionality using Ajax.BeginForm The search functionality of Index view is providing Ajax functionality using Ajax.BeginForm. The Ajax.BeginForm() method writes an opening <form> tag to the response. You can use this method in a using block. In that case, the method renders the closing </form> tag at the end of the using block and the form is submitted asynchronously by using JavaScript. The search functionality will call the Index Action method and this will return partial view ExpenseList for updating the search result. We want to update the response UI for the Ajax request onto divExpenseList element. So we have specified the UpdateTargetId as "divExpenseList" in the Ajax.BeginForm method. Add jQuery DatePicker Our search functionality is using a date range so we are providing two date pickers using jQuery datepicker. You need to add reference to the following JavaScript files to working with jQuery datepicker. jquery-ui.js jquery.ui.datepicker.js For theme support for datepicker, we can use a customized CSS class. In our example we have used a CSS file “jquery-ui-1.8.6.custom.css”. For more details about the datepicker component, visit jquery UI website at http://jqueryui.com/demos/datepicker . In the jQuery ready event, we have used following JavaScript function to initialize the UI element to show date picker. <script type="text/javascript">     $().ready(function () {         $('.ui-datepicker').datepicker({             dateFormat: 'mm/dd/yy',             buttonImage: '@Url.Content("~/Content/calendar.gif")',             buttonImageOnly: true,             showOn: "button"         });     }); </script>   Source Code You can download the source code from http://efmvc.codeplex.com/ . Summary In this two-part series, we have created a simple web application using ASP.NET MVC 3 RTM, Razor and EF Code First CTP 5. I have demonstrated patterns and practices  such as Dependency Injection, Repository pattern, Unit of Work, ViewModel and Service Layer. My primary objective was to demonstrate different practices and options for developing web apps using ASP.NET MVC 3 and EF Code First. You can implement these approaches in your own way for building web apps using ASP.NET MVC 3. I will refactor this demo app on later time.

    Read the article

  • S#arp Architecture 1.5 released

    - by AlecWhittington
    The past two weeks have been wonderful for me, spending 12 days on Oahu, Hawaii. Then followed up with the S#arp Architecture 1.5 release. It has been a short 4 months since taking over as the project lead and this is my first major milestone. With this release, we advance S# even more forward with the ASP.NET MVC 2 enhancements. What's is S#? Pronounced "Sharp Architecture," this is a solid architectural foundation for rapidly building maintainable web applications leveraging the ASP.NET MVC framework...(read more)

    Read the article

  • Spring 3.0 making JSON response using jackson message converter

    - by dupdup
    i configure my messageconverter as Jackson's then class Foo{int x; int y} and in controller @ResponseBody public Foo method(){ return new Foo(3,4) } from that i m expecting to return a JSON string {x:'3',y:'4'} from server without any other configuration. but getting 404 error response to my ajax request If the method is annotated with @ResponseBody, the return type is written to the response HTTP body. The return value will be converted to the declared method argument type using HttpMessageConverters. Am I wrong ? or should I convert my response Object to Json string myself using serializer and then returning that string as response.(I could make string responses correctly) or should I make some other configurations ? like adding annotations for class Foo here is my conf.xml <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jacksonMessageConverter"/> </list> </property>

    Read the article

  • ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes

    - by Rick Strahl
    So here's a binding behavior in ASP.NET MVC that I didn't really get until today: HtmlHelpers controls (like .TextBoxFor() etc.) don't bind to model values on Postback, but rather get their value directly out of the POST buffer from ModelState. Effectively it looks like you can't change the display value of a control via model value updates on a Postback operation. To demonstrate here's an example. I have a small section in a document where I display an editable email address: This is what the form displays on a GET operation and as expected I get the email value displayed in both the textbox and plain value display below, which reflects the value in the mode. I added a plain text value to demonstrate the model value compared to what's rendered in the textbox. The relevant markup is the email address which needs to be manipulated via the model in the Controller code. Here's the Razor markup: <div class="fieldcontainer"> <label> Email: &nbsp; <small>(username and <a href="http://gravatar.com">Gravatar</a> image)</small> </label> <div> @Html.TextBoxFor( mod=> mod.User.Email, new {type="email",@class="inputfield"}) @Model.User.Email </div> </div>   So, I have this form and the user can change their email address. On postback the Post controller code then asks the business layer whether the change is allowed. If it's not I want to reset the email address back to the old value which exists in the database and was previously store. The obvious thing to do would be to modify the model. Here's the Controller logic block that deals with that:// did user change email? if (!string.IsNullOrEmpty(oldEmail) && user.Email != oldEmail) { if (userBus.DoesEmailExist(user.Email)) { userBus.ValidationErrors.Add("New email address exists already. Please…"); user.Email = oldEmail; } else // allow email change but require verification by forcing a login user.IsVerified = false; }… model.user = user; return View(model); The logic is straight forward - if the new email address is not valid because it already exists I don't want to display the new email address the user entered, but rather the old one. To do this I change the value on the model which effectively does this:model.user.Email = oldEmail; return View(model); So when I press the Save button after entering in my new email address ([email protected]) here's what comes back in the rendered view: Notice that the textbox value and the raw displayed model value are different. The TextBox displays the POST value, the raw value displays the actual model value which are different. This means that MVC renders the textbox value from the POST data rather than from the view data when an Http POST is active. Now I don't know about you but this is not the behavior I expected - initially. This behavior effectively means that I cannot modify the contents of the textbox from the Controller code if using HtmlHelpers for binding. Updating the model for display purposes in a POST has in effect - no effect. (Apr. 25, 2012 - edited the post heavily based on comments and more experimentation) What should the behavior be? After getting quite a few comments on this post I quickly realized that the behavior I described above is actually the behavior you'd want in 99% of the binding scenarios. You do want to get the POST values back into your input controls at all times, so that the data displayed on a form for the user matches what they typed. So if an error occurs, the error doesn't mysteriously disappear getting replaced either with a default value or some value that you changed on the model on your own. Makes sense. Still it is a little non-obvious because the way you create the UI elements with MVC, it certainly looks like your are binding to the model value:@Html.TextBoxFor( mod=> mod.User.Email, new {type="email",@class="inputfield",required="required" }) and so unless one understands a little bit about how the model binder works this is easy to trip up. At least it was for me. Even though I'm telling the control which model value to bind to, that model value is only used initially on GET operations. After that ModelState/POST values provide the display value. Workarounds The default behavior should be fine for 99% of binding scenarios. But if you do need fix up values based on your model rather than the default POST values, there are a number of ways that you can work around this. Initially when I ran into this, I couldn't figure out how to set the value using code and so the simplest solution to me was simply to not use the MVC Html Helper for the specific control and explicitly bind the model via HTML markup and @Razor expression: <input type="text" name="User.Email" id="User_Email" value="@Model.User.Email" /> And this produces the right result. This is easy enough to create, but feels a little out of place when using the @Html helpers for everything else. As you can see by the difference in the name and id values, you also are forced to remember the naming conventions that MVC imposes in order for ModelBinding to work properly which is a pain to remember and set manually (name is the same as the property with . syntax, id replaces dots with underlines). Use the ModelState Some of my original confusion came because I didn't understand how the model binder works. The model binder basically maintains ModelState on a postback, which holds a value and binding errors for each of the Post back value submitted on the page that can be mapped to the model. In other words there's one ModelState entry for each bound property of the model. Each ModelState entry contains a value property that holds AttemptedValue and RawValue properties. The AttemptedValue is essentially the POST value retrieved from the form. The RawValue is the value that the model holds. When MVC binds controls like @Html.TextBoxFor() or @Html.TextBox(), it always binds values on a GET operation. On a POST operation however, it'll always used the AttemptedValue to display the control. MVC binds using the ModelState on a POST operation, not the model's value. So, if you want the behavior that I was expecting originally you can actually get it by clearing the ModelState in the controller code:ModelState.Clear(); This clears out all the captured ModelState values, and effectively binds to the model. Note this will produce very similar results - in fact if there are no binding errors you see exactly the same behavior as if binding from ModelState, because the model has been updated from the ModelState already and binding to the updated values most likely produces the same values you would get with POST back values. The big difference though is that any values that couldn't bind - like say putting a string into a numeric field - will now not display back the value the user typed, but the default field value or whatever you changed the model value to. This is the behavior I was actually expecting previously. But - clearing out all values might be a bit heavy handed. You might want to fix up one or two values in a model but rarely would you want the entire model to update from the model. So, you can also clear out individual values on an as needed basis:if (userBus.DoesEmailExist(user.Email)) { userBus.ValidationErrors.Add("New email address exists already. Please…"); user.Email = oldEmail; ModelState.Remove("User.Email"); } This allows you to remove a single value from the ModelState and effectively allows you to replace that value for display from the model. Why? While researching this I came across a post from Microsoft's Brad Wilson who describes the default binding behavior best in a forum post: The reason we use the posted value for editors rather than the model value is that the model may not be able to contain the value that the user typed. Imagine in your "int" editor the user had typed "dog". You want to display an error message which says "dog is not valid", and leave "dog" in the editor field. However, your model is an int: there's no way it can store "dog". So we keep the old value. If you don't want the old values in the editor, clear out the Model State. That's where the old value is stored and pulled from the HTML helpers. There you have it. It's not the most intuitive behavior, but in hindsight this behavior does make some sense even if at first glance it looks like you should be able to update values from the model. The solution of clearing ModelState works and is a reasonable one but you have to know about some of the innards of ModelState and how it actually works to figure that out.© Rick Strahl, West Wind Technologies, 2005-2012Posted in ASP.NET  MVC   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • How to work RavenDB Id with ASP.NET MVC Routes

    - by shiju
    By default RavenDB's Id would be sperated by "/". Let's say that we have a category object, the Ids would be like "categories/1". This will make problems when working with ASP.NET MVC's route rule. For a route category/edit/id, the uri would be category/edit/categories/1. You can solve this problem in two waysSolution 1 - Change Id SeparatorWe can use different Id Separator for RavenDB Ids in order to working with ASP.NET MVC route rules. The following code specify that Ids would be seperated by "-" rather than the default "/"  documentStore = new DocumentStore { Url = "http://localhost:8080/" };  documentStore.Initialize();  documentStore.Conventions.IdentityPartsSeparator = "-"; The above IdentityPartsSeparator would be generate Ids like "categories-1"Solution 2 - Modify ASP.NET MVC Route Modify the ASP.NET MVC routes in the Global.asax.cs file, as shown in the following code  routes.MapRoute(     "WithParam",                                           // Route name     "{controller}/{action}/{*id}"                         // URL with parameters     );  We just put "*" in front of the id variable that will be working with the default Id separator of RavenDB

    Read the article

  • Getting Started with ASP.NET MVC 3 and Razor

    - by dwahlin
    I had a chance to give a talk on ASP.NET MVC 3, Razor and jQuery today at a company and wanted to post the slides and demos from the talk. The focus was on getting started with ASP.NET MVC 3 projects and .cshtml files including creating pages using the new Razor syntax (which I personally love….never going back to the Web Forms View Engine) as well as working with jQuery. Topics covered in the demos (download below) include: Binding form data to custom object properties Validating a model using data annotations and IValidatableObject Integrating jQuery into MVC sites (using the DataTables plugin) Using the new WebGrid class to generate tables with sorting and paging functionality Integrating Silverlight applications into MVC sites Exposing JSON data from a controller action and consuming it in Silverlight Using the Ajax helper to add AJAX functionality (without jQuery)     The code and slides from the talk can be downloaded here.     If you or your company is interested in training, consulting or mentoring on jQuery or .NET technologies please visit http://www.thewahlingroup.com for more information. We’ve provided training, consulting and mentoring services to some of the largest companies in the world and would enjoy sharing our knowledge and real-world lessons learned with you.

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >