Search Results

Search found 806 results on 33 pages for 'httpcontext'.

Page 11/33 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Adding SQL Cache Dependencies to the Loosely coupled .NET Cache Provider

    - by Rhames
    This post adds SQL Cache Dependency support to the loosely coupled .NET Cache Provider that I described in the previous post (http://geekswithblogs.net/Rhames/archive/2012/09/11/loosely-coupled-.net-cache-provider-using-dependency-injection.aspx). The sample code is available on github at https://github.com/RobinHames/CacheProvider.git. Each time we want to apply a cache dependency to a call to fetch or cache a data item we need to supply an instance of the relevant dependency implementation. This suggests an Abstract Factory will be useful to create cache dependencies as needed. We can then use Dependency Injection to inject the factory into the relevant consumer. Castle Windsor provides a typed factory facility that will be utilised to implement the cache dependency abstract factory (see http://docs.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx). Cache Dependency Interfaces First I created a set of cache dependency interfaces in the domain layer, which can be used to pass a cache dependency into the cache provider. ICacheDependency The ICacheDependency interface is simply an empty interface that is used as a parent for the specific cache dependency interfaces. This will allow us to place a generic constraint on the Cache Dependency Factory, and will give us a type that can be passed into the relevant Cache Provider methods. namespace CacheDiSample.Domain.CacheInterfaces { public interface ICacheDependency { } }   ISqlCacheDependency.cs The ISqlCacheDependency interface provides specific SQL caching details, such as a Sql Command or a database connection and table. It is the concrete implementation of this interface that will be created by the factory in passed into the Cache Provider. using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace CacheDiSample.Domain.CacheInterfaces { public interface ISqlCacheDependency : ICacheDependency { ISqlCacheDependency Initialise(string databaseConnectionName, string tableName); ISqlCacheDependency Initialise(System.Data.SqlClient.SqlCommand sqlCommand); } } If we want other types of cache dependencies, such as by key or file, interfaces may be created to support these (the sample code includes an IKeyCacheDependency interface). Modifying ICacheProvider to accept Cache Dependencies Next I modified the exisitng ICacheProvider<T> interface so that cache dependencies may be passed into a Fetch method call. I did this by adding two overloads to the existing Fetch methods, which take an IEnumerable<ICacheDependency> parameter (the IEnumerable allows more than one cache dependency to be included). I also added a method to create cache dependencies. This means that the implementation of the Cache Provider will require a dependency on the Cache Dependency Factory. It is pretty much down to personal choice as to whether this approach is taken, or whether the Cache Dependency Factory is injected directly into the repository or other consumer of Cache Provider. I think, because the cache dependency cannot be used without the Cache Provider, placing the dependency on the factory into the Cache Provider implementation is cleaner. ICacheProvider.cs using System; using System.Collections.Generic;   namespace CacheDiSample.Domain.CacheInterfaces { public interface ICacheProvider<T> { T Fetch(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry); T Fetch(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry, IEnumerable<ICacheDependency> cacheDependencies);   IEnumerable<T> Fetch(string key, Func<IEnumerable<T>> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry); IEnumerable<T> Fetch(string key, Func<IEnumerable<T>> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry, IEnumerable<ICacheDependency> cacheDependencies);   U CreateCacheDependency<U>() where U : ICacheDependency; } }   Cache Dependency Factory Next I created the interface for the Cache Dependency Factory in the domain layer. ICacheDependencyFactory.cs namespace CacheDiSample.Domain.CacheInterfaces { public interface ICacheDependencyFactory { T Create<T>() where T : ICacheDependency;   void Release<T>(T cacheDependency) where T : ICacheDependency; } }   I used the ICacheDependency parent interface as a generic constraint on the create and release methods in the factory interface. Now the interfaces are in place, I moved on to the concrete implementations. ISqlCacheDependency Concrete Implementation The concrete implementation of ISqlCacheDependency will need to provide an instance of System.Web.Caching.SqlCacheDependency to the Cache Provider implementation. Unfortunately this class is sealed, so I cannot simply inherit from this. Instead, I created an interface called IAspNetCacheDependency that will provide a Create method to create an instance of the relevant System.Web.Caching Cache Dependency type. This interface is specific to the ASP.NET implementation of the Cache Provider, so it should be defined in the same layer as the concrete implementation of the Cache Provider (the MVC UI layer in the sample code). IAspNetCacheDependency.cs using System.Web.Caching;   namespace CacheDiSample.CacheProviders { public interface IAspNetCacheDependency { CacheDependency CreateAspNetCacheDependency(); } }   Next, I created the concrete implementation of the ISqlCacheDependency interface. This class also implements the IAspNetCacheDependency interface. This concrete implementation also is defined in the same layer as the Cache Provider implementation. AspNetSqlCacheDependency.cs using System.Web.Caching; using CacheDiSample.Domain.CacheInterfaces;   namespace CacheDiSample.CacheProviders { public class AspNetSqlCacheDependency : ISqlCacheDependency, IAspNetCacheDependency { private string databaseConnectionName;   private string tableName;   private System.Data.SqlClient.SqlCommand sqlCommand;   #region ISqlCacheDependency Members   public ISqlCacheDependency Initialise(string databaseConnectionName, string tableName) { this.databaseConnectionName = databaseConnectionName; this.tableName = tableName; return this; }   public ISqlCacheDependency Initialise(System.Data.SqlClient.SqlCommand sqlCommand) { this.sqlCommand = sqlCommand; return this; }   #endregion   #region IAspNetCacheDependency Members   public System.Web.Caching.CacheDependency CreateAspNetCacheDependency() { if (sqlCommand != null) return new SqlCacheDependency(sqlCommand); else return new SqlCacheDependency(databaseConnectionName, tableName); }   #endregion   } }   ICacheProvider Concrete Implementation The ICacheProvider interface is implemented by the CacheProvider class. This implementation is modified to include the changes to the ICacheProvider interface. First I needed to inject the Cache Dependency Factory into the Cache Provider: private ICacheDependencyFactory cacheDependencyFactory;   public CacheProvider(ICacheDependencyFactory cacheDependencyFactory) { if (cacheDependencyFactory == null) throw new ArgumentNullException("cacheDependencyFactory");   this.cacheDependencyFactory = cacheDependencyFactory; }   Next I implemented the CreateCacheDependency method, which simply passes on the create request to the factory: public U CreateCacheDependency<U>() where U : ICacheDependency { return this.cacheDependencyFactory.Create<U>(); }   The signature of the FetchAndCache helper method was modified to take an additional IEnumerable<ICacheDependency> parameter:   private U FetchAndCache<U>(string key, Func<U> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry, IEnumerable<ICacheDependency> cacheDependencies) and the following code added to create the relevant System.Web.Caching.CacheDependency object for any dependencies and pass them to the HttpContext Cache: CacheDependency aspNetCacheDependencies = null;   if (cacheDependencies != null) { if (cacheDependencies.Count() == 1) // We know that the implementations of ICacheDependency will also implement IAspNetCacheDependency // so we can use a cast here and call the CreateAspNetCacheDependency() method aspNetCacheDependencies = ((IAspNetCacheDependency)cacheDependencies.ElementAt(0)).CreateAspNetCacheDependency(); else if (cacheDependencies.Count() > 1) { AggregateCacheDependency aggregateCacheDependency = new AggregateCacheDependency(); foreach (ICacheDependency cacheDependency in cacheDependencies) { // We know that the implementations of ICacheDependency will also implement IAspNetCacheDependency // so we can use a cast here and call the CreateAspNetCacheDependency() method aggregateCacheDependency.Add(((IAspNetCacheDependency)cacheDependency).CreateAspNetCacheDependency()); } aspNetCacheDependencies = aggregateCacheDependency; } }   HttpContext.Current.Cache.Insert(key, value, aspNetCacheDependencies, absoluteExpiry.Value, relativeExpiry.Value);   The full code listing for the modified CacheProvider class is shown below: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Caching; using CacheDiSample.Domain.CacheInterfaces;   namespace CacheDiSample.CacheProviders { public class CacheProvider<T> : ICacheProvider<T> { private ICacheDependencyFactory cacheDependencyFactory;   public CacheProvider(ICacheDependencyFactory cacheDependencyFactory) { if (cacheDependencyFactory == null) throw new ArgumentNullException("cacheDependencyFactory");   this.cacheDependencyFactory = cacheDependencyFactory; }   public T Fetch(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry) { return FetchAndCache<T>(key, retrieveData, absoluteExpiry, relativeExpiry, null); }   public T Fetch(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry, IEnumerable<ICacheDependency> cacheDependencies) { return FetchAndCache<T>(key, retrieveData, absoluteExpiry, relativeExpiry, cacheDependencies); }   public IEnumerable<T> Fetch(string key, Func<IEnumerable<T>> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry) { return FetchAndCache<IEnumerable<T>>(key, retrieveData, absoluteExpiry, relativeExpiry, null); }   public IEnumerable<T> Fetch(string key, Func<IEnumerable<T>> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry, IEnumerable<ICacheDependency> cacheDependencies) { return FetchAndCache<IEnumerable<T>>(key, retrieveData, absoluteExpiry, relativeExpiry, cacheDependencies); }   public U CreateCacheDependency<U>() where U : ICacheDependency { return this.cacheDependencyFactory.Create<U>(); }   #region Helper Methods   private U FetchAndCache<U>(string key, Func<U> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry, IEnumerable<ICacheDependency> cacheDependencies) { U value; if (!TryGetValue<U>(key, out value)) { value = retrieveData(); if (!absoluteExpiry.HasValue) absoluteExpiry = Cache.NoAbsoluteExpiration;   if (!relativeExpiry.HasValue) relativeExpiry = Cache.NoSlidingExpiration;   CacheDependency aspNetCacheDependencies = null;   if (cacheDependencies != null) { if (cacheDependencies.Count() == 1) // We know that the implementations of ICacheDependency will also implement IAspNetCacheDependency // so we can use a cast here and call the CreateAspNetCacheDependency() method aspNetCacheDependencies = ((IAspNetCacheDependency)cacheDependencies.ElementAt(0)).CreateAspNetCacheDependency(); else if (cacheDependencies.Count() > 1) { AggregateCacheDependency aggregateCacheDependency = new AggregateCacheDependency(); foreach (ICacheDependency cacheDependency in cacheDependencies) { // We know that the implementations of ICacheDependency will also implement IAspNetCacheDependency // so we can use a cast here and call the CreateAspNetCacheDependency() method aggregateCacheDependency.Add( ((IAspNetCacheDependency)cacheDependency).CreateAspNetCacheDependency()); } aspNetCacheDependencies = aggregateCacheDependency; } }   HttpContext.Current.Cache.Insert(key, value, aspNetCacheDependencies, absoluteExpiry.Value, relativeExpiry.Value);   } return value; }   private bool TryGetValue<U>(string key, out U value) { object cachedValue = HttpContext.Current.Cache.Get(key); if (cachedValue == null) { value = default(U); return false; } else { try { value = (U)cachedValue; return true; } catch { value = default(U); return false; } } }   #endregion } }   Wiring up the DI Container Now the implementations for the Cache Dependency are in place, I wired them up in the existing Windsor CacheInstaller. First I needed to register the implementation of the ISqlCacheDependency interface: container.Register( Component.For<ISqlCacheDependency>() .ImplementedBy<AspNetSqlCacheDependency>() .LifestyleTransient());   Next I registered the Cache Dependency Factory. Notice that I have not implemented the ICacheDependencyFactory interface. Castle Windsor will do this for me by using the Type Factory Facility. I do need to bring the Castle.Facilities.TypedFacility namespace into scope: using Castle.Facilities.TypedFactory;   Then I registered the factory: container.AddFacility<TypedFactoryFacility>();   container.Register( Component.For<ICacheDependencyFactory>() .AsFactory()); The full code for the CacheInstaller class is: using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using Castle.Facilities.TypedFactory;   using CacheDiSample.Domain.CacheInterfaces; using CacheDiSample.CacheProviders;   namespace CacheDiSample.WindsorInstallers { public class CacheInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( Component.For(typeof(ICacheProvider<>)) .ImplementedBy(typeof(CacheProvider<>)) .LifestyleTransient());   container.Register( Component.For<ISqlCacheDependency>() .ImplementedBy<AspNetSqlCacheDependency>() .LifestyleTransient());   container.AddFacility<TypedFactoryFacility>();   container.Register( Component.For<ICacheDependencyFactory>() .AsFactory()); } } }   Configuring the ASP.NET SQL Cache Dependency There are a couple of configuration steps required to enable SQL Cache Dependency for the application and database. From the Visual Studio Command Prompt, the following commands should be used to enable the Cache Polling of the relevant database tables: aspnet_regsql -S <servername> -E -d <databasename> –ed aspnet_regsql -S <servername> -E -d CacheSample –et –t <tablename>   (The –t option should be repeated for each table that is to be made available for cache dependencies). Finally the SQL Cache Polling needs to be enabled by adding the following configuration to the <system.web> section of web.config: <caching> <sqlCacheDependency pollTime="10000" enabled="true"> <databases> <add name="BloggingContext" connectionStringName="BloggingContext"/> </databases> </sqlCacheDependency> </caching>   (obviously the name and connection string name should be altered as required). Using a SQL Cache Dependency Now all the coding is complete. To specify a SQL Cache Dependency, I can modify my BlogRepositoryWithCaching decorator class (see the earlier post) as follows: public IList<Blog> GetAll() { var sqlCacheDependency = cacheProvider.CreateCacheDependency<ISqlCacheDependency>() .Initialise("BloggingContext", "Blogs");   ICacheDependency[] cacheDependencies = new ICacheDependency[] { sqlCacheDependency };   string key = string.Format("CacheDiSample.DataAccess.GetAll");   return cacheProvider.Fetch(key, () => { return parentBlogRepository.GetAll(); }, null, null, cacheDependencies) .ToList(); }   This will add a dependency of the “Blogs” table in the database. The data will remain in the cache until the contents of this table change, then the cache item will be invalidated, and the next call to the GetAll() repository method will be routed to the parent repository to refresh the data from the database.

    Read the article

  • SharePoint 2010: CheckSuspiciousPhysicalPath exception

    - by Tommy Jakobsen
    I just installed SharePoint 2010 on my Windows Server 2008 R2 x64 server with SQL Server 2008. Everything is installed on this single server, and I configured SharePoint 2010 as described here: http://sharepoint.microsoft.com/blogs/fromthefield/Lists/Posts/Post.aspx?ID=112 Everything installed correct, and the SQL databases were created. But when I try to access the administration site through http://server:47632/_admin/adminconfigintro.aspx, I get the following exception: [HttpException] at System.Web.Util.FileUtil.CheckSuspiciousPhysicalPath(String physicalPath) at System.Web.CachedPathData.GetConfigPathData(String configPath) at System.Web.CachedPathData.GetConfigPathData(String configPath) at System.Web.CachedPathData.GetConfigPathData(String configPath) at System.Web.HttpContext.GetFilePathData() at System.Web.Configuration.CustomErrorsSection.GetSettings(HttpContext context, Boolean canThrow) at System.Web.HttpResponse.ReportRuntimeError(Exception e, Boolean canThrow, Boolean localExecute) at System.Web.HttpRuntime.FinishRequest(HttpWorkerRequest wr, HttpContext context, Exception e) The same error occurs when accessing http://server:47632/. Do you have any ideas whats causing this? I haven't been able to find anything about this issue. Edit 1: I just tried reinstalling SharePoint 2010 while monitoring the error log. When I run the configuration wizard, the following errors show up in the event log: The site /sites/Help could not be created. The following exception occurred: Dependency feature with id 5f3b0127-2f1d-4cfd-8dd2-85ad1fb00bfc for feature 'BaseSite' (id: b21b090c-c796-4b0f-ac0f-7ef1659c20ae) is not installed.. Safe mode did not start successfully. This page has encountered a critical error. Contact your system administrator if this problem persists. Safe mode did not start successfully. This page has encountered a critical error. Contact your system administrator if this problem persists. The site /sites/Help could not be created. The following exception occurred: Dependency feature with id 2ed1c45e-a73b-4779-ae81-1524e4de467a for feature 'BaseSite' (id: b21b090c-c796-4b0f-ac0f-7ef1659c20ae) is not installed.. The Execute method of job definition Microsoft.Office.InfoPath.Server.Administration.FormsMaintenanceJobDefinition (ID 59158daa-d0b6-458f-bd0a-7d1d713ac743) threw an exception. More information is included below. Access to the path 'C:\ProgramData\Microsoft\SharePoint\Config\319280433bd74178b6b1fd945c064698' is denied. The Execute method of job definition Microsoft.Office.InfoPath.Server.Administration.FormsMaintenanceJobDefinition (ID b3f45215-4d18-44f2-84bd-cc16bc339dd7) threw an exception. More information is included below. Access to the path 'C:\ProgramData\Microsoft\SharePoint\Config\319280433bd74178b6b1fd945c064698' is denied. Any ideas?

    Read the article

  • ASP.NET MVC - HttpPost to ReturnURL after redirect

    - by JP
    Hello, I am writing an ASP.NET MVC 2.0 application which requires users to log in before placing a bid on an item. I am using an actionfilter to ensure that the user is logged in and, if not, send them to a login page and set the return url. Below is the code i use in my action filter. if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.Result = new RedirectResult(String.Concat("~/Account/LogOn","?ReturnUrl=",filterContext.HttpContext.Request.RawUrl)); return; } In my logon controller I validate the users credentials then sign them in and redirect to the return url FormsAuth.SignIn(userName, rememberMe); if (!String.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } My problem is that this will always use a Get (HttpGet) request whereas my original submission was a post (HttpPost) and should always be a post. Can anyone suggest a way of passing this URL including the HttpMethod or any workaround to ensure that the correct HttpMethod is used? Thanks in advance, JP

    Read the article

  • RouteTable.Routes.GetVirtualPath with route data asp.net MVC 2

    - by Bill
    Dear all, I'm trying to get a URL from my routes table. Here is the method. private static void RedirectToRoute(ActionExecutingContext context, string param) { var actionName = context.ActionDescriptor.ActionName; var controllerName = context.ActionDescriptor.ControllerDescriptor.ControllerName; var rc = new RequestContext(context.HttpContext, context.RouteData); string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { actionName = actionName, controller = controllerName, parameter = param })).VirtualPath; context.HttpContext.Response.Redirect(url, true); } I'm trying to map it to. However RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { actionName = actionName, controller = controllerName, parameter = param })) keeps giving me null. Any thoughts? routes.MapRoute( "default3", // Route name "{parameter}/{controller}/{action}", // URL with parameters new { parameter= "parameterValue", controller = "Home", action = "Index" } ); I know I can use redirectToAction and other methods, but I would like to change the URL in the browser with new routedata.

    Read the article

  • Loading any MVC page fails with the error "An item with the same key has already been added."

    - by MajorRefactoring
    I am having an intermittent issue that is appearing on one server only, and is causing all MVC pages to fail to load with the error "An item with the same key has already been added." Restarting the application pool fixes the issue, but until then, loading any mvc page throws the following exception: Event code: 3005 Event message: An unhandled exception has occurred. Event time: 10/11/2012 08:09:24 Event time (UTC): 10/11/2012 08:09:24 Event ID: d76264aedc4241d4bce9247692510466 Event sequence: 6407 Event occurrence: 30 Event detail code: 0 Application information: Application domain: /LM/W3SVC/21/ROOT-2-129969647741292058 Trust level: Full Application Virtual Path: / Application Path: d:\websites\SiteAndAppPoolName\ Machine name: UKSERVER Process information: Process ID: 6156 Process name: w3wp.exe Account name: IIS APPPOOL\SiteAndAppPoolName Exception information: Exception type: ArgumentException Exception message: An item with the same key has already been added. Server stack trace: at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer) at System.Web.WebPages.Scope.WebConfigScopeDictionary.<>c__DisplayClass4.<.ctor>b__0() at System.Lazy`1.CreateValue() Exception rethrown at [0]: at System.Lazy`1.get_Value() at System.Web.WebPages.Scope.WebConfigScopeDictionary.TryGetValue(Object key, Object& value) at System.Web.Mvc.ViewContext.ScopeGet[TValue](IDictionary`2 scope, String name, TValue defaultValue) at System.Web.Mvc.ViewContext.ScopeCache.Get(IDictionary`2 scope, HttpContextBase httpContext) at System.Web.Mvc.ViewContext.GetClientValidationEnabled(IDictionary`2 scope, HttpContextBase httpContext) at System.Web.Mvc.Html.FormExtensions.FormHelper(HtmlHelper htmlHelper, String formAction, FormMethod method, IDictionary`2 htmlAttributes) at System.Web.Mvc.Html.FormExtensions.BeginForm(HtmlHelper htmlHelper, String actionName, String controllerName) at ASP._Page_Views_Dashboard_Functions_BookingQuickLookup_cshtml.Execute() in d:\Websites\SiteAndAppPoolName\Views\Dashboard\Functions\BookingQuickLookup.cshtml:line 3 at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData) at ASP._Page_Views_Dashboard_Functions_cshtml.Execute() in d:\Websites\SiteAndAppPoolName\Views\Dashboard\Functions.cshtml:line 5 at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) at System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper htmlHelper, String partialViewName, Object model) at ASP._Page_Views_Dashboard_Index_cshtml.Execute() in d:\Websites\SiteAndAppPoolName\Views\Dashboard\Index.cshtml:line 9 at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) at System.Web.Mvc.Controller.ExecuteCore() at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0() at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.<EndProcessRequest>b__d() at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) Request information: Request URL: http://SiteAndAppPoolName.spawtz.com/Dashboard Request path: /Dashboard User host address: 86.164.135.41 User: Is authenticated: False Authentication Type: Thread account name: IIS APPPOOL\SiteAndAppPoolName Thread information: Thread ID: 17 Thread account name: IIS APPPOOL\SiteAndAppPoolName Is impersonating: False Stack trace: at System.Lazy`1.get_Value() at System.Web.WebPages.Scope.WebConfigScopeDictionary.TryGetValue(Object key, Object& value) at System.Web.Mvc.ViewContext.ScopeGet[TValue](IDictionary`2 scope, String name, TValue defaultValue) at System.Web.Mvc.ViewContext.ScopeCache.Get(IDictionary`2 scope, HttpContextBase httpContext) at System.Web.Mvc.ViewContext.GetClientValidationEnabled(IDictionary`2 scope, HttpContextBase httpContext) at System.Web.Mvc.Html.FormExtensions.FormHelper(HtmlHelper htmlHelper, String formAction, FormMethod method, IDictionary`2 htmlAttributes) at System.Web.Mvc.Html.FormExtensions.BeginForm(HtmlHelper htmlHelper, String actionName, String controllerName) at ASP._Page_Views_Dashboard_Functions_BookingQuickLookup_cshtml.Execute() in d:\Websites\SiteAndAppPoolName\Views\Dashboard\Functions\BookingQuickLookup.cshtml:line 3 at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData) at ASP._Page_Views_Dashboard_Functions_cshtml.Execute() in d:\Websites\SiteAndAppPoolName\Views\Dashboard\Functions.cshtml:line 5 at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) at System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper htmlHelper, String partialViewName, Object model) at ASP._Page_Views_Dashboard_Index_cshtml.Execute() in d:\Websites\SiteAndAppPoolName\Views\Dashboard\Index.cshtml:line 9 at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) at System.Web.Mvc.Controller.ExecuteCore() at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0() at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.<EndProcessRequest>b__d() at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) Custom event details: As mentioned, it's every MVC action that throws this error until the app pool is restarted, and the error seems to be occurring in System.Web.WebPages.Scope.WebConfigScopeDictionary.TryGetValue(Object key, Object& value) Has anyone seen this issue before? It's only happening on this server, on any of the app pools on the server (not confined to this one) and an app pool restart sorts it. Any help much appreciated. Cheers, Matthew

    Read the article

  • ASP. NET MVC2: Where abouts do I set Current.User from a Session variable?

    - by Adam Brown
    Hi, I'm trying to get authentication and authorisation working in an ASP .NET MVC2 site. I've read loads of tutorials and some books which explain how you can use attributes to require authorisation (and membership in a role) like this: [Authorize(Roles="Admin")] public ActionResult Index() { return View(); } I've made classes that implement IIdentity and IPrincipal, I create a userPrincipal object once the user has successfully logged in and I add it to a session variable. When the user goes to another page I want it to set the HttpContext.Current.User to the object that I stored in the session, something like this: if (Session["User"] != null) { HttpContext.Current.User = Session["User"] as MyUser; } My question is: Where abouts do I put the code directly above? I tried Application_AuthenticateRequest but it tells me Session state is not available in this context. Many thanks.

    Read the article

  • NHibernate: Collection was modified; enumeration operation may not execute

    - by Daoming Yang
    Hi All, I'm currently struggling with this "Collection was modified; enumeration operation may not execute" issue. I have searched about this error message, and it's all related to the foreach statement. I do have the some foreach statements, but they are just simply representing the data. I did not using any remove or add inside the foreach statement. NOTE: The error randomly happens (about 4-5 times a day). The application is the MVC website. There are about 5 users operate this applications (about 150 orders a day). Could it be some another users modified the collection, and then occur this error? I have log4net setup and the settings can be found here Make sure that the controller has a parameterless public constructor I do have parameterless public constructor in AdminProductController Does anyone know why this happen and how to resolve this issue? A friend (Oskar) mentioned that "Theory: Maybe the problem is that your configuration and session factory is initialized on the first request after application restart. If a second request comes in before the first request is finished, maybe it will also try to initialize and then triggering this problem somehow." Many thanks. Daoming Here is the error message: System.InvalidOperationException Collection was modified; enumeration operation may not execute. System.InvalidOperationException: An error occurred when trying to create a controller of type 'WebController.Controllers.Admin.AdminProductController'. Make sure that the controller has a parameterless public constructor. --- System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --- NHibernate.MappingException: Could not configure datastore from input stream DomainModel.Entities.Mappings.OrderProductVariant.hbm.xml --- System.InvalidOperationException: Collection was modified; enumeration operation may not execute. at System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext() at System.Xml.Schema.XmlSchemaSet.AddSchemaToSet(XmlSchema schema) at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlSchema schema) at System.Xml.Schema.XmlSchemaSet.Add(XmlSchema schema) at NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name) at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name) --- End of inner exception stack trace --- at NHibernate.Cfg.Configuration.LogAndThrow(Exception exception) at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name) at NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly) at NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly) at DomainModel.RepositoryBase..ctor() at WebController.Controllers._baseController..ctor() at WebController.Controllers.Admin.AdminProductController..ctor() at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) --- End of inner exception stack trace --- at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) --- End of inner exception stack trace --- at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) UPDATE CODE: In my Global.asax.cs, I'm doing this: protected void Application_BeginRequest(object sender, EventArgs e) { ManagedWebSessionContext.Bind(HttpContext.Current, SessionManager.SessionFactory.OpenSession()); } protected void Application_EndRequest(object sender, EventArgs e) { ISession session = ManagedWebSessionContext.Unbind(HttpContext.Current, SessionManager.SessionFactory); if (session != null) { try { if (session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } else { session.Flush(); } } finally { session.Close(); } } } In the SessionManager class, I'm doing: public class SessionManager { private readonly ISessionFactory sessionFactory; public static ISessionFactory SessionFactory { get { return Instance.sessionFactory; } } private ISessionFactory GetSessionFactory() { return sessionFactory; } public static SessionManager Instance { get { return NestedSessionManager.sessionManager; } } public static ISession OpenSession() { return Instance.GetSessionFactory().OpenSession(); } public static ISession CurrentSession { get { return Instance.GetSessionFactory().GetCurrentSession(); } } private SessionManager() { Configuration config = new Configuration().Configure(); config.AddAssembly(Assembly.GetExecutingAssembly()); sessionFactory = config.BuildSessionFactory(); } class NestedSessionManager { internal static readonly SessionManager sessionManager = new SessionManager(); } } In the Repository, I'm doing this: public IEnumerable<User> GetAll() { ICriteria criteria = SessionManager.CurrentSession.CreateCriteria(typeof(User)); return criteria.List<User>(); } In the Controller, I'm doing this: public class UserController : _baseController { IUserRoleRepository _userRoleRepository; internal static readonly ILogger log = LogManager.GetLogger(typeof(UserController)); public UserController() { _userRoleRepository = new UserRoleRepository(); } public ActionResult UserList() { var myList = _usersRepository.GetAll(); return View(myList); } }

    Read the article

  • PerWebRequest LifetimeManager and Beyond (Asp.net Mvc)

    - by Soe Moe
    Hi, Currently, I created my custom PerWebRequestLifetimeManager using HttpContext.Current.Items as backing store. I used that lifetime manager for Linq2Sql DataContext. Eveything is working fine until I need to use Cache for storing data (for 5 min). After 5 min, I need to retrieve data from DB and put it into the Cache. To do so, I need to use Linq2Sql DataContext for retrieving data. But during that time, HttpContext.Current is null because which was happened when cache is expired; not in Web Request. So, what kind of LifetimeManager should I use for this scenario? Thanks in advance.

    Read the article

  • WCF Global(.asax) Behavior

    - by Theofanis Pantelides
    Hi, I want to create a global option that when a REST call contains &format=json to output the response as a JSON string. If I enter the following String in my method it works: WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json; However, if I add this line, anywhere in my Global.asax file, I get a nullException for Current Context: String format = ""; if (HttpContext.Current.Request.QueryString["format"] != null) format = HttpContext.Current.Request.QueryString["format"]; if (String.Equals("json", format, StringComparison.OrdinalIgnoreCase)) System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.Format = System.ServiceModel.Web.WebMessageFormat.Json; The exception is triggered here: System.ServiceModel.Web.WebOperationContext.Current Anyone know how I can add this functionality globally (WCF)?

    Read the article

  • Complete if statement with strings and array of strings

    - by RandomBen
    I have a page that has 3 variables. They look like this: String[] Headers = new String[] { "Max Width", "Max Length", "Max Height" }; String currentHeader = (String)HttpContext.Current.Request.QueryString["ItemHas"] ?? ""; String checkString = (String)HttpContext.Current.Request.QueryString["ItemIn"] ?? ""; The checkString is a list of Headers delimited by a "|". What is the easiest way to check if my currentHeader is in my Headers array and in my checkString String? I can do it but not in less than 20 lines of code. That seems like a less than optimal solution.

    Read the article

  • Sharepoint dynamic caml query problem?

    - by AB
    Hi, I want to dynamic caml query based on query string.Let me explain it with example my query sting can be anything ?cat=ABC&cat=ABD&cat=ABE... ?Cat=ABC ?Cat=ABC&cat=ABL so no. can be anything now the problem begins I want to query my sharepoint list based on this query string if (HttpContext.Current.Request.QueryString["cat"] != null) { string _cat = HttpContext.Current.Request.QueryString["cat"].ToString(); } so this way my string contains all the query string _cat=ABC,AD,....all. I want to query my sharepoint list based on these query string and with "AND" where title=ABC and title=AD .... if there is only one query string then only where title=ABC....so I want my query string should be dynamic.... Any idea how to acheive this??

    Read the article

  • client ip address in ASP.NET (.asmx) webservices

    - by Zain Shaikh
    I am using ASP.Net (.asmx) web services with Silverlight. since there is no way to find client ip address in Silverlight, therefore I had to log this on service end. these are some methods I have tried: Request.ServerVariables(”REMOTE_HOST”) HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; Request.UserHostAddress() Request.UserHostName() string strHostName = System.Net.Dns.GetHostName(); string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString(); All the above methods work fine on my local system, but when I publish my service on production server. it starts giving errors. Error: Object reference not set to an instance of an object. StackTrace: at System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32 index) at System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String name) at System.Web.Hosting.ISAPIWorkerRequest.GetRemoteAddress() at System.Web.HttpRequest.get_UserHostAddress()

    Read the article

  • ASP.NET MVC Response Filter + OutputCache Attribute

    - by Shane Andrade
    I'm not sure if this is an ASP.NET MVC specific thing or ASP.NET in general but here's what's happening. I have an action filter that removes whitespace by the use of a response filter: public class StripWhitespaceAttribute : ActionFilterAttribute { public StripWhitespaceAttribute () { } public override void OnResultExecuted(ResultExecutedContext filterContext) { base.OnResultExecuted(filterContext); filterContext.HttpContext.Response.Filter = new WhitespaceFilter(filterContext.HttpContext.Response.Filter); } } When used in conjunction with the OutputCache attribute, my calls to Response.WriteSubstitution for "donut hole caching" do not work. The first and second time the page loads the callback passed to WriteSubstitution get called, after that they are not called anymore until the output cache expires. I've noticed this with not just this particular filter but any filter used on Response.Filter... am I missing something? I also forgot to mention I've tried this without the use of an MVC action filter attribute by attaching to the PostReleaseRequestState event in the global.asax and setting the Response.Filter value there... but still no luck.

    Read the article

  • asp.net mvc form add comment

    - by Pinu
    I have a page where a product appears on the right side and the user can add comment so i have a user control which gets all the comments and a small text area where user can add new comment for that product. the link of the page is like http://localhost/Product/TestComment/1 Where 1 indicates the id of the product and I have been hard coding my AddNote function below and fourth argument you see has been hard coded, but i need to pass that as the id of the product. How do i do this AddNote(HttpContext.User.Identity.ToString(), txtComment, 1, DateTime.Now, true); [AcceptVerbs(HttpVerbs.Post)] public ActionResult AddComment(string txtComment) { bool rst = _NotesService.AddNote(HttpContext.User.Identity.ToString(), txtComment, 1, DateTime.Now, true); return RedirectToAction("TestComment"); }

    Read the article

  • Mocking User.Identity in ASP.NET MVC

    - by Trey Carroll
    I need to create Unit Tests for an ASP.NET MVC 2.0 web site. The site uses Windows Authentication. I've been reading up on the necessity to mock the HTTP context for code that deals with the HttpContext. I feel like I'm starting to get a handle on the DI pattern as well. (Give the class an attribute of type IRepository and then pass in a Repository object when you instantiate the controller.) What I don't understand, however, is the proper way to Mock the Windows Principal object available through User.Identity. Is this part of the HttpContext? Does any body have a link to an article that demonstrates this (or a recommendation for a book)? Thanks, Trey Carroll

    Read the article

  • Unable to Retrieve Simplified Chinese Characters From Form

    - by Bullines
    I have a page that displays content retrieved from XML with no problems: <?xml version="1.0" encoding="UTF-8"?> <Root> <Fields> <NamePrompt>??</NamePrompt> </Fields> </Root> Page encoding is set to GB18030 and it displays perfectly. However, when I retrieve inputted text from HttpContext.Current.Request.Form that's been entered with double-byte characters, the retrieved string contains unreadable characters. Single-byte characters are fine, obviously. I've tried the following to no avail: byte[] valueBytes = Encoding.UTF8.GetBytes(HttpContext.Current.Request.Form["fullName"]); string value = Encoding.UTF8.GetString(valueBytes); I don't see this problem with other double-byte languages like Japanese or Korean. How can I successfully retrieve double-byte characters from a page that's GB18030 encoded?

    Read the article

  • Linq help using "Contains"

    - by Kettenbach
    Good Morning All, I'm trying to use "Contains" to see if an object is within the collection. When I break I can see that the object is indeed part of the collection however "Contains" seems to be returning false indicating the item is not in the collection. Any idea what I'm doing wrong? if(HttpContext.Current.Session["AutoPayTypes"] != null) { var autopays = HttpContext.Current.Session["AutoPayTypes"] as List<PaymentTypeInfo>; char? coverageProductLine = null; if(entityProps.ContainsKey("CoverageProductLine")) { coverageProductLine = (char?)entityProps["CoverageProductLine"]; } var paymentTypeInfoRepository = new PaymentTypeInfoRepository(); var payType = paymentTypeInfoRepository.GetPaymentTypeInfo(paymentAdd.PayType, coverageProductLine); if (autopays != null && payType != null) paymentAdd.DaysPaid = autopays.Contains(payType) ? null : paymentAdd.DaysPaid; } If the object is not in the collection the "DaysPaid" needs to be null. Any ideas? Thanks, ~ck in San Diego

    Read the article

  • Asp.Net : Web service throws "Thread was being aborted"

    - by Master Morality
    I have a web service that I call via ajax that requires the user to be logged in. in each method I want to check if the user is logged in and send a 403 code if they are not, however when I call a Response.End() I get the error "Thread was being aborted". What should I call instead? [WebMethod(true)] public string MyMethod() { if(!userIsLoggedIn) { HttpContext.Current.Response.StatusCode = 403; HttpContext.Current.Response.End(); } /* Do stuff that should not execute unless the user is logged in... */ ... }

    Read the article

  • ASP.net getting NT user name returns administrator?

    - by JonH
    This doesnt seem to be an issue with windows XP. But I have an end user (my boss!!!) using windows 7 64 bit... In one of our apps we are grabbing the end user user name via: HttpContext.Current.User.Identity.Name.ToString.Substring (HttpContext.Current.User.Identity.Name.ToString.IndexOf("\") + 1).ToLower For me it is returning the correct user name for instance "jhermiz". When my boss tries getting into the app, it thinks he is Administrator??? Does anyone know of any alternative or why this might be happening? The reason this is an issue is because I use that user name to pull other information... This is visual studio 2003.

    Read the article

  • Internet Explorer shows error when downloading excel file in SSL site

    - by Billy
    I get the following error when downloading excel file in SSL site: Internet Explorer cannot download xxxx.aspx from mysite.com. Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later. After googling, I suspect that it's the problem of the response header. I try the solution in this page and set the header: http://trac.edgewall.org/ticket/1020 HttpContext.Current.Response.AddHeader("Pragma", "no-cache"); HttpContext.Current.Response.CacheControl = "private"; But it doesn't work. Any suggestions?

    Read the article

  • How do you unit test web page authorization using ASP.NET MVC?

    - by Kevin Pang
    Let's say you have a profile page that can only be accessed by the owner of that profile. This profile page is located at: User/Profile/{userID} Now, I imagine in order to prevent access to this page by other users, you could structure your UserController class's Profile function to check the current session's identity: HttpContext.Current.User.Identity.Name If the id matches the one in the url, then you proceed. Otherwise you redirect to some sort of error page. My question is how do you unit test something like this? I'm guessing that you need to use some sort of dependency injection instead of the HttpContext in the controller to do the check on, but I am unclear what the best way to do that is. Any advice would be helpful.

    Read the article

  • Problems setting up an ASP.NET MVC site on IIS7 w/ Nhibernate

    - by Brandon
    When deploying my published website to the host (Its a shared hosting plan) I get this error: [NullReferenceException: Object reference not set to an instance of an object.] System.Web.PipelineStepManager.ResumeSteps(Exception error) +929 System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb) +91 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +508 I found this question which describes my problem, but I'm not initializing NHibernate in Application_Start, it is already being done in Init. The only other cause of this error I can find is that the Global.asax file is inheriting from a class other than HttpApplication, but I'm not doing that either. This is pretty much the Global.asax file protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } public override void Init() { base.Init(); if (_wasNHibernateInitialized) return; // Initialize NHibernate // Other setup like the StructureMap initialization } Is there any other reason why an ASP.NET MVC application would give this error when being deployed to IIS7?

    Read the article

  • ASP.NET Client to Server communication

    - by Nelson
    Can you help me make sense of all the different ways to communicate from browser to client in ASP.NET? I have made this a community wiki so feel free to edit my post to improve it. Specifically, I'm trying to understand in which scenario to use each one by listing how each works. I'm a little fuzzy on UpdatePanel vs CallBack (with ViewState): I know UpdatePanel always returns HTML while CallBack can return JSON. Any other major differences? ...and CallBack (without ViewState) vs WebMethod. CallBack goes through most of the Page lifecycle, WebMethod doesn't. Any other major differences? IHttpHandler Custom handler for anything (page, image, etc.) Only does what you tell it to do (light server processing) Page is an implementation of IHttpHandler If you don't need what Page provides, create a custom IHttpHandler If you are using Page but overriding Render() and not generating HTML, you probably can do it with a custom IHttpHandler (e.g. writing binary data such as images) By default can use the .axd or .ashx file extensions -- both are functionally similar .ashx doesn't have any built-in endpoints, so it's preferred by convention Regular PostBack (System.Web.UI.Page : IHttpHandler) Inherits Page Full PostBack, including ViewState and HTML control values (heavy traffic) Full Page lifecycle (heavy server processing) No JavaScript required Webpage flickers/scrolls since everything is reloaded in browser Returns full page HTML (heavy traffic) UpdatePanel (Control) Control inside Page Full PostBack, including ViewState and HTML control values (heavy traffic) Full Page lifecycle (heavy server processing) Controls outside the UpdatePanel do Render(NullTextWriter) Must use ScriptManager If no client-side JavaScript, it can fall back to regular PostBack with no JavaScript (?) No flicker/scroll since it's an async call, unless it falls back to regular postback. Can be used with master pages and user controls Has built-in support for progress bar Returns HTML for controls inside UpdatePanel (medium traffic) Client CallBack (Page, System.Web.UI.ICallbackEventHandler) Inherits Page Most of Page lifecycle (heavy server processing) Takes only data you specify (light traffic) and optionally ViewState (?) (medium traffic) Client must support JavaScript and use ScriptManager No flicker/scroll since it's an async call Can be used with master pages and user controls Returns only data you specify in format you specify (e.g. JSON, XML...) (?) (light traffic) WebMethod Class implements System.Web.Service.WebService HttpContext available through this.Context Takes only data you specify (light traffic) Server only runs the called method (light server processing) Client must support JavaScript No flicker/scroll since it's an async call Can be used with master pages and user controls Returns only data you specify, typically JSON (light traffic) Can create instance of server control to render HTML and sent back as string, but events, paging in GridView, etc. won't work PageMethods Essentially a WebMethod contained in the Page class, so most of WebMethod's bullet's apply Method must be public static, therefore no Page instance accessible HttpContext available through HttpContext.Current Accessed directly by URL Page.aspx/MethodName (e.g. with XMLHttpRequest directly or with library such as jQuery) Setting ScriptManager property EnablePageMethods="True" generates a JavaScript proxy for each WebMethod Cannot be used directly in user controls with master pages and user controls Any others?

    Read the article

  • what is the global.asax Application_Start equivalent when using WAS in IIS7

    - by Mike Tours
    Hi I'd like to use the netTcpBinding for my WCF application which is currently hosted in IIS7, which means configuring it to use WAS instead. This is fairly straight forward however, my application previously made use of the Application_Start event in the global.asax file. I do not require access to the httpContext(which I understand access has been removed in IIS7), however I would still like to hook into the start or init methods? Does an equivalent exist when hosting an application in WAS as apposed to IIS7? Using classic mode is not an option(again I'm not interested in the httpcontext and this only appears to work if using an http binding) - and I've seen an example of putting a static class instide the app_code folder which looks like a horrible hack.

    Read the article

  • Problem passing ELMAH log id to Custom Error page in ASP.NET

    - by Ronnie Overby
    I am using ELMAH to log unhandled exceptions in an ASP.NET Webforms application. Logging is working fine. I want to pass the ELMAH error log id to a custom error page that will give the user the ability to email an administrator about the error. I have followed the advice from this answer. Here is my global.asax code: void ErrorLog_Logged(object sender, ErrorLoggedEventArgs args) { Session[StateKeys.ElmahLogId] = args.Entry.Id; // this doesn't work either: // HttpContext.Current.Items[StateKeys.ElmahLogId] = args.Entry.Id; } But, on the Custom error page, the session variable reference and HttpContext.Current.Items are giving me a NullReference exception. How can I pass the ID to my custom error page?

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >