Search Results

Search found 53991 results on 2160 pages for 'asp net'.

Page 28/2160 | < Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >

  • MVC 2: Html.TextBoxFor, etc. in VB.NET 2010

    - by Brian
    Hello, I have this sample ASP.NET MVC 2.0 view in C#, bound to a strongly typed model that has a first name, last name, and email: <div> First: <%= Html.TextBoxFor(i => i.FirstName) %> <%= Html.ValidationMessageFor(i => i.FirstName, "*") %> </div> <div> Last: <%= Html.TextBoxFor(i => i.LastName) %> <%= Html.ValidationMessageFor(i => i.LastName, "*")%> </div> <div> Email: <%= Html.TextBoxFor(i => i.Email) %> <%= Html.ValidationMessageFor(i => i.Email, "*")%> </div> I converted it to VB.NET, seeing the appropriate constructs in VB.NET 10, as: <div> First: <%= Html.TextBoxFor(Function(i) i.FirstName) %> <%= Html.ValidationMessageFor(Function(i) i.FirstName, "*") %> </div> <div> Last: <%= Html.TextBoxFor(Function(i) i.LastName)%> <%= Html.ValidationMessageFor(Function(i) i.LastName, "*")%> </div> <div> Email: <%= Html.TextBoxFor(Function(i) i.Email)%> <%= Html.ValidationMessageFor(Function(i) i.Email, "*")%> </div> No luck. Is this right, and if not, what syntax do I need to use? Again, I'm using ASP.NET MVC 2.0, this is a view bound to a strongly typed model... does MVC 2 still not support the new language constructs in .NET 2010? Thanks.

    Read the article

  • ASP.NET Membership with two providers cant use GetAllUsers method

    - by Bayonian
    Hi, I'm using two membership providers. When I declared a following statement Dim allUsers As MembershipUserCollection = Membership.Providers("CustomSqlRoleManager").GetAllUsers Then, it gave me this error message. Argument not specified for paramenter 'totalRecords' of 'Public MustOverride Function GetAllUsers(pageIndex as Integer, pageSize as Integer, ByRef totalRecords as Integer) As System.Web.Security.MembershipUserCollection' Then, I added what it asked for like this : Dim allUsers As MembershipUserCollection = Membership.Providers("CustomSqlRoleManager").GetAllUsers(1, 50, 100) I don't get anything in return. I debugged it and allUsers = Nothing. What's wrong the declaration above? Do I really have to provider the paramenters when calling Membership.Providers("CustomSqlRoleManager").GetAllUsers? Update 1 If, I used the statement below: Dim allUsers As MembershipUserCollection = Membership.Providers("MembershipRoleManager").GetAllUsers(0, 0, totalUser) I got this error message: The pageSize must be greater than zero. Parameter name: pageSize. [ArgumentException: The pageSize must be greater than zero. Parameter name: pageSize] System.Web.Security.SqlMembershipProvider.GetAllUsers(Int32 pageIndex, Int32 pageSize, Int32& totalRecords) +1848357 But it works if I provied the pageSize param: Dim pageSize As Integer = GetTotalNumberOfUser() Dim allUsers As MembershipUserCollection = Membership.Providers("MembershipRoleManager").GetAllUsers(0, pageSize, totalUser) This statment Dim pageSize As Integer = GetTotalNumberOfUser() returns the total counted record, it's already round trip to database, just to get the total number of users, because I need to provide the pageSize param value.

    Read the article

  • Asp.Net MVC - Rob Conery's LazyList - Count() or Count

    - by Adam
    I'm trying to create an html table for order logs for customers. A customer is defined as (I've left out a lot of stuff): public class Customer { public LazyList<Order> Orders { get; set; } } The LazyList is set when fetching a Customer: public Customer GetCustomer(int custID) { Customer c = ... c.Orders = new LazyList<Order>(_repository.GetOrders().ByOrderID(custID)); return c; } The order log model: public class OrderLogTableModel { public OrderLogTableModel(LazyList<Order> orders) { Orders = orders; Page = 0; PageSize = 25; } public LazyList<Order> Orders { get; set; } public int Page { get; set; } public int PageSize { get; set; } } and I pass in the customer.Orders after loading a customer. Now the log i'm trying to make, looks something like: <table> <tbody> <% int rowCount = ViewData.Model.Orders.Count(); int innerRows = rowCount - (ViewData.Model.Page * ViewData.Model.PageSize); foreach (Order order in ViewData.Model.Orders.OrderByDescending(x => x.StartDateTime) .Take(innerRows).OrderBy(x => x.StartDateTime) .Take(ViewData.Model.PageSize)) { %> <tr> <td> <%= order.ID %> </td> </tr> <% } %> </tbody> </table> Which works fine. But the problem is evaluating ViewData.Model.Orders.Count() literally takes about 10 minutes. I've tried with the ViewData.Model.Orders.Count property instead, and the results are the same - takes forever. I've also tried calling _repository.GetOrders().ByCustomerID(custID).Count() directly from the view and that executes perfectly within a few ms. Can anybody see any reason why using the LazyList to get a simple count would take so long? It seems like its trying to iterate through the list when getting a simple count.

    Read the article

  • Bind ISet in ASP.NET MVC2

    - by Dmitriy Nagirnyak
    Hi, I am trying to find out what would be the best bind first element of ISet (Iesi.Collection) as a first element. So basically I only have to use some kind of collection that has an indexer (and ISet doesn't) then I can write code like this (which works perfectly well): <%: Html.EditorFor(x => x.Company.PrimaryUsers[0].Email) %> But as the ISet has no indexer I cannot use it. So how can I then bind the first element of ISet in MVC2? Thanks, Dmitriy.

    Read the article

  • problem with RenderOuterTable property for .net 4.0 controls

    - by Mario
    According to the new 4.0 framework overview, one should be able to add the attrib RenderOuterTable="false" to a control that supports the attribute and see css friendly code be spit out - in other words no html tables. To test this, I threw a login control into a basic fresh webpage with the following code: <asp:Login ID="Login1" runat="server" RenderOuterTable="false"></asp:Login> The result? Crappy html table output, which supposedly doesn't happen with this attrib set to false. Here is the output: &lt;table cellpadding=&quot;0&quot;&gt; <tr> <td align="center" colspan="2">Log In</td> </tr><tr> <td align="right"><label for="MainContent_Login1_UserName">User Name:</label></td><td><input name="ctl00$MainContent$Login1$UserName" type="text" id="MainContent_Login1_UserName" /><span id="MainContent_Login1_UserNameRequired" title="User Name is required." style="visibility:hidden;">*</span></td>... Hopefully you get the point. Anyone know how to stop these controls from outputting tables? This is super annoying.

    Read the article

  • Visual Studio ASP.Net MVC undo set as start page action

    - by kingrichard2005
    I have an web application that I'm working on, it was working fine until my curiosity got the better of me and I right-clicked on a view and chose Set As Start Page option. Now, whenever I run my application it takes me to the Resource Not Found error page. I have the default register route set in my Global config route which was working fine before. I notice that the URL now reads: http://localhost:1234/Views/User/Login.aspx instead of http://localhost:1234/ like it was before. I'm not sure how to undo this action or what was changed, I've looked in my web.config file but I'm not sure what to look for exactly, Help is appreciated.

    Read the article

  • Inline HTML Syntax for Helpers in ASP.NET MVC

    - by kouPhax
    I have a class that extends the HtmlHelper in MVC and allows me to use the builder pattern to construct special output e.g. <%= Html.FieldBuilder<MyModel>(builder => { builder.Field(model => model.PropertyOne); builder.Field(model => model.PropertyTwo); builder.Field(model => model.PropertyThree); }) %> Which outputs some application specific HTML, lets just say, <ul> <li>PropertyOne: 12</li> <li>PropertyTwo: Test</li> <li>PropertyThree: true</li> </ul> What I would like to do, however, is add a new builder methid for defining some inline HTML without having to store is as a string. E.g. I'd like to do this. <% Html.FieldBuilder<MyModel>(builder => { builder.Field(model => model.PropertyOne); builder.Field(model => model.PropertyTwo); builder.ActionField(model => %> Generated: <%=DateTime.Now.ToShortDate()%> (<a href="#">Refresh</a>) <%); }).Render(); %> and generate this <ul> <li>PropertyOne: 12</li> <li>PropertyTwo: Test</li> <li>Generated: 29/12/2008 <a href="#">Refresh</a></li> </ul> Essentially an ActionExpression that accepts a block of HTML. However to do this it seems I need to execute the expression but point the execution of the block to my own StringWriter and I am not sure how to do this. Can anyone advise?

    Read the article

  • Can't Use Path in ASP MVC Action

    - by user1477388
    I am trying to use Path() but it has a blue line under it and says, "local variable (path) cannot be referred to until it is declared." How can I use Path()? Imports System.Globalization Imports System.IO Public Class MessageController Inherits System.Web.Mvc.Controller <EmployeeAuthorize()> <HttpPost()> Function SendReply(ByVal id As Integer, ByVal message As String, ByVal files As IEnumerable(Of HttpPostedFileBase)) As JsonResult ' upload files For Each i In files If (i.ContentLength > 0) Then Dim fileName = path.GetFileName(i.FileName) Dim path = path.Combine(Server.MapPath("~/App_Data/uploads"), fileName) i.SaveAs(path) End If Next End Function End Class

    Read the article

  • ASP.NET - Telling the difference between localhost and 127.0.0.1

    - by tyndall
    How can you tell the difference between a request going to 127.0.0.1 and localhost. This line of code on Windows 7 and VS2010 built-in web server can not tell the difference. if (Request.ServerVariables["SERVER_NAME"].ToLower() == "localhost") { } try hitting your own built-in web server with: http://127.0.0.1/ and then http://localhost/

    Read the article

  • ASP.Net navigation tabs like windows tab control

    - by devphil
    I would like to have a webpage something like windows tab control. Each webpage does not lose the contents and data while moving between pages, postbacks, etc. Here is the website design and my idea: [Master Page] "Fruits" "Cars" "Animals" "Operators" clicking on "Fruits" will forwards to "Fruits" page, and the same for other links (tabs) The user works on "Fruits" page searching fruits, fill up some fields, etc. The user then moves to "Cars" page and then builds up his own car by filling some fields, etc and then the user goes back to "Fruits" page again - the user sees the same page where she/he left on "Fruits" page. Please suggest some good ways other than using javascript:history.go(-1). Is this possible to implement?

    Read the article

  • Code snippets for ASP.NET MVC2 in VS 2010

    - by rajbk
    VS 2010 comes with ready made snippets which helps you save time while coding. You insert a snippet by typing the name of the code snippet and hitting the Tab key twice. You can also use the following method if you wish to see a listing of snippets available. Press Ctrl + K, Ctrl + X Select ASP.NET MVC2 with the arrow keys and hit enter to see a list of snippets available.   The MVC related snippets you get out of the box (for C#) are listed below: HTML actionlink Markup snippet for an ASP.NET MVC action link helper <%= Html.ActionLink("linktext", "actionname") %>   beginformajaxcs Markup snippet for an ASP.NET MVC AJAX-enabled form helper in C# <% using (Ajax.BeginForm("actionname", new AjaxOptions {UpdateTargetId= "elementid" })) { %> <% } %>   beginformcs Markup snippet for an ASP.NET MVC form helper in C# <% using (Html.BeginForm()) { %> <% } %>   displayforcs Markup snippet for an ASP.NET MVC templated helper. <%= Html.DisplayFor(x => x.Property) %>   editorforcs Markup snippet for an ASP.NET MVC templated helper. <%= Html.EditorFor(x => x.Property) %>   foreachcs Markup snippet for an ASP.NET MVC foreach statement in C# <% foreach (var item in collection) { %> <% } %>   ifcs Markup snippet for a code-nugget if else statement in C# <% if (true) { %> <% } %>   ifelsecs Markup snippet for a code-nugget if else statement in C# <% if (true) { %> <% } else { %> <% } %>   renderpartialcs Markup snippet for an ASP.NET MVC partial view rendering in C# <% Html.RenderPartial("viewname"); %>   textboxmvc Markup snippet for an ASP.NET MVC textbox helper <%= Html.TextBox("name") %>   validationsummarymvc Markup snippet for an ASP.NET MVC validation summary helper <%= Html.ValidationSummary() %> CS mvcaction Code snippet for an action. public ActionResult Action() {     return View(); }   mvcpostaction Code snippet for an action via http post. [HttpPost] public ActionResult Action() {     return View(); }   Enjoy!

    Read the article

  • ASP.NET Frameworks and Raw Throughput Performance

    - by Rick Strahl
    A few days ago I had a curious thought: With all these different technologies that the ASP.NET stack has to offer, what's the most efficient technology overall to return data for a server request? When I started this it was mere curiosity rather than a real practical need or result. Different tools are used for different problems and so performance differences are to be expected. But still I was curious to see how the various technologies performed relative to each just for raw throughput of the request getting to the endpoint and back out to the client with as little processing in the actual endpoint logic as possible (aka Hello World!). I want to clarify that this is merely an informal test for my own curiosity and I'm sharing the results and process here because I thought it was interesting. It's been a long while since I've done any sort of perf testing on ASP.NET, mainly because I've not had extremely heavy load requirements and because overall ASP.NET performs very well even for fairly high loads so that often it's not that critical to test load performance. This post is not meant to make a point  or even come to a conclusion which tech is better, but just to act as a reference to help understand some of the differences in perf and give a starting point to play around with this yourself. I've included the code for this simple project, so you can play with it and maybe add a few additional tests for different things if you like. Source Code on GitHub I looked at this data for these technologies: ASP.NET Web API ASP.NET MVC WebForms ASP.NET WebPages ASMX AJAX Services  (couldn't get AJAX/JSON to run on IIS8 ) WCF Rest Raw ASP.NET HttpHandlers It's quite a mixed bag, of course and the technologies target different types of development. What started out as mere curiosity turned into a bit of a head scratcher as the results were sometimes surprising. What I describe here is more to satisfy my curiosity more than anything and I thought it interesting enough to discuss on the blog :-) First test: Raw Throughput The first thing I did is test raw throughput for the various technologies. This is the least practical test of course since you're unlikely to ever create the equivalent of a 'Hello World' request in a real life application. The idea here is to measure how much time a 'NOP' request takes to return data to the client. So for this request I create the simplest Hello World request that I could come up for each tech. Http Handler The first is the lowest level approach which is an HTTP handler. public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World. Time is: " + DateTime.Now.ToString()); } public bool IsReusable { get { return true; } } } WebForms Next I added a couple of ASPX pages - one using CodeBehind and one using only a markup page. The CodeBehind page simple does this in CodeBehind without any markup in the ASPX page: public partial class HelloWorld_CodeBehind : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write("Hello World. Time is: " + DateTime.Now.ToString() ); Response.End(); } } while the Markup page only contains some static output via an expression:<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="HelloWorld_Markup.aspx.cs" Inherits="AspNetFrameworksPerformance.HelloWorld_Markup" %> Hello World. Time is <%= DateTime.Now %> ASP.NET WebPages WebPages is the freestanding Razor implementation of ASP.NET. Here's the simple HelloWorld.cshtml page:Hello World @DateTime.Now WCF REST WCF REST was the token REST implementation for ASP.NET before WebAPI and the inbetween step from ASP.NET AJAX. I'd like to forget that this technology was ever considered for production use, but I'll include it here. Here's an OperationContract class: [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class WcfService { [OperationContract] [WebGet] public Stream HelloWorld() { var data = Encoding.Unicode.GetBytes("Hello World" + DateTime.Now.ToString()); var ms = new MemoryStream(data); // Add your operation implementation here return ms; } } WCF REST can return arbitrary results by returning a Stream object and a content type. The code above turns the string result into a stream and returns that back to the client. ASP.NET AJAX (ASMX Services) I also wanted to test ASP.NET AJAX services because prior to WebAPI this is probably still the most widely used AJAX technology for the ASP.NET stack today. Unfortunately I was completely unable to get this running on my Windows 8 machine. Visual Studio 2012  removed adding of ASP.NET AJAX services, and when I tried to manually add the service and configure the script handler references it simply did not work - I always got a SOAP response for GET and POST operations. No matter what I tried I always ended up getting XML results even when explicitly adding the ScriptHandler. So, I didn't test this (but the code is there - you might be able to test this on a Windows 7 box). ASP.NET MVC Next up is probably the most popular ASP.NET technology at the moment: MVC. Here's the small controller: public class MvcPerformanceController : Controller { public ActionResult Index() { return View(); } public ActionResult HelloWorldCode() { return new ContentResult() { Content = "Hello World. Time is: " + DateTime.Now.ToString() }; } } ASP.NET WebAPI Next up is WebAPI which looks kind of similar to MVC. Except here I have to use a StringContent result to return the response: public class WebApiPerformanceController : ApiController { [HttpGet] public HttpResponseMessage HelloWorldCode() { return new HttpResponseMessage() { Content = new StringContent("Hello World. Time is: " + DateTime.Now.ToString(), Encoding.UTF8, "text/plain") }; } } Testing Take a minute to think about each of the technologies… and take a guess which you think is most efficient in raw throughput. The fastest should be pretty obvious, but the others - maybe not so much. The testing I did is pretty informal since it was mainly to satisfy my curiosity - here's how I did this: I used Apache Bench (ab.exe) from a full Apache HTTP installation to run and log the test results of hitting the server. ab.exe is a small executable that lets you hit a URL repeatedly and provides counter information about the number of requests, requests per second etc. ab.exe and the batch file are located in the \LoadTests folder of the project. An ab.exe command line  looks like this: ab.exe -n100000 -c20 http://localhost/aspnetperf/api/HelloWorld which hits the specified URL 100,000 times with a load factor of 20 concurrent requests. This results in output like this:   It's a great way to get a quick and dirty performance summary. Run it a few times to make sure there's not a large amount of varience. You might also want to do an IISRESET to clear the Web Server. Just make sure you do a short test run to warm up the server first - otherwise your first run is likely to be skewed downwards. ab.exe also allows you to specify headers and provide POST data and many other things if you want to get a little more fancy. Here all tests are GET requests to keep it simple. I ran each test: 100,000 iterations Load factor of 20 concurrent connections IISReset before starting A short warm up run for API and MVC to make sure startup cost is mitigated Here is the batch file I used for the test: IISRESET REM make sure you add REM C:\Program Files (x86)\Apache Software Foundation\Apache2.2\bin REM to your path so ab.exe can be found REM Warm up ab.exe -n100 -c20 http://localhost/aspnetperf/MvcPerformance/HelloWorldJsonab.exe -n100 -c20 http://localhost/aspnetperf/api/HelloWorldJson ab.exe -n100 -c20 http://localhost/AspNetPerf/WcfService.svc/HelloWorld ab.exe -n100000 -c20 http://localhost/aspnetperf/handler.ashx > handler.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/HelloWorld_CodeBehind.aspx > AspxCodeBehind.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/HelloWorld_Markup.aspx > AspxMarkup.txt ab.exe -n100000 -c20 http://localhost/AspNetPerf/WcfService.svc/HelloWorld > Wcf.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/MvcPerformance/HelloWorldCode > Mvc.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/api/HelloWorld > WebApi.txt I ran each of these tests 3 times and took the average score for Requests/second, with the machine otherwise idle. I did see a bit of variance when running many tests but the values used here are the medians. Part of this has to do with the fact I ran the tests on my local machine - result would probably more consistent running the load test on a separate machine hitting across the network. I ran these tests locally on my laptop which is a Dell XPS with quad core Sandibridge I7-2720QM @ 2.20ghz and a fast SSD drive on Windows 8. CPU load during tests ran to about 70% max across all 4 cores (IOW, it wasn't overloading the machine). Ideally you can try running these tests on a separate machine hitting the local machine. If I remember correctly IIS 7 and 8 on client OSs don't throttle so the performance here should be Results Ok, let's cut straight to the chase. Below are the results from the tests… It's not surprising that the handler was fastest. But it was a bit surprising to me that the next fastest was WebForms and especially Web Forms with markup over a CodeBehind page. WebPages also fared fairly well. MVC and WebAPI are a little slower and the slowest by far is WCF REST (which again I find surprising). As mentioned at the start the raw throughput tests are not overly practical as they don't test scripting performance for the HTML generation engines or serialization performances of the data engines. All it really does is give you an idea of the raw throughput for the technology from time of request to reaching the endpoint and returning minimal text data back to the client which indicates full round trip performance. But it's still interesting to see that Web Forms performs better in throughput than either MVC, WebAPI or WebPages. It'd be interesting to try this with a few pages that actually have some parsing logic on it, but that's beyond the scope of this throughput test. But what's also amazing about this test is the sheer amount of traffic that a laptop computer is handling. Even the slowest tech managed 5700 requests a second, which is one hell of a lot of requests if you extrapolate that out over a 24 hour period. Remember these are not static pages, but dynamic requests that are being served. Another test - JSON Data Service Results The second test I used a JSON result from several of the technologies. I didn't bother running WebForms and WebPages through this test since that doesn't make a ton of sense to return data from the them (OTOH, returning text from the APIs didn't make a ton of sense either :-) In these tests I have a small Person class that gets serialized and then returned to the client. The Person class looks like this: public class Person { public Person() { Id = 10; Name = "Rick"; Entered = DateTime.Now; } public int Id { get; set; } public string Name { get; set; } public DateTime Entered { get; set; } } Here are the updated handler classes that use Person: Handler public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { var action = context.Request.QueryString["action"]; if (action == "json") JsonRequest(context); else TextRequest(context); } public void TextRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World. Time is: " + DateTime.Now.ToString()); } public void JsonRequest(HttpContext context) { var json = JsonConvert.SerializeObject(new Person(), Formatting.None); context.Response.ContentType = "application/json"; context.Response.Write(json); } public bool IsReusable { get { return true; } } } This code adds a little logic to check for a action query string and route the request to an optional JSON result method. To generate JSON, I'm using the same JSON.NET serializer (JsonConvert.SerializeObject) used in Web API to create the JSON response. WCF REST   [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class WcfService { [OperationContract] [WebGet] public Stream HelloWorld() { var data = Encoding.Unicode.GetBytes("Hello World " + DateTime.Now.ToString()); var ms = new MemoryStream(data); // Add your operation implementation here return ms; } [OperationContract] [WebGet(ResponseFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedRequest)] public Person HelloWorldJson() { // Add your operation implementation here return new Person(); } } For WCF REST all I have to do is add a method with the Person result type.   ASP.NET MVC public class MvcPerformanceController : Controller { // // GET: /MvcPerformance/ public ActionResult Index() { return View(); } public ActionResult HelloWorldCode() { return new ContentResult() { Content = "Hello World. Time is: " + DateTime.Now.ToString() }; } public JsonResult HelloWorldJson() { return Json(new Person(), JsonRequestBehavior.AllowGet); } } For MVC all I have to do for a JSON response is return a JSON result. ASP.NET internally uses JavaScriptSerializer. ASP.NET WebAPI public class WebApiPerformanceController : ApiController { [HttpGet] public HttpResponseMessage HelloWorldCode() { return new HttpResponseMessage() { Content = new StringContent("Hello World. Time is: " + DateTime.Now.ToString(), Encoding.UTF8, "text/plain") }; } [HttpGet] public Person HelloWorldJson() { return new Person(); } [HttpGet] public HttpResponseMessage HelloWorldJson2() { var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new ObjectContent<Person>(new Person(), GlobalConfiguration.Configuration.Formatters.JsonFormatter); return response; } } Testing and Results To run these data requests I used the following ab.exe commands:REM JSON RESPONSES ab.exe -n100000 -c20 http://localhost/aspnetperf/Handler.ashx?action=json > HandlerJson.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/MvcPerformance/HelloWorldJson > MvcJson.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/api/HelloWorldJson > WebApiJson.txt ab.exe -n100000 -c20 http://localhost/AspNetPerf/WcfService.svc/HelloWorldJson > WcfJson.txt The results from this test run are a bit interesting in that the WebAPI test improved performance significantly over returning plain string content. Here are the results:   The performance for each technology drops a little bit except for WebAPI which is up quite a bit! From this test it appears that WebAPI is actually significantly better performing returning a JSON response, rather than a plain string response. Snag with Apache Benchmark and 'Length Failures' I ran into a little snag with Apache Benchmark, which was reporting failures for my Web API requests when serializing. As the graph shows performance improved significantly from with JSON results from 5580 to 6530 or so which is a 15% improvement (while all others slowed down by 3-8%). However, I was skeptical at first because the WebAPI test reports showed a bunch of errors on about 10% of the requests. Check out this report: Notice the Failed Request count. What the hey? Is WebAPI failing on roughly 10% of requests when sending JSON? Turns out: No it's not! But it took some sleuthing to figure out why it reports these failures. At first I thought that Web API was failing, and so to make sure I re-ran the test with Fiddler attached and runiisning the ab.exe test by using the -X switch: ab.exe -n100 -c10 -X localhost:8888 http://localhost/aspnetperf/api/HelloWorldJson which showed that indeed all requests where returning proper HTTP 200 results with full content. However ab.exe was reporting the errors. After some closer inspection it turned out that the dates varying in size altered the response length in dynamic output. For example: these two results: {"Id":10,"Name":"Rick","Entered":"2012-09-04T10:57:24.841926-10:00"} {"Id":10,"Name":"Rick","Entered":"2012-09-04T10:57:24.8519262-10:00"} are different in length for the number which results in 68 and 69 bytes respectively. The same URL produces different result lengths which is what ab.exe reports. I didn't notice at first bit the same is happening when running the ASHX handler with JSON.NET result since it uses the same serializer that varies the milliseconds. Moral: You can typically ignore Length failures in Apache Benchmark and when in doubt check the actual output with Fiddler. Note that the other failure values are accurate though. Another interesting Side Note: Perf drops over Time As I was running these tests repeatedly I was finding that performance steadily dropped from a startup peak to a 10-15% lower stable level. IOW, with Web API I'd start out with around 6500 req/sec and in subsequent runs it keeps dropping until it would stabalize somewhere around 5900 req/sec occasionally jumping lower. For these tests this is why I did the IIS RESET and warm up for individual tests. This is a little puzzling. Looking at Process Monitor while the test are running memory very quickly levels out as do handles and threads, on the first test run. Subsequent runs everything stays stable, but the performance starts going downwards. This applies to all the technologies - Handlers, Web Forms, MVC, Web API - curious to see if others test this and see similar results. Doing an IISRESET then resets everything and performance starts off at peak again… Summary As I stated at the outset, these were informal to satiate my curiosity not to prove that any technology is better or even faster than another. While there clearly are differences in performance the differences (other than WCF REST which was by far the slowest and the raw handler which was by far the highest) are relatively minor, so there is no need to feel that any one technology is a runaway standout in raw performance. Choosing a technology is about more than pure performance but also about the adequateness for the job and the easy of implementation. The strengths of each technology will make for any minor performance difference we see in these tests. However, to me it's important to get an occasional reality check and compare where new technologies are heading. Often times old stuff that's been optimized and designed for a time of less horse power can utterly blow the doors off newer tech and simple checks like this let you compare. Luckily we're seeing that much of the new stuff performs well even in V1.0 which is great. To me it was very interesting to see Web API perform relatively badly with plain string content, which originally led me to think that Web API might not be properly optimized just yet. For those that caught my Tweets late last week regarding WebAPI's slow responses was with String content which is in fact considerably slower. Luckily where it counts with serialized JSON and XML WebAPI actually performs better. But I do wonder what would make generic string content slower than serialized code? This stresses another point: Don't take a single test as the final gospel and don't extrapolate out from a single set of tests. Certainly Twitter can make you feel like a fool when you post something immediate that hasn't been fleshed out a little more <blush>. Egg on my face. As a result I ended up screwing around with this for a few hours today to compare different scenarios. Well worth the time… I hope you found this useful, if not for the results, maybe for the process of quickly testing a few requests for performance and charting out a comparison. Now onwards with more serious stuff… Resources Source Code on GitHub Apache HTTP Server Project (ab.exe is part of the binary distribution)© Rick Strahl, West Wind Technologies, 2005-2012Posted in ASP.NET  Web Api   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 resolve: 'cmd' is not recognized as an internal or external command?

    - by qwer1234
    I have searched other forums to solve this error where it would either end with: 1.) re-install OS 2.) Setting path variable C:/Windows/System32 The latter did not work, and as you can probably imagine, I do not want to have to re-install my OS... I am running the command "mvn jetty:run" and the following is my stack trace, finishing with the message: "'cmd' is not recognized as an internal or external command, operable problem or batch file" as stated in the title of this question. [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] Building Test Tool [INFO] task-segment: [jetty:run] [INFO] ------------------------------------------------------------------------ [INFO] Preparing jetty:run [WARNING] Removing: run from forked lifecycle, to prevent recursive invocation. [INFO] [resources:resources] [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 32 resources [INFO] Copying 192 resources [INFO] [compiler:compile] [INFO] Compiling 1854 source files to C:\Development\global_stock_record\test\java\Turtle\target\classes [INFO] ------------------------------------------------------------------------ [ERROR] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Compilation failure C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\compilers\JavaScriptClassCompiler.java:[45,29] cannot find symbol symbol : class CompilerEnvirons location: package org.mozilla.javascript C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\compilers\JavaScriptClassCompiler.java:[47,29] cannot find symbol symbol : class ContextFactory location: package org.mozilla.javascript C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\compilers\JavaScriptClassCompiler.java:[49,39] cannot find symbol symbol : class ClassCompiler location: package org.mozilla.javascript.optimizer C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\compilers\JavaScriptClassCompiler.java:[181,55] cannot find symbol symbol : class CompilerEnvirons location: class net.sf.jasperreports.compilers.JavaScriptClassCompiler C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\export\JRXmlExporter.java:[99,26] package org.w3c.tools.codec does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\xml\JRBaseFactory.java:[26,34] package org.apache.commons.digester does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\xml\JRBaseFactory.java:[27,34] package org.apache.commons.digester does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\xml\JRBaseFactory.java:[34,47] cannot find symbol symbol: class ObjectCreationFactory public abstract class JRBaseFactory implements ObjectCreationFactory C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\xml\JRBaseFactory.java:[41,21] cannot find symbol symbol : class Digester location: class net.sf.jasperreports.engine.xml.JRBaseFactory C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\xml\JRBaseFactory.java:[47,8] cannot find symbol symbol : class Digester location: class net.sf.jasperreports.engine.xml.JRBaseFactory C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\xml\JRBaseFactory.java:[56,25] cannot find symbol symbol : class Digester location: class net.sf.jasperreports.engine.xml.JRBaseFactory C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\Code39Component.java:[28,29] package org.krysalis.barcode4j does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\BarcodeComponent.java:[41,29] package org.krysalis.barcode4j does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\Code39Component.java:[66,29] cannot find symbol symbol : class ChecksumMode location: class net.sf.jasperreports.components.barcode4j.Code39Component C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\BarcodeComponent.java:[179,29] cannot find symbol symbol : class HumanReadablePlacement location: class net.sf.jasperreports.components.barcode4j.BarcodeComponent C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\EAN128Component.java:[26,29] package org.krysalis.barcode4j does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\DataMatrixComponent.java:[26,45] package org.krysalis.barcode4j.impl.datamatrix does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\FourStateBarcodeComponent.java:[26,29] package org.krysalis.barcode4j does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\UPCAComponent.java:[28,29] package org.krysalis.barcode4j does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\UPCEComponent.java:[28,29] package org.krysalis.barcode4j does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\EAN13Component.java:[28,29] package org.krysalis.barcode4j does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\EAN8Component.java:[28,29] package org.krysalis.barcode4j does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\Interleaved2Of5Component.java:[28,29] package org.krysalis.barcode4j does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\EAN128Component.java:[57,29] cannot find symbol symbol : class ChecksumMode location: class net.sf.jasperreports.components.barcode4j.EAN128Component C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\DataMatrixComponent.java:[62,22] cannot find symbol symbol : class SymbolShapeHint location: class net.sf.jasperreports.components.barcode4j.DataMatrixComponent C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\FourStateBarcodeComponent.java:[76,29] cannot find symbol symbol : class ChecksumMode location: class net.sf.jasperreports.components.barcode4j.FourStateBarcodeComponent C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\UPCAComponent.java:[56,29] cannot find symbol symbol : class ChecksumMode location: class net.sf.jasperreports.components.barcode4j.UPCAComponent C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\UPCEComponent.java:[56,29] cannot find symbol symbol : class ChecksumMode location: class net.sf.jasperreports.components.barcode4j.UPCEComponent C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\EAN13Component.java:[56,29] cannot find symbol symbol : class ChecksumMode location: class net.sf.jasperreports.components.barcode4j.EAN13Component C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\EAN8Component.java:[56,29] cannot find symbol symbol : class ChecksumMode location: class net.sf.jasperreports.components.barcode4j.EAN8Component C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\Interleaved2Of5Component.java:[60,29] cannot find symbol symbol : class ChecksumMode location: class net.sf.jasperreports.components.barcode4j.Interleaved2Of5Component C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\data\JRHibernateAbstractDataSource.java:[36,25] package org.hibernate.type does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\query\JRHibernateQueryExecuter.java:[49,20] package org.hibernate does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\query\JRHibernateQueryExecuter.java:[50,20] package org.hibernate does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\query\JRHibernateQueryExecuter.java:[51,20] package org.hibernate does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\query\JRHibernateQueryExecuter.java:[52,20] package org.hibernate does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\query\JRHibernateQueryExecuter.java:[53,20] package org.hibernate does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\query\JRHibernateQueryExecuter.java:[54,25] package org.hibernate.type does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\data\JRHibernateAbstractDataSource.java:[173,38] cannot find symbol symbol : class Type location: class net.sf.jasperreports.engine.data.JRHibernateAbstractDataSource C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\query\JRHibernateQueryExecuter.java:[66,35] cannot find symbol symbol : class Type location: class net.sf.jasperreports.engine.query.JRHibernateQueryExecuter C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\query\JRHibernateQueryExecuter.java:[89,9] cannot find symbol symbol : class Session location: class net.sf.jasperreports.engine.query.JRHibernateQueryExecuter C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\query\JRHibernateQueryExecuter.java:[90,9] cannot find symbol symbol : class Query location: class net.sf.jasperreports.engine.query.JRHibernateQueryExecuter C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\query\JRHibernateQueryExecuter.java:[92,9] cannot find symbol symbol : class ScrollableResults location: class net.sf.jasperreports.engine.query.JRHibernateQueryExecuter C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\query\JRHibernateQueryExecuter.java:[359,8] cannot find symbol symbol : class Type location: class net.sf.jasperreports.engine.query.JRHibernateQueryExecuter C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\query\JRHibernateQueryExecuter.java:[474,8] cannot find symbol symbol : class ScrollableResults location: class net.sf.jasperreports.engine.query.JRHibernateQueryExecuter C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barbecue\BarbecueFillComponent.java:[40,31] package net.sourceforge.barbecue does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[38,27] package org.apache.tools.ant does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[39,27] package org.apache.tools.ant does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[40,27] package org.apache.tools.ant does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[41,33] package org.apache.tools.ant.types does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[42,33] package org.apache.tools.ant.types does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[43,43] package org.apache.tools.ant.types.resources does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[44,32] package org.apache.tools.ant.util does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[45,32] package org.apache.tools.ant.util does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRBaseAntTask.java:[34,36] package org.apache.tools.ant.taskdefs does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRBaseAntTask.java:[41,35] cannot find symbol symbol: class MatchingTask public class JRBaseAntTask extends MatchingTask C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[74,9] cannot find symbol symbol : class Path location: class net.sf.jasperreports.ant.JRAntXmlExportTask C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[76,9] cannot find symbol symbol : class Path location: class net.sf.jasperreports.ant.JRAntXmlExportTask C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[86,23] cannot find symbol symbol : class Path location: class net.sf.jasperreports.ant.JRAntXmlExportTask C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[104,8] cannot find symbol symbol : class Path location: class net.sf.jasperreports.ant.JRAntXmlExportTask C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[131,8] cannot find symbol symbol : class Path location: class net.sf.jasperreports.ant.JRAntXmlExportTask C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[145,30] cannot find symbol symbol : class BuildException location: class net.sf.jasperreports.ant.JRAntXmlExportTask C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[183,41] cannot find symbol symbol : class BuildException location: class net.sf.jasperreports.ant.JRAntXmlExportTask C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[211,33] cannot find symbol symbol : class BuildException location: class net.sf.jasperreports.ant.JRAntXmlExportTask C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\ant\JRAntXmlExportTask.java:[276,32] cannot find symbol symbol : class BuildException location: class net.sf.jasperreports.ant.JRAntXmlExportTask C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\xml\TransformedPropertyRule.java:[27,34] package org.apache.commons.digester does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\xml\TransformedPropertyRule.java:[37,54] cannot find symbol symbol: class Rule public abstract class TransformedPropertyRule extends Rule C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\data\mondrian\MondrianDataAdapterService.java:[29,20] package mondrian.olap does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\data\mondrian\MondrianDataAdapterService.java:[30,20] package mondrian.olap does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\data\mondrian\MondrianDataAdapterService.java:[31,20] package mondrian.olap does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\data\mondrian\MondrianDataAdapterService.java:[45,9] cannot find symbol symbol : class Connection location: class net.sf.jasperreports.data.mondrian.MondrianDataAdapterService C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\data\JRXlsDataSource.java:[40,10] package jxl does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\data\JRXlsDataSource.java:[41,10] package jxl does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\data\JRXlsDataSource.java:[42,10] package jxl does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\data\JRXlsDataSource.java:[43,20] package jxl.read.biff does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\data\JRXlsDataSource.java:[66,9] cannot find symbol symbol : class Workbook location: class net.sf.jasperreports.engine.data.JRXlsDataSource C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\engine\data\JRXlsDataSource.java:[83,24] cannot find symbol symbol : class Workbook location: class net.sf.jasperreports.engine.data.JRXlsDataSource C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\olap\xmla\JRXmlaMember.java:[26,20] package mondrian.olap does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\olap\result\JROlapMember.java:[26,20] package mondrian.olap does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\olap\xmla\JRXmlaMember.java:[89,8] cannot find symbol symbol : class Member location: class net.sf.jasperreports.olap.xmla.JRXmlaMember C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\olap\result\JROlapMember.java:[46,1] cannot find symbol symbol : class Member location: interface net.sf.jasperreports.olap.result.JROlapMember C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\web\actions\AbstractAction.java:[43,36] package org.codehaus.jackson.annotate does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\web\actions\AbstractAction.java:[49,1] cannot find symbol symbol: class JsonTypeInfo @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="actionName") C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[32,29] package org.krysalis.barcode4j does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[33,29] package org.krysalis.barcode4j does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[34,29] package org.krysalis.barcode4j does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[35,34] package org.krysalis.barcode4j.impl does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[36,42] package org.krysalis.barcode4j.impl.codabar does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[37,42] package org.krysalis.barcode4j.impl.code128 does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[38,42] package org.krysalis.barcode4j.impl.code128 does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[39,41] package org.krysalis.barcode4j.impl.code39 does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[40,45] package org.krysalis.barcode4j.impl.datamatrix does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[41,45] package org.krysalis.barcode4j.impl.datamatrix does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[42,44] package org.krysalis.barcode4j.impl.fourstate does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[43,44] package org.krysalis.barcode4j.impl.fourstate does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[44,44] package org.krysalis.barcode4j.impl.fourstate does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[45,42] package org.krysalis.barcode4j.impl.int2of5 does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[46,41] package org.krysalis.barcode4j.impl.pdf417 does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[47,42] package org.krysalis.barcode4j.impl.postnet does not exist C:\Development\global_stock_record\test\java\Turtle\src\main\java\net\sf\jasperreports\components\barcode4j\AbstractBarcodeEvaluator.java:[48,41] package org.krysalis.barcode4j.impl.upcean does not exist [INFO] ------------------------------------------------------------------------ [INFO] For more information, run Maven with the -e switch [INFO] ------------------------------------------------------------------------ [INFO] Total time: 17 seconds [INFO] Finished at: Fri Dec 07 11:46:28 EST 2012 [INFO] Final Memory: 27M/63M [INFO] ------------------------------------------------------------------------

    Read the article

  • Adding page title to each page while creating a PDF file using itextsharp in VB.NET

    - by Snowy
    I have recently started using itextsharp and gradually learning it. So far I created a PDF file and it seems great. I have added a table and some subtables as the first table cells to hold data. It is done using two for loops. The first one loops through all data and the second one is each individual data displayed in columns. The html outcome looks like the following: <table> <tr> <td>Page title in center</td> </tr> <tr> <td> <table> <tr> <td>FirstPersonName</td> <td>Rank1</td> <td>info1a</td> <td>infob</td> <td>infoc</td> </tr> </table> </td> <td> <table> <tr> <td>SecondPersonName</td> <td>Rank2</td> <td>info1a</td> <td>infob</td> <td>infoc</td> <td>infod</td> <td>infoe</td> </tr> </table> </td> <td> <table> <tr> <td>ThirdPersonName</td> <td>Rank2</td> <td>info1a</td> <td>infob</td> <td>infoc</td> <td>infod</td> <td>infoe</td> <td>infof</td> <td>infog</td> </tr> </table> </td> </tr> </table> For page headings, I added a cell at the top before any other cells. I need to add this heading to all pages. Depending on the size of data, some pages have two rows and some pages have three rows of data. So I can not tell exactly when the new page starts to add the heading/title. My question is how to add the heading/title to all pages. I use VB.net. I searched for answer online and had no success. Your help would be greatly appreciated.

    Read the article

  • ASP.NET: With C# or C# + VB.NET?

    - by Sahat
    I am currently reading Beginning ASP.NET 4: in C# and VB (Wrox Programmer to Programmer) and it comes with both C# and VB.NET source code. I am definitely planning to use C# in the future for most of my projects. But VB.NET - is it really worth learning side-by-side with C#? Are there such cases when VB.NET is preferred over C#?

    Read the article

  • ASP.NET with C# or VB.NET + C#?

    - by Sahat
    I am currently reading Beginning ASP.NET 4: in C# and VB (Wrox Programmer to Programmer) and it comes with both C# and VB.NET source code. I am definitely planning to use C# in the future for most of my projects. But VB.NET - is it worth learning side-by-side with C#? Will there be a case when VB.NET is preferred over C#?

    Read the article

  • Host AngularJS (Html5Mode) in ASP.NET vNext

    - by Shaun
    Originally posted on: http://geekswithblogs.net/shaunxu/archive/2014/06/10/host-angularjs-html5mode-in-asp.net-vnext.aspxMicrosoft had announced ASP.NET vNext in BUILD and TechED recently and as a developer, I found that we can add features into one ASP.NET vNext application such as MVC, WebAPI, SignalR, etc.. Also it's cross platform which means I can host ASP.NET on Windows, Linux and OS X.   If you are following my blog you should knew that I'm currently working on a project which uses ASP.NET WebAPI, SignalR and AngularJS. Currently the AngularJS part is hosted by Express in Node.js while WebAPI and SignalR are hosted in ASP.NET. I was looking for a solution to host all of them in one platform so that my SignalR can utilize WebSocket. Currently AngularJS and SignalR are hosted in the same domain but different port so it has to use ServerSendEvent. It can be upgraded to WebSocket if I host both of them in the same port.   Host AngularJS in ASP.NET vNext Static File Middleware ASP.NET vNext utilizes middleware pattern to register feature it uses, which is very similar as Express in Node.js. Since AngularJS is a pure client side framework in theory what I need to do is to use ASP.NET vNext as a static file server. This is very easy as there's a build-in middleware shipped alone with ASP.NET vNext. Assuming I have "index.html" as below. 1: <html data-ng-app="demo"> 2: <head> 3: <script type="text/javascript" src="angular.js" /> 4: <script type="text/javascript" src="angular-ui-router.js" /> 5: <script type="text/javascript" src="app.js" /> 6: </head> 7: <body> 8: <h1>ASP.NET vNext with AngularJS</h1> 9: <div> 10: <a href="javascript:void(0)" data-ui-sref="view1">View 1</a> | 11: <a href="javascript:void(0)" data-ui-sref="view2">View 2</a> 12: </div> 13: <div data-ui-view></div> 14: </body> 15: </html> And the AngularJS JavaScript file as below. Notices that I have two views which only contains one line literal indicates the view name. 1: 'use strict'; 2:  3: var app = angular.module('demo', ['ui.router']); 4:  5: app.config(['$stateProvider', '$locationProvider', function ($stateProvider, $locationProvider) { 6: $stateProvider.state('view1', { 7: url: '/view1', 8: templateUrl: 'view1.html', 9: controller: 'View1Ctrl' }); 10:  11: $stateProvider.state('view2', { 12: url: '/view2', 13: templateUrl: 'view2.html', 14: controller: 'View2Ctrl' }); 15: }]); 16:  17: app.controller('View1Ctrl', function ($scope) { 18: }); 19:  20: app.controller('View2Ctrl', function ($scope) { 21: }); All AngularJS files are located in "app" folder and my ASP.NET vNext files are besides it. The "project.json" contains all dependencies I need to host static file server. 1: { 2: "dependencies": { 3: "Helios" : "0.1-alpha-*", 4: "Microsoft.AspNet.FileSystems": "0.1-alpha-*", 5: "Microsoft.AspNet.Http": "0.1-alpha-*", 6: "Microsoft.AspNet.StaticFiles": "0.1-alpha-*", 7: "Microsoft.AspNet.Hosting": "0.1-alpha-*", 8: "Microsoft.AspNet.Server.WebListener": "0.1-alpha-*" 9: }, 10: "commands": { 11: "web": "Microsoft.AspNet.Hosting server=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:22222" 12: }, 13: "configurations" : { 14: "net45" : { 15: }, 16: "k10" : { 17: "System.Diagnostics.Contracts": "4.0.0.0", 18: "System.Security.Claims" : "0.1-alpha-*" 19: } 20: } 21: } Below is "Startup.cs" which is the entry file of my ASP.NET vNext. What I need to do is to let my application use FileServerMiddleware. 1: using System; 2: using Microsoft.AspNet.Builder; 3: using Microsoft.AspNet.FileSystems; 4: using Microsoft.AspNet.StaticFiles; 5:  6: namespace Shaun.AspNet.Plugins.AngularServer.Demo 7: { 8: public class Startup 9: { 10: public void Configure(IBuilder app) 11: { 12: app.UseFileServer(new FileServerOptions() { 13: EnableDirectoryBrowsing = true, 14: FileSystem = new PhysicalFileSystem(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "app")) 15: }); 16: } 17: } 18: } Next, I need to create "NuGet.Config" file in the PARENT folder so that when I run "kpm restore" command later it can find ASP.NET vNext NuGet package successfully. 1: <?xml version="1.0" encoding="utf-8"?> 2: <configuration> 3: <packageSources> 4: <add key="AspNetVNext" value="https://www.myget.org/F/aspnetvnext/api/v2" /> 5: <add key="NuGet.org" value="https://nuget.org/api/v2/" /> 6: </packageSources> 7: <packageSourceCredentials> 8: <AspNetVNext> 9: <add key="Username" value="aspnetreadonly" /> 10: <add key="ClearTextPassword" value="4d8a2d9c-7b80-4162-9978-47e918c9658c" /> 11: </AspNetVNext> 12: </packageSourceCredentials> 13: </configuration> Now I need to run "kpm restore" to resolve all dependencies of my application. Finally, use "k web" to start the application which will be a static file server on "app" sub folder in the local 22222 port.   Support AngularJS Html5Mode AngularJS works well in previous demo. But you will note that there is a "#" in the browser address. This is because by default AngularJS adds "#" next to its entry page so ensure all request will be handled by this entry page. For example, in this case my entry page is "index.html", so when I clicked "View 1" in the page the address will be changed to "/#/view1" which means it still tell the web server I'm still looking for "index.html". This works, but makes the address looks ugly. Hence AngularJS introduces a feature called Html5Mode, which will get rid off the annoying "#" from the address bar. Below is the "app.js" with Html5Mode enabled, just one line of code. 1: 'use strict'; 2:  3: var app = angular.module('demo', ['ui.router']); 4:  5: app.config(['$stateProvider', '$locationProvider', function ($stateProvider, $locationProvider) { 6: $stateProvider.state('view1', { 7: url: '/view1', 8: templateUrl: 'view1.html', 9: controller: 'View1Ctrl' }); 10:  11: $stateProvider.state('view2', { 12: url: '/view2', 13: templateUrl: 'view2.html', 14: controller: 'View2Ctrl' }); 15:  16: // enable html5mode 17: $locationProvider.html5Mode(true); 18: }]); 19:  20: app.controller('View1Ctrl', function ($scope) { 21: }); 22:  23: app.controller('View2Ctrl', function ($scope) { 24: }); Then let's went to the root path of our website and click "View 1" you will see there's no "#" in the address. But the problem is, if we hit F5 the browser will be turn to blank. This is because in this mode the browser told the web server I want static file named "view1" but there's no file on the server. So underlying our web server, which is built by ASP.NET vNext, responded 404. To fix this problem we need to create our own ASP.NET vNext middleware. What it needs to do is firstly try to respond the static file request with the default StaticFileMiddleware. If the response status code was 404 then change the request path value to the entry page and try again. 1: public class AngularServerMiddleware 2: { 3: private readonly AngularServerOptions _options; 4: private readonly RequestDelegate _next; 5: private readonly StaticFileMiddleware _innerMiddleware; 6:  7: public AngularServerMiddleware(RequestDelegate next, AngularServerOptions options) 8: { 9: _next = next; 10: _options = options; 11:  12: _innerMiddleware = new StaticFileMiddleware(next, options.FileServerOptions.StaticFileOptions); 13: } 14:  15: public async Task Invoke(HttpContext context) 16: { 17: // try to resolve the request with default static file middleware 18: await _innerMiddleware.Invoke(context); 19: Console.WriteLine(context.Request.Path + ": " + context.Response.StatusCode); 20: // route to root path if the status code is 404 21: // and need support angular html5mode 22: if (context.Response.StatusCode == 404 && _options.Html5Mode) 23: { 24: context.Request.Path = _options.EntryPath; 25: await _innerMiddleware.Invoke(context); 26: Console.WriteLine(">> " + context.Request.Path + ": " + context.Response.StatusCode); 27: } 28: } 29: } We need an option class where user can specify the host root path and the entry page path. 1: public class AngularServerOptions 2: { 3: public FileServerOptions FileServerOptions { get; set; } 4:  5: public PathString EntryPath { get; set; } 6:  7: public bool Html5Mode 8: { 9: get 10: { 11: return EntryPath.HasValue; 12: } 13: } 14:  15: public AngularServerOptions() 16: { 17: FileServerOptions = new FileServerOptions(); 18: EntryPath = PathString.Empty; 19: } 20: } We also need an extension method so that user can append this feature in "Startup.cs" easily. 1: public static class AngularServerExtension 2: { 3: public static IBuilder UseAngularServer(this IBuilder builder, string rootPath, string entryPath) 4: { 5: var options = new AngularServerOptions() 6: { 7: FileServerOptions = new FileServerOptions() 8: { 9: EnableDirectoryBrowsing = false, 10: FileSystem = new PhysicalFileSystem(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rootPath)) 11: }, 12: EntryPath = new PathString(entryPath) 13: }; 14:  15: builder.UseDefaultFiles(options.FileServerOptions.DefaultFilesOptions); 16:  17: return builder.Use(next => new AngularServerMiddleware(next, options).Invoke); 18: } 19: } Now with these classes ready we will change our "Startup.cs", use this middleware replace the default one, tell the server try to load "index.html" file if it cannot find resource. The code below is just for demo purpose. I just tried to load "index.html" in all cases once the StaticFileMiddleware returned 404. In fact we need to validation to make sure this is an AngularJS route request instead of a normal static file request. 1: using System; 2: using Microsoft.AspNet.Builder; 3: using Microsoft.AspNet.FileSystems; 4: using Microsoft.AspNet.StaticFiles; 5: using Shaun.AspNet.Plugins.AngularServer; 6:  7: namespace Shaun.AspNet.Plugins.AngularServer.Demo 8: { 9: public class Startup 10: { 11: public void Configure(IBuilder app) 12: { 13: app.UseAngularServer("app", "/index.html"); 14: } 15: } 16: } Now let's run "k web" again and try to refresh our browser and we can see the page loaded successfully. In the console window we can find the original request got 404 and we try to find "index.html" and return the correct result.   Summary In this post I introduced how to use ASP.NET vNext to host AngularJS application as a static file server. I also demonstrated how to extend ASP.NET vNext, so that it supports AngularJS Html5Mode. You can download the source code here.   Hope this helps, Shaun All documents and related graphics, codes are provided "AS IS" without warranty of any kind. Copyright © Shaun Ziyan Xu. This work is licensed under the Creative Commons License.

    Read the article

  • asp.net labels and asp.net textboxes are not lining up correctly?

    - by Xaisoft
    My Registration page currently looks like the following: The current styling I have for the above is image is: <style type="text/css"> #contactinfo label { float: left; width: 10em; margin-right: 0.5em; text-align: right; font-size: 14px; } #contactinfo p { padding: 5px; } #contactinfo input[type="text"], input[type="password"] { height: 1.5em; } #contactinfo select { padding: 0.25em; } #contactinfo input[type="text"]:focus, input[type="password"]:focus { background-color: #FFFFE0; } #contactinfo .update { margin-left: 12.5em; } #contactinfo .error { background-color: transparent; } #contactinfo .longtextbox { width: 20em; } #contactinfo .shorttextbox { width: 5em; } </style> and the markup is <div id="contactinfo"> <p> <asp:Label runat="server" AssociatedControlID="txtEmail">Email </asp:Label> <asp:TextBox ID="txtEmail" runat="server" CssClass="longtextbox" /> </p> <p> <asp:Label runat="server" AssociatedControlID="txtFirstName">First Name </asp:Label> <asp:TextBox ID="txtFirstName" runat="server" ValidationGroup="AccountValidation" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="txtFirstName" Text="First Name is required." ValidationGroup="AccountValidation" CssClass="error"> </asp:RequiredFieldValidator> </p> <p> <asp:Label runat="server" AssociatedControlID="txtLastName">Last Name </asp:Label> <asp:TextBox ID="txtLastName" runat="server" ValidationGroup="AccountValidation" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="txtLastName" Text="Last Name is required." ValidationGroup="AccountValidation" CssClass="error"> </asp:RequiredFieldValidator> </p> <p> <asp:Label runat="server" AssociatedControlID="txtBusinessName">Business Name </asp:Label> <asp:TextBox ID="txtBusinessName" runat="server" CssClass="longtextbox" ValidationGroup="AccountValidation" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="txtBusinessName" Text="Business Name is required." ValidationGroup="AccountValidation" CssClass="error"> </asp:RequiredFieldValidator> </p> <p> <asp:Label runat="server" AssociatedControlID="txtPhone">Phone </asp:Label> <asp:TextBox ID="txtPhone" runat="server" ValidationGroup="AccountValidation" /> </p> <p> <asp:Label runat="server" AssociatedControlID="txtAddress">Address </asp:Label> <asp:TextBox ID="txtAddress" runat="server" CssClass="longtextbox" ValidationGroup="AccountValidation" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="txtAddress" Text="Address is required." ValidationGroup="AccountValidation" CssClass="error"></asp:RequiredFieldValidator> </p> <p> <asp:Label runat="server" AssociatedControlID="txtCity">City </asp:Label><asp:TextBox ID="txtCity" runat="server" ValidationGroup="AccountValidation" /> <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtCity" Text="City is required." ValidationGroup="AccountValidation" CssClass="error"> </asp:RequiredFieldValidator> </p> <p> <asp:Label runat="server" AssociatedControlID="ddlState">State </asp:Label> <asp:DropDownList ID="ddlState" runat="server" DataSourceID="dsStates" DataTextField="Name" DataValueField="Id"> </asp:DropDownList> </p> <p> <asp:Label runat="server" AssociatedControlID="txtZipcode">Zipcode</asp:Label> <asp:TextBox ID="txtZipCode" runat="server" CssClass="shorttextbox" ValidationGroup="AccountValidation" /> </p> </div> As you can see from above, I have every label field pair wrapped in a p tag so it breaks to the next line, but I am not sure if I need to do this. I want to get city, state, and zip all on the same line, but as soon as I move all the labels and inputs for city,state,zip into one p tag, it looks like the following and I don't know how to fix it.

    Read the article

  • Adding Unobtrusive Validation To MVCContrib Fluent Html

    - by srkirkland
    ASP.NET MVC 3 includes a new unobtrusive validation strategy that utilizes HTML5 data-* attributes to decorate form elements.  Using a combination of jQuery validation and an unobtrusive validation adapter script that comes with MVC 3, those attributes are then turned into client side validation rules. A Quick Introduction to Unobtrusive Validation To quickly show how this works in practice, assume you have the following Order.cs class (think Northwind) [If you are familiar with unobtrusive validation in MVC 3 you can skip to the next section]: public class Order : DomainObject { [DataType(DataType.Date)] public virtual DateTime OrderDate { get; set; }   [Required] [StringLength(12)] public virtual string ShipAddress { get; set; }   [Required] public virtual Customer OrderedBy { get; set; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Note the System.ComponentModel.DataAnnotations attributes, which provide the validation and metadata information used by ASP.NET MVC 3 to determine how to render out these properties.  Now let’s assume we have a form which can edit this Order class, specifically let’s look at the ShipAddress property: @Html.LabelFor(x => x.Order.ShipAddress) @Html.EditorFor(x => x.Order.ShipAddress) @Html.ValidationMessageFor(x => x.Order.ShipAddress) .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Now the Html.EditorFor() method is smart enough to look at the ShipAddress attributes and write out the necessary unobtrusive validation html attributes.  Note we could have used Html.TextBoxFor() or even Html.TextBox() and still retained the same results. If we view source on the input box generated by the Html.EditorFor() call, we get the following: <input type="text" value="Rua do Paço, 67" name="Order.ShipAddress" id="Order_ShipAddress" data-val-required="The ShipAddress field is required." data-val-length-max="12" data-val-length="The field ShipAddress must be a string with a maximum length of 12." data-val="true" class="text-box single-line input-validation-error"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } As you can see, we have data-val-* attributes for both required and length, along with the proper error messages and additional data as necessary (in this case, we have the length-max=”12”). And of course, if we try to submit the form with an invalid value, we get an error on the client: Working with MvcContrib’s Fluent Html The MvcContrib project offers a fluent interface for creating Html elements which I find very expressive and useful, especially when it comes to creating select lists.  Let’s look at a few quick examples: @this.TextBox(x => x.FirstName).Class("required").Label("First Name:") @this.MultiSelect(x => x.UserId).Options(ViewModel.Users) @this.CheckBox("enabled").LabelAfter("Enabled").Title("Click to enable.").Styles(vertical_align => "middle")   @(this.Select("Order.OrderedBy").Options(Model.Customers, x => x.Id, x => x.CompanyName) .Selected(Model.Order.OrderedBy != null ? Model.Order.OrderedBy.Id : "") .FirstOption(null, "--Select A Company--") .HideFirstOptionWhen(Model.Order.OrderedBy != null) .Label("Ordered By:")) .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } These fluent html helpers create the normal html you would expect, and I think they make life a lot easier and more readable when dealing with complex markup or select list data models (look ma: no anonymous objects for creating class names!). Of course, the problem we have now is that MvcContrib’s fluent html helpers don’t know about ASP.NET MVC 3’s unobtrusive validation attributes and thus don’t take part in client validation on your page.  This is not ideal, so I wrote a quick helper method to extend fluent html with the knowledge of what unobtrusive validation attributes to include when they are rendered. Extending MvcContrib’s Fluent Html Before posting the code, there are just a few things you need to know.  The first is that all Fluent Html elements implement the IElement interface (MvcContrib.FluentHtml.Elements.IElement), and the second is that the base System.Web.Mvc.HtmlHelper has been extended with a method called GetUnobtrusiveValidationAttributes which we can use to determine the necessary attributes to include.  With this knowledge we can make quick work of extending fluent html: public static class FluentHtmlExtensions { public static T IncludeUnobtrusiveValidationAttributes<T>(this T element, HtmlHelper htmlHelper) where T : MvcContrib.FluentHtml.Elements.IElement { IDictionary<string, object> validationAttributes = htmlHelper .GetUnobtrusiveValidationAttributes(element.GetAttr("name"));   foreach (var validationAttribute in validationAttributes) { element.SetAttr(validationAttribute.Key, validationAttribute.Value); }   return element; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } The code is pretty straight forward – basically we use a passed HtmlHelper to get a list of validation attributes for the current element and then add each of the returned attributes to the element to be rendered. The Extension In Action Now let’s get back to the earlier ShipAddress example and see what we’ve accomplished.  First we will use a fluent html helper to render out the ship address text input (this is the ‘before’ case): @this.TextBox("Order.ShipAddress").Label("Ship Address:").Class("class-name") .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } And the resulting HTML: <label id="Order_ShipAddress_Label" for="Order_ShipAddress">Ship Address:</label> <input type="text" value="Rua do Paço, 67" name="Order.ShipAddress" id="Order_ShipAddress" class="class-name"> Now let’s do the same thing except here we’ll use the newly written extension method: @this.TextBox("Order.ShipAddress").Label("Ship Address:") .Class("class-name").IncludeUnobtrusiveValidationAttributes(Html) .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } And the resulting HTML: <label id="Order_ShipAddress_Label" for="Order_ShipAddress">Ship Address:</label> <input type="text" value="Rua do Paço, 67" name="Order.ShipAddress" id="Order_ShipAddress" data-val-required="The ShipAddress field is required." data-val-length-max="12" data-val-length="The field ShipAddress must be a string with a maximum length of 12." data-val="true" class="class-name"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Excellent!  Now we can continue to use unobtrusive validation and have the flexibility to use ASP.NET MVC’s Html helpers or MvcContrib’s fluent html helpers interchangeably, and every element will participate in client side validation. Wrap Up Overall I’m happy with this solution, although in the best case scenario MvcContrib would know about unobtrusive validation attributes and include them automatically (of course if it is enabled in the web.config file).  I know that MvcContrib allows you to author global behaviors, but that requires changing the base class of your views, which I am not willing to do. Enjoy!

    Read the article

< Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >