Search Results

Search found 92675 results on 3707 pages for 'asp net web api'.

Page 7/3707 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • What is New in ASP.NET 4.0 Code Access Security

    - by Xiaohong
    ASP.NET Code Access Security (CAS) is a feature that helps protect server applications on hosting multiple Web sites, ASP.NET lets you assign a configurable trust level that corresponds to a predefined set of permissions. ASP.NET has predefined ASP.NET Trust Levels and Policy Files that you can assign to applications, you also can assign custom trust level and policy files. Most web hosting companies run ASP.NET applications in Medium Trust to prevent that one website affect or harm another site etc. As .NET Framework's Code Access Security model has evolved, ASP.NET 4.0 Code Access Security also has introduced several changes and improvements. The main change in ASP.NET 4.0 CAS In ASP.NET v4.0 partial trust applications, application domain can have a default partial trust permission set as opposed to being full-trust, the permission set name is defined in the <trust /> new attribute permissionSetName that is used to initialize the application domain . By default, the PermissionSetName attribute value is "ASP.Net" which is the name of the permission set you can find in all predefined partial trust configuration files. <trust level="Something" permissionSetName="ASP.Net" /> This is ASP.NET 4.0 new CAS model. For compatibility ASP.NET 4.0 also support legacy CAS model where application domain still has full trust permission set. You can specify new legacyCasModel attribute on the <trust /> element to indicate whether the legacy CAS model is enabled. By default legacyCasModel is false which means that new 4.0 CAS model is the default. <trust level="Something" legacyCasModel="true|false" /> In .Net FX 4.0 Config directory, there are two set of predefined partial trust config files for each new CAS model and legacy CAS model, trust config files with name legacy.XYZ.config are for legacy CAS model: New CAS model: Legacy CAS model: web_hightrust.config legacy.web_hightrust.config web_mediumtrust.config legacy.web_mediumtrust.config web_lowtrust.config legacy.web_lowtrust.config web_minimaltrust.config legacy.web_minimaltrust.config   The figure below shows in ASP.NET 4.0 new CAS model what permission set to grant to code for partial trust application using predefined partial trust levels and policy files:    There also some benefits that comes with the new CAS model: You can lock down a machine by making all managed code no-execute by default (e.g. setting the MyComputer zone to have no managed execution code permissions), it should still be possible to configure ASP.NET web applications to run as either full-trust or partial trust. UNC share doesn’t require full trust with CASPOL at machine-level CAS policy. Side effect that comes with the new CAS model: processRequestInApplicationTrust attribute is deprecated  in new CAS model since application domain always has partial trust permission set in new CAS model.   In ASP.NET 4.0 legacy CAS model or ASP.NET 2.0 CAS model, even though you assign partial trust level to a application but the application domain still has full trust permission set. The figure below shows in ASP.NET 4.0 legacy CAS model (or ASP.NET 2.0 CAS model) what permission set to grant to code for partial trust application using predefined partial trust levels and policy files:     What $AppDirUrl$, $CodeGen$, $Gac$ represents: $AppDirUrl$ The application's virtual root directory. This allows permissions to be applied to code that is located in the application's bin directory. For example, if a virtual directory is mapped to C:\YourWebApp, then $AppDirUrl$ would equate to C:\YourWebApp. $CodeGen$ The directory that contains dynamically generated assemblies (for example, the result of .aspx page compiles). This can be configured on a per application basis and defaults to %windir%\Microsoft.NET\Framework\{version}\Temporary ASP.NET Files. $CodeGen$ allows permissions to be applied to dynamically generated assemblies. $Gac$ Any assembly that is installed in the computer's global assembly cache (GAC). This allows permissions to be granted to strong named assemblies loaded from the GAC by the Web application.   The new customization of CAS Policy in ASP.NET 4.0 new CAS model 1. Define which named permission set in partial trust configuration files By default the permission set that will be assigned at application domain initialization time is the named "ASP.Net" permission set found in all predefined partial trust configuration files. However ASP.NET 4.0 allows you set PermissionSetName attribute to define which named permission set in a partial trust configuration file should be the one used to initialize an application domain. Example: add "ASP.Net_2" named permission set in partial trust configuration file: <PermissionSet class="NamedPermissionSet" version="1" Name="ASP.Net_2"> <IPermission class="FileIOPermission" version="1" Read="$AppDir$" PathDiscovery="$AppDir$" /> <IPermission class="ReflectionPermission" version="1" Flags ="RestrictedMemberAccess" /> <IPermission class="SecurityPermission " version="1" Flags ="Execution, ControlThread, ControlPrincipal, RemotingConfiguration" /></PermissionSet> Then you can use "ASP.Net_2" named permission set for the application domain permission set: <trust level="Something" legacyCasModel="false" permissionSetName="ASP.Net_2" /> 2. Define a custom set of Full Trust Assemblies for an application By using the new fullTrustAssemblies element to configure a set of Full Trust Assemblies for an application, you can modify set of partial trust assemblies to full trust at the machine, site or application level. The configuration definition is shown below: <fullTrustAssemblies> <add assemblyName="MyAssembly" version="1.1.2.3" publicKey="hex_char_representation_of_key_blob" /></fullTrustAssemblies> 3. Define <CodeGroup /> policy in partial trust configuration files ASP.NET 4.0 new CAS model will retain the ability for developers to optionally define <CodeGroup />with membership conditions and assigned permission sets. The specific restriction in ASP.NET 4.0 new CAS model though will be that the results of evaluating custom policies can only result in one of two outcomes: either an assembly is granted full trust, or an assembly is granted the partial trust permission set currently associated with the running application domain. It will not be possible to use custom policies to create additional custom partial trust permission sets. When parsing the partial trust configuration file: Any assemblies that match to code groups associated with "PermissionSet='FullTrust'" will run at full trust. Any assemblies that match to code groups associated with "PermissionSet='Nothing'" will result in a PolicyError being thrown from the CLR. This is acceptable since it provides administrators with a way to do a blanket-deny of managed code followed by selectively defining policy in a <CodeGroup /> that re-adds assemblies that would be allowed to run. Any assemblies that match to code groups associated with other permissions sets will be interpreted to mean the assembly should run at the permission set of the appdomain. This means that even though syntactically a developer could define additional "flavors" of partial trust in an ASP.NET partial trust configuration file, those "flavors" will always be ignored. Example: defines full trust in <CodeGroup /> for my strong named assemblies in partial trust config files: <CodeGroup class="FirstMatchCodeGroup" version="1" PermissionSetName="Nothing"> <IMembershipCondition    class="AllMembershipCondition"    version="1" /> <CodeGroup    class="UnionCodeGroup"    version="1"    PermissionSetName="FullTrust"    Name="My_Strong_Name"    Description="This code group grants code signed full trust. "> <IMembershipCondition      class="StrongNameMembershipCondition" version="1"       PublicKeyBlob="hex_char_representation_of_key_blob" /> </CodeGroup> <CodeGroup   class="UnionCodeGroup" version="1" PermissionSetName="ASP.Net">   <IMembershipCondition class="UrlMembershipCondition" version="1" Url="$AppDirUrl$/*" /> </CodeGroup> <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="ASP.Net">   <IMembershipCondition class="UrlMembershipCondition" version="1" Url="$CodeGen$/*"   /> </CodeGroup></CodeGroup>   4. Customize CAS policy at runtime in ASP.NET 4.0 new CAS model ASP.NET 4.0 new CAS model allows to customize CAS policy at runtime by using custom HostSecurityPolicyResolver that overrides the ASP.NET code access security policy. Example: use custom host security policy resolver to resolve partial trust web application bin folder MyTrustedAssembly.dll to full trust at runtime: You can create a custom host security policy resolver and compile it to assembly MyCustomResolver.dll with strong name enabled and deploy in GAC: public class MyCustomResolver : HostSecurityPolicyResolver{ public override HostSecurityPolicyResults ResolvePolicy(Evidence evidence) { IEnumerator hostEvidence = evidence.GetHostEnumerator(); while (hostEvidence.MoveNext()) { object hostEvidenceObject = hostEvidence.Current; if (hostEvidenceObject is System.Security.Policy.Url) { string assemblyName = hostEvidenceObject.ToString(); if (assemblyName.Contains(“MyTrustedAssembly.dll”) return HostSecurityPolicyResult.FullTrust; } } //default fall-through return HostSecurityPolicyResult.DefaultPolicy; }} Because ASP.NET accesses the custom HostSecurityPolicyResolver during application domain initialization, and a custom policy resolver requires full trust, you also can add a custom policy resolver in <fullTrustAssemblies /> , or deploy in the GAC. You also need configure a custom HostSecurityPolicyResolver instance by adding the HostSecurityPolicyResolverType attribute in the <trust /> element: <trust level="Something" legacyCasModel="false" hostSecurityPolicyResolverType="MyCustomResolver, MyCustomResolver" permissionSetName="ASP.Net" />   Note: If an assembly policy define in <CodeGroup/> and also in hostSecurityPolicyResolverType, hostSecurityPolicyResolverType will win. If an assembly added in <fullTrustAssemblies/> then the assembly has full trust no matter what policy in <CodeGroup/> or in hostSecurityPolicyResolverType.   Other changes in ASP.NET 4.0 CAS Use the new transparency model introduced in .Net Framework 4.0 Change in dynamically compiled code generated assemblies by ASP.NET: In new CAS model they will be marked as security transparent level2 to use Framework 4.0 security transparent rule that means partial trust code is treated as completely Transparent and it is more strict enforcement. In legacy CAS model they will be marked as security transparent level1 to use Framework 2.0 security transparent rule for compatibility. Most of ASP.NET products runtime assemblies are also changed to be marked as security transparent level2 to switch to SecurityTransparent code by default unless SecurityCritical or SecuritySafeCritical attribute specified. You also can look at Security Changes in the .NET Framework 4 for more information about these security attributes. Support conditional APTCA If an assembly is marked with the Conditional APTCA attribute to allow partially trusted callers, and if you want to make the assembly both visible and accessible to partial-trust code in your web application, you must add a reference to the assembly in the partialTrustVisibleAssemblies section: <partialTrustVisibleAssemblies> <add assemblyName="MyAssembly" publicKey="hex_char_representation_of_key_blob" />/partialTrustVisibleAssemblies>   Most of ASP.NET products runtime assemblies are also changed to be marked as conditional APTCA to prevent use of ASP.NET APIs in partial trust environments such as Winforms or WPF UI controls hosted in Internet Explorer.   Differences between ASP.NET new CAS model and legacy CAS model: Here list some differences between ASP.NET new CAS model and legacy CAS model ASP.NET 4.0 legacy CAS model  : Asp.net partial trust appdomains have full trust permission Multiple different permission sets in a single appdomain are allowed in ASP.NET partial trust configuration files Code groups Machine CAS policy is honored processRequestInApplicationTrust attribute is still honored    New configuration setting for legacy model: <trust level="Something" legacyCASModel="true" ></trust><partialTrustVisibleAssemblies> <add assemblyName="MyAssembly" publicKey="hex_char_representation_of_key_blob" /></partialTrustVisibleAssemblies>   ASP.NET 4.0 new CAS model: ASP.NET will now run in homogeneous application domains. Only full trust or the app-domain's partial trust grant set, are allowable permission sets. It is no longer possible to define arbitrary permission sets that get assigned to different assemblies. If an application currently depends on fine-tuning the partial trust permission set using the ASP.NET partial trust configuration file, this will no longer be possible. processRequestInApplicationTrust attribute is deprecated Dynamically compiled assemblies output by ASP.NET build providers will be updated to explicitly mark assemblies as transparent. ASP.NET partial trust grant sets will be independent from any enterprise, machine, or user CAS policy levels. A simplified model for locking down web servers that only allows trusted managed web applications to run. Machine policy used to always grant full-trust to managed code (based on membership conditions) can instead be configured using the new ASP.NET 4.0 full-trust assembly configuration section. The full-trust assembly configuration section requires explicitly listing each assembly as opposed to using membership conditions. Alternatively, the membership condition(s) used in machine policy can instead be re-defined in a <CodeGroup /> within ASP.NET's partial trust configuration file to grant full-trust.   New configuration setting for new model: <trust level="Something" legacyCASModel="false" permissionSetName="ASP.Net" hostSecurityPolicyResolverType=".NET type string" ></trust><fullTrustAssemblies> <add assemblyName=”MyAssembly” version=”1.0.0.0” publicKey="hex_char_representation_of_key_blob" /></fullTrustAssemblies><partialTrustVisibleAssemblies> <add assemblyName="MyAssembly" publicKey="hex_char_representation_of_key_blob" /></partialTrustVisibleAssemblies>     Hope this post is helpful to better understand the ASP.Net 4.0 CAS. Xiaohong Tang ASP.NET QA Team

    Read the article

  • ASP.NET MVC for the php/asp noob

    - by dotjosh
    I was talking to a friend today, who's foremost a php developer, about his thoughts on Umbraco and he said "Well they're apparently working feverishly on the new version of Umbraco, which will be MVC... which i still don't know what that means, but I know you like it." I ended up giving him a ground up explanation of ASP.NET MVC, so I'm posting this so he can link this to his friends and for anyone else who finds it useful.  The whole goal was to be as simple as possible, not being focused on proper syntax. Model-View-Controller (or MVC) is just a pattern that is used for handling UI interaction with your backend.  In a typical web app, you can imagine the *M*odel as your database model, the *V*iew as your HTML page, and the *C*ontroller as the class inbetween.  MVC handles your web request different than your typical php/asp app.In your php/asp app, your url maps directly to a php/asp file that contains html, mixed with database access code and redirects.In an MVC app, your url route is mapped to a method on a class (the controller).  The body of this method can do some database access and THEN decide which *V*iew (html/aspx page) should be displayed;  putting the controller in charge and not the view... a clear seperation of concerns that provides better reusibility and generally promotes cleaner code. Mysite.com, a quick example:Let's say you hit the following url in your application: http://www.mysite.com/Product/ShowItem?Id=4 To avoid tedious configuration, MVC uses a lot of conventions by default. For instance, the above url in your app would automatically make MVC search for a .net class with the name "Product" and a method named "ShowItem" based on the pattern of the url.  So if you name things properly, your method would automatically be called when you entered the above url.  Additionally, it would automatically map/hydrate the "int id" parameter that was in your querystring, matched by name.Product.cspublic class Product : Controller{    public ViewResult ShowItem(int id)    {        return View();    }} From this point you can write the code in the body of this method to do some database access and then pass a "bag" (also known as the ViewData) of data to your chosen *V*iew (html page) to use for display.  The view(html) ONLY needs to be worried about displaying the flattened data that it's been given in the best way it can;  this allows the view to be reused throughout your application as *just* a view, and not be coupled to HOW the data for that view get's loaded.. Product.cspublic class Product : Controller{    public ViewResult ShowItem(int id)    {        var database = new Database();        var item = database.GetItem(id);        ViewData["TheItem"] = item;        return View();    }} Again by convention, since the class' method name is "ShowItem", it'll search for a view named "ShowItem.aspx" by default, and pass the ViewData bag to it to use. ShowItem.aspx<html>     <body>      <%        var item =(Item)ViewData["TheItem"]       %>       <h1><%= item.FullProductName %></h1>     </body></html> BUT WAIT! WHY DOES MICROSOFT HAVE TO DO THINGS SO DIFFERENTLY!?They aren't... here are some other frameworks you may have heard of that use the same pattern in a their own way: Ruby On Rails Grails Spring MVC Struts Django    

    Read the article

  • Routing Issue in ASP.NET MVC 3 RC 2

    - by imran_ku07
         Introduction:             Two weeks ago, ASP.NET MVC team shipped the ASP.NET MVC 3 RC 2 release. This release includes some new features and some performance optimization. This release also fixes most of the bugs but still some minor issues are present in this release. Some of these issues are already discussed by Scott Guthrie at Update on ASP.NET MVC 3 RC2 (and a workaround for a bug in it). In addition to these issues, I have found another issue in this release regarding routing. In this article, I will show you the issue regarding routing and a simple workaround for this issue.       Description:             The easiest way to understand an issue is to reproduce it in the application. So create a MVC 2 application and a MVC 3 RC 2 application. Then in both applications, just open global.asax file and update the default route as below,     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id1}/{id2}", // URL with parameters new { controller = "Home", action = "Index", id1 = UrlParameter.Optional, id2 = UrlParameter.Optional } // Parameter defaults );              Then just open Index View and add the following lines,    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Home Page </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <% Html.RenderAction("About"); %> </asp:Content>             The above view will issue a child request to About action method. Now run both applications. ASP.NET MVC 2 application will run just fine. But ASP.NET MVC 3 RC 2 application will throw an exception as shown below,                  You may think that this is a routing issue but this is not the case here as both ASP.NET MVC 2 and ASP.NET MVC  3 RC 2 applications(created above) are built with .NET Framework 4.0 and both will use the same routing defined in System.Web. Something is wrong in ASP.NET MVC 3 RC 2. So after digging into ASP.NET MVC source code, I have found that the UrlParameter class in ASP.NET MVC 3 RC 2 overrides the ToString method which simply return an empty string.     public sealed class UrlParameter { public static readonly UrlParameter Optional = new UrlParameter(); private UrlParameter() { } public override string ToString() { return string.Empty; } }             In MVC 2 the ToString method was not overridden. So to quickly fix the above problem just replace UrlParameter.Optional default value with a different value other than null or empty(for example, a single white space) or replace UrlParameter.Optional default value with a new class object containing the same code as UrlParameter class have except the ToString method is not overridden (or with a overridden ToString method that return a string value other than null or empty). But by doing this you will loose the benefit of ASP.NET MVC 2 Optional URL Parameters. There may be many different ways to fix the above problem and not loose the benefit of optional parameters. Here I will create a new class MyUrlParameter with the same code as UrlParameter class have except the ToString method is not overridden. Then I will create a base controller class which contains a constructor to remove all MyUrlParameter route data parameters, same like ASP.NET MVC doing with UrlParameter route data parameters early in the request.     public class BaseController : Controller { public BaseController() { if (System.Web.HttpContext.Current.CurrentHandler is MvcHandler) { RouteValueDictionary rvd = ((MvcHandler)System.Web.HttpContext.Current.CurrentHandler).RequestContext.RouteData.Values; string[] matchingKeys = (from entry in rvd where entry.Value == MyUrlParameter.Optional select entry.Key).ToArray(); foreach (string key in matchingKeys) { rvd.Remove(key); } } } } public class HomeController : BaseController { public ActionResult Index(string id1) { ViewBag.Message = "Welcome to ASP.NET MVC!"; return View(); } public ActionResult About() { return Content("Child Request Contents"); } }     public sealed class MyUrlParameter { public static readonly MyUrlParameter Optional = new MyUrlParameter(); private MyUrlParameter() { } }     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id1}/{id2}", // URL with parameters new { controller = "Home", action = "Index", id1 = MyUrlParameter.Optional, id2 = MyUrlParameter.Optional } // Parameter defaults );             MyUrlParameter class is a copy of UrlParameter class except that MyUrlParameter class not overrides the ToString method. Note that the default route is modified to use MyUrlParameter.Optional instead of UrlParameter.Optional. Also note that BaseController class constructor is removing MyUrlParameter parameters from the current request route data so that the model binder will not bind these parameters with action method parameters. Now just run the ASP.NET MVC 3 RC 2 application again, you will find that it runs just fine.             In case if you are curious to know that why ASP.NET MVC 3 RC 2 application throws an exception if UrlParameter class contains a ToString method which returns an empty string, then you need to know something about a feature of routing for url generation. During url generation, routing will call the ParsedRoute.Bind method internally. This method includes a logic to match the route and build the url. During building the url, ParsedRoute.Bind method will call the ToString method of the route values(in our case this will call the UrlParameter.ToString method) and then append the returned value into url. This method includes a logic after appending the returned value into url that if two continuous returned values are empty then don't match the current route otherwise an incorrect url will be generated. Here is the snippet from ParsedRoute.Bind method which will prove this statement.       if ((builder2.Length > 0) && (builder2[builder2.Length - 1] == '/')) { return null; } builder2.Append("/"); ........................................................... ........................................................... ........................................................... ........................................................... if (RoutePartsEqual(obj3, obj4)) { builder2.Append(UrlEncode(Convert.ToString(obj3, CultureInfo.InvariantCulture))); continue; }             In the above example, both id1 and id2 parameters default values are set to UrlParameter object and UrlParameter class include a ToString method that returns an empty string. That's why this route will not matched.            Summary:             In this article I showed you the issue regarding routing and also showed you how to workaround this problem. I explained this issue with an example by creating a ASP.NET MVC 2 and a ASP.NET MVC 3 RC 2 application. Finally I also explained the reason for this issue. Hopefully you will enjoy this article too.   SyntaxHighlighter.all()

    Read the article

  • New Features in ASP.NET Web API 2 - Part I

    - by dwahlin
    I’m a big fan of ASP.NET Web API. It provides a quick yet powerful way to build RESTful HTTP services that can easily be consumed by a variety of clients. While it’s simple to get started using, it has a wealth of features such as filters, formatters, and message handlers that can be used to extend it when needed. In this post I’m going to provide a quick walk-through of some of the key new features in version 2. I’ll focus on some two of my favorite features that are related to routing and HTTP responses and cover additional features in a future post.   Attribute Routing Routing has been a core feature of Web API since it’s initial release and something that’s built into new Web API projects out-of-the-box. However, there are a few scenarios where defining routes can be challenging such as nested routes (more on that in a moment) and any situation where a lot of custom routes have to be defined. For this example, let’s assume that you’d like to define the following nested route:   /customers/1/orders   This type of route would select a customer with an Id of 1 and then return all of their orders. Defining this type of route in the standard WebApiConfig class is certainly possible, but it isn’t the easiest thing to do for people who don’t understand routing well. Here’s an example of how the route shown above could be defined:   public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "CustomerOrdersApiGet", routeTemplate: "api/customers/{custID}/orders", defaults: new { custID = 0, controller = "Customers", action = "Orders" } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpFormatter()); } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   With attribute based routing, defining these types of nested routes is greatly simplified. To get started you first need to make a call to the new MapHttpAttributeRoutes() method in the standard WebApiConfig class (or a custom class that you may have created that defines your routes) as shown next:   public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Allow for attribute based routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } Once attribute based routes are configured, you can apply the Route attribute to one or more controller actions. Here’s an example:   [HttpGet] [Route("customers/{custId:int}/orders")] public List<Order> Orders(int custId) { var orders = _Repository.GetOrders(custId); if (orders == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); } return orders; }   This example maps the custId route parameter to the custId parameter in the Orders() method and also ensures that the route parameter is typed as an integer. The Orders() method can be called using the following route: /customers/2/orders   While this is extremely easy to use and gets the job done, it doesn’t include the default “api” string on the front of the route that you might be used to seeing. You could add “api” in front of the route and make it “api/customers/{custId:int}/orders” but then you’d have to repeat that across other attribute-based routes as well. To simply this type of task you can add the RoutePrefix attribute above the controller class as shown next so that “api” (or whatever the custom starting point of your route is) is applied to all attribute routes: [RoutePrefix("api")] public class CustomersController : ApiController { [HttpGet] [Route("customers/{custId:int}/orders")] public List<Order> Orders(int custId) { var orders = _Repository.GetOrders(custId); if (orders == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); } return orders; } }   There’s much more that you can do with attribute-based routing in ASP.NET. Check out the following post by Mike Wasson for more details.   Returning Responses with IHttpActionResult The first version of Web API provided a way to return custom HttpResponseMessage objects which were pretty easy to use overall. However, Web API 2 now wraps some of the functionality available in version 1 to simplify the process even more. A new interface named IHttpActionResult (similar to ActionResult in ASP.NET MVC) has been introduced which can be used as the return type for Web API controller actions. To return a custom response you can use new helper methods exposed through ApiController such as: Ok NotFound Exception Unauthorized BadRequest Conflict Redirect InvalidModelState Here’s an example of how IHttpActionResult and the helper methods can be used to cleanup code. This is the typical way to return a custom HTTP response in version 1:   public HttpResponseMessage Delete(int id) { var status = _Repository.DeleteCustomer(id); if (status) { return new HttpResponseMessage(HttpStatusCode.OK); } else { throw new HttpResponseException(HttpStatusCode.NotFound); } } With version 2 we can replace HttpResponseMessage with IHttpActionResult and simplify the code quite a bit:   public IHttpActionResult Delete(int id) { var status = _Repository.DeleteCustomer(id); if (status) { //return new HttpResponseMessage(HttpStatusCode.OK); return Ok(); } else { //throw new HttpResponseException(HttpStatusCode.NotFound); return NotFound(); } } You can also cleanup post (insert) operations as well using the helper methods. Here’s a version 1 post action:   public HttpResponseMessage Post([FromBody]Customer cust) { var newCust = _Repository.InsertCustomer(cust); if (newCust != null) { var msg = new HttpResponseMessage(HttpStatusCode.Created); msg.Headers.Location = new Uri(Request.RequestUri + newCust.ID.ToString()); return msg; } else { throw new HttpResponseException(HttpStatusCode.Conflict); } } This is what the code looks like in version 2:   public IHttpActionResult Post([FromBody]Customer cust) { var newCust = _Repository.InsertCustomer(cust); if (newCust != null) { return Created<Customer>(Request.RequestUri + newCust.ID.ToString(), newCust); } else { return Conflict(); } } More details on IHttpActionResult and the different helper methods provided by the ApiController base class can be found here. Conclusion Although there are several additional features available in Web API 2 that I could cover (CORS support for example), this post focused on two of my favorites features. If you have .NET 4.5.1 available then I definitely recommend checking the new features out. Additional articles that cover features in ASP.NET Web API 2 can be found here.

    Read the article

  • Migration & Modernization: Windows/VB6 Apps to ASP.NET HTML5

    - by Visual WebGui
    I would like to invite you to a webinar we are doing in collaboration with Jeffrey S. Hammond , Principal Analyst serving Application Development & Delivery Professionals at Forrester Research. The webinar is free and it will will introduce the substantial changes brought on by the move to Web Applications and Open Web architectures, and the challenges it places on application development shops. We’ll also introduce how we at Gizmox are helping client navigate this mobile shift and evolve existing...(read more)

    Read the article

  • Mulit-tenant ASP.NET MVC – Controllers

    - by zowens
    Part I – Introduction Part II – Foundation   The time has come to talk about controllers in a multi-tenant ASP.NET MVC architecture. This is actually the most critical design decision you will make when dealing with multi-tenancy with MVC. In my design, I took into account the design goals I mentioned in the introduction about inversion of control and what a tenant is to my design. Be aware that this is only one way to achieve multi-tenant controllers.   The Premise MvcEx (which is a sample written by Rob Ashton) utilizes dynamic controllers. Essentially a controller is “dynamic” in that multiple action results can be placed in different “controllers” with the same name. This approach is a bit too complicated for my design. I wanted to stick with plain old inheritance when dealing with controllers. The basic premise of my controller design is that my main host defines a set of universal controllers. It is the responsibility of the tenant to decide if the tenant would like to utilize these core controllers. This can be done either by straight usage of the controller or inheritance for extension of the functionality defined by the controller. The controller is resolved by a StructureMap container that is attached to the tenant, as discussed in Part II.   Controller Resolution I have been thinking about two different ways to resolve controllers with StructureMap. One way is to use named instances. This is a really easy way to simply pull the controller right out of the container without a lot of fuss. I ultimately chose not to use this approach. The reason for this decision is to ensure that the controllers are named properly. If a controller has a different named instance that the controller type, then the resolution has a significant disconnect and there are no guarantees. The final approach, the one utilized by the sample, is to simply pull all controller types and correlate the type with a controller name. This has a bit of a application start performance disadvantage, but is significantly more approachable for maintainability. For example, if I wanted to go back and add a “ControllerName” attribute, I would just have to change the ControllerFactory to suit my needs.   The Code The container factory that I have built is actually pretty simple. That’s really all we need. The most significant method is the GetControllersFor method. This method makes the model from the Container and determines all the concrete types for IController.  The thing you might notice is that this doesn’t depend on tenants, but rather containers. You could easily use this controller factory for an application that doesn’t utilize multi-tenancy. public class ContainerControllerFactory : IControllerFactory { private readonly ThreadSafeDictionary<IContainer, IDictionary<string, Type>> typeCache; public ContainerControllerFactory(IContainerResolver resolver) { Ensure.Argument.NotNull(resolver, "resolver"); this.ContainerResolver = resolver; this.typeCache = new ThreadSafeDictionary<IContainer, IDictionary<string, Type>>(); } public IContainerResolver ContainerResolver { get; private set; } public virtual IController CreateController(RequestContext requestContext, string controllerName) { var controllerType = this.GetControllerType(requestContext, controllerName); if (controllerType == null) return null; var controller = this.ContainerResolver.Resolve(requestContext).GetInstance(controllerType) as IController; // ensure the action invoker is a ContainerControllerActionInvoker if (controller != null && controller is Controller && !((controller as Controller).ActionInvoker is ContainerControllerActionInvoker)) (controller as Controller).ActionInvoker = new ContainerControllerActionInvoker(this.ContainerResolver); return controller; } public void ReleaseController(IController controller) { if (controller != null && controller is IDisposable) ((IDisposable)controller).Dispose(); } internal static IEnumerable<Type> GetControllersFor(IContainer container) { Ensure.Argument.NotNull(container); return container.Model.InstancesOf<IController>().Select(x => x.ConcreteType).Distinct(); } protected virtual Type GetControllerType(RequestContext requestContext, string controllerName) { Ensure.Argument.NotNull(requestContext, "requestContext"); Ensure.Argument.NotNullOrEmpty(controllerName, "controllerName"); var container = this.ContainerResolver.Resolve(requestContext); var typeDictionary = this.typeCache.GetOrAdd(container, () => GetControllersFor(container).ToDictionary(x => ControllerFriendlyName(x.Name))); Type found = null; if (typeDictionary.TryGetValue(ControllerFriendlyName(controllerName), out found)) return found; return null; } private static string ControllerFriendlyName(string value) { return (value ?? string.Empty).ToLowerInvariant().Without("controller"); } } One thing to note about my implementation is that we do not use namespaces that can be utilized in the default ASP.NET MVC controller factory. This is something that I don’t use and have no desire to implement and test. The reason I am not using namespaces in this situation is because each tenant has its own namespaces and the routing would not make sense in this case.   Because we are using IoC, dependencies are automatically injected into the constructor. For example, a tenant container could implement it’s own IRepository and a controller could be defined in the “main” project. The IRepository from the tenant would be injected into the main project’s controller. This is quite a useful feature.   Again, the source code is on GitHub here.   Up Next Up next is the view resolution. This is a complicated issue, so be prepared. I hope that you have found this series useful. If you have any questions about my implementation so far, send me an email or DM me on Twitter. I have had a lot of great conversations about multi-tenancy so far and I greatly appreciate the feedback!

    Read the article

  • Understanding Request Validation in ASP.NET MVC 3

    - by imran_ku07
         Introduction:             A fact that you must always remember "never ever trust user inputs". An application that trusts user inputs may be easily vulnerable to XSS, XSRF, SQL Injection, etc attacks. XSS and XSRF are very dangerous attacks. So to mitigate these attacks ASP.NET introduced request validation in ASP.NET 1.1. During request validation, ASP.NET will throw HttpRequestValidationException: 'A potentially dangerous XXX value was detected from the client', if he found, < followed by an exclamation(like <!) or < followed by the letters a through z(like <s) or & followed by a pound sign(like &#123) as a part of query string, posted form and cookie collection. In ASP.NET 4.0, request validation becomes extensible. This means that you can extend request validation. Also in ASP.NET 4.0, by default request validation is enabled before the BeginRequest phase of an HTTP request. ASP.NET MVC 3 moves one step further by making request validation granular. This allows you to disable request validation for some properties of a model while maintaining request validation for all other cases. In this article I will show you the use of request validation in ASP.NET MVC 3. Then I will briefly explain the internal working of granular request validation.       Description:             First of all create a new ASP.NET MVC 3 application. Then create a simple model class called MyModel,     public class MyModel { public string Prop1 { get; set; } public string Prop2 { get; set; } }             Then just update the index action method as follows,   public ActionResult Index(MyModel p) { return View(); }             Now just run this application. You will find that everything works just fine. Now just append this query string ?Prop1=<s to the url of this application, you will get the HttpRequestValidationException exception.           Now just decorate the Index action method with [ValidateInputAttribute(false)],   [ValidateInput(false)] public ActionResult Index(MyModel p) { return View(); }             Run this application again with same query string. You will find that your application run without any unhandled exception.           Up to now, there is nothing new in ASP.NET MVC 3 because ValidateInputAttribute was present in the previous versions of ASP.NET MVC. Any problem with this approach? Yes there is a problem with this approach. The problem is that now users can send html for both Prop1 and Prop2 properties and a lot of developers are not aware of it. This means that now everyone can send html with both parameters(e.g, ?Prop1=<s&Prop2=<s). So ValidateInput attribute does not gives you the guarantee that your application is safe to XSS or XSRF. This is the reason why ASP.NET MVC team introduced granular request validation in ASP.NET MVC 3. Let's see this feature.           Remove [ValidateInputAttribute(false)] on Index action and update MyModel class as follows,   public class MyModel { [AllowHtml] public string Prop1 { get; set; } public string Prop2 { get; set; } }             Note that AllowHtml attribute is only decorated on Prop1 property. Run this application again with ?Prop1=<s query string. You will find that your application run just fine. Run this application again with ?Prop1=<s&Prop2=<s query string, you will get HttpRequestValidationException exception. This shows that the granular request validation in ASP.NET MVC 3 only allows users to send html for properties decorated with AllowHtml attribute.            Sometimes you may need to access Request.QueryString or Request.Form directly. You may change your code as follows,   [ValidateInput(false)] public ActionResult Index() { var prop1 = Request.QueryString["Prop1"]; return View(); }             Run this application again, you will get the HttpRequestValidationException exception again even you have [ValidateInput(false)] on your Index action. The reason is that Request flags are still not set to unvalidate. I will explain this later. For making this work you need to use Unvalidated extension method,     public ActionResult Index() { var q = Request.Unvalidated().QueryString; var prop1 = q["Prop1"]; return View(); }             Unvalidated extension method is defined in System.Web.Helpers namespace . So you need to add using System.Web.Helpers; in this class file. Run this application again, your application run just fine.             There you have it. If you are not curious to know the internal working of granular request validation then you can skip next paragraphs completely. If you are interested then carry on reading.             Create a new ASP.NET MVC 2 application, then open global.asax.cs file and the following lines,     protected void Application_BeginRequest() { var q = Request.QueryString; }             Then make the Index action method as,    [ValidateInput(false)] public ActionResult Index(string id) { return View(); }             Please note that the Index action method contains a parameter and this action method is decorated with [ValidateInput(false)]. Run this application again, but now with ?id=<s query string, you will get HttpRequestValidationException exception at Application_BeginRequest method. Now just add the following entry in web.config,   <httpRuntime requestValidationMode="2.0"/>             Now run this application again. This time your application will run just fine. Now just see the following quote from ASP.NET 4 Breaking Changes,   In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request.             This clearly state that request validation is enabled before the BeginRequest phase of an HTTP request. For understanding what does enabled means here, we need to see HttpRequest.ValidateInput, HttpRequest.QueryString and HttpRequest.Form methods/properties in System.Web assembly. Here is the implementation of HttpRequest.ValidateInput, HttpRequest.QueryString and HttpRequest.Form methods/properties in System.Web assembly,     public NameValueCollection Form { get { if (this._form == null) { this._form = new HttpValueCollection(); if (this._wr != null) { this.FillInFormCollection(); } this._form.MakeReadOnly(); } if (this._flags[2]) { this._flags.Clear(2); this.ValidateNameValueCollection(this._form, RequestValidationSource.Form); } return this._form; } } public NameValueCollection QueryString { get { if (this._queryString == null) { this._queryString = new HttpValueCollection(); if (this._wr != null) { this.FillInQueryStringCollection(); } this._queryString.MakeReadOnly(); } if (this._flags[1]) { this._flags.Clear(1); this.ValidateNameValueCollection(this._queryString, RequestValidationSource.QueryString); } return this._queryString; } } public void ValidateInput() { if (!this._flags[0x8000]) { this._flags.Set(0x8000); this._flags.Set(1); this._flags.Set(2); this._flags.Set(4); this._flags.Set(0x40); this._flags.Set(0x80); this._flags.Set(0x100); this._flags.Set(0x200); this._flags.Set(8); } }             The above code indicates that HttpRequest.QueryString and HttpRequest.Form will only validate the querystring and form collection if certain flags are set. These flags are automatically set if you call HttpRequest.ValidateInput method. Now run the above application again(don't forget to append ?id=<s query string in the url) with the same settings(i.e, requestValidationMode="2.0" setting in web.config and Application_BeginRequest method in global.asax.cs), your application will run just fine. Now just update the Application_BeginRequest method as,   protected void Application_BeginRequest() { Request.ValidateInput(); var q = Request.QueryString; }             Note that I am calling Request.ValidateInput method prior to use Request.QueryString property. ValidateInput method will internally set certain flags(discussed above). These flags will then tells the Request.QueryString (and Request.Form) property that validate the query string(or form) when user call Request.QueryString(or Request.Form) property. So running this application again with ?id=<s query string will throw HttpRequestValidationException exception. Now I hope it is clear to you that what does requestValidationMode do. It just tells the ASP.NET that not invoke the Request.ValidateInput method internally before the BeginRequest phase of an HTTP request if requestValidationMode is set to a value less than 4.0 in web.config. Here is the implementation of HttpRequest.ValidateInputIfRequiredByConfig method which will prove this statement(Don't be confused with HttpRequest and Request. Request is the property of HttpRequest class),    internal void ValidateInputIfRequiredByConfig() { ............................................................... ............................................................... ............................................................... ............................................................... if (httpRuntime.RequestValidationMode >= VersionUtil.Framework40) { this.ValidateInput(); } }              Hopefully the above discussion will clear you how requestValidationMode works in ASP.NET 4. It is also interesting to note that both HttpRequest.QueryString and HttpRequest.Form only throws the exception when you access them first time. Any subsequent access to HttpRequest.QueryString and HttpRequest.Form will not throw any exception. Continuing with the above example, just update Application_BeginRequest method in global.asax.cs file as,   protected void Application_BeginRequest() { try { var q = Request.QueryString; var f = Request.Form; } catch//swallow this exception { } var q1 = Request.QueryString; var f1 = Request.Form; }             Without setting requestValidationMode to 2.0 and without decorating ValidateInput attribute on Index action, your application will work just fine because both HttpRequest.QueryString and HttpRequest.Form will clear their flags after reading HttpRequest.QueryString and HttpRequest.Form for the first time(see the implementation of HttpRequest.QueryString and HttpRequest.Form above).           Now let's see ASP.NET MVC 3 granular request validation internal working. First of all we need to see type of HttpRequest.QueryString and HttpRequest.Form properties. Both HttpRequest.QueryString and HttpRequest.Form properties are of type NameValueCollection which is inherited from the NameObjectCollectionBase class. NameObjectCollectionBase class contains _entriesArray, _entriesTable, NameObjectEntry.Key and NameObjectEntry.Value fields which granular request validation uses internally. In addition granular request validation also uses _queryString, _form and _flags fields, ValidateString method and the Indexer of HttpRequest class. Let's see when and how granular request validation uses these fields.           Create a new ASP.NET MVC 3 application. Then put a breakpoint at Application_BeginRequest method and another breakpoint at HomeController.Index method. Now just run this application. When the break point inside Application_BeginRequest method hits then add the following expression in quick watch window, System.Web.HttpContext.Current.Request.QueryString. You will see the following screen,                                              Now Press F5 so that the second breakpoint inside HomeController.Index method hits. When the second breakpoint hits then add the following expression in quick watch window again, System.Web.HttpContext.Current.Request.QueryString. You will see the following screen,                            First screen shows that _entriesTable field is of type System.Collections.Hashtable and _entriesArray field is of type System.Collections.ArrayList during the BeginRequest phase of the HTTP request. While the second screen shows that _entriesTable type is changed to Microsoft.Web.Infrastructure.DynamicValidationHelper.LazilyValidatingHashtable and _entriesArray type is changed to Microsoft.Web.Infrastructure.DynamicValidationHelper.LazilyValidatingArrayList during executing the Index action method. In addition to these members, ASP.NET MVC 3 also perform some operation on _flags, _form, _queryString and other members of HttpRuntime class internally. This shows that ASP.NET MVC 3 performing some operation on the members of HttpRequest class for making granular request validation possible.           Both LazilyValidatingArrayList and LazilyValidatingHashtable classes are defined in the Microsoft.Web.Infrastructure assembly. You may wonder why their name starts with Lazily. The fact is that now with ASP.NET MVC 3, request validation will be performed lazily. In simple words, Microsoft.Web.Infrastructure assembly is now taking the responsibility for request validation from System.Web assembly. See the below screens. The first screen depicting HttpRequestValidationException exception in ASP.NET MVC 2 application while the second screen showing HttpRequestValidationException exception in ASP.NET MVC 3 application.   In MVC 2:                 In MVC 3:                          The stack trace of the second screenshot shows that Microsoft.Web.Infrastructure assembly (instead of System.Web assembly) is now performing request validation in ASP.NET MVC 3. Now you may ask: where Microsoft.Web.Infrastructure assembly is performing some operation on the members of HttpRequest class. There are at least two places where the Microsoft.Web.Infrastructure assembly performing some operation , Microsoft.Web.Infrastructure.DynamicValidationHelper.GranularValidationReflectionUtil.GetInstance method and Microsoft.Web.Infrastructure.DynamicValidationHelper.ValidationUtility.CollectionReplacer.ReplaceCollection method, Here is the implementation of these methods,   private static GranularValidationReflectionUtil GetInstance() { try { if (DynamicValidationShimReflectionUtil.Instance != null) { return null; } GranularValidationReflectionUtil util = new GranularValidationReflectionUtil(); Type containingType = typeof(NameObjectCollectionBase); string fieldName = "_entriesArray"; bool isStatic = false; Type fieldType = typeof(ArrayList); FieldInfo fieldInfo = CommonReflectionUtil.FindField(containingType, fieldName, isStatic, fieldType); util._del_get_NameObjectCollectionBase_entriesArray = MakeFieldGetterFunc<NameObjectCollectionBase, ArrayList>(fieldInfo); util._del_set_NameObjectCollectionBase_entriesArray = MakeFieldSetterFunc<NameObjectCollectionBase, ArrayList>(fieldInfo); Type type6 = typeof(NameObjectCollectionBase); string str2 = "_entriesTable"; bool flag2 = false; Type type7 = typeof(Hashtable); FieldInfo info2 = CommonReflectionUtil.FindField(type6, str2, flag2, type7); util._del_get_NameObjectCollectionBase_entriesTable = MakeFieldGetterFunc<NameObjectCollectionBase, Hashtable>(info2); util._del_set_NameObjectCollectionBase_entriesTable = MakeFieldSetterFunc<NameObjectCollectionBase, Hashtable>(info2); Type targetType = CommonAssemblies.System.GetType("System.Collections.Specialized.NameObjectCollectionBase+NameObjectEntry"); Type type8 = targetType; string str3 = "Key"; bool flag3 = false; Type type9 = typeof(string); FieldInfo info3 = CommonReflectionUtil.FindField(type8, str3, flag3, type9); util._del_get_NameObjectEntry_Key = MakeFieldGetterFunc<string>(targetType, info3); Type type10 = targetType; string str4 = "Value"; bool flag4 = false; Type type11 = typeof(object); FieldInfo info4 = CommonReflectionUtil.FindField(type10, str4, flag4, type11); util._del_get_NameObjectEntry_Value = MakeFieldGetterFunc<object>(targetType, info4); util._del_set_NameObjectEntry_Value = MakeFieldSetterFunc(targetType, info4); Type type12 = typeof(HttpRequest); string methodName = "ValidateString"; bool flag5 = false; Type[] argumentTypes = new Type[] { typeof(string), typeof(string), typeof(RequestValidationSource) }; Type returnType = typeof(void); MethodInfo methodInfo = CommonReflectionUtil.FindMethod(type12, methodName, flag5, argumentTypes, returnType); util._del_validateStringCallback = CommonReflectionUtil.MakeFastCreateDelegate<HttpRequest, ValidateStringCallback>(methodInfo); Type type = CommonAssemblies.SystemWeb.GetType("System.Web.HttpValueCollection"); util._del_HttpValueCollection_ctor = CommonReflectionUtil.MakeFastNewObject<Func<NameValueCollection>>(type); Type type14 = typeof(HttpRequest); string str6 = "_form"; bool flag6 = false; Type type15 = type; FieldInfo info6 = CommonReflectionUtil.FindField(type14, str6, flag6, type15); util._del_get_HttpRequest_form = MakeFieldGetterFunc<HttpRequest, NameValueCollection>(info6); util._del_set_HttpRequest_form = MakeFieldSetterFunc(typeof(HttpRequest), info6); Type type16 = typeof(HttpRequest); string str7 = "_queryString"; bool flag7 = false; Type type17 = type; FieldInfo info7 = CommonReflectionUtil.FindField(type16, str7, flag7, type17); util._del_get_HttpRequest_queryString = MakeFieldGetterFunc<HttpRequest, NameValueCollection>(info7); util._del_set_HttpRequest_queryString = MakeFieldSetterFunc(typeof(HttpRequest), info7); Type type3 = CommonAssemblies.SystemWeb.GetType("System.Web.Util.SimpleBitVector32"); Type type18 = typeof(HttpRequest); string str8 = "_flags"; bool flag8 = false; Type type19 = type3; FieldInfo flagsFieldInfo = CommonReflectionUtil.FindField(type18, str8, flag8, type19); Type type20 = type3; string str9 = "get_Item"; bool flag9 = false; Type[] typeArray4 = new Type[] { typeof(int) }; Type type21 = typeof(bool); MethodInfo itemGetter = CommonReflectionUtil.FindMethod(type20, str9, flag9, typeArray4, type21); Type type22 = type3; string str10 = "set_Item"; bool flag10 = false; Type[] typeArray6 = new Type[] { typeof(int), typeof(bool) }; Type type23 = typeof(void); MethodInfo itemSetter = CommonReflectionUtil.FindMethod(type22, str10, flag10, typeArray6, type23); MakeRequestValidationFlagsAccessors(flagsFieldInfo, itemGetter, itemSetter, out util._del_BitVector32_get_Item, out util._del_BitVector32_set_Item); return util; } catch { return null; } } private static void ReplaceCollection(HttpContext context, FieldAccessor<NameValueCollection> fieldAccessor, Func<NameValueCollection> propertyAccessor, Action<NameValueCollection> storeInUnvalidatedCollection, RequestValidationSource validationSource, ValidationSourceFlag validationSourceFlag) { NameValueCollection originalBackingCollection; ValidateStringCallback validateString; SimpleValidateStringCallback simpleValidateString; Func<NameValueCollection> getActualCollection; Action<NameValueCollection> makeCollectionLazy; HttpRequest request = context.Request; Func<bool> getValidationFlag = delegate { return _reflectionUtil.GetRequestValidationFlag(request, validationSourceFlag); }; Func<bool> func = delegate { return !getValidationFlag(); }; Action<bool> setValidationFlag = delegate (bool value) { _reflectionUtil.SetRequestValidationFlag(request, validationSourceFlag, value); }; if ((fieldAccessor.Value != null) && func()) { storeInUnvalidatedCollection(fieldAccessor.Value); } else { originalBackingCollection = fieldAccessor.Value; validateString = _reflectionUtil.MakeValidateStringCallback(context.Request); simpleValidateString = delegate (string value, string key) { if (((key == null) || !key.StartsWith("__", StringComparison.Ordinal)) && !string.IsNullOrEmpty(value)) { validateString(value, key, validationSource); } }; getActualCollection = delegate { fieldAccessor.Value = originalBackingCollection; bool flag = getValidationFlag(); setValidationFlag(false); NameValueCollection col = propertyAccessor(); setValidationFlag(flag); storeInUnvalidatedCollection(new NameValueCollection(col)); return col; }; makeCollectionLazy = delegate (NameValueCollection col) { simpleValidateString(col[null], null); LazilyValidatingArrayList array = new LazilyValidatingArrayList(_reflectionUtil.GetNameObjectCollectionEntriesArray(col), simpleValidateString); _reflectionUtil.SetNameObjectCollectionEntriesArray(col, array); LazilyValidatingHashtable table = new LazilyValidatingHashtable(_reflectionUtil.GetNameObjectCollectionEntriesTable(col), simpleValidateString); _reflectionUtil.SetNameObjectCollectionEntriesTable(col, table); }; Func<bool> hasValidationFired = func; Action disableValidation = delegate { setValidationFlag(false); }; Func<int> fillInActualFormContents = delegate { NameValueCollection values = getActualCollection(); makeCollectionLazy(values); return values.Count; }; DeferredCountArrayList list = new DeferredCountArrayList(hasValidationFired, disableValidation, fillInActualFormContents); NameValueCollection target = _reflectionUtil.NewHttpValueCollection(); _reflectionUtil.SetNameObjectCollectionEntriesArray(target, list); fieldAccessor.Value = target; } }             Hopefully the above code will help you to understand the internal working of granular request validation. It is also important to note that Microsoft.Web.Infrastructure assembly invokes HttpRequest.ValidateInput method internally. For further understanding please see Microsoft.Web.Infrastructure assembly code. Finally you may ask: at which stage ASP NET MVC 3 will invoke these methods. You will find this answer by looking at the following method source,   Unvalidated extension method for HttpRequest class defined in System.Web.Helpers.Validation class. System.Web.Mvc.MvcHandler.ProcessRequestInit method. System.Web.Mvc.ControllerActionInvoker.ValidateRequest method. System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal method.       Summary:             ASP.NET helps in preventing XSS attack using a feature called request validation. In this article, I showed you how you can use granular request validation in ASP.NET MVC 3. I explain you the internal working of  granular request validation. Hope you will enjoy this article too.   SyntaxHighlighter.all()

    Read the article

  • ASP.NET Error Handling: Creating an extension method to send error email

    - by Jalpesh P. Vadgama
    Error handling in asp.net required to handle any kind of error occurred. We all are using that in one or another scenario. But some errors are there which will occur in some specific scenario in production environment in this case We can’t show our programming errors to the End user. So we are going to put a error page over there or whatever best suited as per our requirement. But as a programmer we should know that error so we can track the scenario and we can solve that error or can handle error. In this kind of situation an Error Email comes handy. Whenever any occurs in system it will going to send error in our email. Here I am going to write a extension method which will send errors in email. From asp.net 3.5 or higher version of .NET framework  its provides a unique way to extend your classes. Here you can fine more information about extension method. So lets create extension method via implementing a static class like following. I am going to use same code for sending email via my Gmail account from here. Following is code for that. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net.Mail; namespace Experiement { public static class MyExtension { public static void SendErrorEmail(this Exception ex) { MailMessage mailMessage = new MailMessage(new MailAddress("[email protected]") , new MailAddress("[email protected]")); mailMessage.Subject = "Exception Occured in your site"; mailMessage.IsBodyHtml = true; System.Text.StringBuilder errorMessage = new System.Text.StringBuilder(); errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}<BR/>","Exception",ex.Message)); errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}<BR/>", "Stack Trace", ex.StackTrace)); if (ex.InnerException != null) { errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}<BR/>", " Inner Exception", ex.InnerException.Message)); errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}<BR/>", "Inner Stack Trace", ex.InnerException.StackTrace)); } mailMessage.Body = errorMessage.ToString(); System.Net.NetworkCredential networkCredentials = new System.Net.NetworkCredential("[email protected]", "password"); SmtpClient smtpClient = new SmtpClient(); smtpClient.EnableSsl = true; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = networkCredentials; smtpClient.Host = "smtp.gmail.com"; smtpClient.Port = 587; smtpClient.Send(mailMessage); } } } After creating an extension method let us that extension method to handle error like following in page load event of page. using System; namespace Experiement { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender,System.EventArgs e) { try { throw new Exception("My custom Exception"); } catch (Exception ex) { ex.SendErrorEmail(); Response.Write(ex.Message); } } } } Now in above code I have generated custom exception for example but in production It can be any Exception. And you can see I have use ex.SendErrorEmail() function in catch block to send email. That’s it.. Now it will throw exception and you will email in your email box like below.   That’s its. It’s so simple…Stay tuned for more.. Happy programming.. Technorati Tags: Exception,Extension Mehtod,Error Handling,ASP.NET

    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

  • 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

  • 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

  • Please guide this self-taught Web Developer.

    - by ChickenPuke
    One of the major regrets in life is that I didn't do something with my introversion. I didn't manage to get past the first year of college because of that. I have chosen the path where there are no video games and other time sinks, all I have is the internet to quench my thirst of learning the ins and outs of the field of Web Developing/Designing. Though currently, I'm taking a Web Design Associate course at one of the best Computer Arts and this is the last month of the class. Even though I'm still a sapling, I love this field so much. So basically, At school I'm learning web design while at home I'm teaching myself web-developing. First thing first, returning to college seems impossible at the moment because of some financial problems. I'm pretty comfortable with CSS and HTML and I'm into PHP/MySQL at the moment. Could you please provide me a web-development Curriculum to follow. And do I need to learn about the theories behind? And I think I'm still young(I'm 18 at the time of writing). Is it a good thing or bad thing for choosing this path? I'm glad with my decision but in all honesty, I'm worrying about my future and employment because I'm an undergrad, coming from a country where companies are degree b!tches, it saddens me so. Thank you. (My questions are the bold parts. )

    Read the article

  • Best Web Site Copying Software

    - by GregH
    I just wanted to get some opinions on the best "web site copying" software out there (free or commercial is fine). I have a site that I've recently become responsible for managing, and the previous consultant has not provided operating system access. As such, the plan is to re-host the web site. I realize there are a lot of different issues to consider in doing this. However, I don't have much choice in the matter now. The plan is to use web site copying software (ala HTTrack) to "rip" the web site, and then modify what is downloaded back in to a maintainable site. This, of course, involves HTML, css, javascript, etc on the front-end. I'd like to recover as much of the site as possible to make re-creating it as easy as possible. Your input is appreciated. Input on my approach is also appreciated. Thanks!

    Read the article

  • integration of dynamic forms for 3rd party web apps

    - by afr0
    I've a custom web forms definition interface where I user can define bespoke web forms and those webforms are then rendered on the other part of the my web app. It works well as I can render and submit my forms dynamically. However I have a scenario where there will be different 3rd party apps should be interacting with my custom forms. So the quesion arises how can I have my client side web forms and the fields within to work with the 3rd party interfaces on the fly. Any idea in that regard or best practice will be highly appreciated.

    Read the article

  • ASP.NET Web Forms Extensibility: Handler Factories

    - by Ricardo Peres
    An handler factory is the class that implements IHttpHandlerFactory and is responsible for instantiating an handler (IHttpHandler) that will process the current request. This is true for all kinds of web requests, whether they are for ASPX pages, ASMX/SVC web services, ASHX/AXD handlers, or any other kind of file. Also used for restricting access for certain file types, such as Config, Csproj, etc. Handler factories are registered on the global Web.config file, normally located at %WINDIR%\Microsoft.NET\Framework<x64>\vXXXX\Config for a given path and request type (GET, POST, HEAD, etc). This goes on section <httpHandlers>. You would create a custom handler factory for a number of reasons, let me list just two: A centralized place for using dependency injection; Also a centralized place for invoking custom methods or performing some kind of validation on all pages. Let’s see an example using Unity for injecting dependencies into a page, suppose we have this on Global.asax.cs: 1: public class Global : HttpApplication 2: { 3: internal static readonly IUnityContainer Unity = new UnityContainer(); 4: 5: void Application_Start(Object sender, EventArgs e) 6: { 7: Unity.RegisterType<IFunctionality, ConcreteFunctionality>(); 8: } 9: } We instantiate Unity and register a concrete implementation for an interface, this could/should probably go in the Web.config file. Forget about its actual definition, it’s not important. Then, we create a custom handler factory: 1: public class UnityPageHandlerFactory : PageHandlerFactory 2: { 3: public override IHttpHandler GetHandler(HttpContext context, String requestType, String virtualPath, String path) 4: { 5: IHttpHandler handler = base.GetHandler(context, requestType, virtualPath, path); 6: 7: //one scenario: inject dependencies 8: Global.Unity.BuildUp(handler.GetType(), handler, String.Empty); 9:  10: return (handler); 11: } 12: } It inherits from PageHandlerFactory, which is .NET’s included factory for building regular ASPX pages. We override the GetHandler method and issue a call to the BuildUp method, which will inject required dependencies, if any exist. An example page with dependencies might be: 1: public class SomePage : Page 2: { 3: [Dependency] 4: public IFunctionality Functionality 5: { 6: get; 7: set; 8: } 9: } Notice the DependencyAttribute, it is used by Unity to identify properties that require dependency injection. When BuildUp is called, the Functionality property (or any other properties with the DependencyAttribute attribute) will receive the concrete implementation associated with it’s type, as registered on Unity. Another example, checking a page for authorization. Let’s define an interface first: 1: public interface IRestricted 2: { 3: Boolean Check(HttpContext ctx); 4: } An a page implementing that interface: 1: public class RestrictedPage : Page, IRestricted 2: { 3: public Boolean Check(HttpContext ctx) 4: { 5: //check the context and return a value 6: return ...; 7: } 8: } For this, we would use an handler factory such as this: 1: public class RestrictedPageHandlerFactory : PageHandlerFactory 2: { 3: private static readonly IHttpHandler forbidden = new UnauthorizedHandler(); 4:  5: public override IHttpHandler GetHandler(HttpContext context, String requestType, String virtualPath, String path) 6: { 7: IHttpHandler handler = base.GetHandler(context, requestType, virtualPath, path); 8: 9: if (handler is IRestricted) 10: { 11: if ((handler as IRestricted).Check(context) == false) 12: { 13: return (forbidden); 14: } 15: } 16:  17: return (handler); 18: } 19: } 20:  21: public class UnauthorizedHandler : IHttpHandler 22: { 23: #region IHttpHandler Members 24:  25: public Boolean IsReusable 26: { 27: get { return (true); } 28: } 29:  30: public void ProcessRequest(HttpContext context) 31: { 32: context.Response.StatusCode = (Int32) HttpStatusCode.Unauthorized; 33: context.Response.ContentType = "text/plain"; 34: context.Response.Write(context.Response.Status); 35: context.Response.Flush(); 36: context.Response.Close(); 37: context.ApplicationInstance.CompleteRequest(); 38: } 39:  40: #endregion 41: } The UnauthorizedHandler is an example of an IHttpHandler that merely returns an error code to the client, but does not cause redirection to the login page, it is included merely as an example. One thing we must keep in mind is, there can be only one handler factory registered for a given path/request type (verb) tuple. A typical registration would be: 1: <httpHandlers> 2: <remove path="*.aspx" verb="*"/> 3: <add path="*.aspx" verb="*" type="MyNamespace.MyHandlerFactory, MyAssembly"/> 4: </httpHandlers> First we remove the previous registration for ASPX files, and then we register our own. And that’s it. A very useful mechanism which I use lots of times.

    Read the article

  • Exposing business logic as WCF service

    - by Oren Schwartz
    I'm working on a middle-tier project which encapsulates the business logic (uses a DAL layer, and serves a web application server [ASP.net]) of a product deployed in a LAN. The BL serves as a bunch of services and data objects that are invoked upon user action. At present times, the DAL acts as a separate application whereas the BL uses it, but is consumed by the web application as a DLL. Both the DAL and the web application are deployed on different servers inside organization, and since the BL DLL is consumed by the web application, it resides in the same server. The worst thing about exposing the BL as a DLL is that we lost track with what we expose. Deployment is not such a big issue since mostly, product versions are deployed together. Would you recommend migrating from DLL to WCF service? If so, why? Do you know anyone who had a similar experience?

    Read the article

  • ASP.NET Web API - Screencast series Part 4: Paging and Querying

    - by Jon Galloway
    We're continuing a six part series on ASP.NET Web API that accompanies the getting started screencast series. This is an introductory screencast series that walks through from File / New Project to some more advanced scenarios like Custom Validation and Authorization. The screencast videos are all short (3-5 minutes) and the sample code for the series is both available for download and browsable online. I did the screencasts, but the samples were written by the ASP.NET Web API team. In Part 1 we looked at what ASP.NET Web API is, why you'd care, did the File / New Project thing, and did some basic HTTP testing using browser F12 developer tools. In Part 2 we started to build up a sample that returns data from a repository in JSON format via GET methods. In Part 3, we modified data on the server using DELETE and POST methods. In Part 4, we'll extend on our simple querying methods form Part 2, adding in support for paging and querying. This part shows two approaches to querying data (paging really just being a specific querying case) - you can do it yourself using parameters passed in via querystring (as well as headers, other route parameters, cookies, etc.). You're welcome to do that if you'd like. What I think is more interesting here is that Web API actions that return IQueryable automatically support OData query syntax, making it really easy to support some common query use cases like paging and filtering. A few important things to note: This is just support for OData query syntax - you're not getting back data in OData format. The screencast demonstrates this by showing the GET methods are continuing to return the same JSON they did previously. So you don't have to "buy in" to the whole OData thing, you're just able to use the query syntax if you'd like. This isn't full OData query support - full OData query syntax includes a lot of operations and features - but it is a pretty good subset: filter, orderby, skip, and top. All you have to do to enable this OData query syntax is return an IQueryable rather than an IEnumerable. Often, that could be as simple as using the AsQueryable() extension method on your IEnumerable. Query composition support lets you layer queries intelligently. If, for instance, you had an action that showed products by category using a query in your repository, you could also support paging on top of that. The result is an expression tree that's evaluated on-demand and includes both the Web API query and the underlying query. So with all those bullet points and big words, you'd think this would be hard to hook up. Nope, all I did was change the return type from IEnumerable<Comment> to IQueryable<Comment> and convert the Get() method's IEnumerable result using the .AsQueryable() extension method. public IQueryable<Comment> GetComments() { return repository.Get().AsQueryable(); } You still need to build up the query to provide the $top and $skip on the client, but you'd need to do that regardless. Here's how that looks: $(function () { //--------------------------------------------------------- // Using Queryable to page //--------------------------------------------------------- $("#getCommentsQueryable").click(function () { viewModel.comments([]); var pageSize = $('#pageSize').val(); var pageIndex = $('#pageIndex').val(); var url = "/api/comments?$top=" + pageSize + '&$skip=' + (pageIndex * pageSize); $.getJSON(url, function (data) { // Update the Knockout model (and thus the UI) with the comments received back // from the Web API call. viewModel.comments(data); }); return false; }); }); And the neat thing is that - without any modification to our server-side code - we can modify the above jQuery call to request the comments be sorted by author: $(function () { //--------------------------------------------------------- // Using Queryable to page //--------------------------------------------------------- $("#getCommentsQueryable").click(function () { viewModel.comments([]); var pageSize = $('#pageSize').val(); var pageIndex = $('#pageIndex').val(); var url = "/api/comments?$top=" + pageSize + '&$skip=' + (pageIndex * pageSize) + '&$orderby=Author'; $.getJSON(url, function (data) { // Update the Knockout model (and thus the UI) with the comments received back // from the Web API call. viewModel.comments(data); }); return false; }); }); So if you want to make use of OData query syntax, you can. If you don't like it, you're free to hook up your filtering and paging however you think is best. Neat. In Part 5, we'll add on support for Data Annotation based validation using an Action Filter.

    Read the article

  • Hijacking ASP.NET Sessions

    - by Ricardo Peres
    So, you want to be able to access other user’s session state from the session id, right? Well, I don’t know if you should, but you definitely can do that! Here is an extension method for that purpose. It uses a bit of reflection, which means, it may not work with future versions of .NET (I tested it with .NET 4.0/4.5). 1: public static class HttpApplicationExtensions 2: { 3: private static readonly FieldInfo storeField = typeof(SessionStateModule).GetField("_store", BindingFlags.NonPublic | BindingFlags.Instance); 4:  5: public static ISessionStateItemCollection GetSessionById(this HttpApplication app, String sessionId) 6: { 7: var module = app.Modules["Session"] as SessionStateModule; 8:  9: if (module == null) 10: { 11: return (null); 12: } 13:  14: var provider = storeField.GetValue(module) as SessionStateStoreProviderBase; 15:  16: if (provider == null) 17: { 18: return (null); 19: } 20:  21: Boolean locked; 22: TimeSpan lockAge; 23: Object lockId; 24: SessionStateActions actions; 25:  26: var data = provider.GetItem(HttpContext.Current, sessionId.Trim(), out locked, out lockAge, out lockId, out actions); 27:  28: if (data == null) 29: { 30: return (null); 31: } 32:  33: return (data.Items); 34: } 35: } As you can see, it extends the HttpApplication class, that is because we need to access the modules collection, for the Session module. Use with care!

    Read the article

  • Approached to build app centered around new API and suddenly API is abandoned

    - by LuxuryMode
    This isn't a huge deal, but I was approached by colleagues/friends to build an app using their new API. There was some potential for pecuniary gain for me depending on app usage. I spent a considerable amount of time polishing the mobile app, based on my assumption that, having been approached in a serious way, that the company would not suddenly shift focus and abandon the API. I wasn't even given so much as a heads up that the API was dead even though I had an app in production that relied on it... For the most part, building the app was a learning experience which I enjoyed, but I don't think I'd have expended all the effort if I knew that the company wasn't as serious about the API as their reaching out to me clearly indicated. How, if at all, would you react?

    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

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