Search Results

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

Page 5/2160 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • ASP MVC Learning Path

    - by Tarik Setia
    I know C# (studied from "CLR via C#" and C# 4 Step by Step) ,SQL & HTML. I don't have any previous development experience with any other .net Technology. But I want to develop a web application. Are these skills enough to start learn ASP.net MVC (currently i am learning form www.asp.net/mvc)? And what should be my Learning Path from ABSOLUTE BEGINNER to MASTER. It would be helpful if you Suggest some books.

    Read the article

  • Yet Another ASP.NET MVC CRUD Tutorial

    - by Ricardo Peres
    I know that I have not posted much on MVC, mostly because I don’t use it on my daily life, but since I find it so interesting, and since it is gaining such popularity, I will be talking about it much more. This time, it’s about the most basic of scenarios: CRUD. Although there are several ASP.NET MVC tutorials out there that cover ordinary CRUD operations, I couldn’t find any that would explain how we can have also AJAX, optimistic concurrency control and validation, using Entity Framework Code First, so I set out to write one! I won’t go into explaining what is MVC, Code First or optimistic concurrency control, or AJAX, I assume you are all familiar with these concepts by now. Let’s consider an hypothetical use case, products. For simplicity, we only want to be able to either view a single product or edit this product. First, we need our model: 1: public class Product 2: { 3: public Product() 4: { 5: this.Details = new HashSet<OrderDetail>(); 6: } 7:  8: [Required] 9: [StringLength(50)] 10: public String Name 11: { 12: get; 13: set; 14: } 15:  16: [Key] 17: [ScaffoldColumn(false)] 18: [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 19: public Int32 ProductId 20: { 21: get; 22: set; 23: } 24:  25: [Required] 26: [Range(1, 100)] 27: public Decimal Price 28: { 29: get; 30: set; 31: } 32:  33: public virtual ISet<OrderDetail> Details 34: { 35: get; 36: protected set; 37: } 38:  39: [Timestamp] 40: [ScaffoldColumn(false)] 41: public Byte[] RowVersion 42: { 43: get; 44: set; 45: } 46: } Keep in mind that this is a simple scenario. Let’s see what we have: A class Product, that maps to a product record on the database; A product has a required (RequiredAttribute) Name property which can contain up to 50 characters (StringLengthAttribute); The product’s Price must be a decimal value between 1 and 100 (RangeAttribute); It contains a set of order details, for each time that it has been ordered, which we will not talk about (Details); The record’s primary key (mapped to property ProductId) comes from a SQL Server IDENTITY column generated by the database (KeyAttribute, DatabaseGeneratedAttribute); The table uses a SQL Server ROWVERSION (previously known as TIMESTAMP) column for optimistic concurrency control mapped to property RowVersion (TimestampAttribute). Then we will need a controller for viewing product details, which will located on folder ~/Controllers under the name ProductController: 1: public class ProductController : Controller 2: { 3: [HttpGet] 4: public ViewResult Get(Int32 id = 0) 5: { 6: if (id != 0) 7: { 8: using (ProductContext ctx = new ProductContext()) 9: { 10: return (this.View("Single", ctx.Products.Find(id) ?? new Product())); 11: } 12: } 13: else 14: { 15: return (this.View("Single", new Product())); 16: } 17: } 18: } If the requested product does not exist, or one was not requested at all, one with default values will be returned. I am using a view named Single to display the product’s details, more on that later. As you can see, it delegates the loading of products to an Entity Framework context, which is defined as: 1: public class ProductContext: DbContext 2: { 3: public DbSet<Product> Products 4: { 5: get; 6: set; 7: } 8: } Like I said before, I’ll keep it simple for now, only aggregate root Product is available. The controller will use the standard routes defined by the Visual Studio ASP.NET MVC 3 template: 1: routes.MapRoute( 2: "Default", // Route name 3: "{controller}/{action}/{id}", // URL with parameters 4: new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 5: ); Next, we need a view for displaying the product details, let’s call it Single, and have it located under ~/Views/Product: 1: <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Product>" %> 2: <!DOCTYPE html> 3:  4: <html> 5: <head runat="server"> 6: <title>Product</title> 7: <script src="/Scripts/jquery-1.7.2.js" type="text/javascript"></script> 1:  2: <script src="/Scripts/jquery-ui-1.8.19.js" type="text/javascript"> 1: </script> 2: <script src="/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"> 1: </script> 2: <script src="/Scripts/jquery.validate.js" type="text/javascript"> 1: </script> 2: <script src="/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"> 1: </script> 2: <script type="text/javascript"> 3: function onFailure(error) 4: { 5: } 6:  7: function onComplete(ctx) 8: { 9: } 10:  11: </script> 8: </head> 9: <body> 10: <div> 11: <% 1: : this.Html.ValidationSummary(false) %> 12: <% 1: using (this.Ajax.BeginForm("Edit", "Product", new AjaxOptions{ HttpMethod = FormMethod.Post.ToString(), OnSuccess = "onSuccess", OnFailure = "onFailure" })) { %> 13: <% 1: : this.Html.EditorForModel() %> 14: <input type="submit" name="submit" value="Submit" /> 15: <% 1: } %> 16: </div> 17: </body> 18: </html> Yes… I am using ASPX syntax… sorry about that!   I implemented an editor template for the Product class, which must be located on the ~/Views/Shared/EditorTemplates folder as file Product.ascx: 1: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Product>" %> 2: <div> 3: <%: this.Html.HiddenFor(model => model.ProductId) %> 4: <%: this.Html.HiddenFor(model => model.RowVersion) %> 5: <fieldset> 6: <legend>Product</legend> 7: <div class="editor-label"> 8: <%: this.Html.LabelFor(model => model.Name) %> 9: </div> 10: <div class="editor-field"> 11: <%: this.Html.TextBoxFor(model => model.Name) %> 12: <%: this.Html.ValidationMessageFor(model => model.Name) %> 13: </div> 14: <div class="editor-label"> 15: <%= this.Html.LabelFor(model => model.Price) %> 16: </div> 17: <div class="editor-field"> 18: <%= this.Html.TextBoxFor(model => model.Price) %> 19: <%: this.Html.ValidationMessageFor(model => model.Price) %> 20: </div> 21: </fieldset> 22: </div> One thing you’ll notice is, I am including both the ProductId and the RowVersion properties as hidden fields; they will come handy later or, so that we know what product and version we are editing. The other thing is the included JavaScript files: jQuery, jQuery UI and unobtrusive validations. Also, I am not using the Content extension method for translating relative URLs, because that way I would lose JavaScript intellisense for jQuery functions. OK, so, at this moment, I want to add support for AJAX and optimistic concurrency control. So I write a controller method like this: 1: [HttpPost] 2: [AjaxOnly] 3: [Authorize] 4: public JsonResult Edit(Product product) 5: { 6: if (this.TryValidateModel(product) == true) 7: { 8: using (BlogContext ctx = new BlogContext()) 9: { 10: Boolean success = false; 11:  12: ctx.Entry(product).State = (product.ProductId == 0) ? EntityState.Added : EntityState.Modified; 13:  14: try 15: { 16: success = (ctx.SaveChanges() == 1); 17: } 18: catch (DbUpdateConcurrencyException) 19: { 20: ctx.Entry(product).Reload(); 21: } 22:  23: return (this.Json(new { Success = success, ProductId = product.ProductId, RowVersion = Convert.ToBase64String(product.RowVersion) })); 24: } 25: } 26: else 27: { 28: return (this.Json(new { Success = false, ProductId = 0, RowVersion = String.Empty })); 29: } 30: } So, this method is only valid for HTTP POST requests (HttpPost), coming from AJAX (AjaxOnly, from MVC Futures), and from authenticated users (Authorize). It returns a JSON object, which is what you would normally use for AJAX requests, containing three properties: Success: a boolean flag; RowVersion: the current version of the ROWVERSION column as a Base-64 string; ProductId: the inserted product id, as coming from the database. If the product is new, it will be inserted into the database, and its primary key will be returned into the ProductId property. Success will be set to true; If a DbUpdateConcurrencyException occurs, it means that the value in the RowVersion property does not match the current ROWVERSION column value on the database, so the record must have been modified between the time that the page was loaded and the time we attempted to save the product. In this case, the controller just gets the new value from the database and returns it in the JSON object; Success will be false. Otherwise, it will be updated, and Success, ProductId and RowVersion will all have their values set accordingly. So let’s see how we can react to these situations on the client side. Specifically, we want to deal with these situations: The user is not logged in when the update/create request is made, perhaps the cookie expired; The optimistic concurrency check failed; All went well. So, let’s change our view: 1: <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Product>" %> 2: <%@ Import Namespace="System.Web.Security" %> 3:  4: <!DOCTYPE html> 5:  6: <html> 7: <head runat="server"> 8: <title>Product</title> 9: <script src="/Scripts/jquery-1.7.2.js" type="text/javascript"></script> 1:  2: <script src="/Scripts/jquery-ui-1.8.19.js" type="text/javascript"> 1: </script> 2: <script src="/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"> 1: </script> 2: <script src="/Scripts/jquery.validate.js" type="text/javascript"> 1: </script> 2: <script src="/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"> 1: </script> 2: <script type="text/javascript"> 3: function onFailure(error) 4: { 5: window.alert('An error occurred: ' + error); 6: } 7:  8: function onSuccess(ctx) 9: { 10: if (typeof (ctx.Success) != 'undefined') 11: { 12: $('input#ProductId').val(ctx.ProductId); 13: $('input#RowVersion').val(ctx.RowVersion); 14:  15: if (ctx.Success == false) 16: { 17: window.alert('An error occurred while updating the entity: it may have been modified by third parties. Please try again.'); 18: } 19: else 20: { 21: window.alert('Saved successfully'); 22: } 23: } 24: else 25: { 26: if (window.confirm('Not logged in. Login now?') == true) 27: { 28: document.location.href = '<%: FormsAuthentication.LoginUrl %>?ReturnURL=' + document.location.pathname; 29: } 30: } 31: } 32:  33: </script> 10: </head> 11: <body> 12: <div> 13: <% 1: : this.Html.ValidationSummary(false) %> 14: <% 1: using (this.Ajax.BeginForm("Edit", "Product", new AjaxOptions{ HttpMethod = FormMethod.Post.ToString(), OnSuccess = "onSuccess", OnFailure = "onFailure" })) { %> 15: <% 1: : this.Html.EditorForModel() %> 16: <input type="submit" name="submit" value="Submit" /> 17: <% 1: } %> 18: </div> 19: </body> 20: </html> The implementation of the onSuccess function first checks if the response contains a Success property, if not, the most likely cause is the request was redirected to the login page (using Forms Authentication), because it wasn’t authenticated, so we navigate there as well, keeping the reference to the current page. It then saves the current values of the ProductId and RowVersion properties to their respective hidden fields. They will be sent on each successive post and will be used in determining if the request is for adding a new product or to updating an existing one. The only thing missing is the ability to insert a new product, after inserting/editing an existing one, which can be easily achieved using this snippet: 1: <input type="button" value="New" onclick="$('input#ProductId').val('');$('input#RowVersion').val('');"/> And that’s it.

    Read the article

  • Announcing the ASP.NET and Web Tools 2012.2 Release Candidate

    - by ScottGu
    This week the ASP.NET and Visual Web Developer teams delivered the Release Candidate of the ASP.NET and Web Tools 2012.2 update (formerly ASP.NET Fall 2012 Update BUILD Prerelease). This update extends the existing ASP.NET runtime and adds new web tooling to Visual Studio 2012. Whether you use Web Forms, MVC, Web API, or any other ASP.NET technology, there is something cool in this update for you. You can download and install the RC today: http://www.asp.net/vnext. Great ASP.NET Enhancements This update adds new ASP.NET templates and features, including: New ASP.NET MVC templates. Creating Facebook applications just became easier using the new Facebook Application template. In just a few easy steps you can create a Facebook application that gets data from the logged in user as well as integrates with their friends. A new Single Page Application template allows developers to build interactive client-side web apps using Knockout, jQuery, and ASP.NET Web API. Real-time communication support with ASP.NET SignalR.  This enables you to easily take advantage of the new WebSocket support in .NET 4.5, while also automatically degrading to long-polling and other protocols for older clients.  If you haven’t tried SignalR yet you should – it is awesome. New ASP.NET Web API functionality, including support for OData, integrated tracing, and automatically generating help page documentation for your API. New ASP.NET Friendly URL functionality. This new feature makes it very easy for Web Forms developers to generate cleaner looking URLs (without the .aspx extension). The Friendly URLs feature also makes it easier for developers to add mobile support to their applications with support for mobile .ASPX pages and  supporting switching between desktop and mobile views. It can be used with existing ASP.NET v4.0 applications. Visual Studio 2012 Web publishing enhancements. Web site projects now have the same publish experience as web application projects (including to Windows Azure Web Sites), and you can selectively publish files, see the differences between local and remote files, and update local to remote files or vice versa. Visual Studio 2012 Page Inspector enhancements. JavaScript selection mapping is now supported, and you can CSS updates in real-time. Visual Studio 2012 editor support for Knockout IntelliSense and pasting JSON as a .NET class (which makes it even easier to consume Web APIs from others). Visual Studio 2012 Project Template updates, including the latest versions of jQuery, jQuery UI, jQuery Validation, Modernirz, Knockout and more… How it is delivered You can download and install an integrated setup that contains the above enhancements today from http://www.asp.net/vnext. The new runtime functionality is delivered to ASP.NET via additional NuGet packages. This means that installing this update does not make any changes to the existing ASP.NET binaries, and thus does not cause any compatibility issues with existing projects. New projects will contain the new functionality and existing projects can be updated with the new NuGet packages. Summary Web development is changing, and ASP.NET is rapidly delivering new capabilities to developers that help them take full advantage of new capabilities.  The ASP.NET and Web Tools 2012.2 update installs in minutes without altering the current ASP.NET run time components. For a complete description see the Release Notes. Next week I plan to publish a tutorial showing how to build a cool Facebook application using the new Facebook template. Hope this helps, Scott P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

    Read the article

  • ASP.NET MVC CRUD Validation

    - by Ricardo Peres
    One thing I didn’t refer on my previous post on ASP.NET MVC CRUD with AJAX was how to retrieve model validation information into the client. We want to send any model validation errors to the client in the JSON object that contains the ProductId, RowVersion and Success properties, specifically, if there are any errors, we will add an extra Errors collection property. Here’s how: 1: [HttpPost] 2: [AjaxOnly] 3: [Authorize] 4: public JsonResult Edit(Product product) 5: { 6: if (this.ModelState.IsValid == true) 7: { 8: using (ProductContext ctx = new ProductContext()) 9: { 10: Boolean success = false; 11:  12: ctx.Entry(product).State = (product.ProductId == 0) ? EntityState.Added : EntityState.Modified; 13:  14: try 15: { 16: success = (ctx.SaveChanges() == 1); 17: } 18: catch (DbUpdateConcurrencyException) 19: { 20: ctx.Entry(product).Reload(); 21: } 22:  23: return (this.Json(new { Success = success, ProductId = product.ProductId, RowVersion = Convert.ToBase64String(product.RowVersion) })); 24: } 25: } 26: else 27: { 28: Dictionary<String, String> errors = new Dictionary<String, String>(); 29:  30: foreach (KeyValuePair<String, ModelState> keyValue in this.ModelState) 31: { 32: String key = keyValue.Key; 33: ModelState modelState = keyValue.Value; 34:  35: foreach (ModelError error in modelState.Errors) 36: { 37: errors[key] = error.ErrorMessage; 38: } 39: } 40:  41: return (this.Json(new { Success = false, ProductId = 0, RowVersion = String.Empty, Errors = errors })); 42: } 43: } As for the view, we need to change slightly the onSuccess JavaScript handler on the Single view: 1: function onSuccess(ctx) 2: { 3: if (typeof (ctx.Success) != 'undefined') 4: { 5: $('input#ProductId').val(ctx.ProductId); 6: $('input#RowVersion').val(ctx.RowVersion); 7:  8: if (ctx.Success == false) 9: { 10: var errors = ''; 11:  12: if (typeof (ctx.Errors) != 'undefined') 13: { 14: for (var key in ctx.Errors) 15: { 16: errors += key + ': ' + ctx.Errors[key] + '\n'; 17: } 18:  19: window.alert('An error occurred while updating the entity: the model contained the following errors.\n\n' + errors); 20: } 21: else 22: { 23: window.alert('An error occurred while updating the entity: it may have been modified by third parties. Please try again.'); 24: } 25: } 26: else 27: { 28: window.alert('Saved successfully'); 29: } 30: } 31: else 32: { 33: if (window.confirm('Not logged in. Login now?') == true) 34: { 35: document.location.href = '<% 1: : FormsAuthentication.LoginUrl %>?ReturnURL=' + document.location.pathname; 36: } 37: } 38: } The logic is as this: If the Edit action method is called for a new entity (the ProductId is 0) and it is valid, the entity is saved, and the JSON results contains a Success flag set to true, a ProductId property with the database-generated primary key and a RowVersion with the server-generated ROWVERSION; If the model is not valid, the JSON result will contain the Success flag set to false and the Errors collection populated with all the model validation errors; If the entity already exists in the database (ProductId not 0) and the model is valid, but the stored ROWVERSION is different that the one on the view, the result will set the Success property to false and will return the current (as loaded from the database) value of the ROWVERSION on the RowVersion property. On a future post I will talk about the possibilities that exist for performing model validation, stay tuned!

    Read the article

  • Posting xml from classic asp to asp.net

    - by Chris Dunaway
    I apologize if this has been asked before. I searched and didn't find anything that matched my situation. Also bear in mind I am fairly new to asp/asp.net development. My current project is a relatively simple e-commerce site. The customer will connect to the site, select products, input shipping and billing information, payment information (credit card) and submit the order. The project is being split into two parts: The store front which includes displaying the items and taking the customer's shipping and billing information and the payment site which will collect the customers credit card, compute tax, and save the order into the company's system. The reason that the site was split up, was that our side (payment side) already has facilities for credit card handling and tax computation. There may also be some regulatory issues that the store front side does not want to deal with (which we already do). I'm working on the payment portion of the app and I am using asp.net. The store front side is being written in classic asp (not my decision). Each part will be hosted on different servers. The problem I am having is transferring the contents of the "shopping cart" to our app so that we can collect the cc info and submit the order. We had thought that the classic asp could somehow post an xml fragment which contains the billing/shipping info and the items selected. Our side would display a summary of the order, securely collect the credit card info, and submit the order to our system. But I have been unable to post or send the xml from a classic asp on one server, to our asp.net application on another. It all works just fine when I test on the same server. How can I post (or otherwise transfer) the shopping cart data from classic asp to asp.net across server boundaries and transfer control to the asp.net application? As I said, I am new to web development, so this is proving quite a challenge for me. Thanks

    Read the article

  • Enabling Http caching and compression in IIS 7 for asp.net websites

    - by anil.kasalanati
    Caching – There are 2 ways to set Http caching 1-      Use Max age property 2-      Expires header. Doing the changes via IIS Console – 1.       Select the website for which you want to enable caching and then select Http Responses in the features tab       2.       Select the Expires webcontent and on changing the After setting you can generate the max age property for the cache control    3.       Following is the screenshot of the headers   Then you can use some tool like fiddler and see 302 response coming from the server. Doing it web.config way – We can add static content section in the system.webserver section <system.webServer>   <staticContent>             <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />   </staticContent> Compression - By default static compression is enabled on IIS 7.0 but the only thing which falls under that category is CSS but this is not enough for most of the websites using lots of javascript.  If you just thought by enabling dynamic compression would fix this then you are wrong so please follow following steps –   In some machines the dynamic compression is not enabled and following are the steps to enable it – Open server manager Roles > Web Server (IIS) Role Services (scroll down) > Add Role Services Add desired role (Web Server > Performance > Dynamic Content Compression) Next, Install, Wait…Done!   ?  Roles > Web Server (IIS) ?  Role Services (scroll down) > Add Role Services     Add desired role (Web Server > Performance > Dynamic Content Compression)     Next, Install, Wait…Done!     Enable  - ?  Open server manager ?  Roles > Web Server (IIS) > Internet Information Services (IIS) Manager   Next pane: Sites > Default Web Site > Your Web Site Main pane: IIS > Compression         Then comes the custom configuration for encrypting javascript resources. The problem is that the compression in IIS 7 completely works on the mime types and by default there is a mismatch in the mime types Go to following location C:\Windows\System32\inetsrv\config Open applicationHost.config The mimemap is as follows  <mimeMap fileExtension=".js" mimeType="application/javascript" />   So the section in the staticTypes should be changed          <add mimeType="application/javascript" enabled="true" />     Doing the web.config way –   We can add following section in the system.webserver section <system.webServer> <urlCompression doDynamicCompression="false"  doStaticCompression="true"/> More Information/References – ·         http://weblogs.asp.net/owscott/archive/2009/02/22/iis-7-compression-good-bad-how-much.aspx ·         http://www.west-wind.com/weblog/posts/98538.aspx  

    Read the article

  • Apt-Get Update: failure to fetch; can't connect to any sources

    - by weberc2
    I realize there are dozens of "apt-get update: failure to fetch" questions (I read through all I could find), but my present circumstance is unique to 12.04 and it affects all sources; not just launchpad. Additionally, I've tried several different servers in Europe and the U.S. as well as the "main server" (wherever that is) and they all yield the same result: I can't connect to any software sources. Additionally, I'm fairly certain the problem stems from the upgrade from 11.10-12.04 I performed this morning, as updates worked immediately before. Updates from the Update Manager worked fine and I could download some things (mutter) from the Software Center without incident, which makes me think I can connect to some subset of the Ubuntu servers (however, several other Ubuntu servers--like extras--and some canonical servers are listed as 'unable to connect'). Here is the output from sudo apt-get update: sudo apt-get update Ign http://ftp.u-picardie.fr precise InRelease Ign http://archive.canonical.com precise InRelease Ign http://ftp.u-picardie.fr precise-updates InRelease Ign http://ftp.u-picardie.fr precise-backports InRelease Err http://ftp.u-picardie.fr precise-security InRelease Err http://ftp.u-picardie.fr precise Release.gpg Unable to connect to ftp.u-picardie.fr:http: Err http://ftp.u-picardie.fr precise-updates Release.gpg Unable to connect to ftp.u-picardie.fr:http: Err http://ftp.u-picardie.fr precise-backports Release.gpg Unable to connect to ftp.u-picardie.fr:http: Err http://ftp.u-picardie.fr precise-security Release.gpg Unable to connect to ftp.u-picardie.fr:http: Hit http://archive.canonical.com precise Release.gpg Hit http://archive.canonical.com precise Release Hit http://archive.canonical.com precise/partner i386 Packages Ign http://archive.canonical.com precise/partner TranslationIndex Ign http://dl.google.com stable InRelease Ign http://dl.google.com stable InRelease Err http://archive.canonical.com precise/partner Translation-en_US Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] Err http://archive.canonical.com precise/partner Translation-en Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] Ign http://extras.ubuntu.com precise InRelease Get:1 http://dl.google.com stable Release.gpg [198 B] Err http://extras.ubuntu.com precise Release.gpg Could not connect to extras.ubuntu.com:80 (91.189.88.33). - connect (111: Connection refused) Ign http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Get:2 http://dl.google.com stable Release.gpg [198 B] Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Get:3 http://dl.google.com stable Release [1,347 B] Get:4 http://dl.google.com stable Release [1,347 B] Get:5 http://dl.google.com stable/main i386 Packages [1,268 B] Ign http://dl.google.com stable/main TranslationIndex Get:6 http://dl.google.com stable/main i386 Packages [769 B] Ign http://dl.google.com stable/main TranslationIndex Ign http://dl.google.com stable/main Translation-en_US Ign http://dl.google.com stable/main Translation-en Ign http://dl.google.com stable/main Translation-en_US Ign http://dl.google.com stable/main Translation-en Fetched 5,127 B in 7s (673 B/s) Reading package lists... Done W: Failed to fetch http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/dists/precise-security/InRelease W: Failed to fetch http://ppa.launchpad.net/elementary-os/stable/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/elementaryart/elementary-dev/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/midori/ppa/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/nemequ/sqlheavy/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/ricotz/docky/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/sgringwe/beatbox/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/webupd8team/y-ppa-manager/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/yorba/ppa/ubuntu/dists/precise/InRelease W: Failed to fetch http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/dists/precise/Release.gpg Unable to connect to ftp.u-picardie.fr:http: W: Failed to fetch http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/dists/precise-updates/Release.gpg Unable to connect to ftp.u-picardie.fr:http: W: Failed to fetch http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/dists/precise-backports/Release.gpg Unable to connect to ftp.u-picardie.fr:http: W: Failed to fetch http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/dists/precise-security/Release.gpg Unable to connect to ftp.u-picardie.fr:http: W: Failed to fetch http://archive.canonical.com/ubuntu/dists/precise/partner/i18n/Translation-en_US Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] W: Failed to fetch http://archive.canonical.com/ubuntu/dists/precise/partner/i18n/Translation-en Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] W: Failed to fetch http://extras.ubuntu.com/ubuntu/dists/precise/Release.gpg Could not connect to extras.ubuntu.com:80 (91.189.88.33). - connect (111: Connection refused) W: Failed to fetch http://ppa.launchpad.net/caffeine-developers/ppa/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/elementary-os/stable/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/elementaryart/elementary-dev/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/midori/ppa/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/nemequ/sqlheavy/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/ricotz/docky/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/sgringwe/beatbox/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/webupd8team/y-ppa-manager/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/yorba/ppa/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Some index files failed to download. They have been ignored, or old ones used instead. W: Duplicate sources.list entry http://ppa.launchpad.net/nemequ/sqlheavy/ubuntu/ precise/main i386 Packages (/var/lib/apt/lists/ppa.launchpad.net_nemequ_sqlheavy_ubuntu_dists_precise_main_binary-i386_Packages) W: Duplicate sources.list entry http://ppa.launchpad.net/sgringwe/beatbox/ubuntu/ precise/main i386 Packages (/var/lib/apt/lists/ppa.launchpad.net_sgringwe_beatbox_ubuntu_dists_precise_main_binary-i386_Packages) Contents of /etc/apt/sources.list: # deb cdrom:[Ubuntu 11.10 _Oneiric Ocelot_ - Release i386 (20111012)]/ oneiric main restricted deb-src http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise main restricted #Added by software-properties # See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to # newer versions of the distribution. deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise main restricted deb-src http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise multiverse universe #Added by software-properties ## Major bug fix updates produced after the final release of the ## distribution. deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-updates main restricted deb-src http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-updates restricted main multiverse universe #Added by software-properties ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team. Also, please note that software in universe WILL NOT receive any ## review or updates from the Ubuntu security team. deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise universe deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-updates universe ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team, and may not be under a free licence. Please satisfy yourself as to ## your rights to use the software. Also, please note that software in ## multiverse WILL NOT receive any review or updates from the Ubuntu ## security team. deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise multiverse deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-updates multiverse ## N.B. software from this repository may not have been tested as ## extensively as that contained in the main release, although it includes ## newer versions of some applications which may provide useful features. ## Also, please note that software in backports WILL NOT receive any review ## or updates from the Ubuntu security team. deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-backports main restricted universe multiverse deb-src http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-backports main restricted universe multiverse #Added by software-properties deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-security main restricted deb-src http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-security restricted main multiverse universe #Added by software-properties deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-security universe deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-security multiverse ## Uncomment the following two lines to add software from Canonical's ## 'partner' repository. ## This software is not part of Ubuntu, but is offered by Canonical and the ## respective vendors as a service to Ubuntu users. # deb http://archive.canonical.com/ubuntu oneiric partner # deb-src http://archive.canonical.com/ubuntu oneiric partner ## This software is not part of Ubuntu, but is offered by third-party ## developers who want to ship their latest software. deb http://extras.ubuntu.com/ubuntu precise main deb-src http://extras.ubuntu.com/ubuntu precise main Testing Alternate sources.list file These are the steps I followed to produce the following output: Please backup your sources.list: sudo cp /etc/apt/sources.list /etc/apt/sources.list.backup and then replace the contents of /etc/apt/sources.list with the below lines and run apt-get update: deb http://archive.ubuntu.com/ubuntu/ precise main restricted universe multiverse deb http://archive.ubuntu.com/ubuntu/ precise-updates main restricted universe multiverse deb http://archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu precise-security main restricted universe multiverse deb http://archive.canonical.com/ubuntu precise partner deb http://extras.ubuntu.com/ubuntu precise main Output: someone@someone-UBook:~$ sudo apt-get update Ign http://archive.canonical.com precise InRelease Hit http://archive.canonical.com precise Release.gpg Hit http://archive.canonical.com precise Release Ign http://archive.ubuntu.com precise InRelease Ign http://extras.ubuntu.com precise InRelease Ign http://archive.ubuntu.com precise-updates InRelease Hit http://archive.canonical.com precise/partner i386 Packages Hit http://extras.ubuntu.com precise Release.gpg Ign http://archive.ubuntu.com precise-backports InRelease Ign http://archive.canonical.com precise/partner TranslationIndex Err http://archive.canonical.com precise/partner Translation-en_US Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] Err http://archive.canonical.com precise/partner Translation-en Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] Hit http://extras.ubuntu.com precise Release Get:1 http://archive.ubuntu.com precise Release.gpg [198 B] Ign http://dl.google.com stable InRelease Err http://dl.google.com stable InRelease Err http://dl.google.com stable Release.gpg Unable to connect to dl.google.com:http: [IP: 173.194.34.38 80] Err http://dl.google.com stable Release.gpg Unable to connect to dl.google.com:http: [IP: 173.194.34.38 80] Get:2 http://archive.ubuntu.com precise-updates Release.gpg [198 B] Hit http://extras.ubuntu.com precise/main i386 Packages Get:3 http://archive.ubuntu.com precise-backports Release.gpg [198 B] Ign http://security.ubuntu.com precise-security InRelease Ign http://extras.ubuntu.com precise/main TranslationIndex Err http://extras.ubuntu.com precise/main Translation-en_US Unable to connect to extras.ubuntu.com:http: Err http://extras.ubuntu.com precise/main Translation-en Unable to connect to extras.ubuntu.com:http: Get:4 http://security.ubuntu.com precise-security Release.gpg [198 B] Get:5 http://archive.ubuntu.com precise Release [49.6 kB] Get:6 http://security.ubuntu.com precise-security Release [49.6 kB] Get:7 http://archive.ubuntu.com precise-updates Release [49.6 kB] Get:8 http://archive.ubuntu.com precise-backports Release [49.6 kB] Get:9 http://security.ubuntu.com precise-security/main i386 Packages [32.9 kB] Get:10 http://archive.ubuntu.com precise/main i386 Packages [1,274 kB] Get:11 http://security.ubuntu.com precise-security/restricted i386 Packages [14 B] Get:12 http://security.ubuntu.com precise-security/universe i386 Packages [8,594 B] Get:13 http://security.ubuntu.com precise-security/multiverse i386 Packages [1,393 B] Get:14 http://security.ubuntu.com precise-security/main TranslationIndex [73 B] Get:15 http://security.ubuntu.com precise-security/multiverse TranslationIndex [71 B] Get:16 http://security.ubuntu.com precise-security/restricted TranslationIndex [70 B] Get:17 http://security.ubuntu.com precise-security/universe TranslationIndex [72 B] Get:18 http://security.ubuntu.com precise-security/main Translation-en [13.6 kB] Get:19 http://security.ubuntu.com precise-security/multiverse Translation-en [587 B] Get:20 http://security.ubuntu.com precise-security/restricted Translation-en [14 B] Get:21 http://security.ubuntu.com precise-security/universe Translation-en [6,261 B] Get:22 http://archive.ubuntu.com precise/restricted i386 Packages [8,431 B] Get:23 http://archive.ubuntu.com precise/universe i386 Packages [4,796 kB] Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Get:24 http://ppa.launchpad.net precise Release.gpg [316 B] Get:25 http://ppa.launchpad.net precise Release.gpg [316 B] Get:26 http://ppa.launchpad.net precise Release.gpg [316 B] Ign http://ppa.launchpad.net precise Release.gpg Get:27 http://ppa.launchpad.net precise Release.gpg [316 B] Hit http://ppa.launchpad.net precise Release.gpg Get:28 http://ppa.launchpad.net precise Release.gpg [316 B] Get:29 http://ppa.launchpad.net precise Release.gpg [316 B] Hit http://ppa.launchpad.net precise Release.gpg Get:30 http://ppa.launchpad.net precise Release.gpg [316 B] Hit http://ppa.launchpad.net precise Release.gpg Get:31 http://ppa.launchpad.net precise Release [11.9 kB] Get:32 http://ppa.launchpad.net precise Release [11.9 kB] Get:33 http://archive.ubuntu.com precise/multiverse i386 Packages [121 kB] Get:34 http://ppa.launchpad.net precise Release [11.9 kB] Ign http://ppa.launchpad.net precise Release Get:35 http://ppa.launchpad.net precise Release [11.9 kB] Hit http://archive.ubuntu.com precise/main TranslationIndex Hit http://archive.ubuntu.com precise/multiverse TranslationIndex Hit http://ppa.launchpad.net precise Release Hit http://archive.ubuntu.com precise/restricted TranslationIndex Get:36 http://ppa.launchpad.net precise Release [11.9 kB] Hit http://archive.ubuntu.com precise/universe TranslationIndex Get:37 http://ppa.launchpad.net precise Release [11.9 kB] Get:38 http://archive.ubuntu.com precise-updates/main i386 Packages [96.5 kB] Hit http://ppa.launchpad.net precise Release Get:39 http://ppa.launchpad.net precise Release [11.9 kB] Get:40 http://archive.ubuntu.com precise-updates/restricted i386 Packages [770 B] Hit http://ppa.launchpad.net precise Release Get:41 http://archive.ubuntu.com precise-updates/universe i386 Packages [27.7 kB] Get:42 http://ppa.launchpad.net precise/main Sources [524 B] Get:43 http://archive.ubuntu.com precise-updates/multiverse i386 Packages [1,393 B] Get:44 http://ppa.launchpad.net precise/main i386 Packages [507 B] Hit http://archive.ubuntu.com precise-updates/main TranslationIndex Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://archive.ubuntu.com precise-updates/multiverse TranslationIndex Hit http://archive.ubuntu.com precise-updates/restricted TranslationIndex Get:45 http://ppa.launchpad.net precise/main Sources [932 B] Hit http://archive.ubuntu.com precise-updates/universe TranslationIndex Get:46 http://ppa.launchpad.net precise/main i386 Packages [1,017 B] Get:47 http://archive.ubuntu.com precise-backports/main i386 Packages [559 B] Ign http://ppa.launchpad.net precise/main TranslationIndex Get:48 http://archive.ubuntu.com precise-backports/restricted i386 Packages [14 B] Get:49 http://archive.ubuntu.com precise-backports/universe i386 Packages [1,391 B] Get:50 http://ppa.launchpad.net precise/main Sources [1,402 B] Get:51 http://archive.ubuntu.com precise-backports/multiverse i386 Packages [14 B] Hit http://archive.ubuntu.com precise-backports/main TranslationIndex Get:52 http://ppa.launchpad.net precise/main i386 Packages [1,605 B] Hit http://archive.ubuntu.com precise-backports/multiverse TranslationIndex Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://archive.ubuntu.com precise-backports/restricted TranslationIndex Hit http://archive.ubuntu.com precise-backports/universe TranslationIndex Hit http://archive.ubuntu.com precise/main Translation-en Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://archive.ubuntu.com precise/multiverse Translation-en Get:53 http://ppa.launchpad.net precise/main Sources [931 B] Hit http://archive.ubuntu.com precise/restricted Translation-en Get:54 http://ppa.launchpad.net precise/main i386 Packages [1,079 B] Hit http://archive.ubuntu.com precise/universe Translation-en Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://archive.ubuntu.com precise-updates/main Translation-en Hit http://ppa.launchpad.net precise/main Sources Hit http://archive.ubuntu.com precise-updates/multiverse Translation-en Hit http://ppa.launchpad.net precise/main i386 Packages Hit http://archive.ubuntu.com precise-updates/restricted Translation-en Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://archive.ubuntu.com precise-updates/universe Translation-en Get:55 http://ppa.launchpad.net precise/main Sources [3,611 B] Hit http://archive.ubuntu.com precise-backports/main Translation-en Get:56 http://ppa.launchpad.net precise/main i386 Packages [2,468 B] Hit http://archive.ubuntu.com precise-backports/multiverse Translation-en Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://archive.ubuntu.com precise-backports/restricted Translation-en Hit http://archive.ubuntu.com precise-backports/universe Translation-en Get:57 http://ppa.launchpad.net precise/main Sources [1,524 B] Get:58 http://ppa.launchpad.net precise/main i386 Packages [2,719 B] Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net precise/main Sources Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://ppa.launchpad.net precise/main TranslationIndex Get:59 http://ppa.launchpad.net precise/main Sources [1,052 B] Get:60 http://ppa.launchpad.net precise/main i386 Packages [1,388 B] Ign http://ppa.launchpad.net precise/main TranslationIndex Get:61 http://ppa.launchpad.net precise/main Sources [1,185 B] Get:62 http://ppa.launchpad.net precise/main i386 Packages [1,698 B] Ign http://ppa.launchpad.net precise/main TranslationIndex Err http://ppa.launchpad.net precise/main Sources 404 Not Found Err http://ppa.launchpad.net precise/main i386 Packages 404 Not Found Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Fetched 6,699 kB in 15s (445 kB/s) Reading package lists... Done W: Failed to fetch http://dl.google.com/linux/talkplugin/deb/dists/stable/InRelease W: Failed to fetch http://archive.canonical.com/ubuntu/dists/precise/partner/i18n/Translation-en_US Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] W: Failed to fetch http://archive.canonical.com/ubuntu/dists/precise/partner/i18n/Translation-en Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] W: Failed to fetch http://dl.google.com/linux/chrome/deb/dists/sta

    Read the article

  • 12.04: Apt-Get Update: failure to fetch; can't connect to any sources

    - by weberc2
    I realize there are dozens of "apt-get update: failure to fetch" questions (I read through all I could find), but my present circumstance is unique to 12.04 and it affects all sources; not just launchpad. Additionally, I've tried several different servers in Europe and the U.S. as well as the "main server" (wherever that is) and they all yield the same result: I can't connect to any software sources. Additionally, I'm fairly certain the problem stems from the upgrade from 11.10-12.04 I performed this morning, as updates worked immediately before. Updates from the Update Manager worked fine and I could download some things (mutter) from the Software Center without incident, which makes me think I can connect to some subset of the Ubuntu servers (however, several other Ubuntu servers--like extras--and some canonical servers are listed as 'unable to connect'). Here is the output from sudo apt-get update: sudo apt-get update Ign http://ftp.u-picardie.fr precise InRelease Ign http://archive.canonical.com precise InRelease Ign http://ftp.u-picardie.fr precise-updates InRelease Ign http://ftp.u-picardie.fr precise-backports InRelease Err http://ftp.u-picardie.fr precise-security InRelease Err http://ftp.u-picardie.fr precise Release.gpg Unable to connect to ftp.u-picardie.fr:http: Err http://ftp.u-picardie.fr precise-updates Release.gpg Unable to connect to ftp.u-picardie.fr:http: Err http://ftp.u-picardie.fr precise-backports Release.gpg Unable to connect to ftp.u-picardie.fr:http: Err http://ftp.u-picardie.fr precise-security Release.gpg Unable to connect to ftp.u-picardie.fr:http: Hit http://archive.canonical.com precise Release.gpg Hit http://archive.canonical.com precise Release Hit http://archive.canonical.com precise/partner i386 Packages Ign http://archive.canonical.com precise/partner TranslationIndex Ign http://dl.google.com stable InRelease Ign http://dl.google.com stable InRelease Err http://archive.canonical.com precise/partner Translation-en_US Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] Err http://archive.canonical.com precise/partner Translation-en Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] Ign http://extras.ubuntu.com precise InRelease Get:1 http://dl.google.com stable Release.gpg [198 B] Err http://extras.ubuntu.com precise Release.gpg Could not connect to extras.ubuntu.com:80 (91.189.88.33). - connect (111: Connection refused) Ign http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Err http://ppa.launchpad.net precise InRelease Get:2 http://dl.google.com stable Release.gpg [198 B] Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Err http://ppa.launchpad.net precise Release.gpg Unable to connect to ppa.launchpad.net:http: Get:3 http://dl.google.com stable Release [1,347 B] Get:4 http://dl.google.com stable Release [1,347 B] Get:5 http://dl.google.com stable/main i386 Packages [1,268 B] Ign http://dl.google.com stable/main TranslationIndex Get:6 http://dl.google.com stable/main i386 Packages [769 B] Ign http://dl.google.com stable/main TranslationIndex Ign http://dl.google.com stable/main Translation-en_US Ign http://dl.google.com stable/main Translation-en Ign http://dl.google.com stable/main Translation-en_US Ign http://dl.google.com stable/main Translation-en Fetched 5,127 B in 7s (673 B/s) Reading package lists... Done W: Failed to fetch http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/dists/precise-security/InRelease W: Failed to fetch http://ppa.launchpad.net/elementary-os/stable/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/elementaryart/elementary-dev/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/midori/ppa/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/nemequ/sqlheavy/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/ricotz/docky/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/sgringwe/beatbox/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/webupd8team/y-ppa-manager/ubuntu/dists/precise/InRelease W: Failed to fetch http://ppa.launchpad.net/yorba/ppa/ubuntu/dists/precise/InRelease W: Failed to fetch http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/dists/precise/Release.gpg Unable to connect to ftp.u-picardie.fr:http: W: Failed to fetch http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/dists/precise-updates/Release.gpg Unable to connect to ftp.u-picardie.fr:http: W: Failed to fetch http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/dists/precise-backports/Release.gpg Unable to connect to ftp.u-picardie.fr:http: W: Failed to fetch http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/dists/precise-security/Release.gpg Unable to connect to ftp.u-picardie.fr:http: W: Failed to fetch http://archive.canonical.com/ubuntu/dists/precise/partner/i18n/Translation-en_US Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] W: Failed to fetch http://archive.canonical.com/ubuntu/dists/precise/partner/i18n/Translation-en Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] W: Failed to fetch http://extras.ubuntu.com/ubuntu/dists/precise/Release.gpg Could not connect to extras.ubuntu.com:80 (91.189.88.33). - connect (111: Connection refused) W: Failed to fetch http://ppa.launchpad.net/caffeine-developers/ppa/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/elementary-os/stable/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/elementaryart/elementary-dev/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/midori/ppa/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/nemequ/sqlheavy/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/ricotz/docky/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/sgringwe/beatbox/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/webupd8team/y-ppa-manager/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Failed to fetch http://ppa.launchpad.net/yorba/ppa/ubuntu/dists/precise/Release.gpg Unable to connect to ppa.launchpad.net:http: W: Some index files failed to download. They have been ignored, or old ones used instead. W: Duplicate sources.list entry http://ppa.launchpad.net/nemequ/sqlheavy/ubuntu/ precise/main i386 Packages (/var/lib/apt/lists/ppa.launchpad.net_nemequ_sqlheavy_ubuntu_dists_precise_main_binary-i386_Packages) W: Duplicate sources.list entry http://ppa.launchpad.net/sgringwe/beatbox/ubuntu/ precise/main i386 Packages (/var/lib/apt/lists/ppa.launchpad.net_sgringwe_beatbox_ubuntu_dists_precise_main_binary-i386_Packages) Contents of /etc/apt/sources.list: # deb cdrom:[Ubuntu 11.10 _Oneiric Ocelot_ - Release i386 (20111012)]/ oneiric main restricted deb-src http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise main restricted #Added by software-properties # See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to # newer versions of the distribution. deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise main restricted deb-src http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise multiverse universe #Added by software-properties ## Major bug fix updates produced after the final release of the ## distribution. deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-updates main restricted deb-src http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-updates restricted main multiverse universe #Added by software-properties ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team. Also, please note that software in universe WILL NOT receive any ## review or updates from the Ubuntu security team. deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise universe deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-updates universe ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team, and may not be under a free licence. Please satisfy yourself as to ## your rights to use the software. Also, please note that software in ## multiverse WILL NOT receive any review or updates from the Ubuntu ## security team. deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise multiverse deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-updates multiverse ## N.B. software from this repository may not have been tested as ## extensively as that contained in the main release, although it includes ## newer versions of some applications which may provide useful features. ## Also, please note that software in backports WILL NOT receive any review ## or updates from the Ubuntu security team. deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-backports main restricted universe multiverse deb-src http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-backports main restricted universe multiverse #Added by software-properties deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-security main restricted deb-src http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-security restricted main multiverse universe #Added by software-properties deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-security universe deb http://ftp.u-picardie.fr/mirror/ubuntu/ubuntu/ precise-security multiverse ## Uncomment the following two lines to add software from Canonical's ## 'partner' repository. ## This software is not part of Ubuntu, but is offered by Canonical and the ## respective vendors as a service to Ubuntu users. # deb http://archive.canonical.com/ubuntu oneiric partner # deb-src http://archive.canonical.com/ubuntu oneiric partner ## This software is not part of Ubuntu, but is offered by third-party ## developers who want to ship their latest software. deb http://extras.ubuntu.com/ubuntu precise main deb-src http://extras.ubuntu.com/ubuntu precise main Testing Alternate sources.list file These are the steps I followed to produce the following output: Please backup your sources.list: sudo cp /etc/apt/sources.list /etc/apt/sources.list.backup and then replace the contents of /etc/apt/sources.list with the below lines and run apt-get update: deb http://archive.ubuntu.com/ubuntu/ precise main restricted universe multiverse deb http://archive.ubuntu.com/ubuntu/ precise-updates main restricted universe multiverse deb http://archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu precise-security main restricted universe multiverse deb http://archive.canonical.com/ubuntu precise partner deb http://extras.ubuntu.com/ubuntu precise main Output: someone@someone-UBook:~$ sudo apt-get update Ign http://archive.canonical.com precise InRelease Hit http://archive.canonical.com precise Release.gpg Hit http://archive.canonical.com precise Release Ign http://archive.ubuntu.com precise InRelease Ign http://extras.ubuntu.com precise InRelease Ign http://archive.ubuntu.com precise-updates InRelease Hit http://archive.canonical.com precise/partner i386 Packages Hit http://extras.ubuntu.com precise Release.gpg Ign http://archive.ubuntu.com precise-backports InRelease Ign http://archive.canonical.com precise/partner TranslationIndex Err http://archive.canonical.com precise/partner Translation-en_US Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] Err http://archive.canonical.com precise/partner Translation-en Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] Hit http://extras.ubuntu.com precise Release Get:1 http://archive.ubuntu.com precise Release.gpg [198 B] Ign http://dl.google.com stable InRelease Err http://dl.google.com stable InRelease Err http://dl.google.com stable Release.gpg Unable to connect to dl.google.com:http: [IP: 173.194.34.38 80] Err http://dl.google.com stable Release.gpg Unable to connect to dl.google.com:http: [IP: 173.194.34.38 80] Get:2 http://archive.ubuntu.com precise-updates Release.gpg [198 B] Hit http://extras.ubuntu.com precise/main i386 Packages Get:3 http://archive.ubuntu.com precise-backports Release.gpg [198 B] Ign http://security.ubuntu.com precise-security InRelease Ign http://extras.ubuntu.com precise/main TranslationIndex Err http://extras.ubuntu.com precise/main Translation-en_US Unable to connect to extras.ubuntu.com:http: Err http://extras.ubuntu.com precise/main Translation-en Unable to connect to extras.ubuntu.com:http: Get:4 http://security.ubuntu.com precise-security Release.gpg [198 B] Get:5 http://archive.ubuntu.com precise Release [49.6 kB] Get:6 http://security.ubuntu.com precise-security Release [49.6 kB] Get:7 http://archive.ubuntu.com precise-updates Release [49.6 kB] Get:8 http://archive.ubuntu.com precise-backports Release [49.6 kB] Get:9 http://security.ubuntu.com precise-security/main i386 Packages [32.9 kB] Get:10 http://archive.ubuntu.com precise/main i386 Packages [1,274 kB] Get:11 http://security.ubuntu.com precise-security/restricted i386 Packages [14 B] Get:12 http://security.ubuntu.com precise-security/universe i386 Packages [8,594 B] Get:13 http://security.ubuntu.com precise-security/multiverse i386 Packages [1,393 B] Get:14 http://security.ubuntu.com precise-security/main TranslationIndex [73 B] Get:15 http://security.ubuntu.com precise-security/multiverse TranslationIndex [71 B] Get:16 http://security.ubuntu.com precise-security/restricted TranslationIndex [70 B] Get:17 http://security.ubuntu.com precise-security/universe TranslationIndex [72 B] Get:18 http://security.ubuntu.com precise-security/main Translation-en [13.6 kB] Get:19 http://security.ubuntu.com precise-security/multiverse Translation-en [587 B] Get:20 http://security.ubuntu.com precise-security/restricted Translation-en [14 B] Get:21 http://security.ubuntu.com precise-security/universe Translation-en [6,261 B] Get:22 http://archive.ubuntu.com precise/restricted i386 Packages [8,431 B] Get:23 http://archive.ubuntu.com precise/universe i386 Packages [4,796 kB] Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Get:24 http://ppa.launchpad.net precise Release.gpg [316 B] Get:25 http://ppa.launchpad.net precise Release.gpg [316 B] Get:26 http://ppa.launchpad.net precise Release.gpg [316 B] Ign http://ppa.launchpad.net precise Release.gpg Get:27 http://ppa.launchpad.net precise Release.gpg [316 B] Hit http://ppa.launchpad.net precise Release.gpg Get:28 http://ppa.launchpad.net precise Release.gpg [316 B] Get:29 http://ppa.launchpad.net precise Release.gpg [316 B] Hit http://ppa.launchpad.net precise Release.gpg Get:30 http://ppa.launchpad.net precise Release.gpg [316 B] Hit http://ppa.launchpad.net precise Release.gpg Get:31 http://ppa.launchpad.net precise Release [11.9 kB] Get:32 http://ppa.launchpad.net precise Release [11.9 kB] Get:33 http://archive.ubuntu.com precise/multiverse i386 Packages [121 kB] Get:34 http://ppa.launchpad.net precise Release [11.9 kB] Ign http://ppa.launchpad.net precise Release Get:35 http://ppa.launchpad.net precise Release [11.9 kB] Hit http://archive.ubuntu.com precise/main TranslationIndex Hit http://archive.ubuntu.com precise/multiverse TranslationIndex Hit http://ppa.launchpad.net precise Release Hit http://archive.ubuntu.com precise/restricted TranslationIndex Get:36 http://ppa.launchpad.net precise Release [11.9 kB] Hit http://archive.ubuntu.com precise/universe TranslationIndex Get:37 http://ppa.launchpad.net precise Release [11.9 kB] Get:38 http://archive.ubuntu.com precise-updates/main i386 Packages [96.5 kB] Hit http://ppa.launchpad.net precise Release Get:39 http://ppa.launchpad.net precise Release [11.9 kB] Get:40 http://archive.ubuntu.com precise-updates/restricted i386 Packages [770 B] Hit http://ppa.launchpad.net precise Release Get:41 http://archive.ubuntu.com precise-updates/universe i386 Packages [27.7 kB] Get:42 http://ppa.launchpad.net precise/main Sources [524 B] Get:43 http://archive.ubuntu.com precise-updates/multiverse i386 Packages [1,393 B] Get:44 http://ppa.launchpad.net precise/main i386 Packages [507 B] Hit http://archive.ubuntu.com precise-updates/main TranslationIndex Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://archive.ubuntu.com precise-updates/multiverse TranslationIndex Hit http://archive.ubuntu.com precise-updates/restricted TranslationIndex Get:45 http://ppa.launchpad.net precise/main Sources [932 B] Hit http://archive.ubuntu.com precise-updates/universe TranslationIndex Get:46 http://ppa.launchpad.net precise/main i386 Packages [1,017 B] Get:47 http://archive.ubuntu.com precise-backports/main i386 Packages [559 B] Ign http://ppa.launchpad.net precise/main TranslationIndex Get:48 http://archive.ubuntu.com precise-backports/restricted i386 Packages [14 B] Get:49 http://archive.ubuntu.com precise-backports/universe i386 Packages [1,391 B] Get:50 http://ppa.launchpad.net precise/main Sources [1,402 B] Get:51 http://archive.ubuntu.com precise-backports/multiverse i386 Packages [14 B] Hit http://archive.ubuntu.com precise-backports/main TranslationIndex Get:52 http://ppa.launchpad.net precise/main i386 Packages [1,605 B] Hit http://archive.ubuntu.com precise-backports/multiverse TranslationIndex Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://archive.ubuntu.com precise-backports/restricted TranslationIndex Hit http://archive.ubuntu.com precise-backports/universe TranslationIndex Hit http://archive.ubuntu.com precise/main Translation-en Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://archive.ubuntu.com precise/multiverse Translation-en Get:53 http://ppa.launchpad.net precise/main Sources [931 B] Hit http://archive.ubuntu.com precise/restricted Translation-en Get:54 http://ppa.launchpad.net precise/main i386 Packages [1,079 B] Hit http://archive.ubuntu.com precise/universe Translation-en Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://archive.ubuntu.com precise-updates/main Translation-en Hit http://ppa.launchpad.net precise/main Sources Hit http://archive.ubuntu.com precise-updates/multiverse Translation-en Hit http://ppa.launchpad.net precise/main i386 Packages Hit http://archive.ubuntu.com precise-updates/restricted Translation-en Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://archive.ubuntu.com precise-updates/universe Translation-en Get:55 http://ppa.launchpad.net precise/main Sources [3,611 B] Hit http://archive.ubuntu.com precise-backports/main Translation-en Get:56 http://ppa.launchpad.net precise/main i386 Packages [2,468 B] Hit http://archive.ubuntu.com precise-backports/multiverse Translation-en Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://archive.ubuntu.com precise-backports/restricted Translation-en Hit http://archive.ubuntu.com precise-backports/universe Translation-en Get:57 http://ppa.launchpad.net precise/main Sources [1,524 B] Get:58 http://ppa.launchpad.net precise/main i386 Packages [2,719 B] Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net precise/main Sources Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://ppa.launchpad.net precise/main TranslationIndex Get:59 http://ppa.launchpad.net precise/main Sources [1,052 B] Get:60 http://ppa.launchpad.net precise/main i386 Packages [1,388 B] Ign http://ppa.launchpad.net precise/main TranslationIndex Get:61 http://ppa.launchpad.net precise/main Sources [1,185 B] Get:62 http://ppa.launchpad.net precise/main i386 Packages [1,698 B] Ign http://ppa.launchpad.net precise/main TranslationIndex Err http://ppa.launchpad.net precise/main Sources 404 Not Found Err http://ppa.launchpad.net precise/main i386 Packages 404 Not Found Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Fetched 6,699 kB in 15s (445 kB/s) Reading package lists... Done W: Failed to fetch http://dl.google.com/linux/talkplugin/deb/dists/stable/InRelease W: Failed to fetch http://archive.canonical.com/ubuntu/dists/precise/partner/i18n/Translation-en_US Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] W: Failed to fetch http://archive.canonical.com/ubuntu/dists/precise/partner/i18n/Translation-en Unable to connect to archive.canonical.com:http: [IP: 91.189.92.150 80] W: Failed to fetch http://dl.google.com/linux/chrome/deb/dists/sta

    Read the article

  • Wrapping ASP.NET Client Callbacks

    - by Ricardo Peres
    Client Callbacks are probably the less known (and I dare say, less loved) of all the AJAX options in ASP.NET, which also include the UpdatePanel, Page Methods and Web Services. The reason for that, I believe, is it’s relative complexity: Get a reference to a JavaScript function; Dynamically register function that calls the above reference; Have a JavaScript handler call the registered function. However, it has some the nice advantage of being self-contained, that is, doesn’t need additional files, such as web services, JavaScript libraries, etc, or static methods declared on a page, or any kind of attributes. So, here’s what I want to do: Have a DOM element which exposes a method that is executed server side, passing it a string and returning a string; Have a server-side event that handles the client-side call; Have two client-side user-supplied callback functions for handling the success and error results. I’m going to develop a custom control without user interface that does the registration of the client JavaScript method as well as a server-side event that can be hooked by some handler on a page. My markup will look like this: 1: <script type="text/javascript"> 1:  2:  3: function onCallbackSuccess(result, context) 4: { 5: } 6:  7: function onCallbackError(error, context) 8: { 9: } 10:  </script> 2: <my:CallbackControl runat="server" ID="callback" SendAllData="true" OnCallback="OnCallback"/> The control itself looks like this: 1: public class CallbackControl : Control, ICallbackEventHandler 2: { 3: #region Public constructor 4: public CallbackControl() 5: { 6: this.SendAllData = false; 7: this.Async = true; 8: } 9: #endregion 10:  11: #region Public properties and events 12: public event EventHandler<CallbackEventArgs> Callback; 13:  14: [DefaultValue(true)] 15: public Boolean Async 16: { 17: get; 18: set; 19: } 20:  21: [DefaultValue(false)] 22: public Boolean SendAllData 23: { 24: get; 25: set; 26: } 27:  28: #endregion 29:  30: #region Protected override methods 31:  32: protected override void Render(HtmlTextWriter writer) 33: { 34: writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); 35: writer.RenderBeginTag(HtmlTextWriterTag.Span); 36:  37: base.Render(writer); 38:  39: writer.RenderEndTag(); 40: } 41:  42: protected override void OnInit(EventArgs e) 43: { 44: String reference = this.Page.ClientScript.GetCallbackEventReference(this, "arg", "onCallbackSuccess", "context", "onCallbackError", this.Async); 45: String script = String.Concat("\ndocument.getElementById('", this.ClientID, "').callback = function(arg, context, onCallbackSuccess, onCallbackError){", ((this.SendAllData == true) ? "__theFormPostCollection.length = 0; __theFormPostData = ''; WebForm_InitCallback(); " : String.Empty), reference, ";};\n"); 46:  47: this.Page.ClientScript.RegisterStartupScript(this.GetType(), String.Concat("callback", this.ClientID), script, true); 48:  49: base.OnInit(e); 50: } 51:  52: #endregion 53:  54: #region Protected virtual methods 55: protected virtual void OnCallback(CallbackEventArgs args) 56: { 57: EventHandler<CallbackEventArgs> handler = this.Callback; 58:  59: if (handler != null) 60: { 61: handler(this, args); 62: } 63: } 64:  65: #endregion 66:  67: #region ICallbackEventHandler Members 68:  69: String ICallbackEventHandler.GetCallbackResult() 70: { 71: CallbackEventArgs args = new CallbackEventArgs(this.Context.Items["Data"] as String); 72:  73: this.OnCallback(args); 74:  75: return (args.Result); 76: } 77:  78: void ICallbackEventHandler.RaiseCallbackEvent(String eventArgument) 79: { 80: this.Context.Items["Data"] = eventArgument; 81: } 82:  83: #endregion 84: } And the event argument class: 1: [Serializable] 2: public class CallbackEventArgs : EventArgs 3: { 4: public CallbackEventArgs(String argument) 5: { 6: this.Argument = argument; 7: this.Result = String.Empty; 8: } 9:  10: public String Argument 11: { 12: get; 13: private set; 14: } 15:  16: public String Result 17: { 18: get; 19: set; 20: } 21: } You will notice two properties on the CallbackControl: Async: indicates if the call should be made asynchronously or synchronously (the default); SendAllData: indicates if the callback call will include the view and control state of all of the controls on the page, so that, on the server side, they will have their properties set when the Callback event is fired. The CallbackEventArgs class exposes two properties: Argument: the read-only argument passed to the client-side function; Result: the result to return to the client-side callback function, set from the Callback event handler. An example of an handler for the Callback event would be: 1: protected void OnCallback(Object sender, CallbackEventArgs e) 2: { 3: e.Result = String.Join(String.Empty, e.Argument.Reverse()); 4: } Finally, in order to fire the Callback event from the client, you only need this: 1: <input type="text" id="input"/> 2: <input type="button" value="Get Result" onclick="document.getElementById('callback').callback(callback(document.getElementById('input').value, 'context', onCallbackSuccess, onCallbackError))"/> The syntax of the callback function is: arg: some string argument; context: some context that will be passed to the callback functions (success or failure); callbackSuccessFunction: some function that will be called when the callback succeeds; callbackFailureFunction: some function that will be called if the callback fails for some reason. Give it a try and see if it helps!

    Read the article

  • ASP.Net Authentication with MVC2--how to integrate with DB?

    - by alchemical
    I'm trying to understand the authentication section sample project that opens in a new MVC2 project in VS2010. It essentially lets you register, login, etc. I looked through the code that implements this briefly, it looked fairly complicated. (10 tables, 40 sprocs, 10 views, 4 models, 1 model, 1 controller, etc.) Is it best to utilize this provided framework for authentication? If so, how would I integrate this with my own database models (which has user and role tables, etc.). Also, if I use their framework, are there any performance issues at higher traffic volumes (like SO for example), do I need to become responsible for maintaining the authentication DB as well in this case?

    Read the article

  • Extracting the Date from a DateTime in Entity Framework 4 and LINQ

    - by Ken Cox [MVP]
    In my current ASP.NET 4 project, I’m displaying dates in a GridDateTimeColumn of Telerik’s ASP.NET Radgrid control. I don’t care about the time stuff, so my DataFormatString shows only the date bits: <telerik:GridDateTimeColumn FilterControlWidth="100px"   DataField="DateCreated" HeaderText="Created"    SortExpression="DateCreated" ReadOnly="True"    UniqueName="DateCreated" PickerType="DatePicker"    DataFormatString="{0:dd MMM yy}"> My problem was that I couldn’t get the built-in column filtering (it uses Telerik’s DatePicker control) to behave.  The DatePicker assumes that the time is 00:00:00 but the data would have times like 09:22:21. So, when you select a date and apply the EqualTo filter, you get no results. You would get results if all the time portions were 00:00:00. In essence, I wanted my Entity Framework query to give the DatePicker what it wanted… a Date without the Time portion. Fortunately, EF4 provides the TruncateTime  function. After you include Imports System.Data.Objects.EntityFunctions You’ll find that your EF queries will accept the TruncateTime function. Here’s my routine: Protected Sub RadGrid1_NeedDataSource _     (ByVal source As Object, _      ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) _     Handles RadGrid1.NeedDataSource     Dim ent As New OfficeBookDBEntities1     Dim TopBOMs = From t In ent.TopBom, i In ent.Items _                   Where t.BusActivityID = busActivityID _       And i.BusActivityID And t.ItemID = i.RecordID _       Order By t.DateUpdated Descending _       Select New With {.TopBomID = t.TopBomID, .ItemID = t.ItemID, _                        .PartNumber = i.PartNumber, _                        .Description = i.Description, .Notes = t.Notes, _                        .DateCreated = TruncateTime(t.DateCreated), _                        .DateUpdated = TruncateTime(t.DateUpdated)}     RadGrid1.DataSource = TopBOMs End Sub Now when I select March 14, 2011 on the DatePicker, the filter doesn’t stumble on time values that don’t make sense. Full Disclosure: Telerik gives me (and other developer MVPs) free copies of their suite.

    Read the article

  • ASP.NET MVC and ASP.NET membership template provider

    - by rem
    In a standard ASP.NET MVC template application that is created by default in Visual Studio when starting a new ASP.NET MVC application there is already a built-in membership / authentication / authorization system. Using web search one can find lots of info about how to work with a built-in ASP.NET membership system, but very often this material is a bit of an old and refer to ASP.NET only, not mentioning ASP.NET MVC framework. Just for example: http://msdn.microsoft.com/en-us/library/ms998347.aspx#paght000022%5Fmembershipapis or http://www.4guysfromrolla.com/articles/091207-1.aspx To what extent all that applies to ASP.NET built-in membership system applies also to ASP.NET MVC ready template membership system?

    Read the article

  • The ASP.NET Daily Community Spotlight - How posts get there, and how to make it your Visual Studio Start Page

    - by Jon Galloway
    One really cool part of my job is selecting the articles for the Daily Community Spotlight, on the home page of the ASP.NET website. The spotlight highlights a new post about ASP.NET development every day from a member of the ASP.NET community. You can find it on the home page of the ASP.NET site, at http://asp.net These posts aren't automatically drawn from a pool of RSS feeds or anything - I pick a new post for each day of the year. How I pick the posts I have a few important selection criteria: Interesting to well rounded ASP.NET developers The ASP.NET website has a lot of material for all skill and experience levels, from download / get started to advanced. I try to select community spotlight posts to round that out with fresh and timely information that working ASP.NET developers can really use. Posts highlight solutions to common problems, clever projects and code that helps you leverage ASP.NET, and important announcements about things you can use today. As part of that, I try to mix between ASP.NET MVC, Web Forms, and Web Pages (a.k.a. WebMatrix). As a professional developer, I want to keep on top of all of my options for ASP.NET development, and the common platform base they all share generally means that good ASP.NET code is good ASP.NET code. Exposing new and non-Microsoft community members as much as possible The exercise of selecting good ASP.NET community posts every day of the year has made me think about what the community is. Given the choice, I'll always favor non-Microsoft employees, but since Microsoft often hires ASP.NET community members and MVP's (myself included), I really think that the ASP.NET community includes developers who are using and writing about ASP.NET, both inside and outside of Microsoft. I'm especially excited about the opportunity to highlight new and lesser known bloggers. Usually being featured on the ASP.NET Community Spotlight gives a pretty good traffic bump, and I love being able to both provide great content to the community and encourage lesser known community members by giving them some (much deserved) attention. Announcements only when they're useful to working developers - not marketing Some of the posts are announcements about new releases, such as Scott Hanselman's post on ASP.NET Universal Providers for Session, Memebership, and Roles. I include those when I think they're interesting and of immediate use to you on projects. I occasionally get asked to link to new content from a team at Microsoft; if it's useful and timely content I'll ask them to point me to a blog post by an actual person rather than a faceless team. How the posts are managed This feed used to be managed by an internal spreadsheet on a Sharepoint site, which was painful for a lot of reasons. I took a cue from Jon Udell, who uses of a public Delicious feed feed for his Elm City project, and we moved the management of these posts over to a Delicious feed as well. You can hear more about Jon's use of Delicious in Elm City in our Herding Code interview - still one of my favorite interviews. We ended up with a simpler scenario, but Note: I watched the Yahoo/Delicious news over the past year and was happy to see that Delicious was recently acquired by the founders of YouTube. I investigated several other Delicious competitors, but am happy with Delicious for now. My Delicious feed here: http://www.delicious.com/jon_galloway You can also browse through this past year's ASP.NET Community Spotlight posts using the (pretty cool) Delicious Browse Bar Submitting articles I'm always on the lookout for new articles to feature. The best way to get them to me is to share them via Delicious. It's pretty easy - sign up for an account, then you can add a post and share it to me. Alternatively, you can send them to me via Twitter (@jongalloway) or e-mail (). If you do e-mail me, it helps to include a short description and your full name so I can credit you. Way too many developer blogs don't include names and pictures; if I can't find them I can't feature the post. Subscribing to the Community Spotlight feed The Community Spotlight is available as an RSS feed, so you might want to subscribe to it: http://www.asp.net/rss/spotlight Setting the ASP.NET Community Spotlight feed as your Visual Studio start page If you're an ASP.NET developer, you might consider setting the ASP.NET Community Spotlight as the content for your Visual Studio Start Page. It's really easy - here's how to do it in Visual Studio 2010: Display the Visual Studio Start Page if it's not already showing (View / Start Page) Click on the Latest News tab and enter the following RSS URL: http://www.asp.net/rss/spotlight If you didn't previously have RSS feeds enabled for your start page, click the Enable RSS Feed button Now, every time you start up Visual Studio you'll see great content from members of the ASP.NET community: You can also configure - and disable, if you'd like - the Visual Studio start page in the Tools / Options / Environment / Startup dialog. Credits I'll do a follow-up highlighting some places I commonly find great content for the feed, but I'd like to specifically point out two of them: Elijah Manor posts a lot of great content, which is available in his Twitter feed at @elijahmanor, on his Delicious feed, and on a dedicated website - Web Dev Tweets Chris Alcock's The Morning Brew is a must-read blog which highlights each day's best blog posts across the .NET community. He's an absolute machine, and no matter how obscure the post I find, I can guarantee he'll find it as well if he hasn't already. Did I say must read?

    Read the article

  • C# development with Mono and MonoDevelop

    - by developerit
    In the past two years, I have been developing .NET from my MacBook by running Windows XP into VM Ware and more recently into Virtual Box from OS X. This way, I could install Visual Studio and be able to work seamlessly. But, this way of working has a major down side: it kills the battery of my laptop… I can easiely last for 3 hours if I stay in OS X, but can only last 45 min when XP is running. Recently, I gave MonoDevelop a try for developing Developer IT‘s tools and web site. While being way less complete then Visual Studio, it provides essentials tools when it comes to developping software. It works well with solutions and projects files created from Visual Studio, it has Intellisence (word completion), it can compile your code and can even target your .NET app to linux or unix. This tools can save me a lot of time and batteries! Although I could not only work with MonoDevelop, I find it way better than a simple text editor like Smultron. Thanks to Novell, we can now bring Microsoft technology to OS X.

    Read the article

  • Links to my “Best of 2010” Posts

    - by ScottGu
    I hope everyone is having a Happy New Years! 2010 has been a busy blogging year for me (this is the 100th blog post I’ve done in 2010).  Several people this week suggested I put together a summary post listing/organizing my favorite posts from the year.  Below is a quick listing of some of my favorite posts organized by topic area: VS 2010 and .NET 4 Below is a series of posts I wrote (some in late 2009) about the VS 2010 and .NET 4 (including ASP.NET 4 and WPF 4) release we shipped in April: Visual Studio 2010 and .NET 4 Released Clean Web.Config Files Starter Project Templates Multi-targeting Multiple Monitor Support New Code Focused Web Profile Option HTML / ASP.NET / JavaScript Code Snippets Auto-Start ASP.NET Applications URL Routing with ASP.NET 4 Web Forms Searching and Navigating Code in VS 2010 VS 2010 Code Intellisense Improvements WPF 4 Add Reference Dialog Improvements SEO Improvements with ASP.NET 4 Output Cache Extensibility with ASP.NET 4 Built-in Charting Controls for ASP.NET and Windows Forms Cleaner HTML Markup with ASP.NET 4 - Client IDs Optional Parameters and Named Arguments in C# 4 - and a cool scenarios with ASP.NET MVC 2 Automatic Properties, Collection Initializers and Implicit Line Continuation Support with VB 2010 New <%: %> Syntax for HTML Encoding Output using ASP.NET 4 JavaScript Intellisense Improvements with VS 2010 VS 2010 Debugger Improvements (DataTips, BreakPoints, Import/Export) Box Selection and Multi-line Editing Support with VS 2010 VS 2010 Extension Manager (and the cool new PowerCommands Extension) Pinning Projects and Solutions VS 2010 Web Deployment Debugging Tips/Tricks with Visual Studio Search and Navigation Tips/Tricks with Visual Studio Visual Studio Below are some additional Visual Studio posts I’ve done (not in the first series above) that I thought were nice: Download and Share Visual Studio Color Schemes Visual Studio 2010 Keyboard Shortcuts VS 2010 Productivity Power Tools Fun Visual Studio 2010 Wallpapers Silverlight We shipped Silverlight 4 in April, and announced Silverlight 5 the beginning of December: Silverlight 4 Released Silverlight 4 Tools for VS 2010 and WCF RIA Services Released Silverlight 4 Training Kit Silverlight PivotViewer Now Available Silverlight Questions Announcing Silverlight 5 Silverlight for Windows Phone 7 We shipped Windows Phone 7 this fall and shipped free Visual Studio development tools with great Silverlight and XNA support in September: Windows Phone 7 Developer Tools Released Building a Windows Phone 7 Twitter Application using Silverlight ASP.NET MVC We shipped ASP.NET MVC 2 in March, and started previewing ASP.NET MVC 3 this summer.  ASP.NET MVC 3 will RTM in less than 2 weeks from today: ASP.NET MVC 2: Strongly Typed Html Helpers ASP.NET MVC 2: Model Validation Introducing ASP.NET MVC 3 (Preview 1) Announcing ASP.NET MVC 3 Beta and NuGet (nee NuPack) Announcing ASP.NET MVC 3 Release Candidate 1  Announcing ASP.NET MVC 3 Release Candidate 2 Introducing Razor – A New View Engine for ASP.NET ASP.NET MVC 3: Layouts with Razor ASP.NET MVC 3: New @model keyword in Razor ASP.NET MVC 3: Server-Side Comments with Razor ASP.NET MVC 3: Razor’s @: and <text> syntax ASP.NET MVC 3: Implicit and Explicit code nuggets with Razor ASP.NET MVC 3: Layouts and Sections with Razor IIS and Web Server Stack The IIS and Web Stack teams have made a bunch of great improvements to the core web server this year: Fix Common SEO Problems using the URL Rewrite Extension Introducing the Microsoft Web Farm Framework Automating Deployment with Microsoft Web Deploy Introducing IIS Express SQL CE 4 (New Embedded Database Support with ASP.NET) Introducing Web Matrix EF Code First EF Code First is a really nice new data option that enables a very clean code-oriented data workflow: Announcing Entity Framework Code-First CTP5 Release Class-Level Model Validation with EF Code First and ASP.NET MVC 3 Code-First Development with Entity Framework 4 EF 4 Code First: Custom Database Schema Mapping Using EF Code First with an Existing Database jQuery and AJAX Contributions My team began making some significant source code contributions to the jQuery project this year: jQuery Templates, Data Link and Globalization Accepted as Official jQuery Plugins jQuery Templates and Data Linking (and Microsoft contributing to jQuery) jQuery Globalization Plugin from Microsoft Patches and Hot Fixes Some useful fixes you can download prior to VS 2010 SP1: Patch for Cut/Copy “Insufficient Memory” issue with VS 2010 Patch for VS 2010 Find and Replace Dialog Growing Patch for VS 2010 Scrolling Context Menu Videos of My Talks Some recordings of technical talks I’ve done this year: ASP.NET 4, ASP.NET MVC, and Silverlight 4 Talks I did in Europe VS 2010 and ASP.NET 4 Web Forms Talk in Arizona Other About Technical Debates (and ASP.NET Web Forms and ASP.NET MVC debates in particular) ASP.NET Security Fix Now on Windows Update Upcoming Web Camps I’d like to say a big thank you to everyone who follows my blog – I really appreciate you reading it (the comments you post help encourage me to write it).  See you in the New Year! Scott P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

    Read the article

  • Cleaner HTML Markup with ASP.NET 4 Web Forms - Client IDs (VS 2010 and .NET 4.0 Series)

    - by ScottGu
    This is the sixteenth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release. Today’s post is the first of a few blog posts I’ll be doing that talk about some of the important changes we’ve made to make Web Forms in ASP.NET 4 generate clean, standards-compliant, CSS-friendly markup.  Today I’ll cover the work we are doing to provide better control over the “ID” attributes rendered by server controls to the client. [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu] Clean, Standards-Based, CSS-Friendly Markup One of the common complaints developers have often had with ASP.NET Web Forms is that when using server controls they don’t have the ability to easily generate clean, CSS-friendly output and markup.  Some of the specific complaints with previous ASP.NET releases include: Auto-generated ID attributes within HTML make it hard to write JavaScript and style with CSS Use of tables instead of semantic markup for certain controls (in particular the asp:menu control) make styling ugly Some controls render inline style properties even if no style property on the control has been set ViewState can often be bigger than ideal ASP.NET 4 provides better support for building standards-compliant pages out of the box.  The built-in <asp:> server controls with ASP.NET 4 now generate cleaner markup and support CSS styling – and help address all of the above issues.  Markup Compatibility When Upgrading Existing ASP.NET Web Forms Applications A common question people often ask when hearing about the cleaner markup coming with ASP.NET 4 is “Great - but what about my existing applications?  Will these changes/improvements break things when I upgrade?” To help ensure that we don’t break assumptions around markup and styling with existing ASP.NET Web Forms applications, we’ve enabled a configuration flag – controlRenderingCompatbilityVersion – within web.config that let’s you decide if you want to use the new cleaner markup approach that is the default with new ASP.NET 4 applications, or for compatibility reasons render the same markup that previous versions of ASP.NET used:   When the controlRenderingCompatbilityVersion flag is set to “3.5” your application and server controls will by default render output using the same markup generation used with VS 2008 and .NET 3.5.  When the controlRenderingCompatbilityVersion flag is set to “4.0” your application and server controls will strictly adhere to the XHTML 1.1 specification, have cleaner client IDs, render with semantic correctness in mind, and have extraneous inline styles removed. This flag defaults to 4.0 for all new ASP.NET Web Forms applications built using ASP.NET 4. Any previous application that is upgraded using VS 2010 will have the controlRenderingCompatbilityVersion flag automatically set to 3.5 by the upgrade wizard to ensure backwards compatibility.  You can then optionally change it (either at the application level, or scope it within the web.config file to be on a per page or directory level) if you move your pages to use CSS and take advantage of the new markup rendering. Today’s Cleaner Markup Topic: Client IDs The ability to have clean, predictable, ID attributes on rendered HTML elements is something developers have long asked for with Web Forms (ID values like “ctl00_ContentPlaceholder1_ListView1_ctrl0_Label1” are not very popular).  Having control over the ID values rendered helps make it much easier to write client-side JavaScript against the output, makes it easier to style elements using CSS, and on large pages can help reduce the overall size of the markup generated. New ClientIDMode Property on Controls ASP.NET 4 supports a new ClientIDMode property on the Control base class.  The ClientIDMode property indicates how controls should generate client ID values when they render.  The ClientIDMode property supports four possible values: AutoID—Renders the output as in .NET 3.5 (auto-generated IDs which will still render prefixes like ctrl00 for compatibility) Predictable (Default)— Trims any “ctl00” ID string and if a list/container control concatenates child ids (example: id=”ParentControl_ChildControl”) Static—Hands over full ID naming control to the developer – whatever they set as the ID of the control is what is rendered (example: id=”JustMyId”) Inherit—Tells the control to defer to the naming behavior mode of the parent container control The ClientIDMode property can be set directly on individual controls (or within container controls – in which case the controls within them will by default inherit the setting): Or it can be specified at a page or usercontrol level (using the <%@ Page %> or <%@ Control %> directives) – in which case controls within the pages/usercontrols inherit the setting (and can optionally override it): Or it can be set within the web.config file of an application – in which case pages within the application inherit the setting (and can optionally override it): This gives you the flexibility to customize/override the naming behavior however you want. Example: Using the ClientIDMode property to control the IDs of Non-List Controls Let’s take a look at how we can use the new ClientIDMode property to control the rendering of “ID” elements within a page.  To help illustrate this we can create a simple page called “SingleControlExample.aspx” that is based on a master-page called “Site.Master”, and which has a single <asp:label> control with an ID of “Message” that is contained with an <asp:content> container control called “MainContent”: Within our code-behind we’ll then add some simple code like below to dynamically populate the Label’s Text property at runtime:   If we were running this application using ASP.NET 3.5 (or had our ASP.NET 4 application configured to run using 3.5 rendering or ClientIDMode=AutoID), then the generated markup sent down to the client would look like below: This ID is unique (which is good) – but rather ugly because of the “ct100” prefix (which is bad). Markup Rendering when using ASP.NET 4 and the ClientIDMode is set to “Predictable” With ASP.NET 4, server controls by default now render their ID’s using ClientIDMode=”Predictable”.  This helps ensure that ID values are still unique and don’t conflict on a page, but at the same time it makes the IDs less verbose and more predictable.  This means that the generated markup of our <asp:label> control above will by default now look like below with ASP.NET 4: Notice that the “ct100” prefix is gone. Because the “Message” control is embedded within a “MainContent” container control, by default it’s ID will be prefixed “MainContent_Message” to avoid potential collisions with other controls elsewhere within the page. Markup Rendering when using ASP.NET 4 and the ClientIDMode is set to “Static” Sometimes you don’t want your ID values to be nested hierarchically, though, and instead just want the ID rendered to be whatever value you set it as.  To enable this you can now use ClientIDMode=static, in which case the ID rendered will be exactly the same as what you set it on the server-side on your control.  This will cause the below markup to be rendered with ASP.NET 4: This option now gives you the ability to completely control the client ID values sent down by controls. Example: Using the ClientIDMode property to control the IDs of Data-Bound List Controls Data-bound list/grid controls have historically been the hardest to use/style when it comes to working with Web Form’s automatically generated IDs.  Let’s now take a look at a scenario where we’ll customize the ID’s rendered using a ListView control with ASP.NET 4. The code snippet below is an example of a ListView control that displays the contents of a data-bound collection — in this case, airports: We can then write code like below within our code-behind to dynamically databind a list of airports to the ListView above: At runtime this will then by default generate a <ul> list of airports like below.  Note that because the <ul> and <li> elements in the ListView’s template are not server controls, no IDs are rendered in our markup: Adding Client ID’s to Each Row Item Now, let’s say that we wanted to add client-ID’s to the output so that we can programmatically access each <li> via JavaScript.  We want these ID’s to be unique, predictable, and identifiable. A first approach would be to mark each <li> element within the template as being a server control (by giving it a runat=server attribute) and by giving each one an id of “airport”: By default ASP.NET 4 will now render clean IDs like below (no ctl001-like ids are rendered):   Using the ClientIDRowSuffix Property Our template above now generates unique ID’s for each <li> element – but if we are going to access them programmatically on the client using JavaScript we might want to instead have the ID’s contain the airport code within them to make them easier to reference.  The good news is that we can easily do this by taking advantage of the new ClientIDRowSuffix property on databound controls in ASP.NET 4 to better control the ID’s of our individual row elements. To do this, we’ll set the ClientIDRowSuffix property to “Code” on our ListView control.  This tells the ListView to use the databound “Code” property from our Airport class when generating the ID: And now instead of having row suffixes like “1”, “2”, and “3”, we’ll instead have the Airport.Code value embedded within the IDs (e.g: _CLE, _CAK, _PDX, etc): You can use this ClientIDRowSuffix approach with other databound controls like the GridView as well. It is useful anytime you want to program row elements on the client – and use clean/identified IDs to easily reference them from JavaScript code. Summary ASP.NET 4 enables you to generate much cleaner HTML markup from server controls and from within your Web Forms applications.  In today’s post I covered how you can now easily control the client ID values that are rendered by server controls.  In upcoming posts I’ll cover some of the other markup improvements that are also coming with the ASP.NET 4 release. Hope this helps, Scott

    Read the article

  • Special 48-Hour Offer: Free ASP.NET MVC 3 Video Training

    - by ScottGu
    The Virtual ASP.NET MVC Conference (MVCConf) happened earlier today.  Several thousand developers attended the event online, and had the opportunity to watch 27 great talks presented by the community. All of the live presentations were recorded, and videos of them will be posted shortly so that everyone can watch them (for free).  I’ll do a blog post with links to them once they are available. Special Pluralsight Training Available for Next 48 Hours In my MVCConf keynote this morning, I also mentioned a special offer that Pluralsight (a great .NET training partner) is offering – which is the opportunity to watch their excellent ASP.NET MVC 3 Fundamentals course free of charge for the next 48 hours.  This training is 3 hours and 17 minutes long and covers the new features introduced with ASP.NET MVC 3 including: Razor, Unobtrusive JavaScript, Richer Validation, ViewBag, Output Caching, Global Action Filters, NuGet, Dependency Injection, and much more. Scott Allen is the presenter, and the format, video player, and cadence of the course is really great.  It provides an excellent way to quickly come up to speed with all of the new features introduced with the new ASP.NET MVC 3 release. Click here to watch the Pluralsight training - available free of charge for the next 48 hours (until Thursday at 9pm PST). Other Beginning ASP.NET MVC Tutorials We will be publishing a bunch of new ASP.NET MVC 3 content, training and samples on the http://asp.net/mvc web-site in the weeks ahead.  We’ll include content that is tailored to developers brand-new to ASP.NET MVC, as well as content for advanced ASP.NET MVC developers looking to get the most out of it. Below are two tutorials available today that provide nice introductory step-by-step ASP.NET MVC 3 tutorials: Build your First ASP.NET MVC 3 Application ASP.NET MVC Music Store Tutorial I recommend reviewing both of the above tutorials if you are looking to get started with ASP.NET MVC 3 and want to learn the core concepts and features behind it. Hope this helps, Scott

    Read the article

  • Entity Framework Code-First, OData & Windows Phone Client

    - by Jon Galloway
    Entity Framework Code-First is the coolest thing since sliced bread, Windows  Phone is the hottest thing since Tickle-Me-Elmo and OData is just too great to ignore. As part of the Full Stack project, we wanted to put them together, which turns out to be pretty easy… once you know how.   EF Code-First CTP5 is available now and there should be very few breaking changes in the release edition, which is due early in 2011.  Note: EF Code-First evolved rapidly and many of the existing documents and blog posts which were written with earlier versions, may now be obsolete or at least misleading.   Code-First? With traditional Entity Framework you start with a database and from that you generate “entities” – classes that bridge between the relational database and your object oriented program. With Code-First (Magic-Unicorn) (see Hanselman’s write up and this later write up by Scott Guthrie) the Entity Framework looks at classes you created and says “if I had created these classes, the database would have to have looked like this…” and creates the database for you! By deriving your entity collections from DbSet and exposing them via a class that derives from DbContext, you "turn on" database backing for your POCO with a minimum of code and no hidden designer or configuration files. POCO == Plain Old CLR Objects Your entity objects can be used throughout your applications - in web applications, console applications, Silverlight and Windows Phone applications, etc. In our case, we'll want to read and update data from a Windows Phone client application, so we'll expose the entities through a DataService and hook the Windows Phone client application to that data via proxies.  Piece of Pie.  Easy as cake. The Demo Architecture To see this at work, we’ll create an ASP.NET/MVC application which will act as the host for our Data Service.  We’ll create an incredibly simple data layer using EF Code-First on top of SQLCE4 and we’ll expose the data in a WCF Data Service using the oData protocol.  Our Windows Phone 7 client will instantiate  the data context via a URI and load the data asynchronously. Setting up the Server project with MVC 3, EF Code First, and SQL CE 4 Create a new application of type ASP.NET MVC 3 and name it DeadSimpleServer.  We need to add the latest SQLCE4 and Entity Framework Code First CTP's to our project. Fortunately, NuGet makes that really easy. Open the Package Manager Console (View / Other Windows / Package Manager Console) and type in "Install-Package EFCodeFirst.SqlServerCompact" at the PM> command prompt. Since NuGet handles dependencies for you, you'll see that it installs everything you need to use Entity Framework Code First in your project. PM> install-package EFCodeFirst.SqlServerCompact 'SQLCE (= 4.0.8435.1)' not installed. Attempting to retrieve dependency from source... Done 'EFCodeFirst (= 0.8)' not installed. Attempting to retrieve dependency from source... Done 'WebActivator (= 1.0.0.0)' not installed. Attempting to retrieve dependency from source... Done You are downloading SQLCE from Microsoft, the license agreement to which is available at http://173.203.67.148/licenses/SQLCE/EULA_ENU.rtf. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device. Successfully installed 'SQLCE 4.0.8435.1' You are downloading EFCodeFirst from Microsoft, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=206497. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device. Successfully installed 'EFCodeFirst 0.8' Successfully installed 'WebActivator 1.0.0.0' You are downloading EFCodeFirst.SqlServerCompact from Microsoft, the license agreement to which is available at http://173.203.67.148/licenses/SQLCE/EULA_ENU.rtf. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device. Successfully installed 'EFCodeFirst.SqlServerCompact 0.8' Successfully added 'SQLCE 4.0.8435.1' to EfCodeFirst-CTP5 Successfully added 'EFCodeFirst 0.8' to EfCodeFirst-CTP5 Successfully added 'WebActivator 1.0.0.0' to EfCodeFirst-CTP5 Successfully added 'EFCodeFirst.SqlServerCompact 0.8' to EfCodeFirst-CTP5 Note: We're using SQLCE 4 with Entity Framework here because they work really well together from a development scenario, but you can of course use Entity Framework Code First with other databases supported by Entity framework. Creating The Model using EF Code First Now we can create our model class. Right-click the Models folder and select Add/Class. Name the Class Person.cs and add the following code: using System.Data.Entity; namespace DeadSimpleServer.Models { public class Person { public int ID { get; set; } public string Name { get; set; } } public class PersonContext : DbContext { public DbSet<Person> People { get; set; } } } Notice that the entity class Person has no special interfaces or base class. There's nothing special needed to make it work - it's just a POCO. The context we'll use to access the entities in the application is called PersonContext, but you could name it anything you wanted. The important thing is that it inherits DbContext and contains one or more DbSet which holds our entity collections. Adding Seed Data We need some testing data to expose from our service. The simplest way to get that into our database is to modify the CreateCeDatabaseIfNotExists class in AppStart_SQLCEEntityFramework.cs by adding some seed data to the Seed method: protected virtual void Seed( TContext context ) { var personContext = context as PersonContext; personContext.People.Add( new Person { ID = 1, Name = "George Washington" } ); personContext.People.Add( new Person { ID = 2, Name = "John Adams" } ); personContext.People.Add( new Person { ID = 3, Name = "Thomas Jefferson" } ); personContext.SaveChanges(); } The CreateCeDatabaseIfNotExists class name is pretty self-explanatory - when our DbContext is accessed and the database isn't found, a new one will be created and populated with the data in the Seed method. There's one more step to make that work - we need to uncomment a line in the Start method at the top of of the AppStart_SQLCEEntityFramework class and set the context name, as shown here, public static class AppStart_SQLCEEntityFramework { public static void Start() { DbDatabase.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0"); // Sets the default database initialization code for working with Sql Server Compact databases // Uncomment this line and replace CONTEXT_NAME with the name of your DbContext if you are // using your DbContext to create and manage your database DbDatabase.SetInitializer(new CreateCeDatabaseIfNotExists<PersonContext>()); } } Now our database and entity framework are set up, so we can expose data via WCF Data Services. Note: This is a bare-bones implementation with no administration screens. If you'd like to see how those are added, check out The Full Stack screencast series. Creating the oData Service using WCF Data Services Add a new WCF Data Service to the project (right-click the project / Add New Item / Web / WCF Data Service). We’ll be exposing all the data as read/write.  Remember to reconfigure to control and minimize access as appropriate for your own application. Open the code behind for your service. In our case, the service was called PersonTestDataService.svc so the code behind class file is PersonTestDataService.svc.cs. using System.Data.Services; using System.Data.Services.Common; using System.ServiceModel; using DeadSimpleServer.Models; namespace DeadSimpleServer { [ServiceBehavior( IncludeExceptionDetailInFaults = true )] public class PersonTestDataService : DataService<PersonContext> { // This method is called only once to initialize service-wide policies. public static void InitializeService( DataServiceConfiguration config ) { config.SetEntitySetAccessRule( "*", EntitySetRights.All ); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; config.UseVerboseErrors = true; } } } We're enabling a few additional settings to make it easier to debug if you run into trouble. The ServiceBehavior attribute is set to include exception details in faults, and we're using verbose errors. You can remove both of these when your service is working, as your public production service shouldn't be revealing exception information. You can view the output of the service by running the application and browsing to http://localhost:[portnumber]/PersonTestDataService.svc/: <service xml:base="http://localhost:49786/PersonTestDataService.svc/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns="http://www.w3.org/2007/app"> <workspace> <atom:title>Default</atom:title> <collection href="People"> <atom:title>People</atom:title> </collection> </workspace> </service> This indicates that the service exposes one collection, which is accessible by browsing to http://localhost:[portnumber]/PersonTestDataService.svc/People <?xml version="1.0" encoding="iso-8859-1" standalone="yes"?> <feed xml:base=http://localhost:49786/PersonTestDataService.svc/ xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom"> <title type="text">People</title> <id>http://localhost:49786/PersonTestDataService.svc/People</id> <updated>2010-12-29T01:01:50Z</updated> <link rel="self" title="People" href="People" /> <entry> <id>http://localhost:49786/PersonTestDataService.svc/People(1)</id> <title type="text"></title> <updated>2010-12-29T01:01:50Z</updated> <author> <name /> </author> <link rel="edit" title="Person" href="People(1)" /> <category term="DeadSimpleServer.Models.Person" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /> <content type="application/xml"> <m:properties> <d:ID m:type="Edm.Int32">1</d:ID> <d:Name>George Washington</d:Name> </m:properties> </content> </entry> <entry> ... </entry> </feed> Let's recap what we've done so far. But enough with services and XML - let's get this into our Windows Phone client application. Creating the DataServiceContext for the Client Use the latest DataSvcUtil.exe from http://odata.codeplex.com. As of today, that's in this download: http://odata.codeplex.com/releases/view/54698 You need to run it with a few options: /uri - This will point to the service URI. In this case, it's http://localhost:59342/PersonTestDataService.svc  Pick up the port number from your running server (e.g., the server formerly known as Cassini). /out - This is the DataServiceContext class that will be generated. You can name it whatever you'd like. /Version - should be set to 2.0 /DataServiceCollection - Include this flag to generate collections derived from the DataServiceCollection base, which brings in all the ObservableCollection goodness that handles your INotifyPropertyChanged events for you. Here's the console session from when we ran it: <ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding}" SelectionChanged="MainListBox_SelectionChanged"> Next, to keep things simple, change the Binding on the two TextBlocks within the DataTemplate to Name and ID, <ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding}" SelectionChanged="MainListBox_SelectionChanged"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Margin="0,0,0,17" Width="432"> <TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" /> <TextBlock Text="{Binding ID}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> Getting The Context In the code-behind you’ll first declare a member variable to hold the context from the Entity Framework. This is named using convention over configuration. The db type is Person and the context is of type PersonContext, You initialize it by providing the URI, in this case using the URL obtained from the Cassini web server, PersonContext context = new PersonContext( new Uri( "http://localhost:49786/PersonTestDataService.svc/" ) ); Create a second member variable of type DataServiceCollection<Person> but do not initialize it, DataServiceCollection<Person> people; In the constructor you’ll initialize the DataServiceCollection using the PersonContext, public MainPage() { InitializeComponent(); people = new DataServiceCollection<Person>( context ); Finally, you’ll load the people collection using the LoadAsync method, passing in the fully specified URI for the People collection in the web service, people.LoadAsync( new Uri( "http://localhost:49786/PersonTestDataService.svc/People" ) ); Note that this method runs asynchronously and when it is finished the people  collection is already populated. Thus, since we didn’t need or want to override any of the behavior we don’t implement the LoadCompleted. You can use the LoadCompleted event if you need to do any other UI updates, but you don't need to. The final code is as shown below: using System; using System.Data.Services.Client; using System.Windows; using System.Windows.Controls; using DeadSimpleServer.Models; using Microsoft.Phone.Controls; namespace WindowsPhoneODataTest { public partial class MainPage : PhoneApplicationPage { PersonContext context = new PersonContext( new Uri( "http://localhost:49786/PersonTestDataService.svc/" ) ); DataServiceCollection<Person> people; // Constructor public MainPage() { InitializeComponent(); // Set the data context of the listbox control to the sample data // DataContext = App.ViewModel; people = new DataServiceCollection<Person>( context ); people.LoadAsync( new Uri( "http://localhost:49786/PersonTestDataService.svc/People" ) ); DataContext = people; this.Loaded += new RoutedEventHandler( MainPage_Loaded ); } // Handle selection changed on ListBox private void MainListBox_SelectionChanged( object sender, SelectionChangedEventArgs e ) { // If selected index is -1 (no selection) do nothing if ( MainListBox.SelectedIndex == -1 ) return; // Navigate to the new page NavigationService.Navigate( new Uri( "/DetailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative ) ); // Reset selected index to -1 (no selection) MainListBox.SelectedIndex = -1; } // Load data for the ViewModel Items private void MainPage_Loaded( object sender, RoutedEventArgs e ) { if ( !App.ViewModel.IsDataLoaded ) { App.ViewModel.LoadData(); } } } } With people populated we can set it as the DataContext and run the application; you’ll find that the Name and ID are displayed in the list on the Mainpage. Here's how the pieces in the client fit together: Complete source code available here

    Read the article

  • Sending Messages to SignalR Hubs from the Outside

    - by Ricardo Peres
    Introduction You are by now probably familiarized with SignalR, Microsoft’s API for real-time web functionality. This is, in my opinion, one of the greatest products Microsoft has released in recent time. Usually, people login to a site and enter some page which is connected to a SignalR hub. Then they can send and receive messages – not just text messages, mind you – to other users in the same hub. Also, the server can also take the initiative to send messages to all or a specified subset of users on its own, this is known as server push. The normal flow is pretty straightforward, Microsoft has done a great job with the API, it’s clean and quite simple to use. And for the latter – the server taking the initiative – it’s also quite simple, just involves a little more work. The Problem The API for sending messages can be achieved from inside a hub – an instance of the Hub class – which is something that we don’t have if we are the server and we want to send a message to some user or group of users: the Hub instance is only instantiated in response to a client message. The Solution It is possible to acquire a hub’s context from outside of an actual Hub instance, by calling GlobalHost.ConnectionManager.GetHubContext<T>(). This API allows us to: Broadcast messages to all connected clients (possibly excluding some); Send messages to a specific client; Send messages to a group of clients. So, we have groups and clients, each is identified by a string. Client strings are called connection ids and group names are free-form, given by us. The problem with client strings is, we do not know how these map to actual users. One way to achieve this mapping is by overriding the Hub’s OnConnected and OnDisconnected methods and managing the association there. Here’s an example: 1: public class MyHub : Hub 2: { 3: private static readonly IDictionary<String, ISet<String>> users = new ConcurrentDictionary<String, ISet<String>>(); 4:  5: public static IEnumerable<String> GetUserConnections(String username) 6: { 7: ISet<String> connections; 8:  9: users.TryGetValue(username, out connections); 10:  11: return (connections ?? Enumerable.Empty<String>()); 12: } 13:  14: private static void AddUser(String username, String connectionId) 15: { 16: ISet<String> connections; 17:  18: if (users.TryGetValue(username, out connections) == false) 19: { 20: connections = users[username] = new HashSet<String>(); 21: } 22:  23: connections.Add(connectionId); 24: } 25:  26: private static void RemoveUser(String username, String connectionId) 27: { 28: users[username].Remove(connectionId); 29: } 30:  31: public override Task OnConnected() 32: { 33: AddUser(this.Context.Request.User.Identity.Name, this.Context.ConnectionId); 34: return (base.OnConnected()); 35: } 36:  37: public override Task OnDisconnected() 38: { 39: RemoveUser(this.Context.Request.User.Identity.Name, this.Context.ConnectionId); 40: return (base.OnDisconnected()); 41: } 42: } As you can see, I am using a static field to store the mapping between a user and its possibly many connections – for example, multiple open browser tabs or even multiple browsers accessing the same page with the same login credentials. The user identity, as is normal in .NET, is obtained from the IPrincipal which in SignalR hubs case is stored in Context.Request.User. Of course, this property will only have a meaningful value if we enforce authentication. Another way to go is by creating a group for each user that connects: 1: public class MyHub : Hub 2: { 3: public override Task OnConnected() 4: { 5: this.Groups.Add(this.Context.ConnectionId, this.Context.Request.User.Identity.Name); 6: return (base.OnConnected()); 7: } 8:  9: public override Task OnDisconnected() 10: { 11: this.Groups.Remove(this.Context.ConnectionId, this.Context.Request.User.Identity.Name); 12: return (base.OnDisconnected()); 13: } 14: } In this case, we will have a one-to-one equivalence between users and groups. All connections belonging to the same user will fall in the same group. So, if we want to send messages to a user from outside an instance of the Hub class, we can do something like this, for the first option – user mappings stored in a static field: 1: public void SendUserMessage(String username, String message) 2: { 3: var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); 4: 5: foreach (String connectionId in HelloHub.GetUserConnections(username)) 6: { 7: context.Clients.Client(connectionId).sendUserMessage(message); 8: } 9: } And for using groups, its even simpler: 1: public void SendUserMessage(String username, String message) 2: { 3: var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); 4:  5: context.Clients.Group(username).sendUserMessage(message); 6: } Using groups has the advantage that the IHubContext interface returned from GetHubContext has direct support for groups, no need to send messages to individual connections. Of course, you can wrap both mapping options in a common API, perhaps exposed through IoC. One example of its interface might be: 1: public interface IUserToConnectionMappingService 2: { 3: //associate and dissociate connections to users 4:  5: void AddUserConnection(String username, String connectionId); 6:  7: void RemoveUserConnection(String username, String connectionId); 8: } SignalR has built-in dependency resolution, by means of the static GlobalHost.DependencyResolver property: 1: //for using groups (in the Global class) 2: GlobalHost.DependencyResolver.Register(typeof(IUserToConnectionMappingService), () => new GroupsMappingService()); 3:  4: //for using a static field (in the Global class) 5: GlobalHost.DependencyResolver.Register(typeof(IUserToConnectionMappingService), () => new StaticMappingService()); 6:  7: //retrieving the current service (in the Hub class) 8: var mapping = GlobalHost.DependencyResolver.Resolve<IUserToConnectionMappingService>(); Now all you have to do is implement GroupsMappingService and StaticMappingService with the code I shown here and change SendUserMessage method to rely in the dependency resolver for the actual implementation. Stay tuned for more SignalR posts!

    Read the article

  • Allowing asterisk in URL - ASP.NET MVC 2 - .NET 4.0 or encoding

    - by raRaRa
    I'm having a trouble allowing asterisk (*) in the URL of my website. I am running ASP.NET MVC 2 and .NET 4.0. Here's an example that describes the problem: http://mysite.com/profile/view/Nice* The username is Nice* and ASP.NET says there are illegal characters in the URL: Illegal characters in path. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: Illegal characters in path. I have tried all the Web.config methods I've seen online such as: <pages validateRequest="false"> and <httpRuntime requestPathInvalidCharacters="" requestValidationMode="2.0" /> So my question is: Is it possible to allow asterisk in URL? If not, is there some encoding method in .NET that can encode asterisk(*) ? Thanks!

    Read the article

  • Introduction to the ASP.NET Web API

    - by Stephen.Walther
    I am a huge fan of Ajax. If you want to create a great experience for the users of your website – regardless of whether you are building an ASP.NET MVC or an ASP.NET Web Forms site — then you need to use Ajax. Otherwise, you are just being cruel to your customers. We use Ajax extensively in several of the ASP.NET applications that my company, Superexpert.com, builds. We expose data from the server as JSON and use jQuery to retrieve and update that data from the browser. One challenge, when building an ASP.NET website, is deciding on which technology to use to expose JSON data from the server. For example, how do you expose a list of products from the server as JSON so you can retrieve the list of products with jQuery? You have a number of options (too many options) including ASMX Web services, WCF Web Services, ASHX Generic Handlers, WCF Data Services, and MVC controller actions. Fortunately, the world has just been simplified. With the release of ASP.NET 4 Beta, Microsoft has introduced a new technology for exposing JSON from the server named the ASP.NET Web API. You can use the ASP.NET Web API with both ASP.NET MVC and ASP.NET Web Forms applications. The goal of this blog post is to provide you with a brief overview of the features of the new ASP.NET Web API. You learn how to use the ASP.NET Web API to retrieve, insert, update, and delete database records with jQuery. We also discuss how you can perform form validation when using the Web API and use OData when using the Web API. Creating an ASP.NET Web API Controller The ASP.NET Web API exposes JSON data through a new type of controller called an API controller. You can add an API controller to an existing ASP.NET MVC 4 project through the standard Add Controller dialog box. Right-click your Controllers folder and select Add, Controller. In the dialog box, name your controller MovieController and select the Empty API controller template: A brand new API controller looks like this: using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web.Http; namespace MyWebAPIApp.Controllers { public class MovieController : ApiController { } } An API controller, unlike a standard MVC controller, derives from the base ApiController class instead of the base Controller class. Using jQuery to Retrieve, Insert, Update, and Delete Data Let’s create an Ajaxified Movie Database application. We’ll retrieve, insert, update, and delete movies using jQuery with the MovieController which we just created. Our Movie model class looks like this: namespace MyWebAPIApp.Models { public class Movie { public int Id { get; set; } public string Title { get; set; } public string Director { get; set; } } } Our application will consist of a single HTML page named Movies.html. We’ll place all of our jQuery code in the Movies.html page. Getting a Single Record with the ASP.NET Web API To support retrieving a single movie from the server, we need to add a Get method to our API controller: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using MyWebAPIApp.Models; namespace MyWebAPIApp.Controllers { public class MovieController : ApiController { public Movie GetMovie(int id) { // Return movie by id if (id == 1) { return new Movie { Id = 1, Title = "Star Wars", Director = "Lucas" }; } // Otherwise, movie was not found throw new HttpResponseException(HttpStatusCode.NotFound); } } } In the code above, the GetMovie() method accepts the Id of a movie. If the Id has the value 1 then the method returns the movie Star Wars. Otherwise, the method throws an exception and returns 404 Not Found HTTP status code. After building your project, you can invoke the MovieController.GetMovie() method by entering the following URL in your web browser address bar: http://localhost:[port]/api/movie/1 (You’ll need to enter the correct randomly generated port). In the URL api/movie/1, the first “api” segment indicates that this is a Web API route. The “movie” segment indicates that the MovieController should be invoked. You do not specify the name of the action. Instead, the HTTP method used to make the request – GET, POST, PUT, DELETE — is used to identify the action to invoke. The ASP.NET Web API uses different routing conventions than normal ASP.NET MVC controllers. When you make an HTTP GET request then any API controller method with a name that starts with “GET” is invoked. So, we could have called our API controller action GetPopcorn() instead of GetMovie() and it would still be invoked by the URL api/movie/1. The default route for the Web API is defined in the Global.asax file and it looks like this: routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); We can invoke our GetMovie() controller action with the jQuery code in the following HTML page: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Get Movie</title> </head> <body> <div> Title: <span id="title"></span> </div> <div> Director: <span id="director"></span> </div> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> getMovie(1, function (movie) { $("#title").html(movie.Title); $("#director").html(movie.Director); }); function getMovie(id, callback) { $.ajax({ url: "/api/Movie", data: { id: id }, type: "GET", contentType: "application/json;charset=utf-8", statusCode: { 200: function (movie) { callback(movie); }, 404: function () { alert("Not Found!"); } } }); } </script> </body> </html> In the code above, the jQuery $.ajax() method is used to invoke the GetMovie() method. Notice that the Ajax call handles two HTTP response codes. When the GetMove() method successfully returns a movie, the method returns a 200 status code. In that case, the details of the movie are displayed in the HTML page. Otherwise, if the movie is not found, the GetMovie() method returns a 404 status code. In that case, the page simply displays an alert box indicating that the movie was not found (hopefully, you would implement something more graceful in an actual application). You can use your browser’s Developer Tools to see what is going on in the background when you open the HTML page (hit F12 in the most recent version of most browsers). For example, you can use the Network tab in Google Chrome to see the Ajax request which invokes the GetMovie() method: Getting a Set of Records with the ASP.NET Web API Let’s modify our Movie API controller so that it returns a collection of movies. The following Movie controller has a new ListMovies() method which returns a (hard-coded) collection of movies: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using MyWebAPIApp.Models; namespace MyWebAPIApp.Controllers { public class MovieController : ApiController { public IEnumerable<Movie> ListMovies() { return new List<Movie> { new Movie {Id=1, Title="Star Wars", Director="Lucas"}, new Movie {Id=1, Title="King Kong", Director="Jackson"}, new Movie {Id=1, Title="Memento", Director="Nolan"} }; } } } Because we named our action ListMovies(), the default Web API route will never match it. Therefore, we need to add the following custom route to our Global.asax file (at the top of the RegisterRoutes() method): routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); This route enables us to invoke the ListMovies() method with the URL /api/movie/listmovies. Now that we have exposed our collection of movies from the server, we can retrieve and display the list of movies using jQuery in our HTML page: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>List Movies</title> </head> <body> <div id="movies"></div> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> listMovies(function (movies) { var strMovies=""; $.each(movies, function (index, movie) { strMovies += "<div>" + movie.Title + "</div>"; }); $("#movies").html(strMovies); }); function listMovies(callback) { $.ajax({ url: "/api/Movie/ListMovies", data: {}, type: "GET", contentType: "application/json;charset=utf-8", }).then(function(movies){ callback(movies); }); } </script> </body> </html>     Inserting a Record with the ASP.NET Web API Now let’s modify our Movie API controller so it supports creating new records: public HttpResponseMessage<Movie> PostMovie(Movie movieToCreate) { // Add movieToCreate to the database and update primary key movieToCreate.Id = 23; // Build a response that contains the location of the new movie var response = new HttpResponseMessage<Movie>(movieToCreate, HttpStatusCode.Created); var relativePath = "/api/movie/" + movieToCreate.Id; response.Headers.Location = new Uri(Request.RequestUri, relativePath); return response; } The PostMovie() method in the code above accepts a movieToCreate parameter. We don’t actually store the new movie anywhere. In real life, you will want to call a service method to store the new movie in a database. When you create a new resource, such as a new movie, you should return the location of the new resource. In the code above, the URL where the new movie can be retrieved is assigned to the Location header returned in the PostMovie() response. Because the name of our method starts with “Post”, we don’t need to create a custom route. The PostMovie() method can be invoked with the URL /Movie/PostMovie – just as long as the method is invoked within the context of a HTTP POST request. The following HTML page invokes the PostMovie() method. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Create Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var movieToCreate = { title: "The Hobbit", director: "Jackson" }; createMovie(movieToCreate, function (newMovie) { alert("New movie created with an Id of " + newMovie.Id); }); function createMovie(movieToCreate, callback) { $.ajax({ url: "/api/Movie", data: JSON.stringify( movieToCreate ), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (newMovie) { callback(newMovie); } } }); } </script> </body> </html> This page creates a new movie (the Hobbit) by calling the createMovie() method. The page simply displays the Id of the new movie: The HTTP Post operation is performed with the following call to the jQuery $.ajax() method: $.ajax({ url: "/api/Movie", data: JSON.stringify( movieToCreate ), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (newMovie) { callback(newMovie); } } }); Notice that the type of Ajax request is a POST request. This is required to match the PostMovie() method. Notice, furthermore, that the new movie is converted into JSON using JSON.stringify(). The JSON.stringify() method takes a JavaScript object and converts it into a JSON string. Finally, notice that success is represented with a 201 status code. The HttpStatusCode.Created value returned from the PostMovie() method returns a 201 status code. Updating a Record with the ASP.NET Web API Here’s how we can modify the Movie API controller to support updating an existing record. In this case, we need to create a PUT method to handle an HTTP PUT request: public void PutMovie(Movie movieToUpdate) { if (movieToUpdate.Id == 1) { // Update the movie in the database return; } // If you can't find the movie to update throw new HttpResponseException(HttpStatusCode.NotFound); } Unlike our PostMovie() method, the PutMovie() method does not return a result. The action either updates the database or, if the movie cannot be found, returns an HTTP Status code of 404. The following HTML page illustrates how you can invoke the PutMovie() method: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Put Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var movieToUpdate = { id: 1, title: "The Hobbit", director: "Jackson" }; updateMovie(movieToUpdate, function () { alert("Movie updated!"); }); function updateMovie(movieToUpdate, callback) { $.ajax({ url: "/api/Movie", data: JSON.stringify(movieToUpdate), type: "PUT", contentType: "application/json;charset=utf-8", statusCode: { 200: function () { callback(); }, 404: function () { alert("Movie not found!"); } } }); } </script> </body> </html> Deleting a Record with the ASP.NET Web API Here’s the code for deleting a movie: public HttpResponseMessage DeleteMovie(int id) { // Delete the movie from the database // Return status code return new HttpResponseMessage(HttpStatusCode.NoContent); } This method simply deletes the movie (well, not really, but pretend that it does) and returns a No Content status code (204). The following page illustrates how you can invoke the DeleteMovie() action: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Delete Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> deleteMovie(1, function () { alert("Movie deleted!"); }); function deleteMovie(id, callback) { $.ajax({ url: "/api/Movie", data: JSON.stringify({id:id}), type: "DELETE", contentType: "application/json;charset=utf-8", statusCode: { 204: function () { callback(); } } }); } </script> </body> </html> Performing Validation How do you perform form validation when using the ASP.NET Web API? Because validation in ASP.NET MVC is driven by the Default Model Binder, and because the Web API uses the Default Model Binder, you get validation for free. Let’s modify our Movie class so it includes some of the standard validation attributes: using System.ComponentModel.DataAnnotations; namespace MyWebAPIApp.Models { public class Movie { public int Id { get; set; } [Required(ErrorMessage="Title is required!")] [StringLength(5, ErrorMessage="Title cannot be more than 5 characters!")] public string Title { get; set; } [Required(ErrorMessage="Director is required!")] public string Director { get; set; } } } In the code above, the Required validation attribute is used to make both the Title and Director properties required. The StringLength attribute is used to require the length of the movie title to be no more than 5 characters. Now let’s modify our PostMovie() action to validate a movie before adding the movie to the database: public HttpResponseMessage PostMovie(Movie movieToCreate) { // Validate movie if (!ModelState.IsValid) { var errors = new JsonArray(); foreach (var prop in ModelState.Values) { if (prop.Errors.Any()) { errors.Add(prop.Errors.First().ErrorMessage); } } return new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest); } // Add movieToCreate to the database and update primary key movieToCreate.Id = 23; // Build a response that contains the location of the new movie var response = new HttpResponseMessage<Movie>(movieToCreate, HttpStatusCode.Created); var relativePath = "/api/movie/" + movieToCreate.Id; response.Headers.Location = new Uri(Request.RequestUri, relativePath); return response; } If ModelState.IsValid has the value false then the errors in model state are copied to a new JSON array. Each property – such as the Title and Director property — can have multiple errors. In the code above, only the first error message is copied over. The JSON array is returned with a Bad Request status code (400 status code). The following HTML page illustrates how you can invoke our modified PostMovie() action and display any error messages: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Create Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var movieToCreate = { title: "The Hobbit", director: "" }; createMovie(movieToCreate, function (newMovie) { alert("New movie created with an Id of " + newMovie.Id); }, function (errors) { var strErrors = ""; $.each(errors, function(index, err) { strErrors += "*" + err + "\n"; }); alert(strErrors); } ); function createMovie(movieToCreate, success, fail) { $.ajax({ url: "/api/Movie", data: JSON.stringify(movieToCreate), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (newMovie) { success(newMovie); }, 400: function (xhr) { var errors = JSON.parse(xhr.responseText); fail(errors); } } }); } </script> </body> </html> The createMovie() function performs an Ajax request and handles either a 201 or a 400 status code from the response. If a 201 status code is returned then there were no validation errors and the new movie was created. If, on the other hand, a 400 status code is returned then there was a validation error. The validation errors are retrieved from the XmlHttpRequest responseText property. The error messages are displayed in an alert: (Please don’t use JavaScript alert dialogs to display validation errors, I just did it this way out of pure laziness) This validation code in our PostMovie() method is pretty generic. There is nothing specific about this code to the PostMovie() method. In the following video, Jon Galloway demonstrates how to create a global Validation filter which can be used with any API controller action: http://www.asp.net/web-api/overview/web-api-routing-and-actions/video-custom-validation His validation filter looks like this: using System.Json; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace MyWebAPIApp.Filters { public class ValidationActionFilter:ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { var modelState = actionContext.ModelState; if (!modelState.IsValid) { dynamic errors = new JsonObject(); foreach (var key in modelState.Keys) { var state = modelState[key]; if (state.Errors.Any()) { errors[key] = state.Errors.First().ErrorMessage; } } actionContext.Response = new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest); } } } } And you can register the validation filter in the Application_Start() method in the Global.asax file like this: GlobalConfiguration.Configuration.Filters.Add(new ValidationActionFilter()); After you register the Validation filter, validation error messages are returned from any API controller action method automatically when validation fails. You don’t need to add any special logic to any of your API controller actions to take advantage of the filter. Querying using OData The OData protocol is an open protocol created by Microsoft which enables you to perform queries over the web. The official website for OData is located here: http://odata.org For example, here are some of the query options which you can use with OData: · $orderby – Enables you to retrieve results in a certain order. · $top – Enables you to retrieve a certain number of results. · $skip – Enables you to skip over a certain number of results (use with $top for paging). · $filter – Enables you to filter the results returned. The ASP.NET Web API supports a subset of the OData protocol. You can use all of the query options listed above when interacting with an API controller. The only requirement is that the API controller action returns its data as IQueryable. For example, the following Movie controller has an action named GetMovies() which returns an IQueryable of movies: public IQueryable<Movie> GetMovies() { return new List<Movie> { new Movie {Id=1, Title="Star Wars", Director="Lucas"}, new Movie {Id=2, Title="King Kong", Director="Jackson"}, new Movie {Id=3, Title="Willow", Director="Lucas"}, new Movie {Id=4, Title="Shrek", Director="Smith"}, new Movie {Id=5, Title="Memento", Director="Nolan"} }.AsQueryable(); } If you enter the following URL in your browser: /api/movie?$top=2&$orderby=Title Then you will limit the movies returned to the top 2 in order of the movie Title. You will get the following results: By using the $top option in combination with the $skip option, you can enable client-side paging. For example, you can use $top and $skip to page through thousands of products, 10 products at a time. The $filter query option is very powerful. You can use this option to filter the results from a query. Here are some examples: Return every movie directed by Lucas: /api/movie?$filter=Director eq ‘Lucas’ Return every movie which has a title which starts with ‘S’: /api/movie?$filter=startswith(Title,’S') Return every movie which has an Id greater than 2: /api/movie?$filter=Id gt 2 The complete documentation for the $filter option is located here: http://www.odata.org/developers/protocols/uri-conventions#FilterSystemQueryOption Summary The goal of this blog entry was to provide you with an overview of the new ASP.NET Web API introduced with the Beta release of ASP.NET 4. In this post, I discussed how you can retrieve, insert, update, and delete data by using jQuery with the Web API. I also discussed how you can use the standard validation attributes with the Web API. You learned how to return validation error messages to the client and display the error messages using jQuery. Finally, we briefly discussed how the ASP.NET Web API supports the OData protocol. For example, you learned how to filter records returned from an API controller action by using the $filter query option. I’m excited about the new Web API. This is a feature which I expect to use with almost every ASP.NET application which I build in the future.

    Read the article

  • Introduction to the ASP.NET Web API

    - by Stephen.Walther
    I am a huge fan of Ajax. If you want to create a great experience for the users of your website – regardless of whether you are building an ASP.NET MVC or an ASP.NET Web Forms site — then you need to use Ajax. Otherwise, you are just being cruel to your customers. We use Ajax extensively in several of the ASP.NET applications that my company, Superexpert.com, builds. We expose data from the server as JSON and use jQuery to retrieve and update that data from the browser. One challenge, when building an ASP.NET website, is deciding on which technology to use to expose JSON data from the server. For example, how do you expose a list of products from the server as JSON so you can retrieve the list of products with jQuery? You have a number of options (too many options) including ASMX Web services, WCF Web Services, ASHX Generic Handlers, WCF Data Services, and MVC controller actions. Fortunately, the world has just been simplified. With the release of ASP.NET 4 Beta, Microsoft has introduced a new technology for exposing JSON from the server named the ASP.NET Web API. You can use the ASP.NET Web API with both ASP.NET MVC and ASP.NET Web Forms applications. The goal of this blog post is to provide you with a brief overview of the features of the new ASP.NET Web API. You learn how to use the ASP.NET Web API to retrieve, insert, update, and delete database records with jQuery. We also discuss how you can perform form validation when using the Web API and use OData when using the Web API. Creating an ASP.NET Web API Controller The ASP.NET Web API exposes JSON data through a new type of controller called an API controller. You can add an API controller to an existing ASP.NET MVC 4 project through the standard Add Controller dialog box. Right-click your Controllers folder and select Add, Controller. In the dialog box, name your controller MovieController and select the Empty API controller template: A brand new API controller looks like this: using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web.Http; namespace MyWebAPIApp.Controllers { public class MovieController : ApiController { } } An API controller, unlike a standard MVC controller, derives from the base ApiController class instead of the base Controller class. Using jQuery to Retrieve, Insert, Update, and Delete Data Let’s create an Ajaxified Movie Database application. We’ll retrieve, insert, update, and delete movies using jQuery with the MovieController which we just created. Our Movie model class looks like this: namespace MyWebAPIApp.Models { public class Movie { public int Id { get; set; } public string Title { get; set; } public string Director { get; set; } } } Our application will consist of a single HTML page named Movies.html. We’ll place all of our jQuery code in the Movies.html page. Getting a Single Record with the ASP.NET Web API To support retrieving a single movie from the server, we need to add a Get method to our API controller: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using MyWebAPIApp.Models; namespace MyWebAPIApp.Controllers { public class MovieController : ApiController { public Movie GetMovie(int id) { // Return movie by id if (id == 1) { return new Movie { Id = 1, Title = "Star Wars", Director = "Lucas" }; } // Otherwise, movie was not found throw new HttpResponseException(HttpStatusCode.NotFound); } } } In the code above, the GetMovie() method accepts the Id of a movie. If the Id has the value 1 then the method returns the movie Star Wars. Otherwise, the method throws an exception and returns 404 Not Found HTTP status code. After building your project, you can invoke the MovieController.GetMovie() method by entering the following URL in your web browser address bar: http://localhost:[port]/api/movie/1 (You’ll need to enter the correct randomly generated port). In the URL api/movie/1, the first “api” segment indicates that this is a Web API route. The “movie” segment indicates that the MovieController should be invoked. You do not specify the name of the action. Instead, the HTTP method used to make the request – GET, POST, PUT, DELETE — is used to identify the action to invoke. The ASP.NET Web API uses different routing conventions than normal ASP.NET MVC controllers. When you make an HTTP GET request then any API controller method with a name that starts with “GET” is invoked. So, we could have called our API controller action GetPopcorn() instead of GetMovie() and it would still be invoked by the URL api/movie/1. The default route for the Web API is defined in the Global.asax file and it looks like this: routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); We can invoke our GetMovie() controller action with the jQuery code in the following HTML page: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Get Movie</title> </head> <body> <div> Title: <span id="title"></span> </div> <div> Director: <span id="director"></span> </div> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> getMovie(1, function (movie) { $("#title").html(movie.Title); $("#director").html(movie.Director); }); function getMovie(id, callback) { $.ajax({ url: "/api/Movie", data: { id: id }, type: "GET", contentType: "application/json;charset=utf-8", statusCode: { 200: function (movie) { callback(movie); }, 404: function () { alert("Not Found!"); } } }); } </script> </body> </html> In the code above, the jQuery $.ajax() method is used to invoke the GetMovie() method. Notice that the Ajax call handles two HTTP response codes. When the GetMove() method successfully returns a movie, the method returns a 200 status code. In that case, the details of the movie are displayed in the HTML page. Otherwise, if the movie is not found, the GetMovie() method returns a 404 status code. In that case, the page simply displays an alert box indicating that the movie was not found (hopefully, you would implement something more graceful in an actual application). You can use your browser’s Developer Tools to see what is going on in the background when you open the HTML page (hit F12 in the most recent version of most browsers). For example, you can use the Network tab in Google Chrome to see the Ajax request which invokes the GetMovie() method: Getting a Set of Records with the ASP.NET Web API Let’s modify our Movie API controller so that it returns a collection of movies. The following Movie controller has a new ListMovies() method which returns a (hard-coded) collection of movies: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using MyWebAPIApp.Models; namespace MyWebAPIApp.Controllers { public class MovieController : ApiController { public IEnumerable<Movie> ListMovies() { return new List<Movie> { new Movie {Id=1, Title="Star Wars", Director="Lucas"}, new Movie {Id=1, Title="King Kong", Director="Jackson"}, new Movie {Id=1, Title="Memento", Director="Nolan"} }; } } } Because we named our action ListMovies(), the default Web API route will never match it. Therefore, we need to add the following custom route to our Global.asax file (at the top of the RegisterRoutes() method): routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); This route enables us to invoke the ListMovies() method with the URL /api/movie/listmovies. Now that we have exposed our collection of movies from the server, we can retrieve and display the list of movies using jQuery in our HTML page: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>List Movies</title> </head> <body> <div id="movies"></div> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> listMovies(function (movies) { var strMovies=""; $.each(movies, function (index, movie) { strMovies += "<div>" + movie.Title + "</div>"; }); $("#movies").html(strMovies); }); function listMovies(callback) { $.ajax({ url: "/api/Movie/ListMovies", data: {}, type: "GET", contentType: "application/json;charset=utf-8", }).then(function(movies){ callback(movies); }); } </script> </body> </html>     Inserting a Record with the ASP.NET Web API Now let’s modify our Movie API controller so it supports creating new records: public HttpResponseMessage<Movie> PostMovie(Movie movieToCreate) { // Add movieToCreate to the database and update primary key movieToCreate.Id = 23; // Build a response that contains the location of the new movie var response = new HttpResponseMessage<Movie>(movieToCreate, HttpStatusCode.Created); var relativePath = "/api/movie/" + movieToCreate.Id; response.Headers.Location = new Uri(Request.RequestUri, relativePath); return response; } The PostMovie() method in the code above accepts a movieToCreate parameter. We don’t actually store the new movie anywhere. In real life, you will want to call a service method to store the new movie in a database. When you create a new resource, such as a new movie, you should return the location of the new resource. In the code above, the URL where the new movie can be retrieved is assigned to the Location header returned in the PostMovie() response. Because the name of our method starts with “Post”, we don’t need to create a custom route. The PostMovie() method can be invoked with the URL /Movie/PostMovie – just as long as the method is invoked within the context of a HTTP POST request. The following HTML page invokes the PostMovie() method. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Create Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var movieToCreate = { title: "The Hobbit", director: "Jackson" }; createMovie(movieToCreate, function (newMovie) { alert("New movie created with an Id of " + newMovie.Id); }); function createMovie(movieToCreate, callback) { $.ajax({ url: "/api/Movie", data: JSON.stringify( movieToCreate ), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (newMovie) { callback(newMovie); } } }); } </script> </body> </html> This page creates a new movie (the Hobbit) by calling the createMovie() method. The page simply displays the Id of the new movie: The HTTP Post operation is performed with the following call to the jQuery $.ajax() method: $.ajax({ url: "/api/Movie", data: JSON.stringify( movieToCreate ), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (newMovie) { callback(newMovie); } } }); Notice that the type of Ajax request is a POST request. This is required to match the PostMovie() method. Notice, furthermore, that the new movie is converted into JSON using JSON.stringify(). The JSON.stringify() method takes a JavaScript object and converts it into a JSON string. Finally, notice that success is represented with a 201 status code. The HttpStatusCode.Created value returned from the PostMovie() method returns a 201 status code. Updating a Record with the ASP.NET Web API Here’s how we can modify the Movie API controller to support updating an existing record. In this case, we need to create a PUT method to handle an HTTP PUT request: public void PutMovie(Movie movieToUpdate) { if (movieToUpdate.Id == 1) { // Update the movie in the database return; } // If you can't find the movie to update throw new HttpResponseException(HttpStatusCode.NotFound); } Unlike our PostMovie() method, the PutMovie() method does not return a result. The action either updates the database or, if the movie cannot be found, returns an HTTP Status code of 404. The following HTML page illustrates how you can invoke the PutMovie() method: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Put Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var movieToUpdate = { id: 1, title: "The Hobbit", director: "Jackson" }; updateMovie(movieToUpdate, function () { alert("Movie updated!"); }); function updateMovie(movieToUpdate, callback) { $.ajax({ url: "/api/Movie", data: JSON.stringify(movieToUpdate), type: "PUT", contentType: "application/json;charset=utf-8", statusCode: { 200: function () { callback(); }, 404: function () { alert("Movie not found!"); } } }); } </script> </body> </html> Deleting a Record with the ASP.NET Web API Here’s the code for deleting a movie: public HttpResponseMessage DeleteMovie(int id) { // Delete the movie from the database // Return status code return new HttpResponseMessage(HttpStatusCode.NoContent); } This method simply deletes the movie (well, not really, but pretend that it does) and returns a No Content status code (204). The following page illustrates how you can invoke the DeleteMovie() action: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Delete Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> deleteMovie(1, function () { alert("Movie deleted!"); }); function deleteMovie(id, callback) { $.ajax({ url: "/api/Movie", data: JSON.stringify({id:id}), type: "DELETE", contentType: "application/json;charset=utf-8", statusCode: { 204: function () { callback(); } } }); } </script> </body> </html> Performing Validation How do you perform form validation when using the ASP.NET Web API? Because validation in ASP.NET MVC is driven by the Default Model Binder, and because the Web API uses the Default Model Binder, you get validation for free. Let’s modify our Movie class so it includes some of the standard validation attributes: using System.ComponentModel.DataAnnotations; namespace MyWebAPIApp.Models { public class Movie { public int Id { get; set; } [Required(ErrorMessage="Title is required!")] [StringLength(5, ErrorMessage="Title cannot be more than 5 characters!")] public string Title { get; set; } [Required(ErrorMessage="Director is required!")] public string Director { get; set; } } } In the code above, the Required validation attribute is used to make both the Title and Director properties required. The StringLength attribute is used to require the length of the movie title to be no more than 5 characters. Now let’s modify our PostMovie() action to validate a movie before adding the movie to the database: public HttpResponseMessage PostMovie(Movie movieToCreate) { // Validate movie if (!ModelState.IsValid) { var errors = new JsonArray(); foreach (var prop in ModelState.Values) { if (prop.Errors.Any()) { errors.Add(prop.Errors.First().ErrorMessage); } } return new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest); } // Add movieToCreate to the database and update primary key movieToCreate.Id = 23; // Build a response that contains the location of the new movie var response = new HttpResponseMessage<Movie>(movieToCreate, HttpStatusCode.Created); var relativePath = "/api/movie/" + movieToCreate.Id; response.Headers.Location = new Uri(Request.RequestUri, relativePath); return response; } If ModelState.IsValid has the value false then the errors in model state are copied to a new JSON array. Each property – such as the Title and Director property — can have multiple errors. In the code above, only the first error message is copied over. The JSON array is returned with a Bad Request status code (400 status code). The following HTML page illustrates how you can invoke our modified PostMovie() action and display any error messages: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Create Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var movieToCreate = { title: "The Hobbit", director: "" }; createMovie(movieToCreate, function (newMovie) { alert("New movie created with an Id of " + newMovie.Id); }, function (errors) { var strErrors = ""; $.each(errors, function(index, err) { strErrors += "*" + err + "n"; }); alert(strErrors); } ); function createMovie(movieToCreate, success, fail) { $.ajax({ url: "/api/Movie", data: JSON.stringify(movieToCreate), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (newMovie) { success(newMovie); }, 400: function (xhr) { var errors = JSON.parse(xhr.responseText); fail(errors); } } }); } </script> </body> </html> The createMovie() function performs an Ajax request and handles either a 201 or a 400 status code from the response. If a 201 status code is returned then there were no validation errors and the new movie was created. If, on the other hand, a 400 status code is returned then there was a validation error. The validation errors are retrieved from the XmlHttpRequest responseText property. The error messages are displayed in an alert: (Please don’t use JavaScript alert dialogs to display validation errors, I just did it this way out of pure laziness) This validation code in our PostMovie() method is pretty generic. There is nothing specific about this code to the PostMovie() method. In the following video, Jon Galloway demonstrates how to create a global Validation filter which can be used with any API controller action: http://www.asp.net/web-api/overview/web-api-routing-and-actions/video-custom-validation His validation filter looks like this: using System.Json; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace MyWebAPIApp.Filters { public class ValidationActionFilter:ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { var modelState = actionContext.ModelState; if (!modelState.IsValid) { dynamic errors = new JsonObject(); foreach (var key in modelState.Keys) { var state = modelState[key]; if (state.Errors.Any()) { errors[key] = state.Errors.First().ErrorMessage; } } actionContext.Response = new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest); } } } } And you can register the validation filter in the Application_Start() method in the Global.asax file like this: GlobalConfiguration.Configuration.Filters.Add(new ValidationActionFilter()); After you register the Validation filter, validation error messages are returned from any API controller action method automatically when validation fails. You don’t need to add any special logic to any of your API controller actions to take advantage of the filter. Querying using OData The OData protocol is an open protocol created by Microsoft which enables you to perform queries over the web. The official website for OData is located here: http://odata.org For example, here are some of the query options which you can use with OData: · $orderby – Enables you to retrieve results in a certain order. · $top – Enables you to retrieve a certain number of results. · $skip – Enables you to skip over a certain number of results (use with $top for paging). · $filter – Enables you to filter the results returned. The ASP.NET Web API supports a subset of the OData protocol. You can use all of the query options listed above when interacting with an API controller. The only requirement is that the API controller action returns its data as IQueryable. For example, the following Movie controller has an action named GetMovies() which returns an IQueryable of movies: public IQueryable<Movie> GetMovies() { return new List<Movie> { new Movie {Id=1, Title="Star Wars", Director="Lucas"}, new Movie {Id=2, Title="King Kong", Director="Jackson"}, new Movie {Id=3, Title="Willow", Director="Lucas"}, new Movie {Id=4, Title="Shrek", Director="Smith"}, new Movie {Id=5, Title="Memento", Director="Nolan"} }.AsQueryable(); } If you enter the following URL in your browser: /api/movie?$top=2&$orderby=Title Then you will limit the movies returned to the top 2 in order of the movie Title. You will get the following results: By using the $top option in combination with the $skip option, you can enable client-side paging. For example, you can use $top and $skip to page through thousands of products, 10 products at a time. The $filter query option is very powerful. You can use this option to filter the results from a query. Here are some examples: Return every movie directed by Lucas: /api/movie?$filter=Director eq ‘Lucas’ Return every movie which has a title which starts with ‘S’: /api/movie?$filter=startswith(Title,’S') Return every movie which has an Id greater than 2: /api/movie?$filter=Id gt 2 The complete documentation for the $filter option is located here: http://www.odata.org/developers/protocols/uri-conventions#FilterSystemQueryOption Summary The goal of this blog entry was to provide you with an overview of the new ASP.NET Web API introduced with the Beta release of ASP.NET 4. In this post, I discussed how you can retrieve, insert, update, and delete data by using jQuery with the Web API. I also discussed how you can use the standard validation attributes with the Web API. You learned how to return validation error messages to the client and display the error messages using jQuery. Finally, we briefly discussed how the ASP.NET Web API supports the OData protocol. For example, you learned how to filter records returned from an API controller action by using the $filter query option. I’m excited about the new Web API. This is a feature which I expect to use with almost every ASP.NET application which I build in the future.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >