Search Results

Search found 59694 results on 2388 pages for 'samir asp net with c technology'.

Page 19/2388 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • 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

  • Inline Image in ASP.NET

    - by Ricardo Peres
    Inline images is a technique that, instead of referring to an external URL, includes all of the image’s content in the HTML itself, in the form of a Base64-encoded string. It avoids a second browser request, at the cost of making the HTML page slightly heavier and not using cache. Not all browsers support it, but current versions of IE, Firefox and Chrome do. In order to use inline images, you must write the img element’s src attribute like this: 1: <img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/ 2: /ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp 3: V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" 4: width="16" height="14" alt="embedded folder icon"/> The syntax is: data:[<mediatype>][;base64],<data> I developed a simple control that allows you to use inline images in your ASP.NET pages. Here it is: 1: public class InnerImage: Image 2: { 3: protected override void OnInit(EventArgs e) 4: { 5: String imagePath = this.Context.Server.MapPath(this.ImageUrl); 6: String extension = Path.GetExtension(imagePath).Substring(1); 7: Byte[] imageData = File.ReadAllBytes(imagePath); 8:  9: this.ImageUrl = String.Format("data:image/{0};base64,{1}", extension, Convert.ToBase64String(imageData)); 10:  11: base.OnInit(e); 12: } 13: } Simple, don’t you think?

    Read the article

  • I can't access Page.RouteData or Response.RedirectPermanent in web forms upgraded from 3.5 to 4.0 ?

    - by Barbaros Alp
    Hi, I have upgraded my web application from 3.5 to 4.0 to get benefits of the new features of ASP.NET 4.0. When i try to get Route Data Values; Page.RouteData.Values["customerId"] with this code i couldn't reach the RouteData.Values collection the Page class doesnt contain a member called routedata. I also have the same issue with Response.RedirectPermanent... What might be the reason ? Thanks in advance

    Read the article

  • Redmine on Apache2 with Passenger issue

    - by nkr1pt
    I installed Redmine and run it in Apache2 with the Passenger module. Apache2 boots, Passenger module gets loaded and the Redmine welcome page is shown, however when trying to login or navigate to other parts of the Redmine site, the browser keeps loading and loading and loading forever, although the Redmine production.log indicates redirects and HTTP 200 codes in the header, so everything seems to work correctly according to the log. I tested in various browsers. Does anyone have an idea what could be wrong? I will add apache configuration and some relevant log snippets from both apache and redmine hereafter. Apache2 Redmine configuration: DocumentRoot /var/www <Directory /var/www/redmine> RailsEnv production AllowOverride all RailsBaseURI /redmine PassengerResolveSymLinksInDocumentRoot on </Directory> Apache2 error log after booting Apache: [Wed Feb 09 19:59:58 2011] [notice] Apache/2.2.14 (Ubuntu) Phusion_Passenger/3.0.2 DAV/2 SVN/1.6.6 configured -- resuming normal operations Redmine production log after logging in: Logfile created on Wed Feb 09 20:01:40 +0100 2011 Processing WelcomeController#index (for 192.168.1.55 at 2011-02-09 20:01:48) [GET] Parameters: {"action"=>"index", "controller"=>"welcome"} Rendering template within layouts/base Rendering welcome/index Completed in 220ms (View: 96, DB: 16) | 200 OK [http://sirius/redmine] Processing AccountController#login (for 192.168.1.55 at 2011-02-09 20:03:17) [GET] Parameters: {"action"=>"login", "controller"=>"account"} Rendering template within layouts/base Rendering account/login Completed in 85ms (View: 63, DB: 1) | 200 OK [http://sirius/redmine/login] Processing AccountController#login (for 192.168.1.55 at 2011-02-09 20:03:20) [POST] Parameters: {"back_url"=>"http%3A%2F%2Fsirius%2Fredmine", "action"=>"login", "authenticity_token"=>"cEMUZHhRKJU8w3p6d+xQQhJTk4/pnnzUdg5g5fwhxDU=", "username"=>"admin", "controller"=>"account", "password"=>"[FILTERED]", "login"=>"Login \302\273"} Redirected to http://sirius/redmine Completed in 37ms (DB: 6) | 302 Found [http://sirius/redmine/login] Processing WelcomeController#index (for 192.168.1.55 at 2011-02-09 20:03:20) [GET] Parameters: {"action"=>"index", "controller"=>"welcome"} Rendering template within layouts/base Rendering welcome/index Completed in 100ms (View: 77, DB: 6) | 200 OK [http://sirius/redmine] Apache2 error log afterwards: [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/mod_instaweb.cc(247)] ModPagespeed OutputFilter called for request /redmine/login [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/mod_instaweb.cc(272)] unparsed=/redmine/login, absolute_url=http://sirius/redmine/login [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: HtmlParse::StartParse [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/mod_instaweb.cc(299)] Request headers:\nHTTP/1.1 0 Internal Server Error\r\nHost: sirius\r\nUser-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8\r\nAccept-Language: en-us,en;q=0.5\r\nAccept-Encoding: gzip,deflate\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\nKeep-Alive: 115\r\nConnection: keep-alive\r\nReferer: http://sirius/redmine\r\nCookie: _redmine_session=BAh7BjoPc2Vzc2lvbl9pZCIlNmVlMzFiMDc4MWQxZDU5ZTI5MTk2NjU0NGY3MzJmYzQ%3D--ea4b7adbc35551051632b5544faaad138ae08d90\r\n\r\n [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/mod_instaweb.cc(302)] request-filename=/var/www/redmine/login, uri=/redmine/login [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/mod_instaweb.cc(319)] ModPagespeed Response headers:\nHTTP/1.1 200 OK\r\nStatus: 200\r\nX-Mod-Pagespeed: 0.9.0.0-128\r\n\r\n [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 2157us: HtmlParse::Flush [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 2272us: HtmlParse::CoalesceAdjacentCharactersNodes [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 2342us: HtmlParse::ApplyFilter:AddHead [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 2407us: HtmlParse::SanityCheck [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 2504us: HtmlParse::ApplyFilter:CssCombine [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/stylesheets/application.css?1296181549 [Wed Feb 09 20:03:17 2011] [warn] [0209/200317:WARNING:net/instaweb/util/google_message_handler.cc(32)] Failed to create or read input resource /redmine/stylesheets/application.css?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/stylesheets/jstoolbar.css?1296181549 [Wed Feb 09 20:03:17 2011] [warn] [0209/200317:WARNING:net/instaweb/util/google_message_handler.cc(32)] Failed to create or read input resource /redmine/stylesheets/jstoolbar.css?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 3642us: HtmlParse::ApplyFilter:CssFilter [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/stylesheets/application.css?1296181549 [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] http://sirius/redmine/login:9: Failed to load resource http://sirius/redmine/stylesheets/application.css?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/stylesheets/jstoolbar.css?1296181549 [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] http://sirius/redmine/login:17: Failed to load resource http://sirius/redmine/stylesheets/jstoolbar.css?1296181549 [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Failed to load resource http://sirius/redmine/stylesheets/jstoolbar.css?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 4863us: HtmlParse::ApplyFilter:Javascript [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:11: Found script with src /redmine/javascripts/prototype.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/prototype.js?1296181549 [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/prototype.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:12: Found script with src /redmine/javascripts/effects.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/effects.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/effects.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/effects.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:13: Found script with src /redmine/javascripts/dragdrop.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/dragdrop.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] Creating connection [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:14: Found script with src /redmine/javascripts/controls.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/controls.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/controls.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:15: Found script with src /redmine/javascripts/application.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/application.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] Creating connection [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 8389us: HtmlParse::SanityCheck [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 8588us: HtmlParse::CoalesceAdjacentCharactersNodes [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 8701us: HtmlParse::ApplyFilter:InlineCss [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: 8701us: HtmlParse::ApplyFilter:InlineCss [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/stylesheets/application.css?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/stylesheets/application.css?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 9199us: HtmlParse::ApplyFilter:InlineJs [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/prototype.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/prototype.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/effects.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] Creating connectionhttp://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/effects.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connectionhttp://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/effects.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/dragdrop.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/dragdrop.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/controls.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/controls.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/application.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/application.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 11398us: HtmlParse::ApplyFilter:ImgRewrite [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 11506us: HtmlParse::ApplyFilter:CacheExtender [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/stylesheets/application.css?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/stylesheets/application.css?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/prototype.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/prototype.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/effects.js?1296181549 [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/effects.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/dragdrop.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/dragdrop.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/controls.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/controls.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/javascripts/application.js?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/javascripts/application.js?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/stylesheets/jstoolbar.css?1296181549 [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(29)] http://sirius/redmine/login: Couldn't fetch resource /redmine/stylesheets/jstoolbar.css?1296181549 to rewrite. [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 14401us: HtmlParse::ApplyFilter:HtmlWriter [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [notice] [0209/200317:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 15218us: HtmlParse::FinishParse [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:17 2011] [error] [0209/200317:ERROR:net/instaweb/util/google_message_handler.cc(54)] net/instaweb/apache/serf_url_async_fetcher.cc:506: Creating connection [Wed Feb 09 20:03:20 2011] [warn] [client 192.168.1.55] Not GET request: 2., referer: http://sirius/redmine/login [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/apache/mod_instaweb.cc(247)] ModPagespeed OutputFilter called for request /redmine/login [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/apache/mod_instaweb.cc(272)] unparsed=/redmine/login, absolute_url=http://sirius/redmine/login [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: HtmlParse::StartParse [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/apache/mod_instaweb.cc(299)] Request headers:\nHTTP/1.1 0 Internal Server Error\r\nHost: sirius\r\nUser-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8\r\nAccept-Language: en-us,en;q=0.5\r\nAccept-Encoding: gzip,deflate\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\nKeep-Alive: 115\r\nConnection: keep-alive\r\nReferer: http://sirius/redmine/login\r\nCookie: _redmine_session=BAh7BzoPc2Vzc2lvbl9pZCIlNmVlMzFiMDc4MWQxZDU5ZTI5MTk2NjU0NGY3MzJmYzQ6EF9jc3JmX3Rva2VuIjFjRU1VWkhoUktKVTh3M3A2ZCt4UVFoSlRrNC9wbm56VWRnNWc1ZndoeERVPQ%3D%3D--8b195ac3cab88b5a1f408e3f18aaddc70782140e\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 165\r\n\r\n [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/apache/mod_instaweb.cc(302)] request-filename=/var/www/redmine/login, uri=/redmine/login [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/apache/mod_instaweb.cc(319)] ModPagespeed Response headers:\nHTTP/1.1 302 Found\r\nLocation: http://sirius/redmine\r\nStatus: 302\r\nX-Mod-Pagespeed: 0.9.0.0-128\r\n\r\n [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 604us: HtmlParse::Flush [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 697us: HtmlParse::CoalesceAdjacentCharactersNodes [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 758us: HtmlParse::ApplyFilter:AddHead [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 813us: HtmlParse::SanityCheck [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 912us: HtmlParse::CoalesceAdjacentCharactersNodes [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 965us: HtmlParse::ApplyFilter:CssCombine [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 1020us: HtmlParse::ApplyFilter:CssFilter [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 1073us: HtmlParse::ApplyFilter:Javascript [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 1125us: HtmlParse::ApplyFilter:InlineCss [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 1179us: HtmlParse::ApplyFilter:InlineJs [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 1233us: HtmlParse::ApplyFilter:ImgRewrite [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 1285us: HtmlParse::ApplyFilter:CacheExtender [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 1338us: HtmlParse::ApplyFilter:HtmlWriter [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine/login:1: 1415us: HtmlParse::FinishParse [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/apache/mod_instaweb.cc(247)] ModPagespeed OutputFilter called for request /redmine [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/apache/mod_instaweb.cc(272)] unparsed=/redmine, absolute_url=http://sirius/redmine [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine:1: HtmlParse::StartParse [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/apache/mod_instaweb.cc(299)] Request headers:\nHTTP/1.1 0 Internal Server Error\r\nHost: sirius\r\nUser-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8\r\nAccept-Language: en-us,en;q=0.5\r\nAccept-Encoding: gzip,deflate\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\nKeep-Alive: 115\r\nConnection: keep-alive\r\nReferer: http://sirius/redmine/login\r\nCookie: _redmine_session=BAh7BzoMdXNlcl9pZGkGOg9zZXNzaW9uX2lkIiVlYjNmYTY5NmZjNzMwYTdhMjA5ZDJmZmM4MTM0MzcyMw%3D%3D--57a4931aae681664d2a6ff6c039ac84b6ebc9e55\r\nIf-None-Match: "76628aff953f11fbdefb77ce3d575718"\r\n\r\n [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/apache/mod_instaweb.cc(302)] request-filename=/var/www/redmine, uri=/redmine [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/apache/mod_instaweb.cc(319)] ModPagespeed Response headers:\nHTTP/1.1 200 OK\r\nStatus: 200\r\nX-Mod-Pagespeed: 0.9.0.0-128\r\n\r\n [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine:1: 1870us: HtmlParse::Flush [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine:1: 1973us: HtmlParse::CoalesceAdjacentCharactersNodes [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine:1: 2040us: HtmlParse::ApplyFilter:AddHead [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine:1: 2101us: HtmlParse::SanityCheck [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/util/google_message_handler.cc(48)] http://sirius/redmine:1: 2231us: HtmlParse::ApplyFilter:CssCombine [Wed Feb 09 20:03:20 2011] [notice] [0209/200320:INFO:net/instaweb/apache/serf_url_async_fetcher.cc(632)] Initiating async fetch for http://sirius/redmine/stylesheets/application.css?1296181549

    Read the article

  • Enum.HasFlag method in C# 4.0

    - by Jalpesh P. Vadgama
    Enums in dot net programming is a great facility and we all used it to increase code readability. In earlier version of .NET framework we don’t have any method anything that will check whether a value is assigned to it or not. In C# 4.0 we have new static method called HasFlag which will check that particular value is assigned or not. Let’s take an example for that. First I have created a enum called PaymentType which could have two values Credit Card or Debit Card. Just like following. public enum PaymentType { DebitCard=1, CreditCard=2 } Now We are going to assigned one of the value to this enum instance and then with the help of HasFlag method we are going to check whether particular value is assigned to enum or not like following. protected void Page_Load(object sender, EventArgs e) { PaymentType paymentType = PaymentType.CreditCard; if (paymentType.HasFlag(PaymentType.DebitCard)) { Response.Write("Process Debit Card"); } if (paymentType.HasFlag(PaymentType.CreditCard)) { Response.Write("Process Credit Card"); } } Now Let’s check out in browser as following. As expected it will print process Credit Card as we have assigned that value to enum. That’s it It’s so simple and cool. Stay tuned for more.. Happy Programming.. Technorati Tags: Enum,C#4.0,ASP.NET 4.0

    Read the article

  • ASP.NET MVC : strange POST behavior

    - by user93422
    ASP.NET MVC 2 app I have two actions on my controller (Toons): [GET] List [POST] Add App is running on IIS7 integration mode, so /Toons/List works fine. But when I do POST (that redirects to /Toons/List internally) it redirects (with 302 Object Moved) back to /Toons/Add. The problem goes away if I use .aspx hack (that works in IIS6/IIS7 classic mode). But without .aspx - GET work fine, but POST redirects me onto itself but with GET. What am I missing? I'm hosting with webhost4life.com and they did change IIS7 to integrated mode already. EDIT: The code works as expected using UltiDev Cassini server. EDIT: It turned out to be trailing-slash-in-URL issue. Somehow IIS7 doesn't route request properly if there is no slash at the end. EDET: Explanation of the behavior What happens is when I request (POST) /Toons/List (without trailing slash), IIS doesn't find the handler (I do not have knowledge to understand how exactly IIS does URL-to-handler mapping) and redirects the request (using 302 code) to /Toons/List/ (notice trailing slash). A browser, according to the HTTP specification, must redirect the request using same method (POST in this case), but instead it handles 302 as if it is 303 and issues GET request for the new URL. This is incorrect, but known behavior of most browsers. The solution is either to use .aspx-hack to make it unambiguous for IIS how to map requests to ASP.NET handler, or configure IIS to handle everything in the virtual directory using ASP.NET handler. Q: what is a better way to handle this?

    Read the article

  • Transalation of tasks in .NET 1.1 to .NET 3.5

    - by ggonsalv
    In .Net 1.1 I would run a stored procedure to fill a typed dataset. I would use a Datareader to fill the dataset for speed (though it was probably not necessary) Then I would use the Dataset to bind to multiple controls on the page so as to render the data to multiple CSS/javsript based tabs on the page. This would also reduce the database call to 1. So I know I could this in 3.5, but is there a better way. For example can one stored procedure create an EDM object to be used. Since the data is mainly readonly should I even bother changing or keep using the Stored proc -> Data set -> Bind individual controls to specific data tables

    Read the article

  • Insert Stored Procedure, Using Asp.Net WebForm to Insert new [Customer]

    - by user2953815
    Can someone please help me create a stored procedure to insert a new customer from a web form. I am having difficulty making the state a drop down list for customer to pick a state from the list and having that inserted into the database. INSERT INTO Customer ( Cust_First, Cust_Middle, Cust_Last, Cust_Phone, Cust_Alt_Phone, Cust_Email, Add_Line1, Add_Line2, Add_Bill_Line1, Add_Bill_Line2, City, State_Prov_Name, Postal_Zip_Code, Country_ID ) VALUES ( @Cust_First, @Cust_Middle, @Cust_Last, @Cust_Phone, @Cust_Alt_Phone, @Cust_Email, @Add_Line1, @Add_Line2, @Add_Bill_Line1, @Add_Bill_Line2, @City, @State_Prov_Name, @Postal_Zip_Code, @Country_ID )"> <InsertParameters> <asp:Parameter Name="Cust_First" Type="String"></asp:Parameter> <asp:Parameter Name="Cust_Middle" Type="String"></asp:Parameter> <asp:Parameter Name="Cust_Last" Type="String"></asp:Parameter> <asp:Parameter Name="Cust_Phone" Type="String"></asp:Parameter> <asp:Parameter Name="Cust_Alt_Phone" Type="String"></asp:Parameter> <asp:Parameter Name="Cust_Email" Type="String"></asp:Parameter> <asp:Parameter Name="Add_Line1" Type="String"></asp:Parameter> <asp:Parameter Name="Add_Line2" Type="String"></asp:Parameter> <asp:Parameter Name="Add_Bill_Line1" Type="String"></asp:Parameter> <asp:Parameter Name="Add_Bill_Line2" Type="String"></asp:Parameter> <asp:Parameter Name="City" Type="String"></asp:Parameter> <asp:Parameter Name="Postal_Zip_Code" Type="String"></asp:Parameter> <asp:Parameter Name="Cust_ID" Type="Int32"></asp:Parameter> <asp:Parameter Name="State_Prov_Name" Type="String"></asp:Parameter> <asp:Parameter Name="Country_Name" Type="String"></asp:Parameter> </InsertParameters>

    Read the article

  • How to go about converting this classic asp to asp.net

    - by Phil
    I have some classic asp code that needs converting to asp.net. So far I have tried to achieve this using datareaders and repeaters and had no luck as the menu loops through 4 different record sets, passing along the menuNid before moving to the next record. Please can you tell me what method you would use to conver this code... i.e datareaders? dataset? etc? Thanks <% set RSMenuLevel0 = conn.execute("select id, DepartmentID, GroupingID, Heading, OrderID, Publish, moduleid, url, urltarget " &_ "from T where (DepartmentID = 0 and GroupingID = 0 and Publish <> 0) order by OrderID") %> <% if session("JavaScriptEnabled") = "False" Then %> <% while not RSMenuLevel0.EOF if RSMenuLevel0("Publish") <> 0 then Menu0heading = RSMenuLevel0("Heading") Menu0id = RSMenuLevel0("id") %> <%if RSMenuLevel0("url") > "" and RSMenuLevel0("moduleid") = 0 then%> &nbsp;<a href="http://<%=RSMenuLevel0("url")%>" target="<%=RSMenuLevel0("urltarget")%>"><%=Menu0heading%></a> <%else%> &nbsp;<a href="/default.asp?id=<%=Menu0id%>"><%=Menu0heading%></a> <%end if%> <% end if RSMenuLevel0.MoveNext wend %> <% else %> <ul id="Menu1" class="MM"> <%if home <> 1 then%> <!-- <li><a href="/default.asp"><span class="item">Home</span></a> --> <%end if%> <% numone=0 while not RSMenuLevel0.EOF ' numone = numone + 1 Menu0heading = RSMenuLevel0("Heading") 'itemID = lcase(replace(Menu0heading," ","")) Menu0id = RSMenuLevel0("id") if RSMenuLevel0("url") > "" and RSMenuLevel0("moduleid") = 0 then url = RSMenuLevel0("url") if instr(url,"file:///") > 0 then %> <li><a href="<%=RSMenuLevel0("url")%>" target="<%=RSMenuLevel0("urltarget")%>" <%if numone=1 then%>class="CURRENT"<%end if%>><span class="item"><%=Menu0heading%></span></a> <%else%> <li><a href="http://<%=RSMenuLevel0("url")%>" target="<%=RSMenuLevel0("urltarget")%>" <%if numone=1 then%>class="CURRENT"<%end if%>><span class="item"><%=Menu0heading%></span></a> <%end if%> <%else%> <li><a href="/default.asp?id=<%=RSMenuLevel0("id")%>" <%if numone=1 then%>class="CURRENT"<%end if%>><span class="item"><%=Menu0heading%></span></a> <%end if%> <% set RSMenuLevel1 = conn.execute("select id, DepartmentID, GroupingID, Heading, OrderID, Publish, moduleid, url, urltarget " &_ "from T where (DepartmentID = 0 and GroupingID = " & Menu0id & " and Publish <> 0) order by OrderID") if not RSMenuLevel1.EOF then %> <ul> <% while not RSMenuLevel1.EOF Menu1heading = RSMenuLevel1("Heading") Menu1id = RSMenuLevel1("id") if RSMenuLevel1("url") > "" and RSMenuLevel1("moduleid") = 0 then url = RSMenuLevel1("url") if instr(url,"file:///") > 0 then %> <li><a href="<%=RSMenuLevel1("url")%>" target="<%=RSMenuLevel1("urltarget")%>"><%=Menu1heading%></a> <%else%> <li><a href="http://<%=RSMenuLevel1("url")%>" target="<%=RSMenuLevel1("urltarget")%>"><%=Menu1heading%></a> <%end if%> <%else%> <li><a href="/default.asp?id=<%=RSMenuLevel1("id")%>"><%=Menu1heading%></a> <%end if%> <% set RSMenuLevel2 = conn.execute("select id, DepartmentID, GroupingID, Heading, OrderID, Publish, moduleid, url, urltarget " &_ "from T where (DepartmentID = 0 and GroupingID = " & Menu1id & " and Publish <> 0) order by OrderID") if not RSMenuLevel2.EOF then %> <ul> <% while not RSMenuLevel2.EOF Menu2heading = RSMenuLevel2("Heading") Menu2id = RSMenuLevel2("id") if RSMenuLevel2("url") > "" and RSMenuLevel2("moduleid") = 0 then %> <li><a href="http://<%=RSMenuLevel2("url")%>" target="<%=RSMenuLevel2("urltarget")%>"><%=Menu2heading%></a> <%else%> <li><a href="/default.asp?id=<%=RSMenuLevel2("id")%>"><%=Menu2heading%></a> <%end if%> <% set RSMenuLevel3 = conn.execute("select id, DepartmentID, GroupingID, Heading, OrderID, Publish, moduleid, url, urltarget " &_ "from T where (DepartmentID = 0 and GroupingID = " & Menu2id & " and Publish <> 0) order by OrderID") if not RSMenuLevel3.EOF then %> <ul> <% while not RSMenuLevel3.EOF Menu3heading = RSMenuLevel3("Heading") Menu3id = RSMenuLevel3("id") if RSMenuLevel3("url") > "" and RSMenuLevel3("moduleid") = 0 then %> <li><a href="http://<%=RSMenuLevel3("url")%>" target="<%=RSMenuLevel3("urltarget")%>"><%=Menu3heading%></a></li> <%else%> <li><a href="/default.asp?id=<%=RSMenuLevel3("id")%>"><%=Menu3heading%></a></li> <%end if%> <% RSMenuLevel3.MoveNext wend %> </ul> <% end if RSMenuLevel2.MoveNext %> </li> <% wend %> </ul> <% end if RSMenuLevel1.MoveNext %> </li> <% wend %> </ul> <% end if RSMenuLevel0.MoveNext %> </li> <% wend %> </ul> <% end if %>

    Read the article

  • Add new row to asp .net grid view using button

    - by SARAVAN
    Hi, I am working in ASP .net 2.0. I am a learner. I have a grid view which has a button in it. Please find the asp mark up below <form id="form1" runat="server"> <div> <asp:GridView ID="myGridView" runat="server"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:Button CommandName="AddARowBelow" Text="Add A Row Below" runat="server" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> </form> Please find the code behind below. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Data; using System.Web.UI.WebControls; namespace GridViewDemo { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataTable dt = new DataTable("myTable"); dt.Columns.Add("col1"); dt.Columns.Add("col2"); dt.Columns.Add("col3"); dt.Rows.Add(1, 2, 3); dt.Rows.Add(1, 2, 3); dt.Rows.Add(1, 2, 3); dt.Rows.Add(1, 2, 3); dt.Rows.Add(1, 2, 3); myGridView.DataSource = dt; myGridView.DataBind(); } protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e) { } } } I was thinking that when I click the command button, it would fire the mygridview_rowcommand() but instead it threw an error as follows: Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" % in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. Can any one let me know on where I am going wrong?

    Read the article

  • CascadingDropDown jQuery Plugin for ASP.NET MVC

    - by rajbk
    CascadingDropDown is a jQuery plugin that can be used by a select list to get automatic population using AJAX. A sample ASP.NET MVC project is attached at the bottom of this post.   Usage The code below shows two select lists : <select id="customerID" name="customerID"> <option value="ALFKI">Maria Anders</option> <option value="ANATR">Ana Trujillo</option> <option value="ANTON">Antonio Moreno</option> </select>   <select id="orderID" name="orderID"> </select> When a customer is selected in the first select list, the second list will auto populate itself with the following code: $("#orderID").CascadingDropDown("#customerID", '/Sales/AsyncOrders'); Internally, an AJAX post is made to ‘/Sales/AsyncOrders’ with the post body containing  customerID=[selectedCustomerID]. This executes the action AsyncOrders on the SalesController with signature AsyncOrders(string customerID).  The AsyncOrders method returns JSON which is then used to populate the select list. The JSON format expected is shown below : [{ "Text": "John", "Value": "10326" }, { "Text": "Jane", "Value": "10801" }] Details $(targetID).CascadingDropDown(sourceID, url, settings) targetID The ID of the select list that will auto populate.  sourceID The ID of the select list, which, on change, causes the targetID to auto populate. url The url to post to Options promptText Text for the first item in the select list Default : -- Select -- loadingText Optional text to display in the select list while it is being loaded. Default : Loading.. errorText Optional text to display if an error occurs while populating the list Default: Error loading data. postData Data you want posted to the url in place of the default Example : { postData : { customerID : $(‘#custID’), orderID : $(‘#orderID’) }} will cause customerID=ALFKI&orderID=2343 to be sent as the POST body. Default: A text string obtained by calling serialize on the sourceID onLoading (event) Raised before the list is populated. onLoaded (event) Raised after the list is populated, The code below shows how to “animate” the  select list after load. Example using custom options: $("#orderID").CascadingDropDown("#customerID", '/Sales/AsyncOrders', { promptText: '-- Pick an Order--', onLoading: function () { $(this).css("background-color", "#ff3"); }, onLoaded: function () { $(this).animate({ backgroundColor: '#ffffff' }, 300); } }); To return JSON from our action method, we use the Json ActionResult passing in an IEnumerable<SelectListItem>. public ActionResult AsyncOrders(string customerID) { var orders = repository.GetOrders(customerID).ToList().Select(a => new SelectListItem() { Text = a.OrderDate.HasValue ? a.OrderDate.Value.ToString("MM/dd/yyyy") : "[ No Date ]", Value = a.OrderID.ToString(), }); return Json(orders); } Sample Project using VS 2010 RTM NorthwindCascading.zip

    Read the article

  • Pages in IE render differently when served through the ASP.NET Development server and Production Ser

    - by rajbk
    You see differences in the way IE renders your web application locally on the ASP.NET Development server compared to your production server. Comparing the response from both servers including response headers and CSS show no difference. The issue may occur because of a setting in IE. In IE, go to Tools –> Compatibility ViewSettings. The checkbox “Display intranet sites in Compatibility View” turned on forces IE8 to display the web application content in a way similar to how Internet Explorer 7 handles standards mode web pages. Since your local web server is considered to be in the intranet zone, IE uses “Compatibility View” to render your pages. While you could uncheck this setting in or propagate the change to all developers through group policy settings, a different way is described below. To force IE to mimic the behavior of a certain version of IE when rendering the pages, you use the meta element  to include a “X-UA-Compatible” http-equiv header in  your web page or have it sent as part of the header by adding it to your web.config file. The values are listed below: <meta http-equiv="X-UA-Compatible" content="IE=4"> <!-- IE5 mode --> <meta http-equiv="X-UA-Compatible" content="IE=7.5"> <!-- IE7 mode --> <meta http-equiv="X-UA-Compatible" content="IE=100"> <!-- IE8 mode --> <meta http-equiv="X-UA-Compatible" content="IE=a"> <!-- IE5 mode --> This value can also be set in web.config like so: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <httpProtocol> <customHeaders> <clear /> <add name="X-UA-Compatible" value="IE=EmulateIE7" /> </customHeaders> </httpProtocol> </system.webServer> </configuration> The setting can added in the IIS metabase as described here. Similarly, you can do the same in Apache by adding the directive in httpd.conf <Location /store> Header set X-UA-Compatible “IE=EmulateIE7” </Location> Even though it can be done on a site level, I recommend you do it on a per application level to avoid confusing the developer. References Defining Document Compatibility Implementing the META Switch on IIS Implementing the META Switch on Apache

    Read the article

  • Customizing the processing of ListItems for asp:RadioButtonList with "Flow" layout and "Horizontal"

    - by evovision
    Hi, recently I was asked to add an ability to pad specific elements from each other to a certain distance in RadioButtonList control. Not quite common everyday task I would say :)   Ok, let's get started!   Prerequisites: ASP.NET Page having RadioButtonList control with RepeatLayout="Flow" RepeatDirection="Horizontal" properties set.   Implementation:  The underlying data was coming from another source, so the only fast way to add meta information about padding was the text value itself (yes, not very optimal solution): Id = 1, Name = "This is first element" and for padding we agreed to use <space/> meta tag: Id = 2, Name = "<space padcount="30px"/>This is second padded element"   To handle items rendering in RadioButtonList control I've created custom class and subclassed from it:    public class CustomRadioButtonList : RadioButtonList    {        private Action<ListItem, HtmlTextWriter> _preProcess;         protected override void RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)        {            if (_preProcess != null)            {                _preProcess(this.Items[repeatIndex], writer);            }             base.RenderItem(itemType, repeatIndex, repeatInfo, writer);        }         public void SetPrePrenderItemFunction(Action<ListItem, HtmlTextWriter> func)        {            _preProcess = func;        }    }   It is pretty straightforward approach, the key is to override RenderItem method. Class has SetPrePrenderItemFunction method which is used to pass custom processing function that takes 2 parameters: ListItem and HtmlTextWriter objects.   Now update existing RadioButtonList control in Default.aspx: add this to beginning of the page:   <%@ Register Namespace="Sample.Controls" TagPrefix="uc1" %>   and update the control to:   <uc1:CustomRadioButtonList ID="customRbl" runat="server" DataValueField="Id" DataTextField="Name"            RepeatLayout="Flow" RepeatDirection="Horizontal"></uc1:CustomRadioButtonList>   Now, from codebehind of the page:   Add regular expression that will be used for parsing:   private Regex _regex = new Regex(@"(?:[<]space padcount\s*?=\s*?(?:'|"")(?<padcount>\d+)(?:(?:\s+)?px)?(?:'|"")\s*?/>)(?<content>.*)?", RegexOptions.IgnoreCase | RegexOptions.Compiled);   and finally setup the processing function in Page_Load:   protected void Page_Load(object sender, EventArgs e)    {        customRbl.DataSource = DataObjects;         customRbl.SetPrePrenderItemFunction((listItem, writer) =>        {            Match match = _regex.Match(listItem.Text);            if (match.Success)            {                writer.Write(string.Format(@"<span style=""padding-left:{0}"">Extreme values: </span>", match.Groups["padcount"].Value + "px"));                 // if you need to pad listitem use code below                //x.Attributes.CssStyle.Add("padding-left", match.Groups["padcount"].Value + "px");                 // remove meta tag from text                listItem.Text = match.Groups["content"].Value;            }        });         customRbl.DataBind();    }   That's it! :)   Run the attached sample application:     P.S.: of course several other approaches could have been used for that purpose including events and the functionality for processing could also be embedded inside control itself. Current solution suits slightly better due some other reasons for situation where it was used, in your case consider this as a kick start for your own implementation :)   Source application: CustomRadioButtonList.zip

    Read the article

  • ASP.NET List Control

    - by Ricardo Peres
    Today I developed a simple control for generating lists in ASP.NET, something that the base class library does not contain; it allows for nested lists where the list item types and images can be configured on a list by list basis. Since it was a great fun to develop, I'd like to share it here. Here is the code: [ParseChildren(true)] [PersistChildren(false)] public class List: WebControl { public List(): base("ul") { this.Items = new List(); this.ListStyleType = ListStyleType.Auto; this.ListStyleImageUrl = String.Empty; this.CommonCssClass = String.Empty; this.ContainerCssClass = String.Empty; } [DefaultValue(ListStyleType.Auto)] public ListStyleType ListStyleType { get; set; } [DefaultValue("")] [UrlProperty("*.png;*.gif;*.jpg")] public String ListStyleImageUrl { get; set; } [DefaultValue("")] [CssClassProperty] public String CommonCssClass { get; set; } [DefaultValue("")] [CssClassProperty] public String ContainerCssClass { get; set; } [Browsable(false)] [PersistenceModeAttribute(PersistenceMode.InnerProperty)] public List Items { private set; get; } protected override void Render(HtmlTextWriter writer) { String cssClass = String.Join(" ", new String [] { this.CssClass, this.ContainerCssClass }); if (cssClass.Trim().Length != 0) { this.CssClass = cssClass; } if (String.IsNullOrEmpty(this.ListStyleImageUrl) == false) { this.Style[ HtmlTextWriterStyle.ListStyleImage ] = String.Format("url('{0}')", this.ResolveClientUrl(this.ListStyleImageUrl)); } if (this.ListStyleType != ListStyleType.Auto) { switch (this.ListStyleType) { case ListStyleType.Circle: case ListStyleType.Decimal: case ListStyleType.Disc: case ListStyleType.None: case ListStyleType.Square: this.Style [ HtmlTextWriterStyle.ListStyleType ] = this.ListStyleType.ToString().ToLower(); break; case ListStyleType.LowerAlpha: this.Style [ HtmlTextWriterStyle.ListStyleType ] = "lower-alpha"; break; case ListStyleType.LowerRoman: this.Style [ HtmlTextWriterStyle.ListStyleType ] = "lower-roman"; break; case ListStyleType.UpperAlpha: this.Style [ HtmlTextWriterStyle.ListStyleType ] = "upper-alpha"; break; case ListStyleType.UpperRoman: this.Style [ HtmlTextWriterStyle.ListStyleType ] = "upper-roman"; break; } } base.Render(writer); } protected override void RenderChildren(HtmlTextWriter writer) { foreach (ListItem item in this.Items) { this.writeItem(item, this, 0); } base.RenderChildren(writer); } private void writeItem(ListItem item, Control control, Int32 depth) { HtmlGenericControl li = new HtmlGenericControl("li"); control.Controls.Add(li); if (String.IsNullOrEmpty(this.CommonCssClass) == false) { String cssClass = String.Join(" ", new String [] { this.CommonCssClass, this.CommonCssClass + depth }); li.Attributes [ "class" ] = cssClass; } foreach (String key in item.Attributes.Keys) { li.Attributes[key] = item.Attributes [ key ]; } li.InnerText = item.Text; if (item.ChildItems.Count != 0) { HtmlGenericControl ul = new HtmlGenericControl("ul"); li.Controls.Add(ul); if (String.IsNullOrEmpty(this.ContainerCssClass) == false) { ul.Attributes["class"] = this.ContainerCssClass; } if ((item.ListStyleType != ListStyleType.Auto) || (String.IsNullOrEmpty(item.ListStyleImageUrl) == false)) { if (String.IsNullOrEmpty(item.ListStyleImageUrl) == false) { ul.Style[HtmlTextWriterStyle.ListStyleImage] = String.Format("url('{0}');", this.ResolveClientUrl(item.ListStyleImageUrl)); } if (item.ListStyleType != ListStyleType.Auto) { switch (this.ListStyleType) { case ListStyleType.Circle: case ListStyleType.Decimal: case ListStyleType.Disc: case ListStyleType.None: case ListStyleType.Square: ul.Style[ HtmlTextWriterStyle.ListStyleType ] = item.ListStyleType.ToString().ToLower(); break; case ListStyleType.LowerAlpha: ul.Style [ HtmlTextWriterStyle.ListStyleType ] = "lower-alpha"; break; case ListStyleType.LowerRoman: ul.Style [ HtmlTextWriterStyle.ListStyleType ] = "lower-roman"; break; case ListStyleType.UpperAlpha: ul.Style [ HtmlTextWriterStyle.ListStyleType ] = "upper-alpha"; break; case ListStyleType.UpperRoman: ul.Style [ HtmlTextWriterStyle.ListStyleType ] = "upper-roman"; break; } } } foreach (ListItem childItem in item.ChildItems) { this.writeItem(childItem, ul, depth + 1); } } } } [Serializable] [ParseChildren(true, "ChildItems")] public class ListItem: IAttributeAccessor { public ListItem() { this.ChildItems = new List(); this.Attributes = new Dictionary(); this.Text = String.Empty; this.Value = String.Empty; this.ListStyleType = ListStyleType.Auto; this.ListStyleImageUrl = String.Empty; } [DefaultValue(ListStyleType.Auto)] public ListStyleType ListStyleType { get; set; } [DefaultValue("")] [UrlProperty("*.png;*.gif;*.jpg")] public String ListStyleImageUrl { get; set; } [DefaultValue("")] public String Text { get; set; } [DefaultValue("")] public String Value { get; set; } [Browsable(false)] public List ChildItems { get; private set; } [Browsable(false)] public Dictionary Attributes { get; private set; } String IAttributeAccessor.GetAttribute(String key) { return (this.Attributes [ key ]); } void IAttributeAccessor.SetAttribute(String key, String value) { this.Attributes [ key ] = value; } } [Serializable] public enum ListStyleType { Auto = 0, Disc, Circle, Square, Decimal, LowerRoman, UpperRoman, LowerAlpha, UpperAlpha, None } SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

  • Anti-Forgery Request in ASP.NET MVC and AJAX

    - by Dixin
    Background To secure websites from cross-site request forgery (CSRF, or XSRF) attack, ASP.NET MVC provides an excellent mechanism: The server prints tokens to cookie and inside the form; When the form is submitted to server, token in cookie and token inside the form are sent by the HTTP request; Server validates the tokens. To print tokens to browser, just invoke HtmlHelper.AntiForgeryToken():<% using (Html.BeginForm()) { %> <%: this.Html.AntiForgeryToken(Constants.AntiForgeryTokenSalt)%> <%-- Other fields. --%> <input type="submit" value="Submit" /> <% } %> which writes to token to the form:<form action="..." method="post"> <input name="__RequestVerificationToken" type="hidden" value="J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP" /> <!-- Other fields. --> <input type="submit" value="Submit" /> </form> and the cookie: __RequestVerificationToken_Lw__=J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP When the above form is submitted, they are both sent to server. [ValidateAntiForgeryToken] attribute is used to specify the controllers or actions to validate them:[HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult Action(/* ... */) { // ... } This is very productive for form scenarios. But recently, when resolving security vulnerabilities for Web products, I encountered 2 problems: It is expected to add [ValidateAntiForgeryToken] to each controller, but actually I have to add it for each POST actions, which is a little crazy; After anti-forgery validation is turned on for server side, AJAX POST requests will consistently fail. Specify validation on controller (not on each action) Problem For the first problem, usually a controller contains actions for both HTTP GET and HTTP POST requests, and usually validations are expected for HTTP POST requests. So, if the [ValidateAntiForgeryToken] is declared on the controller, the HTTP GET requests become always invalid:[ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public class SomeController : Controller { [HttpGet] public ActionResult Index() // Index page cannot work at all. { // ... } [HttpPost] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] public ActionResult PostAction2(/* ... */) { // ... } // ... } If user sends a HTTP GET request from a link: http://Site/Some/Index, validation definitely fails, because no token is provided. So the result is, [ValidateAntiForgeryToken] attribute must be distributed to each HTTP POST action in the application:public class SomeController : Controller { [HttpGet] public ActionResult Index() // Works. { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction2(/* ... */) { // ... } // ... } Solution To avoid a large number of [ValidateAntiForgeryToken] attributes (one attribute for one HTTP POST action), I created a wrapper class of ValidateAntiForgeryTokenAttribute, where HTTP verbs can be specified:[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ValidateAntiForgeryTokenWrapperAttribute : FilterAttribute, IAuthorizationFilter { private readonly ValidateAntiForgeryTokenAttribute _validator; private readonly AcceptVerbsAttribute _verbs; public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs) : this(verbs, null) { } public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs, string salt) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = salt }; } public void OnAuthorization(AuthorizationContext filterContext) { string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride(); if (this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase)) { this._validator.OnAuthorization(filterContext); } } } When this attribute is declared on controller, only HTTP requests with the specified verbs are validated:[ValidateAntiForgeryTokenWrapper(HttpVerbs.Post, Constants.AntiForgeryTokenSalt)] public class SomeController : Controller { // Actions for HTTP GET requests are not affected. // Only HTTP POST requests are validated. } Now one single attribute on controller turns on validation for all HTTP POST actions. Submit token via AJAX Problem For AJAX scenarios, when request is sent by JavaScript instead of form:$.post(url, { productName: "Tofu", categoryId: 1 // Token is not posted. }, callback); This kind of AJAX POST requests will always be invalid, because server side code cannot see the token in the posted data. Solution The token must be printed to browser then submitted back to server. So first of all, HtmlHelper.AntiForgeryToken() must be called in the page where the AJAX POST will be sent. Then jQuery must find the printed token in the page, and post it:$.post(url, { productName: "Tofu", categoryId: 1, __RequestVerificationToken: getToken() // Token is posted. }, callback); To be reusable, this can be encapsulated in a tiny jQuery plugin:(function ($) { $.getAntiForgeryToken = function () { // HtmlHelper.AntiForgeryToken() must be invoked to print the token. return $("input[type='hidden'][name='__RequestVerificationToken']").val(); }; var addToken = function (data) { // Converts data if not already a string. if (data && typeof data !== "string") { data = $.param(data); } data = data ? data + "&" : ""; return data + "__RequestVerificationToken=" + encodeURIComponent($.getAntiForgeryToken()); }; $.postAntiForgery = function (url, data, callback, type) { return $.post(url, addToken(data), callback, type); }; $.ajaxAntiForgery = function (settings) { settings.data = addToken(settings.data); return $.ajax(settings); }; })(jQuery); Then in the application just replace $.post() invocation with $.postAntiForgery(), and replace $.ajax() instead of $.ajaxAntiForgery():$.postAntiForgery(url, { productName: "Tofu", categoryId: 1 }, callback); // Token is posted. This solution looks hard coded and stupid. If you have more elegant solution, please do tell me.

    Read the article

  • Blog Now Hosted on IIS 8.0–DiscountASP.Net

    - by The Official Microsoft IIS Site
    On Thursday night I was having an email conversation with Takeshi Eto from DiscountASP.Net about the hosting of my blog.  I’ve been hosting my blog with DiscountASP.Net for nearly five years and have been very, very happy with their service – always up to date often offering services faster than other hosters and very quick turn around of support tickets if ever I’ve had any issues – they also host the NEBytes site. Well on Thursday I was asking about migrating my site onto IIS 8.0 hosting and...(read more)

    Read the article

  • Writing an ASP.Net Web based TFS Client

    - by Glav
    So one of the things I needed to do was write an ASP.Net MVC based application for our senior execs to manage a set of arbitrary attributes against stories, bugs etc to be able to attribute whether the item was related to Research and Development, and if so, what kind. We are using TFS Azure and don’t have the option of custom templates. I have decided on using a string based field within the template that is not very visible and which we don’t use to write a small set of custom which will determine the research and development association. However, this string munging on the field is not very user friendly so we need a simple tool that can display attributes against items in a simple dropdown list or something similar. Enter a custom web app that accesses our TFS items in Azure (Note: We are also using Visual Studio 2012) Now TFS Azure uses your Live ID and it is not really possible to easily do this in a server based app where no interaction is available. Even if you capture the Live ID credentials yourself and try to submit them to TFS Azure, it wont work. Bottom line is that it is not straightforward nor obvious what you have to do. In fact, it is a real pain to find and there are some answers out there which don’t appear to be answers at all given they didn’t work in my scenario. So for anyone else who wants to do this, here is a simple breakdown on what you have to do: Go here and get the “TFS Service Credential Viewer”. Install it, run it and connect to your TFS instance in azure and create a service account. Note the username and password exactly as it presents it to you. This is the magic identity that will allow unattended, programmatic access. Without this step, don’t bother trying to do anything else. In your MVC app, reference the following assemblies from “C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ReferenceAssemblies\v2.0”: Microsoft.TeamFoundation.Client.dll Microsoft.TeamFoundation.Common.dll Microsoft.TeamFoundation.VersionControl.Client.dll Microsoft.TeamFoundation.VersionControl.Common.dll Microsoft.TeamFoundation.WorkItemTracking.Client.DataStoreLoader.dll Microsoft.TeamFoundation.WorkItemTracking.Client.dll Microsoft.TeamFoundation.WorkItemTracking.Common.dll If hosting this in Internet Information Server, for the application pool this app runs under, you will need to enable 32 Bit support. You also have to allow the TFS client assemblies to store a cache of files on your system. If you don’t do this, you will authenticate fine, but then get an exception saying that it is unable to access the cache at some directory path when you query work items. You can set this up by adding the following to your web.config, in the <appSettings> element as shown below: <appSettings> <!-- Add reference to TFS Client Cache --> <add key="WorkItemTrackingCacheRoot" value="C:\windows\temp" /> </appSettings> With all that in place, you can write the following code: var token = new Microsoft.TeamFoundation.Client.SimpleWebTokenCredential("{you-service-account-name", "{your-service-acct-password}"); var clientCreds = new Microsoft.TeamFoundation.Client.TfsClientCredentials(token); var currentCollection = new TfsTeamProjectCollection(new Uri(“https://{yourdomain}.visualstudio.com/defaultcollection”), clientCreds); TfsConfigurationServercurrentCollection.EnsureAuthenticated(); In the above code, not the URL contains the “defaultcollection” at the end of the URL. Obviously replace {yourdomain} with whatever is defined for your TFS in Azure instance. In addition, make sure the service user account and password that was generated in the first step is substituted in here. Note: If something is not right, the “EnsureAuthenticated()” call will throw an exception with the message being you are not authorised. If you forget the “defaultcollection” on the URL, it will still fail but with a message saying you are not authorised. That is, a similar but different exception message. And that is it. You can then query the collection using something like: var service = currentCollection.GetService<WorkItemStore>(); var proj = service.Projects[0]; var allQueries = proj.StoredQueries; for (int qcnt = 0; qcnt < allQueries.Count; qcnt++) {     var query = allQueries[qcnt];     var queryDesc = string.format(“Query found named: {0}”,query.Name); } You get the idea. If you search around, you will find references to the ServiceIdentityCredentialProvider which is referenced in this article. I had no luck with this method and it all looked too hard since it required an extra KB article and other magic sauce. So I hope that helps. This article certainly would have helped me save a boat load of time and frustration.

    Read the article

  • ASP.NET MVC Paging/Sorting/Filtering a list using ModelMetadata

    - by rajbk
    This post looks at how to control paging, sorting and filtering when displaying a list of data by specifying attributes in your Model using the ASP.NET MVC framework and the excellent MVCContrib library. It also shows how to hide/show columns and control the formatting of data using attributes.  This uses the Northwind database. A sample project is attached at the end of this post. Let’s start by looking at a class called ProductViewModel. The properties in the class are decorated with attributes. The OrderBy attribute tells the system that the Model can be sorted using that property. The SearchFilter attribute tells the system that filtering is allowed on that property. Filtering type is set by the  FilterType enum which currently supports Equals and Contains. The ScaffoldColumn property specifies if a column is hidden or not The DisplayFormat specifies how the data is formatted. public class ProductViewModel { [OrderBy(IsDefault = true)] [ScaffoldColumn(false)] public int? ProductID { get; set; }   [SearchFilter(FilterType.Contains)] [OrderBy] [DisplayName("Product Name")] public string ProductName { get; set; }   [OrderBy] [DisplayName("Unit Price")] [DisplayFormat(DataFormatString = "{0:c}")] public System.Nullable<decimal> UnitPrice { get; set; }   [DisplayName("Category Name")] public string CategoryName { get; set; }   [SearchFilter] [ScaffoldColumn(false)] public int? CategoryID { get; set; }   [SearchFilter] [ScaffoldColumn(false)] public int? SupplierID { get; set; }   [OrderBy] public bool Discontinued { get; set; } } Before we explore the code further, lets look at the UI.  The UI has a section for filtering the data. The column headers with links are sortable. Paging is also supported with the help of a pager row. The pager is rendered using the MVCContrib Pager component. The data is displayed using a customized version of the MVCContrib Grid component. The customization was done in order for the Grid to be aware of the attributes mentioned above. Now, let’s look at what happens when we perform actions on this page. The diagram below shows the process: The form on the page has its method set to “GET” therefore we see all the parameters in the query string. The query string is shown in blue above. This query gets routed to an action called Index with parameters of type ProductViewModel and PageSortOptions. The parameters in the query string get mapped to the input parameters using model binding. The ProductView object created has the information needed to filter data while the PageAndSorting object is used for paging and sorting the data. The last block in the figure above shows how the filtered and paged list is created. We receive a product list from our product repository (which is of type IQueryable) and first filter it by calliing the AsFiltered extension method passing in the productFilters object and then call the AsPagination extension method passing in the pageSort object. The AsFiltered extension method looks at the type of the filter instance passed in. It skips properties in the instance that do not have the SearchFilter attribute. For properties that have the SearchFilter attribute, it adds filter expression trees to filter against the IQueryable data. The AsPagination extension method looks at the type of the IQueryable and ensures that the column being sorted on has the OrderBy attribute. If it does not find one, it looks for the default sort field [OrderBy(IsDefault = true)]. It is required that at least one attribute in your model has the [OrderBy(IsDefault = true)]. This because a person could be performing paging without specifying an order by column. As you may recall the LINQ Skip method now requires that you call an OrderBy method before it. Therefore we need a default order by column to perform paging. The extension method adds a order expressoin tree to the IQueryable and calls the MVCContrib AsPagination extension method to page the data. Implementation Notes Auto Postback The search filter region auto performs a get request anytime the dropdown selection is changed. This is implemented using the following jQuery snippet $(document).ready(function () { $("#productSearch").change(function () { this.submit(); }); }); Strongly Typed View The code used in the Action method is shown below: public ActionResult Index(ProductViewModel productFilters, PageSortOptions pageSortOptions) { var productPagedList = productRepository.GetProductsProjected().AsFiltered(productFilters).AsPagination(pageSortOptions);   var productViewFilterContainer = new ProductViewFilterContainer(); productViewFilterContainer.Fill(productFilters.CategoryID, productFilters.SupplierID, productFilters.ProductName);   var gridSortOptions = new GridSortOptions { Column = pageSortOptions.Column, Direction = pageSortOptions.Direction };   var productListContainer = new ProductListContainerModel { ProductPagedList = productPagedList, ProductViewFilterContainer = productViewFilterContainer, GridSortOptions = gridSortOptions };   return View(productListContainer); } As you see above, the object that is returned to the view is of type ProductListContainerModel. This contains all the information need for the view to render the Search filter section (including dropdowns),  the Html.Pager (MVCContrib) and the Html.Grid (from MVCContrib). It also stores the state of the search filters so that they can recreate themselves when the page reloads (Viewstate, I miss you! :0)  The class diagram for the container class is shown below.   Custom MVCContrib Grid The MVCContrib grid default behavior was overridden so that it would auto generate the columns and format the columns based on the metadata and also make it aware of our custom attributes (see MetaDataGridModel in the sample code). The Grid ensures that the ShowForDisplay on the column is set to true This can also be set by the ScaffoldColumn attribute ref: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html) Column headers are set using the DisplayName attribute Column sorting is set using the OrderBy attribute. The data is formatted using the DisplayFormat attribute. Generic Extension methods for Sorting and Filtering The extension method AsFiltered takes in an IQueryable<T> and uses expression trees to query against the IQueryable data. The query is constructed using the Model metadata and the properties of the T filter (productFilters in our case). Properties in the Model that do not have the SearchFilter attribute are skipped when creating the filter expression tree.  It returns an IQueryable<T>. The extension method AsPagination takes in an IQuerable<T> and first ensures that the column being sorted on has the OrderBy attribute. If not, we look for the default OrderBy column ([OrderBy(IsDefault = true)]). We then build an expression tree to sort on this column. We finally hand off the call to the MVCContrib AsPagination which returns an IPagination<T>. This type as you can see in the class diagram above is passed to the view and used by the MVCContrib Grid and Pager components. Custom Provider To get the system to recognize our custom attributes, we create our MetadataProvider as mentioned in this article (http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html) protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) { ModelMetadata metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);   SearchFilterAttribute searchFilterAttribute = attributes.OfType<SearchFilterAttribute>().FirstOrDefault(); if (searchFilterAttribute != null) { metadata.AdditionalValues.Add(Globals.SearchFilterAttributeKey, searchFilterAttribute); }   OrderByAttribute orderByAttribute = attributes.OfType<OrderByAttribute>().FirstOrDefault(); if (orderByAttribute != null) { metadata.AdditionalValues.Add(Globals.OrderByAttributeKey, orderByAttribute); }   return metadata; } We register our MetadataProvider in Global.asax.cs. protected void Application_Start() { AreaRegistration.RegisterAllAreas();   RegisterRoutes(RouteTable.Routes);   ModelMetadataProviders.Current = new MvcFlan.QueryModelMetaDataProvider(); } Bugs, Comments and Suggestions are welcome! You can download the sample code below. This code is purely experimental. Use at your own risk. Download Sample Code (VS 2010 RTM) MVCNorthwindSales.zip

    Read the article

  • Anti-Forgery Request Recipes For ASP.NET MVC And AJAX

    - by Dixin
    Background To secure websites from cross-site request forgery (CSRF, or XSRF) attack, ASP.NET MVC provides an excellent mechanism: The server prints tokens to cookie and inside the form; When the form is submitted to server, token in cookie and token inside the form are sent in the HTTP request; Server validates the tokens. To print tokens to browser, just invoke HtmlHelper.AntiForgeryToken():<% using (Html.BeginForm()) { %> <%: this.Html.AntiForgeryToken(Constants.AntiForgeryTokenSalt)%> <%-- Other fields. --%> <input type="submit" value="Submit" /> <% } %> This invocation generates a token then writes inside the form:<form action="..." method="post"> <input name="__RequestVerificationToken" type="hidden" value="J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP" /> <!-- Other fields. --> <input type="submit" value="Submit" /> </form> and also writes into the cookie: __RequestVerificationToken_Lw__= J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP When the above form is submitted, they are both sent to server. In the server side, [ValidateAntiForgeryToken] attribute is used to specify the controllers or actions to validate them:[HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult Action(/* ... */) { // ... } This is very productive for form scenarios. But recently, when resolving security vulnerabilities for Web products, some problems are encountered. Specify validation on controller (not on each action) The server side problem is, It is expected to declare [ValidateAntiForgeryToken] on controller, but actually it has be to declared on each POST actions. Because POST actions are usually much more then controllers, the work would be a little crazy. Problem Usually a controller contains actions for HTTP GET and actions for HTTP POST requests, and usually validations are expected for HTTP POST requests. So, if the [ValidateAntiForgeryToken] is declared on the controller, the HTTP GET requests become invalid:[ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public class SomeController : Controller // One [ValidateAntiForgeryToken] attribute. { [HttpGet] public ActionResult Index() // Index() cannot work. { // ... } [HttpPost] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] public ActionResult PostAction2(/* ... */) { // ... } // ... } If browser sends an HTTP GET request by clicking a link: http://Site/Some/Index, validation definitely fails, because no token is provided. So the result is, [ValidateAntiForgeryToken] attribute must be distributed to each POST action:public class SomeController : Controller // Many [ValidateAntiForgeryToken] attributes. { [HttpGet] public ActionResult Index() // Works. { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction2(/* ... */) { // ... } // ... } This is a little bit crazy, because one application can have a lot of POST actions. Solution To avoid a large number of [ValidateAntiForgeryToken] attributes (one for each POST action), the following ValidateAntiForgeryTokenWrapperAttribute wrapper class can be helpful, where HTTP verbs can be specified:[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ValidateAntiForgeryTokenWrapperAttribute : FilterAttribute, IAuthorizationFilter { private readonly ValidateAntiForgeryTokenAttribute _validator; private readonly AcceptVerbsAttribute _verbs; public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs) : this(verbs, null) { } public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs, string salt) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = salt }; } public void OnAuthorization(AuthorizationContext filterContext) { string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride(); if (this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase)) { this._validator.OnAuthorization(filterContext); } } } When this attribute is declared on controller, only HTTP requests with the specified verbs are validated:[ValidateAntiForgeryTokenWrapper(HttpVerbs.Post, Constants.AntiForgeryTokenSalt)] public class SomeController : Controller { // GET actions are not affected. // Only HTTP POST requests are validated. } Now one single attribute on controller turns on validation for all POST actions. Maybe it would be nice if HTTP verbs can be specified on the built-in [ValidateAntiForgeryToken] attribute, which is easy to implemented. Specify Non-constant salt in runtime By default, the salt should be a compile time constant, so it can be used for the [ValidateAntiForgeryToken] or [ValidateAntiForgeryTokenWrapper] attribute. Problem One Web product might be sold to many clients. If a constant salt is evaluated in compile time, after the product is built and deployed to many clients, they all have the same salt. Of course, clients do not like this. Even some clients might want to specify a custom salt in configuration. In these scenarios, salt is required to be a runtime value. Solution In the above [ValidateAntiForgeryToken] and [ValidateAntiForgeryTokenWrapper] attribute, the salt is passed through constructor. So one solution is to remove this parameter:public class ValidateAntiForgeryTokenWrapperAttribute : FilterAttribute, IAuthorizationFilter { public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = AntiForgeryToken.Value }; } // Other members. } But here the injected dependency becomes a hard dependency. So the other solution is moving validation code into controller to work around the limitation of attributes:public abstract class AntiForgeryControllerBase : Controller { private readonly ValidateAntiForgeryTokenAttribute _validator; private readonly AcceptVerbsAttribute _verbs; protected AntiForgeryControllerBase(HttpVerbs verbs, string salt) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = salt }; } protected override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride(); if (this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase)) { this._validator.OnAuthorization(filterContext); } } } Then make controller classes inheriting from this AntiForgeryControllerBase class. Now the salt is no long required to be a compile time constant. Submit token via AJAX For browser side, once server side turns on anti-forgery validation for HTTP POST, all AJAX POST requests will fail by default. Problem In AJAX scenarios, the HTTP POST request is not sent by form. Take jQuery as an example:$.post(url, { productName: "Tofu", categoryId: 1 // Token is not posted. }, callback); This kind of AJAX POST requests will always be invalid, because server side code cannot see the token in the posted data. Solution Basically, the tokens must be printed to browser then sent back to server. So first of all, HtmlHelper.AntiForgeryToken() need to be called somewhere. Now the browser has token in both HTML and cookie. Then jQuery must find the printed token in the HTML, and append token to the data before sending:$.post(url, { productName: "Tofu", categoryId: 1, __RequestVerificationToken: getToken() // Token is posted. }, callback); To be reusable, this can be encapsulated into a tiny jQuery plugin:/// <reference path="jquery-1.4.2.js" /> (function ($) { $.getAntiForgeryToken = function (tokenWindow, appPath) { // HtmlHelper.AntiForgeryToken() must be invoked to print the token. tokenWindow = tokenWindow && typeof tokenWindow === typeof window ? tokenWindow : window; appPath = appPath && typeof appPath === "string" ? "_" + appPath.toString() : ""; // The name attribute is either __RequestVerificationToken, // or __RequestVerificationToken_{appPath}. tokenName = "__RequestVerificationToken" + appPath; // Finds the <input type="hidden" name={tokenName} value="..." /> from the specified. // var inputElements = $("input[type='hidden'][name='__RequestVerificationToken" + appPath + "']"); var inputElements = tokenWindow.document.getElementsByTagName("input"); for (var i = 0; i < inputElements.length; i++) { var inputElement = inputElements[i]; if (inputElement.type === "hidden" && inputElement.name === tokenName) { return { name: tokenName, value: inputElement.value }; } } return null; }; $.appendAntiForgeryToken = function (data, token) { // Converts data if not already a string. if (data && typeof data !== "string") { data = $.param(data); } // Gets token from current window by default. token = token ? token : $.getAntiForgeryToken(); // $.getAntiForgeryToken(window). data = data ? data + "&" : ""; // If token exists, appends {token.name}={token.value} to data. return token ? data + encodeURIComponent(token.name) + "=" + encodeURIComponent(token.value) : data; }; // Wraps $.post(url, data, callback, type). $.postAntiForgery = function (url, data, callback, type) { return $.post(url, $.appendAntiForgeryToken(data), callback, type); }; // Wraps $.ajax(settings). $.ajaxAntiForgery = function (settings) { settings.data = $.appendAntiForgeryToken(settings.data); return $.ajax(settings); }; })(jQuery); In most of the scenarios, it is Ok to just replace $.post() invocation with $.postAntiForgery(), and replace $.ajax() with $.ajaxAntiForgery():$.postAntiForgery(url, { productName: "Tofu", categoryId: 1 }, callback); // Token is posted. There might be some scenarios of custom token, where $.appendAntiForgeryToken() is useful:data = $.appendAntiForgeryToken(data, token); // Token is already in data. No need to invoke $.postAntiForgery(). $.post(url, data, callback); And there are scenarios that the token is not in the current window. For example, an HTTP POST request can be sent by an iframe, while the token is in the parent window. Here, token's container window can be specified for $.getAntiForgeryToken():data = $.appendAntiForgeryToken(data, $.getAntiForgeryToken(window.parent)); // Token is already in data. No need to invoke $.postAntiForgery(). $.post(url, data, callback); If you have better solution, please do tell me.

    Read the article

  • .NET 3.5 Installation Problems in Windows 8

    - by Rick Strahl
    Windows 8 installs with .NET 4.5. A default installation of Windows 8 doesn't seem to include .NET 3.0 or 3.5, although .NET 2.0 does seem to be available by default (presumably because Windows has app dependencies on that). I ran into some pretty nasty compatibility issues regarding .NET 3.5 which I'll describe in this post. I'll preface this by saying that depending on how you install Windows 8 you may not run into these issues. In fact, it's probably a special case, but one that might be common with developer folks reading my blog. Specifically it's the install order that screwed things up for me -  installing Visual Studio before explicitly installing .NET 3.5 from Windows Features - in particular. If you install Visual Studio 2010 I highly recommend you install .NET 3.5 from Windows features BEFORE you install Visual Studio 2010 and save yourself the trouble I went through. So when I installed Windows 8, and then looked at the Windows Features to install after the fact in the Windows Feature dialog, I thought - .NET 3.5 - who needs it. I'd be happy to not have to install .NET 3.5, but unfortunately I found out quite a while after initial installation that one of my applications/tools (DevExpress's awesome CodeRush) depends on it and won't install without it. Enabling .NET 3.5 in Windows 8 If you want to run .NET 3.5 on Windows 8, don't download an installer - those installers don't work on Windows 8, and you don't need to do this because you can use the Windows Features dialog to enable .NET 3.5: And that *should* do the trick. If you do this before you install other apps that require .NET 3.5 and install a non-SP1 one version of it, you are going to have no problems. Unfortunately for me, even after I've installed the above, when I run the CodeRush installer I still get this lovely dialog: Now I double checked to see if .NET 3.5 is installed - it is, both for 32 bit and 64 bit. I went as far as creating a small .NET Console app and running it to verify that it actually runs. And it does… So naturally I thought the CodeRush installer is a little whacky. After some back and forth Alex Skorkin on Twitter pointed me in the right direction: He asked me to look in the registry for exact info on which version of .NET 3.5 is installed here: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP where I found that .NET 3.5 SP1 was installed. This is the 64 bit key which looks all correct. However, when I looked under the 32 bit node I found: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\NET Framework Setup\NDP\v3.5 Notice that the service pack number is set to 0, rather than 1 (which it was for the 64 bit install), which is what the installer requires. So to summarize: the 64 bit version is installed with SP1, the 32 bit version is not. Uhm, Ok… thanks for that! Easy to fix, you say - just install SP1. Nope, not so easy because the standalone installer doesn't work on Windows 8. I can't get either .NET 3.5 installer or the SP 1 installer to even launch. They simply start and hang (or exit immediately) without messages. I also tried to get Windows to update .NET 3.5 by checking for Windows Updates, which should pick up on the dated version of .NET 3.5 and pull down SP1, but that's also no go. Check for Updates doesn't bring down any updates for me yet. I'm sure at some random point in the future Windows will deem it necessary to update .NET 3.5 to SP1, but at this point it's not letting me coerce it to do it explicitly. How did this happen I'm not sure exactly whether this is the cause and effect, but I suspect the story goes like this: Installed Windows 8 without support for .NET 3.5 Installed Visual Studio 2010 which installs .NET 3.5 (no SP) I now had .NET 3.5 installed but without SP1. I then: Tried to install CodeRush - Error: .NET 3.5 SP1 required Enabled .NET 3.5 in Windows Features I figured enabling the .NET 3.5 Windows Features would do the trick. But still no go. Now I suspect Visual Studio installed the 32 bit version of .NET 3.5 on my machine and Windows Features detected the previous install and didn't reinstall it. This left the 32 bit install at least with no SP1 installed. How to Fix it My final solution was to completely uninstall .NET 3.5 *and* to reboot: Go to Windows Features Uncheck the .NET Framework 3.5 Restart Windows Go to Windows Features Check .NET Framework 3.5 and voila, I now have a proper installation of .NET 3.5. I tried this before but without the reboot step in between which did not work. Make sure you reboot between uninstalling and reinstalling .NET 3.5! More Problems The above fixed me right up, but in looking for a solution it seems that a lot of people are also having problems with .NET 3.5 installing properly from the Windows Features dialog. The problem there is that the feature wasn't properly loading from the installer disks or not downloading the proper components for updates. It turns out you can explicitly install Windows features using the DISM tool in Windows.dism.exe /online /enable-feature /featurename:NetFX3 /Source:f:\sources\sxs You can try this without the /Source flag first - which uses the hidden Windows installer files if you kept those. Otherwise insert the DVD or ISO and point at the path \sources\sxs path where the installer lives. This also gives you a little more information if something does go wrong.© Rick Strahl, West Wind Technologies, 2005-2012Posted in Windows  .NET   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Anti-Forgery Request Helpers for ASP.NET MVC and jQuery AJAX

    - by Dixin
    Background To secure websites from cross-site request forgery (CSRF, or XSRF) attack, ASP.NET MVC provides an excellent mechanism: The server prints tokens to cookie and inside the form; When the form is submitted to server, token in cookie and token inside the form are sent in the HTTP request; Server validates the tokens. To print tokens to browser, just invoke HtmlHelper.AntiForgeryToken():<% using (Html.BeginForm()) { %> <%: this.Html.AntiForgeryToken(Constants.AntiForgeryTokenSalt)%> <%-- Other fields. --%> <input type="submit" value="Submit" /> <% } %> This invocation generates a token then writes inside the form:<form action="..." method="post"> <input name="__RequestVerificationToken" type="hidden" value="J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP" /> <!-- Other fields. --> <input type="submit" value="Submit" /> </form> and also writes into the cookie: __RequestVerificationToken_Lw__= J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP When the above form is submitted, they are both sent to server. In the server side, [ValidateAntiForgeryToken] attribute is used to specify the controllers or actions to validate them:[HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult Action(/* ... */) { // ... } This is very productive for form scenarios. But recently, when resolving security vulnerabilities for Web products, some problems are encountered. Specify validation on controller (not on each action) The server side problem is, It is expected to declare [ValidateAntiForgeryToken] on controller, but actually it has be to declared on each POST actions. Because POST actions are usually much more then controllers, this is a little crazy Problem Usually a controller contains actions for HTTP GET and actions for HTTP POST requests, and usually validations are expected for HTTP POST requests. So, if the [ValidateAntiForgeryToken] is declared on the controller, the HTTP GET requests become invalid:[ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public class SomeController : Controller // One [ValidateAntiForgeryToken] attribute. { [HttpGet] public ActionResult Index() // Index() cannot work. { // ... } [HttpPost] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] public ActionResult PostAction2(/* ... */) { // ... } // ... } If browser sends an HTTP GET request by clicking a link: http://Site/Some/Index, validation definitely fails, because no token is provided. So the result is, [ValidateAntiForgeryToken] attribute must be distributed to each POST action:public class SomeController : Controller // Many [ValidateAntiForgeryToken] attributes. { [HttpGet] public ActionResult Index() // Works. { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction2(/* ... */) { // ... } // ... } This is a little bit crazy, because one application can have a lot of POST actions. Solution To avoid a large number of [ValidateAntiForgeryToken] attributes (one for each POST action), the following ValidateAntiForgeryTokenAttribute wrapper class can be helpful, where HTTP verbs can be specified:[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ValidateAntiForgeryTokenWrapperAttribute : FilterAttribute, IAuthorizationFilter { private readonly ValidateAntiForgeryTokenAttribute _validator; private readonly AcceptVerbsAttribute _verbs; public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs) : this(verbs, null) { } public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs, string salt) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = salt }; } public void OnAuthorization(AuthorizationContext filterContext) { string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride(); if (this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase)) { this._validator.OnAuthorization(filterContext); } } } When this attribute is declared on controller, only HTTP requests with the specified verbs are validated:[ValidateAntiForgeryTokenWrapper(HttpVerbs.Post, Constants.AntiForgeryTokenSalt)] public class SomeController : Controller { // GET actions are not affected. // Only HTTP POST requests are validated. } Now one single attribute on controller turns on validation for all POST actions. Maybe it would be nice if HTTP verbs can be specified on the built-in [ValidateAntiForgeryToken] attribute, which is easy to implemented. Submit token via AJAX The browser side problem is, if server side turns on anti-forgery validation for POST, then AJAX POST requests will fail be default. Problem For AJAX scenarios, when request is sent by jQuery instead of form:$.post(url, { productName: "Tofu", categoryId: 1 // Token is not posted. }, callback); This kind of AJAX POST requests will always be invalid, because server side code cannot see the token in the posted data. Solution The tokens are printed to browser then sent back to server. So first of all, HtmlHelper.AntiForgeryToken() must be called somewhere. Now the browser has token in HTML and cookie. Then jQuery must find the printed token in the HTML, and append token to the data before sending:$.post(url, { productName: "Tofu", categoryId: 1, __RequestVerificationToken: getToken() // Token is posted. }, callback); To be reusable, this can be encapsulated into a tiny jQuery plugin:/// <reference path="jquery-1.4.2.js" /> (function ($) { $.getAntiForgeryToken = function (tokenWindow, appPath) { // HtmlHelper.AntiForgeryToken() must be invoked to print the token. tokenWindow = tokenWindow && typeof tokenWindow === typeof window ? tokenWindow : window; appPath = appPath && typeof appPath === "string" ? "_" + appPath.toString() : ""; // The name attribute is either __RequestVerificationToken, // or __RequestVerificationToken_{appPath}. tokenName = "__RequestVerificationToken" + appPath; // Finds the <input type="hidden" name={tokenName} value="..." /> from the specified. // var inputElements = $("input[type='hidden'][name='__RequestVerificationToken" + appPath + "']"); var inputElements = tokenWindow.document.getElementsByTagName("input"); for (var i = 0; i < inputElements.length; i++) { var inputElement = inputElements[i]; if (inputElement.type === "hidden" && inputElement.name === tokenName) { return { name: tokenName, value: inputElement.value }; } } return null; }; $.appendAntiForgeryToken = function (data, token) { // Converts data if not already a string. if (data && typeof data !== "string") { data = $.param(data); } // Gets token from current window by default. token = token ? token : $.getAntiForgeryToken(); // $.getAntiForgeryToken(window). data = data ? data + "&" : ""; // If token exists, appends {token.name}={token.value} to data. return token ? data + encodeURIComponent(token.name) + "=" + encodeURIComponent(token.value) : data; }; // Wraps $.post(url, data, callback, type). $.postAntiForgery = function (url, data, callback, type) { return $.post(url, $.appendAntiForgeryToken(data), callback, type); }; // Wraps $.ajax(settings). $.ajaxAntiForgery = function (settings) { settings.data = $.appendAntiForgeryToken(settings.data); return $.ajax(settings); }; })(jQuery); In most of the scenarios, it is Ok to just replace $.post() invocation with $.postAntiForgery(), and replace $.ajax() with $.ajaxAntiForgery():$.postAntiForgery(url, { productName: "Tofu", categoryId: 1 }, callback); // Token is posted. There might be some scenarios of custom token. Here $.appendAntiForgeryToken() is provided:data = $.appendAntiForgeryToken(data, token); // Token is already in data. No need to invoke $.postAntiForgery(). $.post(url, data, callback); And there are scenarios that the token is not in the current window. For example, an HTTP POST request can be sent by iframe, while the token is in the parent window. Here window can be specified for $.getAntiForgeryToken():data = $.appendAntiForgeryToken(data, $.getAntiForgeryToken(window.parent)); // Token is already in data. No need to invoke $.postAntiForgery(). $.post(url, data, callback); If you have better solution, please do tell me.

    Read the article

  • Edit and Continue does not Work in VS 2010 / ASP.Net MVC 2

    - by Eric J.
    Although Enable Edit and Continue is checked on the Web tab of my ASP.Net MVC 2 project, I cannot in fact change the source code while running. For example, if I try to edit a controller while paused in the debugger, I cannot change the file (acts as if read only). I found a related post Edit and continue in ASP.NET web projects, however The answers seem to suggest I should be able to at least edit the code, then reload the page to see the result. I don't know what the distinction is between a Web Application and Web Site projects Any guidance is appreciated.

    Read the article

  • Invalid padding on ASP 2.0 cookie, MVC looks ok

    - by brian b
    We have a cookie management library that writes a cookie containing some sensitive information, encrypted with Rijndael. The cookie encrypts and decrypts fine in unit tests (using Moq), works fine for MVC web applications, but when called from an ASP.net 2.0 website, the cookie cannot be decrypted. "Padding is invalid and cannot be removed." We are sure that the cookie value is valid because we tested it 10,000 times with random data in a unit test. There is something about what ASP.NET 2.0 does when it reads and writes the cookie that causes trouble. There has to be a gotcha. Any suggestions?

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >