Search Results

Search found 9394 results on 376 pages for 'mvc scaffolding'.

Page 47/376 | < Previous Page | 43 44 45 46 47 48 49 50 51 52 53 54  | Next Page >

  • Creating an API for an ASP.NET MVC site with rate-limiting and caching

    - by Maxim Z.
    Recently, I've been very interested in APIs, specifically in how to create them. For the purpose of this question, let's say that I have created an ASP.NET MVC site that has some data on it; I want to create an API for this site. I have multiple questions about this: What type of API should I create? I know that REST and oData APIs are very popular. What are the pros and cons of each, and how do I implement them? From what I understand so far, REST APIs with ASP.NET MVC would just be actions that return JSON instead of Views, and oData APIs are documented here. How do I handle writing? Reading from both API types is quite simple. However, writing is more complex. With the REST approach, I understand that I can use HTTP POST, but how do I implement authentication? Also, with oData, how does writing work in the first place? How do I implement basic rate-limiting and caching? From my past experience with APIs, these are very important things, so that the API server isn't overloaded. What's the best way to set these two things up? Can I get some sample code? Any code that relates to C# and ASP.NET MVC would be appreciated. Thanks in advance! While this is a broad question, I think it's not too broad... :) There are some similar questions to this one that are about APIs, but I haven't found any that directly address the questions I outlined here.

    Read the article

  • How to use a Base ViewModel in Asp.net MVC 2

    - by Picflight
    As I familiarize myself with Asp.Net MVC, I am using MVC 2, I have noticed the use of a BaseViewData class in the Kigg project which I am unsure how to implement. I want each of my ViewModels to have certain values available. Using an iterface comes to mind but I am wondering what the best practice is and how does Kigg do it? Kigg public abstract class BaseViewData { public string SiteTitle { get; set; } // ...other properties } public class UserListViewData : BaseViewData { public string Title { get; set; } // .. other stuff } In my WebForms application I use a BasePage that inherits from System.Web.UI.Page. So, in my MVC project, I have this: public abstract class BaseViewModel { public int SiteId { get; set; } } public class UserViewModel : BaseViewModel { // Some arbitrary ViewModel } Referencing the Kigg methodology, how do I make sure that each of my ViewModel that inherits from the BaseViewModel have the SiteId property? What is the best practice, samples or patterns I should be using?

    Read the article

  • Best practices for deploying an MVC application on IIS7

    - by gsiler
    I'm not a web admin, and I'm new to IIS. So, I'm looking for advice. My MVC application (e.g. fooapp) is the default application for my site (e.g. foo.bar). I used IIS Manager to add the site to IIS7. When I import the application, IIS Manager wants to put it in it's own directory (/foo), and tells me I shouldn't put it in the base (site) directory. This means that to get to my default MVC view, I have to enter the URL http://foo.bar/fooapp/. Needless to say, I want to get there via http://foo.bar/ I see 2 possible solutions: Add a default page to the site directory that redirects to the MVC app. Ignore the IIS admonition and load the app into the site directory. My IIS7 knowledge is limited. I have played around with some options (such as HTTP Redirect). Since nothing changed, I obviously don't understand what I'm doing. Anyway, if there are some considered "best practices" and/or other suggestions, please let me know.

    Read the article

  • Java Mvc And Hibernate

    - by GigaPr
    Hi i am trying to learn Java, Hibernate and the MVC pattern. Following various tutorial online i managed to map my database, i have created few Main methods to test it and it works. Furthermore i have created few pages using the MVC patter and i am able to display some mock data as well in a view. the problem is i can not connect the two. this is what i have My view Looks like this <%@ include file="/WEB-INF/jsp/include.jsp" %> <html> <head> <title>Users</title> <%@ include file="/WEB-INF/jsp/head.jsp" %> </head> <body> <%@ include file="/WEB-INF/jsp/header.jsp" %> <img src="images/rss.png" alt="Rss Feed"/> <%@ include file="/WEB-INF/jsp/menu.jsp" %> <div class="ContainerIntroText"> <img src="images/usersList.png" class="marginL150px" alt="Add New User"/> <br/> <br/> <div class="usersList"> <div class="listHeaders"> <div class="headerBox"> <strong>FirstName</strong> </div> <div class="headerBox"> <strong>LastName</strong> </div> <div class="headerBox"> <strong>Username</strong> </div> <div class="headerAction"> <strong>Edit</strong> </div> <div class="headerAction"> <strong>Delete</strong> </div> </div> <br><br> <c:forEach items="${users}" var="user"> <div class="listElement"> <c:out value="${user.firstName}"/> </div> <div class="listElement"> <c:out value="${user.lastName}"/> </div> <div class="listElement"> <c:out value="${user.username}"/> </div> <div class="listElementAction"> <input type="button" name="Edit" title="Edit" value="Edit"/> </div> <div class="listElementAction"> <input type="image" src="images/delete.png" name="image" alt="Delete" > </div> <br /> </c:forEach> </div> </div> <a id="addUser" href="addUser.htm" title="Click to add a new user">&nbsp;</a> </body> </html> My controller public class UsersController implements Controller { private UserServiceImplementation userServiceImplementation; public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ModelAndView modelAndView = new ModelAndView("users"); List<User> users = this.userServiceImplementation.get(); modelAndView.addObject("users", users); return modelAndView; } public UserServiceImplementation getUserServiceImplementation() { return userServiceImplementation; } public void setUserServiceImplementation(UserServiceImplementation userServiceImplementation) { this.userServiceImplementation = userServiceImplementation; } } My servelet definitions <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- the application context definition for the springapp DispatcherServlet --> <bean name="/home.htm" class="com.rssFeed.mvc.HomeController"/> <bean name="/rssFeeds.htm" class="com.rssFeed.mvc.RssFeedsController"/> <bean name="/addUser.htm" class="com.rssFeed.mvc.AddUserController"/> <bean name="/users.htm" class="com.rssFeed.mvc.UsersController"> <property name="userServiceImplementation" ref="userServiceImplementation"/> </bean> <bean id="userServiceImplementation" class="com.rssFeed.ServiceImplementation.UserServiceImplementation"> <property name="users"> <list> <ref bean="user1"/> <ref bean="user2"/> </list> </property> </bean> <bean id="user1" class="com.rssFeed.domain.User"> <property name="firstName" value="firstName1"/> <property name="lastName" value="lastName1"/> <property name="username" value="username1"/> <property name="password" value="password1"/> </bean> <bean id="user2" class="com.rssFeed.domain.User"> <property name="firstName" value="firstName2"/> <property name="lastName" value="lastName2"/> <property name="username" value="username2"/> <property name="password" value="password2"/> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> and finally this class to access the database public class HibernateUserDao extends HibernateDaoSupport implements UserDao { public void addUser(User user) { getHibernateTemplate().saveOrUpdate(user); } public List<User> get() { User user1 = new User(); user1.setFirstName("FirstName"); user1.setLastName("LastName"); user1.setUsername("Username"); user1.setPassword("Password"); List<User> users = new LinkedList<User>(); users.add(user1); return users; } public User get(int id) { throw new UnsupportedOperationException("Not supported yet."); } public User get(String username) { return null; } } the database connection occurs in this file <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:hsql://localhost/rss"/> <property name="username" value="sa"/> <property name="password" value=""/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" > <property name="dataSource" ref="dataSource" /> <property name="mappingResources"> <list> <value>com/rssFeed/domain/User.hbm.xml</value> </list> </property> <property name="hibernateProperties" > <props> <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="userDao" class="com.rssFeed.dao.hibernate.HibernateUserDao"> <property name="sessionFactory" ref="sessionFactory"/> </bean> </beans> Could you help me to solve this problem i spent the last 4 days and nights on this issue without any success Thanks

    Read the article

  • How should I organize my mvc templates?

    - by CatZ
    Hi, In the new version of MVC we have been given display and editor templates. I was wondering how to make the best possible use of these. I was at first thinking in the line of creating one for a collection and one for an item in the case I want to display either as a list or single but it does not really make sense to me. I'll show you what I mean and please comment if this is wrong. I have trouble figuring it out myself. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<DisplayPhoneModel>>" %> <% foreach (var item in Model){%> <%= Html.DisplayFor(x => item) %> <%}%> So in my tiny reality that would for every item in the model search for a display template for DisplayPhoneModel. That display template could then simply look like. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DisplayPhoneModel>" %> <%= Html.LabelFor(x => x.PhoneType) %>&nbsp;<%= Html.LabelFor(x => x.PhoneNumber) %> So, question is if there is a better way to handle this? Am I at all on the right path?

    Read the article

  • ASP.NET MVC (VB) error when publishing to test server

    - by Colin
    I have an ASP.NET MVC project that works fine on my local machine (no build errors, server errors or anything). However, when I publish the project to a test server, I get an "Object reference not set to an instance of an object" error on a For Each I have in my view. I have a function within a model that returns a DataRowCollection. I'm calling that function in my controller and passing the DataRowCollection to my View, which then iterates over the rows and displays the necessary information: In the Controller I have: Function Index() As ActionResult Dim MyModel As New Model ViewData("MyDataRowCollection") = MyModel.GetDataRowCollection() Return View() End Function And then in the View, which is throwing the error: <%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server"> My Page Title </asp:Content> <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server"> <% For Each MyDataRow In ViewData("MyDataRowCollection") ' do stuff with each MyDataRow Next %> I'm pretty new to ASP.NET MVC so I'm sure there might be a better way to do what I'm doing (I'd be happy to hear if there is), but my main concern is why this works fine on my local machine but throws an error on the For Each on the test server? Please let me know if I can clarify any of the above, and thanks in advance for any information.

    Read the article

  • Custom View Engine in ASP.NET MVC 2 does not work with Areas

    - by mare
    I used the code below so far with ASP.NET MVC v1 and v2 but when I added an Area today to my application, the controller for the area couldn't find any views in my Areas/Views/controllerView folder. It issued the very well known exception that it searched those 4 standard folders but it did not look under Areas.. How can I change the code so that it will work with Areas? Maybe an example of custom view engine under ASP.NET MVC 2 with Areas support? The information about it on the net is very scarse.. Here's the code: public class PendingViewEngine : VirtualPathProviderViewEngine { public PendingViewEngine() { // This is where we tell MVC where to look for our files. /* {0} = view name or master page name * {1} = controller name */ MasterLocationFormats = new[] {"~/Views/Shared/{0}.master", "~/Views/{0}.master"}; ViewLocationFormats = new[] { "~/Views/{1}/{0}.aspx", "~/Views/Shared/{0}.aspx", "~/Views/Shared/{0}.ascx", "~/Views/{1}/{0}.ascx" }; PartialViewLocationFormats = new[] {"~/Views/{1}/{0}.ascx", "~/Views/Shared/{0}.ascx"}; } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { return new WebFormView(partialPath, ""); } protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { return new WebFormView(viewPath, masterPath); } }

    Read the article

  • ASP.Net MVC and Windows 7 404 error

    - by Paul Rivers
    O.K. Stupid question..... I sepnt nearly a day getting an MVC site working, and then I published it. After that, the hell began. I'm using Windows 7, Visual Studio 2008 and MVC. I published it and first the Default.aspx wouldn't come up. I gave up on playing with that for a few and just did the easy thing a typed in default.aspx. I'll fix that problem later. So, I clicked on one of my navigation buttons which prior to this worked just fine in the internal development IIS, and I get a 404 error. I spent two days surfing the Microsoft support forums and every other support forum I can find. No fix. So, I tried something a little different. Just to see if I screwed up. I created a new TestMVC application. Set the output to a website on the local IIS. Compiled and after typing in the default.aspx (it was set as the startup file in the project) I then clicked on the About button on the base MVC application. And what do I get? 404. I know this is new, folks, but this is crazy. What is it about this process that would take this much effort to get it right, especially since it works on the test server.

    Read the article

  • Converting to MVC3 - some views still want 'System.Web.Mvc, Version=1.0.0.0,

    - by justSteve
    I've used the directions from the release notes and have been able to navigate most pages - my unit tests are not comprehensive but most all pass. However...when I attempt to edit an existing or create a new user I'm getting the error pasted below - notice that it's references version=1... - this project started life as a v1 and was converted to mvc2 at the RTM. I'm still working with V2 projects but no longer any v1. Am i due for a GAC cleansing? Server Error in '/' Application. Could not load file or assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. === Pre-bind state information === LOG: User = STUDIO11\mUser LOG: DisplayName = System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 (Fully-specified) LOG: Appbase = file:///C:/Users/C:\Users\[path to project]/ LOG: Initial PrivatePath = C:\Users\[path to project]\bin Calling assembly : App_Web_qcjylaoc, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null. === LOG: This bind starts in default load context. LOG: Using application configuration file: C:\Users\[path to project]\web.config LOG: Using host configuration file: LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config. LOG: Post-policy reference: System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 LOG: The same bind was seen before, and was failed with hr = 0x80070002.

    Read the article

  • Is there a point to have multiple VS projects for an ASP.NET MVC application?

    - by mare
    I'm developing MVC application where I currently have 3 projects in solution. Core (it is supposed to be for Repositories, Business Classes, Models, HttpModules, HttpFilters, Settings, etc.) Data access (Data provider, for instance SqlDataProvider for working with SQL Server datastore - implements Repository interfaces, XmlDataProvider - also implements Repository interfaces but for local XML files as datastore) ASP.NET MVC project (all the typical stuff, UI, controllers, content, scripts, resources and helpers). I have no Models in my ASP.NET MVC project. I've just run into a problem because of that coz I want to use the new DataAnnotation feature in MVC 2 on my Bussiness class, which are, as said in Core, however I have I want to be able to localize the error messages. This where my problem starts. I cannot use my Resources from MVC project in Core. The MVC project references Core and it cannot be vice-versa. My options as I see them are: 1) Move Resources out but this would require correcting a whole bunch of Views and Controllers where I reference them, 2) Make a complete restructure of my app What are your thoughts on this? Also, Should I just move everything business related into Models folder in MVC project?? Does it even make any sense to have it structured like that, because we can just make subfolders for everything under MVC project? The whole Core library is not intended to ever be used for anything else, so there actually no point of compiling it to a separate DLL. Suggestions appreciated.

    Read the article

  • Setup asp.net mvc application as subdomain website

    - by a_m0d
    I'm trying to setup a local application on a subdomain on our company server. There is already an installation of sharepoint running on http://companyweb/, but I would like my application to run on http://orders.companyweb/. I tried creating a new website, leaving the IP address the same as it is for http://companyweb, and just changing the host header value to orders.companyweb. However, no matter where I try to access the site from (different computers around the network, including the server itself), I keep getting 404 errors. I then tried setting up a simple index.html and serving that up as the highest priority; however, I still got 404 errors. This makes me think that I have actually setup the site itself wrong. What should I change to be able to access this application correctly on all the local computers?

    Read the article

  • ASP.NET MVC multi-instance session management on amazon ec2

    - by gandil
    I have a web application written in asp.net mvc2. Currently hosted on amazon cloud ec2. Because of growing traffic we want move multi instance enviorenment. I have a custom session class which currently initiate at session start (global asax) and i am using via getter or setter class in application. Because of multi instance chore i have to handle hole security architecture. I am looking a better way to handle this problem. I am looking for good implementation of session and how to apply on amazon ec2 multi instance environment. What is road blocks for system architecture?

    Read the article

  • Extract Distinct restful MVC routes from IIS logs

    - by Grummle
    This is a cross post from StackOverflow that after some consideration I believe can be asked here (not getting anything on SO). My shop is using MVC3/FUBU on IIS 7. I recently put something into production and I wanted to gather metrics from the IIS logs using log parser. I've done this many times before with file endpoints but because the MVC3 routes are of the form /api/person/{personid}/address/{addressid} the log saves /api/person/123/address/456 in the uristem column. Does anyone have any ideas on how to get data about specific routes from IIS logs? As an exmaple: Log Like this: cs-uri-stem /api/person/123/address/456 /api/person/121/address/33 /api/person/3555 /api/person/1555/address/5555 I want information about all where the route used was /api/person/{personid} so the count would be 1 in this case. Ideally what I'd like to figure out is how to do is is have IIS log the regex for the route that is choose for a particular url. So in the IIS logs have /api/person/{personid}/address/{addressid} in a column in addition to the cs-uristem /api/person/1555/address/5555

    Read the article

  • MVC 2 with IIS 6 Problems

    - by SlackerCoder
    Hey guys, I'm using IIS 6 on a Windows 2003 Server and I am trying to get an MVC2 project installed on that machine. I am having nightmare-ish problems doing so! I've looked up TONS of references on what to do, and not 1 single one works. (They work for MVC1 projects, as I have a few of those running already using said solutions). Does anyone have any tips/hints/ideas on what needs to be done for MVC2 projects with IIS 6? I am definitely pulling my hair out over this. I have tried it on 2 of my dev servers, and both get the same result. The closest I can get to a served page is an error page "Object reference not set to an instance of an object", however, the page has try/catch blocks that are being ignored, so I dont think its running the code on the controller, I think it's saying that the controller is the error. (For the reference, the error in question is directed at the HomeController.cs file). What I've tried: Wildcard mapping Changing routes to {controller}.mvc Changing routes to {controller}.aspx Adding the .mvc extension to IIS Modifying routes in Global.asax There's a LOT of code in this project so far, so I will only post the first page(s) that should get served: MASTER PAGE: <div class="page"> <div id="header"> <div id="title"> <h1>Meritain RedCard Interface 2.0</h1> </div> <!-- This is the main menu. Each security role will have access to certain buttons. --> <div id="menucontainer"> <% if (Session["UserData"] != null) { %> <% if (/*User Security Checks Out*/) { %> <ul id="menu"> <li><%= Html.ActionLink("Home", "Index", "Home")%></li> <li><%= Html.ActionLink("Selection", "Index", "Select", new { area = "Selector" }, null)%></li> <li><%= Html.ActionLink("Audit", "Index", "Audit", new { area = "Auditor" }, null)%></li> <li><%= Html.ActionLink("Setup", "Index", "Setup", new { area = "Setup" }, null)%></li> <li><%= Html.ActionLink("About", "About", "Home")%></li> </ul> <% } %> <% } %> </div> </div> <div id="main"> <asp:ContentPlaceHolder ID="MainContent" runat="server" /> <div id="footer"> </div> </div> </div> Default.aspx.cs: [I added this file as a potential solution, since it works with MVC 1] protected void Page_Load(object sender, EventArgs e) { string originalPath = Request.Path; HttpContext.Current.RewritePath(Request.ApplicationPath, false); IHttpHandler httpHandler = new MvcHttpHandler(); httpHandler.ProcessRequest(HttpContext.Current); HttpContext.Current.RewritePath(originalPath, false); } HomeController.cs: public ActionResult Index() { loadApplication(); ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(); } public ActionResult About() { return View(); } private void loadApplication() { Session["UserData"] = CreateUserSecurity(HttpContext.User.Identity.Name.ToString()); } I did not list the CreateUserSecurity method, but all it does it call the DB using the Username and returns the record in the database that matches the username. EDIT: Added code and what I've tried so far (as requested).

    Read the article

  • MVC Page not showing up, 404 not found

    - by mwright
    I have a very simple MVC site that is returning a 404 not found error when trying to load a page at the very beginning. I'm looking for some direction to troubleshoot this problem since there is really nothing to go on from the error message. The error I'm getting is: Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. Requested URL: /Views/Other/Index.aspx Below I have included the code for the various pieces, routing rules are default: routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults ); The site is using nested MasterPages, not sure if this is involved with the problem but trying to include as much detail as possible. I have: Controllers OtherController Views: Shared Folder: Site.Master Other Folder: Other.Master Index.aspx Site.Master Code: <%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title> <asp:ContentPlaceHolder ID="TitleContent" runat="server" /> </title> </head> <body> <div> <asp:ContentPlaceHolder ID="MainContent" runat="server"> </asp:ContentPlaceHolder> </div> </body> </html> Other.Master Code: <%@ Master Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewMasterPage" %> <asp:Content ID="OtherTitle" ContentPlaceHolderID="TitleContent" runat="server"> OTHER PAGE - MASTER TITLE <asp:ContentPlaceHolder ID="OtherPageTitle" runat="server"> </asp:ContentPlaceHolder> </asp:Content> <asp:Content ID="OtherContent" ContentPlaceHolderID="MainContent" runat="server"> Some other content. <asp:ContentPlaceHolder ID="PageContent" runat="server"> </asp:ContentPlaceHolder> </asp:Content> Index.aspx Code: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Other/Other.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="IndexTitle" ContentPlaceHolderID="OtherTitle" runat="server"> Home </asp:Content> <asp:Content ID="IndexContent" ContentPlaceHolderID="OtherContent" runat="server"> Index content </asp:Content> OtherController Code namespace MVCProject.Controllers { public class OtherController : Controller { // // GET: /Member/ public ActionResult Index() { // Have also tried: // return View("Index", "Other.Master"); return View(); } } }

    Read the article

  • MVC using ODP.NET getting ORA-01840

    - by sse
    I am writing a simple MVC Application using ODP.NET. I am trying to call a Pl/Sql proc that inserts a record. Here is the simple Pl/Sql: procedure spAddCountry(pGisRecid in country.GISRECID%type, pCountryCode in country.COUNTRYCODE%type, pCountryName in country.COUNTRYNAME%type, pCurrencyCode in country.CURRENCYCODE%type, pEUTerritory in country.EUTERRITORY%type, pFatCAStatus in country.FATCASTATUS%type, pFATF in country.FATF%type, pFSCountryCode in country.COUNTRYCODE%type, pInsertedBy in country.INSERTEDBY%type, pInsertedOn in country.INSERTEDON%type, pLanguages in country.LANGUAGES%type, pNCCT in country.NCCT%type) is PRAGMA AUTONOMOUS_TRANSACTION; begin INSERT INTO COUNTRY (GISRECID, COUNTRYCODE, COUNTRYNAME, CURRENCYCODE, EUTERRITORY, FATCASTATUS, FATF, FSCOUNTRYCODE, INSERTEDBY, INSERTEDON, LANGUAGES, NCCT) VALUES(pGISRECID, pCOUNTRYCODE, pCOUNTRYNAME, pCURRENCYCODE, pEUTERRITORY, pFATCASTATUS, pFATF, pFSCOUNTRYCODE, pINSERTEDBY, pINSERTEDON, pLANGUAGES, pNCCT); Commit; end; I am having difficulty passing the date parameter, pInsertedOn, to the Stored Proc. I have verified that the web form retrieves the form data successfully and calls the AddCountry method below, which in turns calls the stored proc, spAddCountry, after populating all of the parms. Here is a snippet of the MVC C# code. I get the following exception: "ORA-01840 input value not long enough for date format". public void AddCountry(Country aCountry) //because the country object field names match the form field names they automatically get bound!! { string oradb = "Data Source=XYZ;User Id=XYZ;Password=xyz;"; OracleConnection conn = new OracleConnection(oradb); OracleCommand cmd = conn.CreateCommand(); cmd.CommandText = "tstpack.spAddCountry"; cmd.CommandType = CommandType.StoredProcedure; ... OracleParameter paramInsertedBy = new OracleParameter(); paramInsertedBy.ParameterName = "pInsertedBy"; paramInsertedBy.Value = aCountry.InsertedBy; cmd.Parameters.Add(paramInsertedBy); // CultureInfo ci = new CultureInfo("en-US"); OracleParameter paramInsertedOn = new OracleParameter(); paramInsertedOn.ParameterName = "pInsertedOn"; // paramInsertedOn.Value = DateTime.Now; //just testing to see if it's WebForm issue // paramInsertedOn.Value = Convert.ToDateTime(DateTime.Now.ToString(), ci); //flail! paramInsertedOn.Value = aCountry.InsertedOn; cmd.Parameters.Add(paramInsertedOn); ... conn.Open(); cmd.ExecuteNonQuery(); //CRASH! ORA-01840 conn.Close(); } Just to verify that the flow of the program is working, I tried removing the date parm "pInsertedOn" from the pl/sql and from the parm list above, and everything worked fine. I know I am going off of the rails with the date. Can someone tell me how to pass a date to Oracle from an MVC WebForm? Is there some sort of type cast needed? I would really appreciate an example too. Thanks so much! ps, I did try changing the parm type to Varchar2 in the Pl/Sql and doing some conversions myself in the Pl/Sql, the automatic MVC binder was getting in my way, forcing the property of paramInsertedOn.OracleType to DateTime. I tried forcing it to Varchar2, but no luck there either...

    Read the article

  • Why you shouldn't add methods to interfaces in APIs

    - by Simon Cooper
    It is an oft-repeated maxim that you shouldn't add methods to a publically-released interface in an API. Recently, I was hit hard when this wasn't followed. As part of the work on ApplicationMetrics, I've been implementing auto-reporting of MVC action methods; whenever an action was called on a controller, ApplicationMetrics would automatically report it without the developer needing to add manual ReportEvent calls. Fortunately, MVC provides easy hook when a controller is created, letting me log when it happens - the IControllerFactory interface. Now, the dll we provide to instrument an MVC webapp has to be compiled against .NET 3.5 and MVC 1, as the lowest common denominator. This MVC 1 dll will still work when used in an MVC 2, 3 or 4 webapp because all MVC 2+ webapps have a binding redirect redirecting all references to previous versions of System.Web.Mvc to the correct version, and type forwards taking care of any moved types in the new assemblies. Or at least, it should. IControllerFactory In MVC 1 and 2, IControllerFactory was defined as follows: public interface IControllerFactory { IController CreateController(RequestContext requestContext, string controllerName); void ReleaseController(IController controller); } So, to implement the logging controller factory, we simply wrap the existing controller factory: internal sealed class LoggingControllerFactory : IControllerFactory { private readonly IControllerFactory m_CurrentController; public LoggingControllerFactory(IControllerFactory currentController) { m_CurrentController = currentController; } public IController CreateController( RequestContext requestContext, string controllerName) { // log the controller being used FeatureSessionData.ReportEvent("Controller used:", controllerName); return m_CurrentController.CreateController(requestContext, controllerName); } public void ReleaseController(IController controller) { m_CurrentController.ReleaseController(controller); } } Easy. This works as expected in MVC 1 and 2. However, in MVC 3 this type was throwing a TypeLoadException, saying a method wasn't implemented. It turns out that, in MVC 3, the definition of IControllerFactory was changed to this: public interface IControllerFactory { IController CreateController(RequestContext requestContext, string controllerName); SessionStateBehavior GetControllerSessionBehavior( RequestContext requestContext, string controllerName); void ReleaseController(IController controller); } There's a new method in the interface. So when our MVC 1 dll was redirected to reference System.Web.Mvc v3, LoggingControllerFactory tried to implement version 3 of IControllerFactory, was missing the GetControllerSessionBehaviour method, and so couldn't be loaded by the CLR. Implementing the new method Fortunately, there was a workaround. Because interface methods are normally implemented implicitly in the CLR, if we simply declare a virtual method matching the signature of the new method in MVC 3, then it will be ignored in MVC 1 and 2 and implement the extra method in MVC 3: internal sealed class LoggingControllerFactory : IControllerFactory { ... public virtual SessionStateBehaviour GetControllerSessionBehaviour( RequestContext requestContext, string controllerName) {} ... } However, this also has problems - the SessionStateBehaviour type only exists in .NET 4, and we're limited to .NET 3.5 by support for MVC 1 and 2. This means that the only solutions to support all MVC versions are: Construct the LoggingControllerFactory type at runtime using reflection Produce entirely separate dlls for MVC 1&2 and MVC 3. Ugh. And all because of that blasted extra method! Another solution? Fortunately, in this case, there is a third option - System.Web.Mvc also provides a DefaultControllerFactory type that can provide the implementation of GetControllerSessionBehaviour for us in MVC 3, while still allowing us to override CreateController and ReleaseController. However, this does mean that LoggingControllerFactory won't be able to wrap any calls to GetControllerSessionBehaviour. This is an acceptable bug, given the other options, as very few developers will be overriding GetControllerSessionBehaviour in their own custom controller factory. So, if you're providing an interface as part of an API, then please please please don't add methods to it. Especially if you don't provide a 'default' implementing type. Any code compiled against the previous version that can't be updated will have some very tough decisions to make to support both versions.

    Read the article

  • Mocking HttpContext in .NET MVC2 using Moq

    - by Richard
    Hi, This was working in MVC 1, but has broken in MVC 2. I'm mocking the HttpContext so I can test routes. The code was originally taken from Steven Sanderson's book. I've tried mocking some extra properties as suggested in this comment but it hasn't fixed it. What am I missing? This is the start of my test code. routeData is null when this code completes. // Arange RouteCollection routeConfig = new RouteCollection(); MvcApplication.RegisterRoutes(routeConfig); var mockHttpContext = makeMockHttpContext(url); // Act RouteData routeData = routeConfig.GetRouteData(mockHttpContext.Object); This method creates my mock HttpContext: private static Mock<HttpContextBase> makeMockHttpContext(String url) { var mockHttpContext = new Mock<System.Web.HttpContextBase>(); // Mock the request var mockRequest = new Mock<HttpRequestBase>(); mockHttpContext.Setup(t => t.Request).Returns(mockRequest.Object); mockRequest.Setup(t => t.AppRelativeCurrentExecutionFilePath).Returns(url); // Tried adding these to fix in MVC2 (didn't work) mockRequest.Setup(r => r.HttpMethod).Returns("GET"); mockRequest.Setup(r => r.Headers).Returns(new NameValueCollection()); mockRequest.Setup(r => r.Form).Returns(new NameValueCollection()); mockRequest.Setup(r => r.QueryString).Returns(new NameValueCollection()); mockRequest.Setup(r => r.Files).Returns(new Mock<HttpFileCollectionBase>().Object); // Mock the response var mockResponse = new Mock<HttpResponseBase>(); mockHttpContext.Setup(t => t.Response).Returns(mockResponse.Object); mockResponse.Setup(t => t.ApplyAppPathModifier(It.IsAny<String>())).Returns<String>(t => t); return mockHttpContext; }

    Read the article

  • Legacy URL rewriting with query string parameters

    - by John Kaster
    I've looked at http://stackoverflow.com/questions/817325/asp-net-mvc-routing-legacy-urls-passing-querystring-ids-to-controller-actions and several other similar posts for legacy URL routing, but I can't get past the error "The RouteData must contain an item named 'controller' with a non-empty string value." Looking this up on line didn't give me any hints to solve my problem. I've implemented the Legacy routing class described in the link above, and this is what I've defined in the routing table: routes.Add( "Legacy", new LegacyRoute("fooref.aspx", "FooRef", new LegacyRouteHandler()) ); routes.MapRoute( "FooRef", "{controller}/{action}", new { controller = "Home", action = "Index", foo_id = UrlParameter.Optional, bar_id = UrlParameter.Optional } ); When I use Phil Haack's route debugger, it indicates that fooref.aspx has a match, but when I turn the route debugger off, I get the error above. If I reverse the statement order, I get "Resource not found" for /ctprefer.aspx, which makes sense -- so it appears to be finding that as a valid route when put in the other order. Where do I need to declare this missing controller reference? Have routing requirements changed for ASP.NET MVC 2 RTM?

    Read the article

  • Validation Summary for Collections

    - by Myster
    Hi All, EDIT: upgraded this question to MVC 2.0 With asp.net MVC 2.0 is there an existing method of creating Validation Summary that makes sense for models containing collections? If not I can create my own validation summary Example Model: public class GroupDetailsViewModel { public string GroupName { get; set; } public int NumberOfPeople { get; set; } public List<Person> People{ get; set; } } public class Person { [Required(ErrorMessage = "Please enter your Email Address")] [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid Email Address")] public string EmailAddress { get; set; } [Required(ErrorMessage = "Please enter your Phone Number")] public string Phone { get; set; } [Required(ErrorMessage = "Please enter your First Name")] public string FirstName { get; set; } [Required(ErrorMessage = "Please enter your Last Name")] public string LastName { get; set; } } The existing summary <%=Html.ValidationSummary %> if nothing is entered looks like this. The following error(s) must be corrected before proceeding to the next step * Please enter your Email Address * Please enter your Phone Number * Please enter your First Name * Please enter your Last Name * Please enter your Email Address * Please enter your Phone Number * Please enter your First Name * Please enter your Last Name The design calls for headings to be inserted like this: The following error(s) must be corrected before proceeding to the next step Person 1 * Please enter your Email Address * Please enter your Phone Number * Please enter your First Name * Please enter your Last Name Person 2 * Please enter your Email Address * Please enter your Phone Number * Please enter your First Name * Please enter your Last Name

    Read the article

  • Host WCF in MVC2 Site

    - by Basiclife
    Hi, We've got a very large, complex MVC2 website. We want to add an API for some internal tools and decided to use WCF. Ideally, we want MVC itself to host the WCF service. Reasons include: Although there's multiple tiers to the application, some functionality we'd like in the API requires the website itself (e.g. formatting emails). We use TFS to auto-build (continuous integration) and deploy - The less we need to modify the build and release mechanism the better We use the Unity container and Inversion of Control throughout the application. Being part of the Website would allow us to re-use configuration classes and other helper methods. I've written a custom ServiceBehavior which in turn has a custom InstanceProvider - This allows me to instantiate and configure a container which is then used to service all requests for class instances from WCF. So my question is; Is it possible to host a WCF service from within MVC itself? I've only had experience in Services / Standard Asp.Net websites before and didn't realise MVC2 might be different until I actually tried to wire it into the config and nothing happened. After some googling, there don't seem to be many references to doing this - so thought I'd ask here.

    Read the article

  • jQuery Ajax call for buttons on a list

    - by lloydphillips
    I have a list of data that i have in a view from an asp.net mvc application. It's a list of stock and I have two images (a plus and a minus) on the end of each row which will allow me to increase or decrease stock quantity. It works fine at present with a call to the mvc action but since the list is long I want to use jQuery and AJAX to have the call go without a refresh. I want to do this with unobtrusive javascript so don't want onclick handlers on my images. Since I'm just starting out with jQuery I have no idea how I can iterate all the images and add the function. Here are the images with the form tags as they stand: <td> <% using (Html.BeginForm("Increase", "Stock", new { Id = item.StockId })) {%> <input type="image" src="/Content/Images/bullet_add.png" style="margin-left:20px;" /> <% } %> </td> <td><% using (Html.BeginForm("Decrease", "Stock", new { Id = item.StockId })) {%> <input type="image" src="/Content/Images/bullet_delete.png" style="margin-left:10px;" /><% } %> </td> Can anyone help me out a little? Many thanks. Lloyd

    Read the article

  • How to safely use PayPal IPN with Asp.Net MVC

    - by Picflight
    Here are two sources for PayPal IPN: Kona.Web IPN DotNetNuke IPN DNN has a loop in the beginning of the Page_Load method that captures txn_type and txn_id, which I don't see in the Kona code. DNN also captures payer email and other information into local variables. I am trying to make sure that I incorporate some of the security checks that I see in DNN into my MVC IPN. How do I do what DNN is doing with MVC 2 with Kona as the base? Is the Kona.Web IPN safe for production, does it need some more tweaking?

    Read the article

  • ASP.NET MVC Html.ActionLink Maintains Route Values

    - by Carl
    Hi, I have a question that has pretty much been asked here: http://stackoverflow.com/questions/780643/asp-net-mvc-html-actionlink-keeping-route-value-i-dont-want However, the final solution is a kludge, pure and simple and I really would like to understand why this happens, if someone can please explain it to me? For completeness, it is possible to recreate the scenario very easily: Create a new MVC web app. Run it up. Visit the About tab Modify the URL to read /Home/About/Flib - This obviously takes you to the action with an id of 'Flib' which we don't care about. Notice that the top menu link to About now actually links to /Home/About/Flib - this is wrong as far as I can see, as I now have absolutely no way of using site links to get back to /Home/About I really don't understand why I should be forced to modify all of my Html.ActionLinks to include new { id = string.Empty } for the routevalues and null for the htmlAttribs. This seems especially out of whack because I already specify id = 0 as part of the route itself. Hopefully I'm missing a trick here.

    Read the article

  • ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

    - by tyndall
    What is the correct way to find the absolute path to the App_Data folder from a Controller in an ASP.NET MVC project? I'd like to be able to temporarily work with an .xml file and I don't want to hardcode the path. This does not work: [HandleError] public class HomeController : Controller { public ActionResult Index() { string path = VirtualPathUtility.ToAbsolute("~/App_Data/somedata.xml"); //.... do whatever return View(); } } I think outside of the web context VirtualPathUtility.ToAbsolute() doesn't work. string path comes back as "C:\App_Data\somedata.xml" Where should I determine the path of the .xml file in an MVC app? global.asax and stick it an application-level variable?

    Read the article

< Previous Page | 43 44 45 46 47 48 49 50 51 52 53 54  | Next Page >