Search Results

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

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

  • How does this Singleton-like web class persists session data, even though session is not updated in

    - by Micah Burnett
    Ok, I've got this singleton-like web class which uses session to maintain state. I initially thought I was going to have to manipulate the session variables on each "set" so that the new values were updated in the session. However I tried using it as-is, and somehow, it remembers state. For example, if run this code on one page: UserContext.Current.User.FirstName = "Micah"; And run this code in a different browser tab, FirstName is displayed correctly: Response.Write(UserContext.Current.User.FirstName); Can someone tell me (prove) how this data is getting persisted in the session? Here is the class: using System; using System.Collections.Generic; using System.Linq; using System.Web; public class UserContext { private UserContext() { } public static UserContext Current { get { if (System.Web.HttpContext.Current.Session["UserContext"] == null) { UserContext uc = new UserContext(); uc.User = new User(); System.Web.HttpContext.Current.Session["UserContext"] = uc; } return (UserContext)System.Web.HttpContext.Current.Session["UserContext"]; } } private string HospitalField; public string Hospital { get { return HospitalField; } set { HospitalField = value; ContractField = null; ModelType = null; } } private string ContractField; public string Contract { get { return ContractField; } set { ContractField = value; ModelType = string.Empty; } } private string ModelTypeField; public string ModelType { get { return ModelTypeField; } set { ModelTypeField = value; } } private User UserField; public User User { get { return UserField; } set { UserField = value; } } public void DoSomething() { } } public class User { public int UserId { get; set; } public string FirstName { get; set; } } I added this to a watch, and can see that the session variable is definitely being set somewhere: (UserContext)System.Web.HttpContext.Current.Session["UserContext"]; As soon as a setter is called the Session var is immediately updated: set { HospitalField = value; //<--- here ContractField = null; ModelType = null; }

    Read the article

  • QueryString From Shared Function

    - by Kezzer
    I'm trying to get a query string from a shared function in a code-behind model using VB.NET. You have to use HttpContext.Current.Request.QueryString("Query") in order to get it from a shared function, however doing HttpContext.Current.Request.QueryString.Count gives back 0, which obviously isn't right in my case as there's many that exist. Is there some sort of issue with using this static call from a shared function?

    Read the article

  • C# and WCF + Getting the location of execution

    - by user208662
    Hello, I have a WCF service that is responsible for writing a log file. I would like to write a log file relative to the location of my WCF service. This service does NOT have an HttpContext available. Because of this, I cannot use HttpContext.Current.Server.MapPath. How can I get the location of where my WCF service is running so that I can create a log file? Thank you

    Read the article

  • using a Singleton to pass credentials in a multi-tenant application a code smell?

    - by Hans Gruber
    Currently working on a multi-tenant application that employs Shared DB/Shared Schema approach. IOW, we enforce tenant data segregation by defining a TenantID column on all tables. By convention, all SQL reads/writes must include a Where TenantID = '?' clause. Not an ideal solution, but hindsight is 20/20. Anyway, since virtually every page/workflow in our app must display tenant specific data, I made the (poor) decision at the project's outset to employ a Singleton to encapsulate the current user credentials (i.e. TenantID and UserID). My thinking at the time was that I didn't want to add a TenantID parameter to each and every method signature in my Data layer. Here's what the basic pseudo-code looks like: public class UserIdentity { public UserIdentity(int tenantID, int userID) { TenantID = tenantID; UserID = userID; } public int TenantID { get; private set; } public int UserID { get; private set; } } public class AuthenticationModule : IHttpModule { public void Init(HttpApplication context) { context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest); } private void context_AuthenticateRequest(object sender, EventArgs e) { var userIdentity = _authenticationService.AuthenticateUser(sender); if (userIdentity == null) { //authentication failed, so redirect to login page, etc } else { //put the userIdentity into the HttpContext object so that //its only valid for the lifetime of a single request HttpContext.Current.Items["UserIdentity"] = userIdentity; } } } public static class CurrentUser { public static UserIdentity Instance { get { return HttpContext.Current.Items["UserIdentity"]; } } } public class WidgetRepository: IWidgetRepository{ public IEnumerable<Widget> ListWidgets(){ var tenantId = CurrentUser.Instance.TenantID; //call sproc with tenantId parameter } } As you can see, there are several code smells here. This is a singleton, so it's already not unit test friendly. On top of that you have a very tight-coupling between CurrentUser and the HttpContext object. By extension, this also means that I have a reference to System.Web in my Data layer (shudder). I want to pay down some technical debt this sprint by getting rid of this singleton for the reasons mentioned above. I have a few thoughts on what an better implementation might be, but if anyone has any guidance or lessons learned they could share, I would be much obliged.

    Read the article

  • ASP.NET MVC 2 Preview 2 Route Request Not Working

    - by Kezzer
    Here's the error: The incoming request does not match any route. Basically I upgraded from Preview 1 to Preview 2 and got rid of a load of redundant stuff in relation to areas (as described by Phil Haack). It didn't work so I created a brand new project to check out how its dealt with in Preview 2. The file Default.aspx no longer exists which contains the following: public void Page_Load(object sender, System.EventArgs e) { // Change the current path so that the Routing handler can correctly interpret // the request, then restore the original path so that the OutputCache module // can correctly process the response (if caching is enabled). string originalPath = Request.Path; HttpContext.Current.RewritePath(Request.ApplicationPath, false); IHttpHandler httpHandler = new MvcHttpHandler(); httpHandler.ProcessRequest(HttpContext.Current); HttpContext.Current.RewritePath(originalPath, false); } The error I received points to the line httpHandler.ProcessRequest(HttpContext.Current); yet in newer projects none of this even exists. To test it, I quickly deleted Default.aspx but then absolutely nothing worked, I didn't even receive any errors. Here's some code extracts: Global.asax.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Intranet { public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); AreaRegistration.RegisterAllAreas(); routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); } protected void App_Start() { RegisterRoutes(RouteTable.Routes); } } } Notice the area registration as that's what I'm using. Routes.cs using System.Web.Mvc; namespace Intranet.Areas.Accounts { public class Routes : AreaRegistration { public override string AreaName { get { return "Accounts"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute("Accounts_Default", "Accounts/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }); } } } Check the latest docs for more info on this part. It's to register the area. The Routes.cs files are located in the root folder of each area. Cheers

    Read the article

  • folder deleting not working

    - by user1150440
    If System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(Server.MapPath("images/TravelogueGallery/" & getMaxID()))) Then System.IO.Directory.Delete(HttpContext.Current.Server.MapPath("images/TravelogueGallery/" & getMaxID()), True) End If I am using the above code snippet to delete a directory but i get this error "'G:\Projects\Latest\LTCIndia 05-04-12 1415\images\TravelogueGallery\19' is not a valid virtual path. " Whats wrong with the code?

    Read the article

  • Custom ASP.NET Routing to an HttpHandler

    - by Rick Strahl
    As of version 4.0 ASP.NET natively supports routing via the now built-in System.Web.Routing namespace. Routing features are automatically integrated into the HtttpRuntime via a few custom interfaces. New Web Forms Routing Support In ASP.NET 4.0 there are a host of improvements including routing support baked into Web Forms via a RouteData property available on the Page class and RouteCollection.MapPageRoute() route handler that makes it easy to route to Web forms. To map ASP.NET Page routes is as simple as setting up the routes with MapPageRoute:protected void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } void RegisterRoutes(RouteCollection routes) { routes.MapPageRoute("StockQuote", "StockQuote/{symbol}", "StockQuote.aspx"); routes.MapPageRoute("StockQuotes", "StockQuotes/{symbolList}", "StockQuotes.aspx"); } and then accessing the route data in the page you can then use the new Page class RouteData property to retrieve the dynamic route data information:public partial class StockQuote1 : System.Web.UI.Page { protected StockQuote Quote = null; protected void Page_Load(object sender, EventArgs e) { string symbol = RouteData.Values["symbol"] as string; StockServer server = new StockServer(); Quote = server.GetStockQuote(symbol); // display stock data in Page View } } Simple, quick and doesn’t require much explanation. If you’re using WebForms most of your routing needs should be served just fine by this simple mechanism. Kudos to the ASP.NET team for putting this in the box and making it easy! How Routing Works To handle Routing in ASP.NET involves these steps: Registering Routes Creating a custom RouteHandler to retrieve an HttpHandler Attaching RouteData to your HttpHandler Picking up Route Information in your Request code Registering routes makes ASP.NET aware of the Routes you want to handle via the static RouteTable.Routes collection. You basically add routes to this collection to let ASP.NET know which URL patterns it should watch for. You typically hook up routes off a RegisterRoutes method that fires in Application_Start as I did in the example above to ensure routes are added only once when the application first starts up. When you create a route, you pass in a RouteHandler instance which ASP.NET caches and reuses as routes are matched. Once registered ASP.NET monitors the routes and if a match is found just prior to the HttpHandler instantiation, ASP.NET uses the RouteHandler registered for the route and calls GetHandler() on it to retrieve an HttpHandler instance. The RouteHandler.GetHandler() method is responsible for creating an instance of an HttpHandler that is to handle the request and – if necessary – to assign any additional custom data to the handler. At minimum you probably want to pass the RouteData to the handler so the handler can identify the request based on the route data available. To do this you typically add  a RouteData property to your handler and then assign the property from the RouteHandlers request context. This is essentially how Page.RouteData comes into being and this approach should work well for any custom handler implementation that requires RouteData. It’s a shame that ASP.NET doesn’t have a top level intrinsic object that’s accessible off the HttpContext object to provide route data more generically, but since RouteData is directly tied to HttpHandlers and not all handlers support it it might cause some confusion of when it’s actually available. Bottom line is that if you want to hold on to RouteData you have to assign it to a custom property of the handler or else pass it to the handler via Context.Items[] object that can be retrieved on an as needed basis. It’s important to understand that routing is hooked up via RouteHandlers that are responsible for loading HttpHandler instances. RouteHandlers are invoked for every request that matches a route and through this RouteHandler instance the Handler gains access to the current RouteData. Because of this logic it’s important to understand that Routing is really tied to HttpHandlers and not available prior to handler instantiation, which is pretty late in the HttpRuntime’s request pipeline. IOW, Routing works with Handlers but not with earlier in the pipeline within Modules. Specifically ASP.NET calls RouteHandler.GetHandler() from the PostResolveRequestCache HttpRuntime pipeline event. Here’s the call stack at the beginning of the GetHandler() call: which fires just before handler resolution. Non-Page Routing – You need to build custom RouteHandlers If you need to route to a custom Http Handler or other non-Page (and non-MVC) endpoint in the HttpRuntime, there is no generic mapping support available. You need to create a custom RouteHandler that can manage creating an instance of an HttpHandler that is fired in response to a routed request. Depending on what you are doing this process can be simple or fairly involved as your code is responsible based on the route data provided which handler to instantiate, and more importantly how to pass the route data on to the Handler. Luckily creating a RouteHandler is easy by implementing the IRouteHandler interface which has only a single GetHttpHandler(RequestContext context) method. In this method you can pick up the requestContext.RouteData, instantiate the HttpHandler of choice, and assign the RouteData to it. Then pass back the handler and you’re done.Here’s a simple example of GetHttpHandler() method that dynamically creates a handler based on a passed in Handler type./// <summary> /// Retrieves an Http Handler based on the type specified in the constructor /// </summary> /// <param name="requestContext"></param> /// <returns></returns> IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { IHttpHandler handler = Activator.CreateInstance(CallbackHandlerType) as IHttpHandler; // If we're dealing with a Callback Handler // pass the RouteData for this route to the Handler if (handler is CallbackHandler) ((CallbackHandler)handler).RouteData = requestContext.RouteData; return handler; } Note that this code checks for a specific type of handler and if it matches assigns the RouteData to this handler. This is optional but quite a common scenario if you want to work with RouteData. If the handler you need to instantiate isn’t under your control but you still need to pass RouteData to Handler code, an alternative is to pass the RouteData via the HttpContext.Items collection:IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { IHttpHandler handler = Activator.CreateInstance(CallbackHandlerType) as IHttpHandler; requestContext.HttpContext.Items["RouteData"] = requestContext.RouteData; return handler; } The code in the handler implementation can then pick up the RouteData from the context collection as needed:RouteData routeData = HttpContext.Current.Items["RouteData"] as RouteData This isn’t as clean as having an explicit RouteData property, but it does have the advantage that the route data is visible anywhere in the Handler’s code chain. It’s definitely preferable to create a custom property on your handler, but the Context work-around works in a pinch when you don’t’ own the handler code and have dynamic code executing as part of the handler execution. An Example of a Custom RouteHandler: Attribute Based Route Implementation In this post I’m going to discuss a custom routine implementation I built for my CallbackHandler class in the West Wind Web & Ajax Toolkit. CallbackHandler can be very easily used for creating AJAX, REST and POX requests following RPC style method mapping. You can pass parameters via URL query string, POST data or raw data structures, and you can retrieve results as JSON, XML or raw string/binary data. It’s a quick and easy way to build service interfaces with no fuss. As a quick review here’s how CallbackHandler works: You create an Http Handler that derives from CallbackHandler You implement methods that have a [CallbackMethod] Attribute and that’s it. Here’s an example of an CallbackHandler implementation in an ashx.cs based handler:// RestService.ashx.cs public class RestService : CallbackHandler { [CallbackMethod] public StockQuote GetStockQuote(string symbol) { StockServer server = new StockServer(); return server.GetStockQuote(symbol); } [CallbackMethod] public StockQuote[] GetStockQuotes(string symbolList) { StockServer server = new StockServer(); string[] symbols = symbolList.Split(new char[2] { ',',';' },StringSplitOptions.RemoveEmptyEntries); return server.GetStockQuotes(symbols); } } CallbackHandler makes it super easy to create a method on the server, pass data to it via POST, QueryString or raw JSON/XML data, and then retrieve the results easily back in various formats. This works wonderful and I’ve used these tools in many projects for myself and with clients. But one thing missing has been the ability to create clean URLs. Typical URLs looked like this: http://www.west-wind.com/WestwindWebToolkit/samples/Rest/StockService.ashx?Method=GetStockQuote&symbol=msfthttp://www.west-wind.com/WestwindWebToolkit/samples/Rest/StockService.ashx?Method=GetStockQuotes&symbolList=msft,intc,gld,slw,mwe&format=xml which works and is clear enough, but also clearly very ugly. It would be much nicer if URLs could look like this: http://www.west-wind.com//WestwindWebtoolkit/Samples/StockQuote/msfthttp://www.west-wind.com/WestwindWebtoolkit/Samples/StockQuotes/msft,intc,gld,slw?format=xml (the Virtual Root in this sample is WestWindWebToolkit/Samples and StockQuote/{symbol} is the route)(If you use FireFox try using the JSONView plug-in make it easier to view JSON content) So, taking a clue from the WCF REST tools that use RouteUrls I set out to create a way to specify RouteUrls for each of the endpoints. The change made basically allows changing the above to: [CallbackMethod(RouteUrl="RestService/StockQuote/{symbol}")] public StockQuote GetStockQuote(string symbol) { StockServer server = new StockServer(); return server.GetStockQuote(symbol); } [CallbackMethod(RouteUrl = "RestService/StockQuotes/{symbolList}")] public StockQuote[] GetStockQuotes(string symbolList) { StockServer server = new StockServer(); string[] symbols = symbolList.Split(new char[2] { ',',';' },StringSplitOptions.RemoveEmptyEntries); return server.GetStockQuotes(symbols); } where a RouteUrl is specified as part of the Callback attribute. And with the changes made with RouteUrls I can now get URLs like the second set shown earlier. So how does that work? Let’s find out… How to Create Custom Routes As mentioned earlier Routing is made up of several steps: Creating a custom RouteHandler to create HttpHandler instances Mapping the actual Routes to the RouteHandler Retrieving the RouteData and actually doing something useful with it in the HttpHandler In the CallbackHandler routing example above this works out to something like this: Create a custom RouteHandler that includes a property to track the method to call Set up the routes using Reflection against the class Looking for any RouteUrls in the CallbackMethod attribute Add a RouteData property to the CallbackHandler so we can access the RouteData in the code of the handler Creating a Custom Route Handler To make the above work I created a custom RouteHandler class that includes the actual IRouteHandler implementation as well as a generic and static method to automatically register all routes marked with the [CallbackMethod(RouteUrl="…")] attribute. Here’s the code:/// <summary> /// Route handler that can create instances of CallbackHandler derived /// callback classes. The route handler tracks the method name and /// creates an instance of the service in a predictable manner /// </summary> /// <typeparam name="TCallbackHandler">CallbackHandler type</typeparam> public class CallbackHandlerRouteHandler : IRouteHandler { /// <summary> /// Method name that is to be called on this route. /// Set by the automatically generated RegisterRoutes /// invokation. /// </summary> public string MethodName { get; set; } /// <summary> /// The type of the handler we're going to instantiate. /// Needed so we can semi-generically instantiate the /// handler and call the method on it. /// </summary> public Type CallbackHandlerType { get; set; } /// <summary> /// Constructor to pass in the two required components we /// need to create an instance of our handler. /// </summary> /// <param name="methodName"></param> /// <param name="callbackHandlerType"></param> public CallbackHandlerRouteHandler(string methodName, Type callbackHandlerType) { MethodName = methodName; CallbackHandlerType = callbackHandlerType; } /// <summary> /// Retrieves an Http Handler based on the type specified in the constructor /// </summary> /// <param name="requestContext"></param> /// <returns></returns> IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { IHttpHandler handler = Activator.CreateInstance(CallbackHandlerType) as IHttpHandler; // If we're dealing with a Callback Handler // pass the RouteData for this route to the Handler if (handler is CallbackHandler) ((CallbackHandler)handler).RouteData = requestContext.RouteData; return handler; } /// <summary> /// Generic method to register all routes from a CallbackHandler /// that have RouteUrls defined on the [CallbackMethod] attribute /// </summary> /// <typeparam name="TCallbackHandler">CallbackHandler Type</typeparam> /// <param name="routes"></param> public static void RegisterRoutes<TCallbackHandler>(RouteCollection routes) { // find all methods var methods = typeof(TCallbackHandler).GetMethods(BindingFlags.Instance | BindingFlags.Public); foreach (var method in methods) { var attrs = method.GetCustomAttributes(typeof(CallbackMethodAttribute), false); if (attrs.Length < 1) continue; CallbackMethodAttribute attr = attrs[0] as CallbackMethodAttribute; if (string.IsNullOrEmpty(attr.RouteUrl)) continue; // Add the route routes.Add(method.Name, new Route(attr.RouteUrl, new CallbackHandlerRouteHandler(method.Name, typeof(TCallbackHandler)))); } } } The RouteHandler implements IRouteHandler, and its responsibility via the GetHandler method is to create an HttpHandler based on the route data. When ASP.NET calls GetHandler it passes a requestContext parameter which includes a requestContext.RouteData property. This parameter holds the current request’s route data as well as an instance of the current RouteHandler. If you look at GetHttpHandler() you can see that the code creates an instance of the handler we are interested in and then sets the RouteData property on the handler. This is how you can pass the current request’s RouteData to the handler. The RouteData object also has a  RouteData.RouteHandler property that is also available to the Handler later, which is useful in order to get additional information about the current route. In our case here the RouteHandler includes a MethodName property that identifies the method to execute in the handler since that value no longer comes from the URL so we need to figure out the method name some other way. The method name is mapped explicitly when the RouteHandler is created and here the static method that auto-registers all CallbackMethods with RouteUrls sets the method name when it creates the routes while reflecting over the methods (more on this in a minute). The important point here is that you can attach additional properties to the RouteHandler and you can then later access the RouteHandler and its properties later in the Handler to pick up these custom values. This is a crucial feature in that the RouteHandler serves in passing additional context to the handler so it knows what actions to perform. The automatic route registration is handled by the static RegisterRoutes<TCallbackHandler> method. This method is generic and totally reusable for any CallbackHandler type handler. To register a CallbackHandler and any RouteUrls it has defined you simple use code like this in Application_Start (or other application startup code):protected void Application_Start(object sender, EventArgs e) { // Register Routes for RestService CallbackHandlerRouteHandler.RegisterRoutes<RestService>(RouteTable.Routes); } If you have multiple CallbackHandler style services you can make multiple calls to RegisterRoutes for each of the service types. RegisterRoutes internally uses reflection to run through all the methods of the Handler, looking for CallbackMethod attributes and whether a RouteUrl is specified. If it is a new instance of a CallbackHandlerRouteHandler is created and the name of the method and the type are set. routes.Add(method.Name,           new Route(attr.RouteUrl, new CallbackHandlerRouteHandler(method.Name, typeof(TCallbackHandler) )) ); While the routing with CallbackHandlerRouteHandler is set up automatically for all methods that use the RouteUrl attribute, you can also use code to hook up those routes manually and skip using the attribute. The code for this is straightforward and just requires that you manually map each individual route to each method you want a routed: protected void Application_Start(objectsender, EventArgs e){    RegisterRoutes(RouteTable.Routes);}void RegisterRoutes(RouteCollection routes) { routes.Add("StockQuote Route",new Route("StockQuote/{symbol}",                     new CallbackHandlerRouteHandler("GetStockQuote",typeof(RestService) ) ) );     routes.Add("StockQuotes Route",new Route("StockQuotes/{symbolList}",                     new CallbackHandlerRouteHandler("GetStockQuotes",typeof(RestService) ) ) );}I think it’s clearly easier to have CallbackHandlerRouteHandler.RegisterRoutes() do this automatically for you based on RouteUrl attributes, but some people have a real aversion to attaching logic via attributes. Just realize that the option to manually create your routes is available as well. Using the RouteData in the Handler A RouteHandler’s responsibility is to create an HttpHandler and as mentioned earlier, natively IHttpHandler doesn’t have any support for RouteData. In order to utilize RouteData in your handler code you have to pass the RouteData to the handler. In my CallbackHandlerRouteHandler when it creates the HttpHandler instance it creates the instance and then assigns the custom RouteData property on the handler:IHttpHandler handler = Activator.CreateInstance(CallbackHandlerType) as IHttpHandler; if (handler is CallbackHandler) ((CallbackHandler)handler).RouteData = requestContext.RouteData; return handler; Again this only works if you actually add a RouteData property to your handler explicitly as I did in my CallbackHandler implementation:/// <summary> /// Optionally store RouteData on this handler /// so we can access it internally /// </summary> public RouteData RouteData {get; set; } and the RouteHandler needs to set it when it creates the handler instance. Once you have the route data in your handler you can access Route Keys and Values and also the RouteHandler. Since my RouteHandler has a custom property for the MethodName to retrieve it from within the handler I can do something like this now to retrieve the MethodName (this example is actually not in the handler but target is an instance pass to the processor): // check for Route Data method name if (target is CallbackHandler) { var routeData = ((CallbackHandler)target).RouteData; if (routeData != null) methodToCall = ((CallbackHandlerRouteHandler)routeData.RouteHandler).MethodName; } When I need to access the dynamic values in the route ( symbol in StockQuote/{symbol}) I can retrieve it easily with the Values collection (RouteData.Values["symbol"]). In my CallbackHandler processing logic I’m basically looking for matching parameter names to Route parameters: // look for parameters in the routeif(routeData != null){    string parmString = routeData.Values[parameter.Name] as string;    adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType);} And with that we’ve come full circle. We’ve created a custom RouteHandler() that passes the RouteData to the handler it creates. We’ve registered our routes to use the RouteHandler, and we’ve utilized the route data in our handler. For completeness sake here’s the routine that executes a method call based on the parameters passed in and one of the options is to retrieve the inbound parameters off RouteData (as well as from POST data or QueryString parameters):internal object ExecuteMethod(string method, object target, string[] parameters, CallbackMethodParameterType paramType, ref CallbackMethodAttribute callbackMethodAttribute) { HttpRequest Request = HttpContext.Current.Request; object Result = null; // Stores parsed parameters (from string JSON or QUeryString Values) object[] adjustedParms = null; Type PageType = target.GetType(); MethodInfo MI = PageType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (MI == null) throw new InvalidOperationException("Invalid Server Method."); object[] methods = MI.GetCustomAttributes(typeof(CallbackMethodAttribute), false); if (methods.Length < 1) throw new InvalidOperationException("Server method is not accessible due to missing CallbackMethod attribute"); if (callbackMethodAttribute != null) callbackMethodAttribute = methods[0] as CallbackMethodAttribute; ParameterInfo[] parms = MI.GetParameters(); JSONSerializer serializer = new JSONSerializer(); RouteData routeData = null; if (target is CallbackHandler) routeData = ((CallbackHandler)target).RouteData; int parmCounter = 0; adjustedParms = new object[parms.Length]; foreach (ParameterInfo parameter in parms) { // Retrieve parameters out of QueryString or POST buffer if (parameters == null) { // look for parameters in the route if (routeData != null) { string parmString = routeData.Values[parameter.Name] as string; adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType); } // GET parameter are parsed as plain string values - no JSON encoding else if (HttpContext.Current.Request.HttpMethod == "GET") { // Look up the parameter by name string parmString = Request.QueryString[parameter.Name]; adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType); } // POST parameters are treated as methodParameters that are JSON encoded else if (paramType == CallbackMethodParameterType.Json) //string newVariable = methodParameters.GetValue(parmCounter) as string; adjustedParms[parmCounter] = serializer.Deserialize(Request.Params["parm" + (parmCounter + 1).ToString()], parameter.ParameterType); else adjustedParms[parmCounter] = SerializationUtils.DeSerializeObject( Request.Params["parm" + (parmCounter + 1).ToString()], parameter.ParameterType); } else if (paramType == CallbackMethodParameterType.Json) adjustedParms[parmCounter] = serializer.Deserialize(parameters[parmCounter], parameter.ParameterType); else adjustedParms[parmCounter] = SerializationUtils.DeSerializeObject(parameters[parmCounter], parameter.ParameterType); parmCounter++; } Result = MI.Invoke(target, adjustedParms); return Result; } The code basically uses Reflection to loop through all the parameters available on the method and tries to assign the parameters from RouteData, QueryString or POST variables. The parameters are converted into their appropriate types and then used to eventually make a Reflection based method call. What’s sweet is that the RouteData retrieval is just another option for dealing with the inbound data in this scenario and it adds exactly two lines of code plus the code to retrieve the MethodName I showed previously – a seriously low impact addition that adds a lot of extra value to this endpoint callback processing implementation. Debugging your Routes If you create a lot of routes it’s easy to run into Route conflicts where multiple routes have the same path and overlap with each other. This can be difficult to debug especially if you are using automatically generated routes like the routes created by CallbackHandlerRouteHandler.RegisterRoutes. Luckily there’s a tool that can help you out with this nicely. Phill Haack created a RouteDebugging tool you can download and add to your project. The easiest way to do this is to grab and add this to your project is to use NuGet (Add Library Package from your Project’s Reference Nodes):   which adds a RouteDebug assembly to your project. Once installed you can easily debug your routes with this simple line of code which needs to be installed at application startup:protected void Application_Start(object sender, EventArgs e) { CallbackHandlerRouteHandler.RegisterRoutes<StockService>(RouteTable.Routes); // Debug your routes RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes); } Any routed URL then displays something like this: The screen shows you your current route data and all the routes that are mapped along with a flag that displays which route was actually matched. This is useful – if you have any overlap of routes you will be able to see which routes are triggered – the first one in the sequence wins. This tool has saved my ass on a few occasions – and with NuGet now it’s easy to add it to your project in a few seconds and then remove it when you’re done. Routing Around Custom routing seems slightly complicated on first blush due to its disconnected components of RouteHandler, route registration and mapping of custom handlers. But once you understand the relationship between a RouteHandler, the RouteData and how to pass it to a handler, utilizing of Routing becomes a lot easier as you can easily pass context from the registration to the RouteHandler and through to the HttpHandler. The most important thing to understand when building custom routing solutions is to figure out how to map URLs in such a way that the handler can figure out all the pieces it needs to process the request. This can be via URL routing parameters and as I did in my example by passing additional context information as part of the RouteHandler instance that provides the proper execution context. In my case this ‘context’ was the method name, but it could be an actual static value like an enum identifying an operation or category in an application. Basically user supplied data comes in through the url and static application internal data can be passed via RouteHandler property values. Routing can make your application URLs easier to read by non-techie types regardless of whether you’re building Service type or REST applications, or full on Web interfaces. Routing in ASP.NET 4.0 makes it possible to create just about any extensionless URLs you can dream up and custom RouteHanmdler References Sample ProjectIncludes the sample CallbackHandler service discussed here along with compiled versionsof the Westwind.Web and Westwind.Utilities assemblies.  (requires .NET 4.0/VS 2010) West Wind Web Toolkit includes full implementation of CallbackHandler and the Routing Handler West Wind Web Toolkit Source CodeContains the full source code to the Westwind.Web and Westwind.Utilities assemblies usedin these samples. Includes the source described in the post.(Latest build in the Subversion Repository) CallbackHandler Source(Relevant code to this article tree in Westwind.Web assembly) JSONView FireFoxPluginA simple FireFox Plugin to easily view JSON data natively in FireFox.For IE you can use a registry hack to display JSON as raw text.© Rick Strahl, West Wind Technologies, 2005-2011Posted in ASP.NET  AJAX  HTTP  

    Read the article

  • ASP.NET MVC 3 Hosting :: How to Deploy Web Apps Using ASP.NET MVC 3, Razor and EF Code First - Part I

    - by mbridge
    First, you can download the source code from http://efmvc.codeplex.com. The following frameworks will be used for this step by step tutorial. public class Category {     public int CategoryId { get; set; }     [Required(ErrorMessage = "Name Required")]     [StringLength(25, ErrorMessage = "Must be less than 25 characters")]     public string Name { get; set;}     public string Description { get; set; }     public virtual ICollection<Expense> Expenses { get; set; } } Expense Class public class Expense {             public int ExpenseId { get; set; }            public string  Transaction { get; set; }     public DateTime Date { get; set; }     public double Amount { get; set; }     public int CategoryId { get; set; }     public virtual Category Category { get; set; } }    Define Domain Model Let’s create domain model for our simple web application Category Class We have two domain entities - Category and Expense. A single category contains a list of expense transactions and every expense transaction should have a Category. In this post, we will be focusing on CRUD operations for the entity Category and will be working on the Expense entity with a View Model object in the later post. And the source code for this application will be refactored over time. The above entities are very simple POCO (Plain Old CLR Object) classes and the entity Category is decorated with validation attributes in the System.ComponentModel.DataAnnotations namespace. Now we want to use these entities for defining model objects for the Entity Framework 4. Using the Code First approach of Entity Framework, we can first define the entities by simply writing POCO classes without any coupling with any API or database library. This approach lets you focus on domain model which will enable Domain-Driven Development for applications. EF code first support is currently enabled with a separate API that is runs on top of the Entity Framework 4. EF Code First is reached CTP 5 when I am writing this article. Creating Context Class for Entity Framework We have created our domain model and let’s create a class in order to working with Entity Framework Code First. For this, you have to download EF Code First CTP 5 and add reference to the assembly EntitFramework.dll. You can also use NuGet to download add reference to EEF Code First. public class MyFinanceContext : DbContext {     public MyFinanceContext() : base("MyFinance") { }     public DbSet<Category> Categories { get; set; }     public DbSet<Expense> Expenses { get; set; }         }   The above class MyFinanceContext is derived from DbContext that can connect your model classes to a database. The MyFinanceContext class is mapping our Category and Expense class into database tables Categories and Expenses using DbSet<TEntity> where TEntity is any POCO class. When we are running the application at first time, it will automatically create the database. EF code-first look for a connection string in web.config or app.config that has the same name as the dbcontext class. If it is not find any connection string with the convention, it will automatically create database in local SQL Express database by default and the name of the database will be same name as the dbcontext class. You can also define the name of database in constructor of the the dbcontext class. Unlike NHibernate, we don’t have to use any XML based mapping files or Fluent interface for mapping between our model and database. The model classes of Code First are working on the basis of conventions and we can also use a fluent API to refine our model. The convention for primary key is ‘Id’ or ‘<class name>Id’.  If primary key properties are detected with type ‘int’, ‘long’ or ‘short’, they will automatically registered as identity columns in the database by default. Primary key detection is not case sensitive. We can define our model classes with validation attributes in the System.ComponentModel.DataAnnotations namespace and it automatically enforces validation rules when a model object is updated or saved. Generic Repository for EF Code First We have created model classes and dbcontext class. Now we have to create generic repository pattern for data persistence with EF code first. If you don’t know about the repository pattern, checkout Martin Fowler’s article on Repository Let’s create a generic repository to working with DbContext and DbSet generics. public interface IRepository<T> where T : class     {         void Add(T entity);         void Delete(T entity);         T GetById(long Id);         IEnumerable<T> All();     } RepositoryBasse – Generic Repository class protected MyFinanceContext Database {     get { return database ?? (database = DatabaseFactory.Get()); } } public virtual void Add(T entity) {     dbset.Add(entity);            }        public virtual void Delete(T entity) {     dbset.Remove(entity); }   public virtual T GetById(long id) {     return dbset.Find(id); }   public virtual IEnumerable<T> All() {     return dbset.ToList(); } } DatabaseFactory class public class DatabaseFactory : Disposable, IDatabaseFactory {     private MyFinanceContext database;     public MyFinanceContext Get()     {         return database ?? (database = new MyFinanceContext());     }     protected override void DisposeCore()     {         if (database != null)             database.Dispose();     } } Unit of Work If you are new to Unit of Work pattern, checkout Fowler’s article on Unit of Work . According to Martin Fowler, the Unit of Work pattern "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." Let’s create a class for handling Unit of Work public interface IUnitOfWork {     void Commit(); } UniOfWork class public class UnitOfWork : IUnitOfWork {     private readonly IDatabaseFactory databaseFactory;     private MyFinanceContext dataContext;       public UnitOfWork(IDatabaseFactory databaseFactory)     {         this.databaseFactory = databaseFactory;     }       protected MyFinanceContext DataContext     {         get { return dataContext ?? (dataContext = databaseFactory.Get()); }     }       public void Commit()     {         DataContext.Commit();     } } The Commit method of the UnitOfWork will call the commit method of MyFinanceContext class and it will execute the SaveChanges method of DbContext class.   Repository class for Category In this post, we will be focusing on the persistence against Category entity and will working on other entities in later post. Let’s create a repository for handling CRUD operations for Category using derive from a generic Repository RepositoryBase<T>. public class CategoryRepository: RepositoryBase<Category>, ICategoryRepository     {     public CategoryRepository(IDatabaseFactory databaseFactory)         : base(databaseFactory)         {         }                } public interface ICategoryRepository : IRepository<Category> { } If we need additional methods than generic repository for the Category, we can define in the CategoryRepository. Dependency Injection using Unity 2.0 If you are new to Inversion of Control/ Dependency Injection or Unity, please have a look on my articles at http://weblogs.asp.net/shijuvarghese/archive/tags/IoC/default.aspx. I want to create a custom lifetime manager for Unity to store container in the current HttpContext. public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable {     public override object GetValue()     {         return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];     }     public override void RemoveValue()     {         HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);     }     public override void SetValue(object newValue)     {         HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;     }     public void Dispose()     {         RemoveValue();     } } Let’s create controller factory for Unity in the ASP.NET MVC 3 application.                 404, String.Format(                     "The controller for path '{0}' could not be found" +     "or it does not implement IController.",                 reqContext.HttpContext.Request.Path));       if (!typeof(IController).IsAssignableFrom(controllerType))         throw new ArgumentException(                 string.Format(                     "Type requested is not a controller: {0}",                     controllerType.Name),                     "controllerType");     try     {         controller= container.Resolve(controllerType) as IController;     }     catch (Exception ex)     {         throw new InvalidOperationException(String.Format(                                 "Error resolving controller {0}",                                 controllerType.Name), ex);     }     return controller; }   } Configure contract and concrete types in Unity Let’s configure our contract and concrete types in Unity for resolving our dependencies. private void ConfigureUnity() {     //Create UnityContainer               IUnityContainer container = new UnityContainer()                 .RegisterType<IDatabaseFactory, DatabaseFactory>(new HttpContextLifetimeManager<IDatabaseFactory>())     .RegisterType<IUnitOfWork, UnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>())     .RegisterType<ICategoryRepository, CategoryRepository>(new HttpContextLifetimeManager<ICategoryRepository>());                 //Set container for Controller Factory                ControllerBuilder.Current.SetControllerFactory(             new UnityControllerFactory(container)); } In the above ConfigureUnity method, we are registering our types onto Unity container with custom lifetime manager HttpContextLifetimeManager. Let’s call ConfigureUnity method in the Global.asax.cs for set controller factory for Unity and configuring the types with Unity. protected void Application_Start() {     AreaRegistration.RegisterAllAreas();     RegisterGlobalFilters(GlobalFilters.Filters);     RegisterRoutes(RouteTable.Routes);     ConfigureUnity(); } Developing web application using ASP.NET MVC 3 We have created our domain model for our web application and also have created repositories and configured dependencies with Unity container. Now we have to create controller classes and views for doing CRUD operations against the Category entity. Let’s create controller class for Category Category Controller public class CategoryController : Controller {     private readonly ICategoryRepository categoryRepository;     private readonly IUnitOfWork unitOfWork;           public CategoryController(ICategoryRepository categoryRepository, IUnitOfWork unitOfWork)     {         this.categoryRepository = categoryRepository;         this.unitOfWork = unitOfWork;     }       public ActionResult Index()     {         var categories = categoryRepository.All();         return View(categories);     }     [HttpGet]     public ActionResult Edit(int id)     {         var category = categoryRepository.GetById(id);         return View(category);     }       [HttpPost]     public ActionResult Edit(int id, FormCollection collection)     {         var category = categoryRepository.GetById(id);         if (TryUpdateModel(category))         {             unitOfWork.Commit();             return RedirectToAction("Index");         }         else return View(category);                 }       [HttpGet]     public ActionResult Create()     {         var category = new Category();         return View(category);     }           [HttpPost]     public ActionResult Create(Category category)     {         if (!ModelState.IsValid)         {             return View("Create", category);         }                     categoryRepository.Add(category);         unitOfWork.Commit();         return RedirectToAction("Index");     }       [HttpPost]     public ActionResult Delete(int  id)     {         var category = categoryRepository.GetById(id);         categoryRepository.Delete(category);         unitOfWork.Commit();         var categories = categoryRepository.All();         return PartialView("CategoryList", categories);       }        } Creating Views in Razor Now we are going to create views in Razor for our ASP.NET MVC 3 application.  Let’s create a partial view CategoryList.cshtml for listing category information and providing link for Edit and Delete operations. CategoryList.cshtml @using MyFinance.Helpers; @using MyFinance.Domain; @model IEnumerable<Category>      <table>         <tr>         <th>Actions</th>         <th>Name</th>          <th>Description</th>         </tr>     @foreach (var item in Model) {             <tr>             <td>                 @Html.ActionLink("Edit", "Edit",new { id = item.CategoryId })                 @Ajax.ActionLink("Delete", "Delete", new { id = item.CategoryId }, new AjaxOptions { Confirm = "Delete Expense?", HttpMethod = "Post", UpdateTargetId = "divCategoryList" })                           </td>             <td>                 @item.Name             </td>             <td>                 @item.Description             </td>         </tr>         }       </table>     <p>         @Html.ActionLink("Create New", "Create")     </p> The delete link is providing Ajax functionality using the Ajax.ActionLink. This will call an Ajax request for Delete action method in the CategoryCotroller class. In the Delete action method, it will return Partial View CategoryList after deleting the record. We are using CategoryList view for the Ajax functionality and also for Index view using for displaying list of category information. Let’s create Index view using partial view CategoryList  Index.chtml @model IEnumerable<MyFinance.Domain.Category> @{     ViewBag.Title = "Index"; }    <h2>Category List</h2>    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>    <div id="divCategoryList">               @Html.Partial("CategoryList", Model) </div> We can call the partial views using Html.Partial helper method. Now we are going to create View pages for insert and update functionality for the Category. Both view pages are sharing common user interface for entering the category information. So I want to create an EditorTemplate for the Category information. We have to create the EditorTemplate with the same name of entity object so that we can refer it on view pages using @Html.EditorFor(model => model) . So let’s create template with name Category. Category.cshtml @model MyFinance.Domain.Category <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Description) </div> <div class="editor-field"> @Html.EditorFor(model => model.Description) @Html.ValidationMessageFor(model => model.Description) </div> Let’s create view page for insert Category information @model MyFinance.Domain.Category   @{     ViewBag.Title = "Save"; }   <h2>Create</h2>   <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>   @using (Html.BeginForm()) {     @Html.ValidationSummary(true)     <fieldset>         <legend>Category</legend>                @Html.EditorFor(model => model)               <p>             <input type="submit" value="Create" />         </p>     </fieldset> }   <div>     @Html.ActionLink("Back to List", "Index") </div> ViewStart file In Razor views, we can add a file named _viewstart.cshtml in the views directory  and this will be shared among the all views with in the Views directory. The below code in the _viewstart.cshtml, sets the Layout page for every Views in the Views folder.     @{     Layout = "~/Views/Shared/_Layout.cshtml"; } Tomorrow, we will cotinue the second part of this article. :)

    Read the article

  • More SharePoint 2010 Expression Builders

    - by Ricardo Peres
    Introduction Following my last post, I decided to publish the whole set of expression builders that I use with SharePoint. For all who don’t know about expression builders, they allow us to employ a declarative approach, so that we don’t have to write code for “gluing” things together, like getting a value from the query string, the page’s underlying SPListItem or the current SPContext and assigning it to a control’s property. These expression builders are for some quite common scenarios, I use them quite often, and I hope you find them useful as well. SPContextExpression This expression builder allows us to specify an expression to be processed on the SPContext.Current property object. For example: 1: <asp:Literal runat="server" Text=“<%$ SPContextExpression:Site.RootWeb.Lists[0].Author.LoginName %>”/> It is identical to having the following code: 1: String authorName = SPContext.Current.Site.RootWeb.Lists[0].Author.LoginName; SPFarmProperty Returns a property stored on the farm level: 1: <asp:Literal runat="server" Text="<%$ SPFarmProperty:SomeProperty %>"/> Identical to: 1: Object someProperty = SPFarm.Local.Properties["SomeProperty"]; SPField Returns the value of a selected page’s list item field: 1: <asp:Literal runat="server" Text="<%$ SPField:Title %>"/> Does the same as: 1: String title = SPContext.Current.ListItem["Title"] as String; SPIsInAudience Checks if the current user belongs to an audience: 1: <asp:CheckBox runat="server" Checked="<%$ SPIsInAudience:SomeAudience %>"/> Equivalent to: 1: AudienceManager audienceManager = new AudienceManager(SPServiceContext.Current); 2: Audience audience = audienceManager.Audiences["SomeAudience"]; 3: Boolean isMember = audience.IsMember(SPContext.Current.Web.User.LoginName); SPIsInGroup Checks if the current user belongs to a group: 1: <asp:CheckBox runat="server" Checked="<%$ SPIsInGroup:SomeGroup %>"/> The equivalent C# code is: 1: SPContext.Current.Web.CurrentUser.Groups.OfType<SPGroup>().Any(x => String.Equals(x.Name, “SomeGroup”, StringComparison.OrdinalIgnoreCase)); SPProperty Returns the value of a user profile property for the current user: 1: <asp:Literal runat="server" Text="<%$ SPProperty:LastName %>"/> Where the same code in C# would be: 1: UserProfileManager upm = new UserProfileManager(SPServiceContext.Current); 2: UserProfile u = upm.GetUserProfile(false); 3: Object property = u["LastName"].Value; SPQueryString Returns a value passed on the query string: 1: <asp:GridView runat="server" PageIndex="<%$ SPQueryString:PageIndex %>" /> Is equivalent to (no SharePoint code this time): 1: Int32 pageIndex = Convert.ChangeType(typeof(Int32), HttpContext.Current.Request.QueryString["PageIndex"]); SPWebProperty Returns the value of a property stored at the site level: 1: <asp:Literal runat="server" Text="<%$ SPWebProperty:__ImagesListId %>"/> You can get the same result as: 1: String imagesListId = SPContext.Current.Web.AllProperties["__ImagesListId"] as String; Code OK, let’s move to the code. First, a common abstract base class, mainly for inheriting the conversion method: 1: public abstract class SPBaseExpressionBuilder : ExpressionBuilder 2: { 3: #region Protected static methods 4: protected static Object Convert(Object value, PropertyInfo propertyInfo) 5: { 6: if (value != null) 7: { 8: if (propertyInfo.PropertyType.IsAssignableFrom(value.GetType()) == false) 9: { 10: if (propertyInfo.PropertyType.IsEnum == true) 11: { 12: value = Enum.Parse(propertyInfo.PropertyType, value.ToString(), true); 13: } 14: else if (propertyInfo.PropertyType == typeof(String)) 15: { 16: value = value.ToString(); 17: } 18: else if ((typeof(IConvertible).IsAssignableFrom(propertyInfo.PropertyType) == true) && (typeof(IConvertible).IsAssignableFrom(value.GetType()) == true)) 19: { 20: value = System.Convert.ChangeType(value, propertyInfo.PropertyType); 21: } 22: } 23: } 24:  25: return (value); 26: } 27: #endregion 28:  29: #region Public override methods 30: public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 31: { 32: if (String.IsNullOrEmpty(entry.Expression) == true) 33: { 34: return (new CodePrimitiveExpression(String.Empty)); 35: } 36: else 37: { 38: return (new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(this.GetType()), "GetValue"), new CodePrimitiveExpression(entry.Expression.Trim()), new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("entry"), "PropertyInfo"))); 39: } 40: } 41: #endregion 42:  43: #region Public override properties 44: public override Boolean SupportsEvaluate 45: { 46: get 47: { 48: return (true); 49: } 50: } 51: #endregion 52: } Next, the code for each expression builder: 1: [ExpressionPrefix("SPContext")] 2: public class SPContextExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String expression, PropertyInfo propertyInfo) 6: { 7: SPContext context = SPContext.Current; 8: Object expressionValue = DataBinder.Eval(context, expression.Trim().Replace('\'', '"')); 9:  10: expressionValue = Convert(expressionValue, propertyInfo); 11:  12: return (expressionValue); 13: } 14:  15: #endregion 16:  17: #region Public override methods 18: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 19: { 20: return (GetValue(entry.Expression, entry.PropertyInfo)); 21: } 22: #endregion 23: }   1: [ExpressionPrefix("SPFarmProperty")] 2: public class SPFarmPropertyExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String propertyName, PropertyInfo propertyInfo) 6: { 7: Object propertyValue = SPFarm.Local.Properties[propertyName]; 8:  9: propertyValue = Convert(propertyValue, propertyInfo); 10:  11: return (propertyValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: }   1: [ExpressionPrefix("SPField")] 2: public class SPFieldExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String fieldName, PropertyInfo propertyInfo) 6: { 7: Object fieldValue = SPContext.Current.ListItem[fieldName]; 8:  9: fieldValue = Convert(fieldValue, propertyInfo); 10:  11: return (fieldValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: }   1: [ExpressionPrefix("SPIsInAudience")] 2: public class SPIsInAudienceExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String audienceName, PropertyInfo info) 6: { 7: Debugger.Break(); 8: audienceName = audienceName.Trim(); 9:  10: if ((audienceName.StartsWith("'") == true) && (audienceName.EndsWith("'") == true)) 11: { 12: audienceName = audienceName.Substring(1, audienceName.Length - 2); 13: } 14:  15: AudienceManager manager = new AudienceManager(); 16: Object value = manager.IsMemberOfAudience(SPControl.GetContextWeb(HttpContext.Current).CurrentUser.LoginName, audienceName); 17:  18: if (info.PropertyType == typeof(String)) 19: { 20: value = value.ToString(); 21: } 22:  23: return(value); 24: } 25:  26: #endregion 27:  28: #region Public override methods 29: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 30: { 31: return (GetValue(entry.Expression, entry.PropertyInfo)); 32: } 33: #endregion 34: }   1: [ExpressionPrefix("SPIsInGroup")] 2: public class SPIsInGroupExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String groupName, PropertyInfo info) 6: { 7: groupName = groupName.Trim(); 8:  9: if ((groupName.StartsWith("'") == true) && (groupName.EndsWith("'") == true)) 10: { 11: groupName = groupName.Substring(1, groupName.Length - 2); 12: } 13:  14: Object value = SPControl.GetContextWeb(HttpContext.Current).CurrentUser.Groups.OfType<SPGroup>().Any(x => String.Equals(x.Name, groupName, StringComparison.OrdinalIgnoreCase)); 15:  16: if (info.PropertyType == typeof(String)) 17: { 18: value = value.ToString(); 19: } 20:  21: return(value); 22: } 23:  24: #endregion 25:  26: #region Public override methods 27: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 28: { 29: return (GetValue(entry.Expression, entry.PropertyInfo)); 30: } 31: #endregion 32: }   1: [ExpressionPrefix("SPProperty")] 2: public class SPPropertyExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String propertyName, System.Reflection.PropertyInfo propertyInfo) 6: { 7: SPServiceContext serviceContext = SPServiceContext.GetContext(HttpContext.Current); 8: UserProfileManager upm = new UserProfileManager(serviceContext); 9: UserProfile up = upm.GetUserProfile(false); 10: Object propertyValue = (up[propertyName] != null) ? up[propertyName].Value : null; 11:  12: propertyValue = Convert(propertyValue, propertyInfo); 13:  14: return (propertyValue); 15: } 16:  17: #endregion 18:  19: #region Public override methods 20: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 21: { 22: return (GetValue(entry.Expression, entry.PropertyInfo)); 23: } 24: #endregion 25: }   1: [ExpressionPrefix("SPQueryString")] 2: public class SPQueryStringExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String parameterName, PropertyInfo propertyInfo) 6: { 7: Object parameterValue = HttpContext.Current.Request.QueryString[parameterName]; 8:  9: parameterValue = Convert(parameterValue, propertyInfo); 10:  11: return (parameterValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: }   1: [ExpressionPrefix("SPWebProperty")] 2: public class SPWebPropertyExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String propertyName, PropertyInfo propertyInfo) 6: { 7: Object propertyValue = SPContext.Current.Web.AllProperties[propertyName]; 8:  9: propertyValue = Convert(propertyValue, propertyInfo); 10:  11: return (propertyValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: } Registration You probably know how to register them, but here it goes again: add this following snippet to your Web.config file, inside the configuration/system.web/compilation/expressionBuilders section: 1: <add expressionPrefix="SPContext" type="MyNamespace.SPContextExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 2: <add expressionPrefix="SPFarmProperty" type="MyNamespace.SPFarmPropertyExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 3: <add expressionPrefix="SPField" type="MyNamespace.SPFieldExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 4: <add expressionPrefix="SPIsInAudience" type="MyNamespace.SPIsInAudienceExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 5: <add expressionPrefix="SPIsInGroup" type="MyNamespace.SPIsInGroupExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 6: <add expressionPrefix="SPProperty" type="MyNamespace.SPPropertyExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 7: <add expressionPrefix="SPQueryString" type="MyNamespace.SPQueryStringExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 8: <add expressionPrefix="SPWebProperty" type="MyNamespace.SPWebPropertyExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> I’ll leave it up to you to figure out the best way to deploy this to your server!

    Read the article

  • MVC Portable Area Modules *Without* MasterPages

    - by Steve Michelotti
    Portable Areas from MvcContrib provide a great way to build modular and composite applications on top of MVC. In short, portable areas provide a way to distribute MVC binary components as simple .NET assemblies where the aspx/ascx files are actually compiled into the assembly as embedded resources. I’ve blogged about Portable Areas in the past including this post here which talks about embedding resources and you can read more of an intro to Portable Areas here. As great as Portable Areas are, the question that seems to come up the most is: what about MasterPages? MasterPages seems to be the one thing that doesn’t work elegantly with portable areas because you specify the MasterPage in the @Page directive and it won’t use the same mechanism of the view engine so you can’t just embed them as resources. This means that you end up referencing a MasterPage that exists in the host application but not in your portable area. If you name the ContentPlaceHolderId’s correctly, it will work – but it all seems a little fragile. Ultimately, what I want is to be able to build a portable area as a module which has no knowledge of the host application. I want to be able to invoke the module by a full route on the user’s browser and it gets invoked and “automatically appears” inside the application’s visual chrome just like a MasterPage. So how could we accomplish this with portable areas? With this question in mind, I looked around at what other people are doing to address similar problems. Specifically, I immediately looked at how the Orchard team is handling this and I found it very compelling. Basically Orchard has its own custom layout/theme framework (utilizing a custom view engine) that allows you to build your module without any regard to the host. You simply decorate your controller with the [Themed] attribute and it will render with the outer chrome around it: 1: [Themed] 2: public class HomeController : Controller Here is the slide from the Orchard talk at this year MIX conference which shows how it conceptually works:   It’s pretty cool stuff.  So I figure, it must not be too difficult to incorporate this into the portable areas view engine as an optional piece of functionality. In fact, I’ll even simplify it a little – rather than have 1) Document.aspx, 2) Layout.ascx, and 3) <view>.ascx (as shown in the picture above); I’ll just have the outer page be “Chrome.aspx” and then the specific view in question. The Chrome.aspx not only takes the place of the MasterPage, but now since we’re no longer constrained by the MasterPage infrastructure, we have the choice of the Chrome.aspx living in the host or inside the portable areas as another embedded resource! Disclaimer: credit where credit is due – much of the code from this post is me re-purposing the Orchard code to suit my needs. To avoid confusion with Orchard, I’m going to refer to my implementation (which will be based on theirs) as a Chrome rather than a Theme. The first step I’ll take is to create a ChromedAttribute which adds a flag to the current HttpContext to indicate that the controller designated Chromed like this: 1: [Chromed] 2: public class HomeController : Controller The attribute itself is an MVC ActionFilter attribute: 1: public class ChromedAttribute : ActionFilterAttribute 2: { 3: public override void OnActionExecuting(ActionExecutingContext filterContext) 4: { 5: var chromedAttribute = GetChromedAttribute(filterContext.ActionDescriptor); 6: if (chromedAttribute != null) 7: { 8: filterContext.HttpContext.Items[typeof(ChromedAttribute)] = null; 9: } 10: } 11:   12: public static bool IsApplied(RequestContext context) 13: { 14: return context.HttpContext.Items.Contains(typeof(ChromedAttribute)); 15: } 16:   17: private static ChromedAttribute GetChromedAttribute(ActionDescriptor descriptor) 18: { 19: return descriptor.GetCustomAttributes(typeof(ChromedAttribute), true) 20: .Concat(descriptor.ControllerDescriptor.GetCustomAttributes(typeof(ChromedAttribute), true)) 21: .OfType<ChromedAttribute>() 22: .FirstOrDefault(); 23: } 24: } With that in place, we only have to override the FindView() method of the custom view engine with these 6 lines of code: 1: public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) 2: { 3: if (ChromedAttribute.IsApplied(controllerContext.RequestContext)) 4: { 5: var bodyView = ViewEngines.Engines.FindPartialView(controllerContext, viewName); 6: var documentView = ViewEngines.Engines.FindPartialView(controllerContext, "Chrome"); 7: var chromeView = new ChromeView(bodyView, documentView); 8: return new ViewEngineResult(chromeView, this); 9: } 10:   11: // Just execute normally without applying Chromed View Engine 12: return base.FindView(controllerContext, viewName, masterName, useCache); 13: } If the view engine finds the [Chromed] attribute, it will invoke it’s own process – otherwise, it’ll just defer to the normal web forms view engine (with masterpages). The ChromeView’s primary job is to independently set the BodyContent on the view context so that it can be rendered at the appropriate place: 1: public class ChromeView : IView 2: { 3: private ViewEngineResult bodyView; 4: private ViewEngineResult documentView; 5:   6: public ChromeView(ViewEngineResult bodyView, ViewEngineResult documentView) 7: { 8: this.bodyView = bodyView; 9: this.documentView = documentView; 10: } 11:   12: public void Render(ViewContext viewContext, System.IO.TextWriter writer) 13: { 14: ChromeViewContext chromeViewContext = ChromeViewContext.From(viewContext); 15:   16: // First render the Body view to the BodyContent 17: using (var bodyViewWriter = new StringWriter()) 18: { 19: var bodyViewContext = new ViewContext(viewContext, bodyView.View, viewContext.ViewData, viewContext.TempData, bodyViewWriter); 20: this.bodyView.View.Render(bodyViewContext, bodyViewWriter); 21: chromeViewContext.BodyContent = bodyViewWriter.ToString(); 22: } 23: // Now render the Document view 24: this.documentView.View.Render(viewContext, writer); 25: } 26: } The ChromeViewContext (code excluded here) mainly just has a string property for the “BodyContent” – but it also makes sure to put itself in the HttpContext so it’s available. Finally, we created a little extension method so the module’s view can be rendered in the appropriate place: 1: public static void RenderBody(this HtmlHelper htmlHelper) 2: { 3: ChromeViewContext chromeViewContext = ChromeViewContext.From(htmlHelper.ViewContext); 4: htmlHelper.ViewContext.Writer.Write(chromeViewContext.BodyContent); 5: } At this point, the other thing left is to decide how we want to implement the Chrome.aspx page. One approach is the copy/paste the HTML from the typical Site.Master and change the main content placeholder to use the HTML helper above – this way, there are no MasterPages anywhere. Alternatively, we could even have Chrome.aspx utilize the MasterPage if we wanted (e.g., in the case where some pages are Chromed and some pages want to use traditional MasterPage): 1: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> 2: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 3: <% Html.RenderBody(); %> 4: </asp:Content> At this point, it’s all academic. I can create a controller like this: 1: [Chromed] 2: public class WidgetController : Controller 3: { 4: public ActionResult Index() 5: { 6: return View(); 7: } 8: } Then I’ll just create Index.ascx (a partial view) and put in the text “Inside my widget”. Now when I run the app, I can request the full route (notice the controller name of “widget” in the address bar below) and the HTML from my Index.ascx will just appear where it is supposed to.   This means no more warnings for missing MasterPages and no more need for your module to have knowledge of the host’s MasterPage placeholders. You have the option of using the Chrome.aspx in the host or providing your own while embedding it as an embedded resource itself. I’m curious to know what people think of this approach. The code above was done with my own local copy of MvcContrib so it’s not currently something you can download. At this point, these are just my initial thoughts – just incorporating some ideas for Orchard into non-Orchard apps to enable building modular/composite apps more easily. Additionally, on the flip side, I still believe that Portable Areas have potential as the module packaging story for Orchard itself.   What do you think?

    Read the article

  • ASp.Net Mvc 1.0 Dynamic Images Returned from Controller taking 154 seconds+ to display in IE8, firef

    - by julian guppy
    I have a curious problem with IE, IIS 6.0 dynamic PNG files and I am baffled as to how to fix.. Snippet from Helper (this returns the URL to the view for requesting the images from my Controller. string url = LinkBuilder.BuildUrlFromExpression(helper.ViewContext.RequestContext, helper.RouteCollection, c = c.FixHeight(ir.Filename, ir.AltText, "FFFFFF")); url = url.Replace("&", "&"); sb.Append(string.Format("<removed id=\"TheImage\" src=\"{0}\" alt=\"\" /", url)+Environment.NewLine); This produces a piece of html as follows:- img id="TheImage" src="/ImgText/FixHeight?sFile=Images%2FUser%2FJulianGuppy%2FMediums%2Fconservatory.jpg&backgroundColour=FFFFFF" alt="" / brackets missing because i cant post an image... even though I dont want to post an image I jsut want to post the markup... sigh Snippet from Controller ImgTextController /// <summary> /// This function fixes the height of the image /// </summary> /// <param name="sFile"></param> /// <param name="alternateText"></param> /// <param name="backgroundColour"></param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Get)] public ActionResult FixHeight(string sFile, string alternateText, string backgroundColour) { #region File if (string.IsNullOrEmpty(sFile)) { return new ImgTextResult(); } // MVC specific change to prepend the new directory if (sFile.IndexOf("Content") == -1) { sFile = "~/Content/" + sFile; } // open the file System.Drawing.Image img; try { img = System.Drawing.Image.FromFile(Server.MapPath(sFile)); } catch { img = null; } // did we fail? if (img == null) { return new ImgTextResult(); } #endregion File #region Width // Sort out the width from the image passed to me Int32 nWidth = img.Width; #endregion Width #region Height Int32 nHeight = img.Height; #endregion Height // What is the ideal height given a width of 2100 this should be 1400. var nIdealHeight = (int)(nWidth / 1.40920096852); // So is the actual height of the image already greater than the ideal height? Int32 nSplit; if (nIdealHeight < nHeight) { // Yes, do nothing, well i need to return the iamge... nSplit = 0; } else { // rob wants to not show the white at the top or bottom, so if we were to crop the image how would be do it // 1. Calculate what the width should be If we dont adjust the heigt var newIdealWidth = (int)(nHeight * 1.40920096852); // 2. This newIdealWidth should be smaller than the existing width... so work out the split on that Int32 newSplit = (nWidth - newIdealWidth) / 2; // 3. Now recrop the image using 0-nHeight as the height (i.e. full height) // but crop the sides so that its the correct aspect ration var newRect = new Rectangle(newSplit, 0, newIdealWidth, nHeight); img = CropImage(img, newRect); nHeight = img.Height; nWidth = img.Width; nSplit = 0; } // No, so I want to place this image on a larger canvas and we do this by Creating a new image to be the size that we want System.Drawing.Image canvas = new Bitmap(nWidth, nIdealHeight, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(canvas); #region Color // Whilst we can set the background colour we shall default to white if (string.IsNullOrEmpty(backgroundColour)) { backgroundColour = "FFFFFF"; } Color bc = ColorTranslator.FromHtml("#" + backgroundColour); #endregion Color // Filling the background (which gives us our broder) Brush backgroundBrush = new SolidBrush(bc); g.FillRectangle(backgroundBrush, -1, -1, nWidth + 1, nIdealHeight + 1); // draw the image at the position var rect = new Rectangle(0, nSplit, nWidth, nHeight); g.DrawImage(img, rect); return new ImgTextResult { Image = canvas, ImageFormat = ImageFormat.Png }; } My ImgTextResult is a class that returns an Action result for me but embedding the image from a memory stream into the response.outputstream. snippet from my ImageResults /// <summary> /// Execute the result /// </summary> /// <param name="context"></param> public override void ExecuteResult(ControllerContext context) { // output context.HttpContext.Response.Clear(); context.HttpContext.Response.ContentType = "image/png"; try { var memStream = new MemoryStream(); Image.Save(memStream, ImageFormat.Png); context.HttpContext.Response.BinaryWrite(memStream.ToArray()); context.HttpContext.Response.Flush(); context.HttpContext.Response.Close(); memStream.Dispose(); Image.Dispose(); } catch (Exception ex) { string a = ex.Message; } } Now all of this works locally and lovely, and indeed all of this works on my production server BUT Only for Firefox, Safari, Chrome (and other browsers) IE has a fit and decides that it either wont display the image or it does display the image after approx 154seconds of waiting..... I have made sure my HTML is XHTML compliant, I have made sure I am getting no Routing errors or crashes in my event log on the server.... Now obviously I have been a muppet and have done something wrong... but what I cant fathom is why in development all works fine, and in production all non IE browsers also work fine, but IE 8 using IIS 6.0 production server is having some kind of problem in returning this PNG and I dont have an error to trace... so what I am looking for is guidance as to how I can debug this problem.

    Read the article

  • Autofac Unit Testing using RegisterControllers()

    - by Kane
    I am having problems using Autofac 2.1.13 and writing my unit tests for my ASP.NET MV2 application. I can't seem to resolve controllers when using the RegisterControllers method. I have tried using the Resolve<() and ControllerBuilder.Current.GetControllerFactory().CreateController() methods but to no avail. I am sure that I've missed something simple here so can anyone assist? This was my first attempt at resolving the HomeController - but does not work. ContainerBuilder builder = new ContainerBuilder(); builder.RegisterControllers(typeof(HomeController).Assembly); IContainer container = builder.Build(); // Throws a Throws a A first chance exception of type 'Autofac.Core.Registration.ComponentNotRegisteredException' occurred in Autofac.dll var homeController = container.Resolve<HomeController>(); Similarly this does not work either. ContainerBuilder builder = new ContainerBuilder(); builder.RegisterControllers(typeof(HomeController).Assembly); IContainer container = builder.Build(); var containerProvider = new ContainerProvider(container); ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(containerProvider)); var request = new Mock<HttpRequestBase>(MockBehavior.Loose); request.Setup(r => r.Path).Returns("Path"); var httpContext = new Mock<HttpContextBase>(MockBehavior.Loose); httpContext.SetupGet(c => c.Request).Returns(request.Object); ControllerBuilder.Current.GetControllerFactory().CreateController(new RequestContext(httpContext.Object, new RouteData()), "home"); Any assistance would be greatly appreciated. I should note if I register my controllers without using the RegisterControllers() method my unit tests work. My question would seem to be limited to specifically using the RegisterControllers() method.

    Read the article

  • Stack Overflow Problem in DotNetNuke

    - by Vivek
    Hi, I'm getting this error message when I try to access my website. Can someone please tell me what is going on? Thanks. V Server Error in '/' Application. Attempted to read or write protected memory. This is often an indication that other memory is corrupt. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.] AspDotNetStorefrontExcelWrapper.ExcelToXml.SetLicense() +0 AspDotNetStorefrontCommon.AppLogic.ApplicationStart() +150 AspDotNetStorefrontDNNComponents.AppStart..cctor() +103 [TypeInitializationException: The type initializer for 'AspDotNetStorefrontDNNComponents.AppStart' threw an exception.] AspDotNetStorefrontDNNComponents.AppStart.Execute() +0 AspDotNetStorefront.HttpModules.InitializerModule.System.Web.IHttpModule.Init(HttpApplication context) +42 System.Web.HttpApplication.InitModulesCommon() +65 System.Web.HttpApplication.InitModules() +43 System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +729 System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +298 System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +107 System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +289 Version Information: Microsoft .NET Framework Version:2.0.50727.3082; ASP.NET Version:2.0.50727.3082

    Read the article

  • Struggling running ASP MVC2 on IIS6.0

    - by Luke
    Hi I could use a little Help using MVC2 on an IIS6.0 Its an MVC2 RC2 [.NET 3.5]. I followed the famous Haacked Tutorial, created a virtual folder, created a Default.aspx Website for my Project, put everything to my virtual folder. The routing is modified, using wildcard mapping [anyway its not running without, too], according to the Tutorial. I also checked, that all Webservices are running [asp.net 2 / asp.net 4 / active server pages]. The routing is working fine on my development machine, even checked it using Haacks routing debugger ... [http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx] Seems fine so far, but I get only 404 - not found errors. Is there something I might be missing ? Global.asax.cs public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", "{controller}.mvc/{action}/{id}", new { action = "Index", id = "" } ); routes.MapRoute( "Root", "", new { controller = "Home", action = "Index", id = "" } ); } Default.aspx.cs public void Page_Load(object sender, System.EventArgs e) { // Change the current path so that the Routing handler can correctly interpret // the request, then restore the original path so that the OutputCache module // can correctly process the response (if caching is enabled). string originalPath = Request.Path; HttpContext.Current.RewritePath(Request.ApplicationPath, false); IHttpHandler httpHandler = new MvcHttpHandler(); httpHandler.ProcessRequest(HttpContext.Current); HttpContext.Current.RewritePath(originalPath, false); }

    Read the article

  • Why am I getting: InvalidOperationException: Failed to map the path '/app42/App_Code/'.

    - by serialhobbyist
    I've been working on a little Silverlight utility which calls a Silverlight web service. It works from my dev machine (XPsp2). I've tried publishing it to a 2008 R2 IIS 7.5 server and it doesn't work when trying to contact the web service. So I've tried using the WcfTestClient to connect to the web service. That gave an error. So I turned off CustomErrors and used IE and I get the following. Any idea why? There's no App_Code folder in the app. Failed to map the path '/app42/App_Code/'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: Failed to map the path '/app42/App_Code/'. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [InvalidOperationException: Failed to map the path '/app42/App_Code/'.] System.Web.Configuration.ProcessHostConfigUtils.MapPathActual(String siteName, VirtualPath path) +320 System.Web.Configuration.ProcessHostServerConfig.System.Web.Configuration.IServerConfig.MapPath(IApplicationHost appHost, VirtualPath path) +34 System.Web.Hosting.MapPathBasedVirtualPathEnumerator..ctor(VirtualPath virtualPath, RequestedEntryType requestedEntryType) +169 System.Web.Hosting.MapPathBasedVirtualPathCollection.System.Collections.IEnumerable.GetEnumerator() +43 System.Web.Compilation.CodeDirectoryCompiler.ProcessDirectoryRecursive(VirtualDirectory vdir, Boolean topLevel) +147 System.Web.Compilation.CodeDirectoryCompiler.GetCodeDirectoryAssembly(VirtualPath virtualDir, CodeDirectoryType dirType, String assemblyName, StringSet excludedSubdirectories, Boolean isDirectoryAllowed) +11196502 System.Web.Compilation.BuildManager.CompileCodeDirectory(VirtualPath virtualDir, CodeDirectoryType dirType, String assemblyName, StringSet excludedSubdirectories) +185 System.Web.Compilation.BuildManager.CompileCodeDirectories() +654 System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +658 [HttpException (0x80004005): Failed to map the path '/app42/App_Code/'.] System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +76 System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +1012 System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters) +1025 [HttpException (0x80004005): Failed to map the path '/app42/App_Code/'.] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11301302 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +88 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4338644 Version Information: Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927

    Read the article

  • invalid viewstate error - OnPreRender

    - by dan
    I'm getting 100+ errors per day on my website with System.Web.HttpException: Invalid viewstate. The website is asp.net 3.5 running on iis6 , not running in a web-garden/web-farm , single server. Here are a few sample errors. Machine: ML Framework Version: 2.0.50727.3603 Assembly Version: 6.5.3664.33889 Source: http://www.domain.com/WebResource.axd?d=z5VmXXoSLLpQHoPictureAlert Exception: System.Web.HttpException: Invalid viewstate. at System.Web.UI.Page.DecryptStringWithIV(String s, IVType ivType) at System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) Machine: MLFramework Version: 2.0.50727.3603 Assembly Version: 6.5.3664.33889 Source: http://www.mydomain.com/ScriptResource.axd?d=SE0Ej7OlEAx91j2Cjv_6KkRPplqT-5wB4M7CZPdGdGn3LahLwqlRPApUcdxBsbFXYHZ91Q76FHAHWgHs8SmOC4zemr7 siym0QY0rF3XtJTu%3C/a%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3Ca%20id= Exception: System.Web.HttpException: Invalid viewstate. at System.Web.UI.Page.DecryptStringWithIV(String s, IVType ivType) at System.Web.UI.Page.DecryptString(String s) at System.Web.Handlers.ScriptResourceHandler.DecryptParameter(NameValueCollection queryString) at System.Web.Handlers.ScriptResourceHandler.ProcessRequestInternal(HttpResponse response, NameValueCollection queryString, VirtualFileReader fileReader) at System.Web.Handlers.ScriptResourceHandler.ProcessRequest(HttpContext context) at System.Web.Handlers.ScriptResourceHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) i already tried wraping all inline javascript with //<![CDATA[ //]]> i already set enableViewStateMac to false. From looking at all the errors guessing out of the "d" paramter it seems to focus on a single usercontrol on my website. in this control i change the visiblity of div's + text in the usercontrol OnPreRender function. protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); PreparePage(); } Can the errors be related to the usercontrol behavioral? thanks!

    Read the article

  • Why does IIS respond to a secure(SSL) page request with a 302 to its non-secure version?

    - by ISawrub
    I have SSL installed at the root of a server. I have a page whose code behind code is supposed to redirect after certain validation to a secure page. Here's the redirect code: switch (PageBase2.GetParameterValue("Environment")) //Retrieves App Setting named Environment from web.config { case "Server": strURL = @"https://" + HttpContext.Current.Request.Url.Authority + "/checkout/payment.aspx"; break; case "Local": strURL = @"http://" + HttpContext.Current.Request.Url.Authority + "/checkout/payment.aspx"; break; default: strURL = @"https://" + HttpContext.Current.Request.Url.Authority + "/checkout/payment.aspx"; break; } Response.Redirect(strURL, false); But the page that's been served by IIS is non-secure. I looked at the firebug console and it appears that the client does make a get request to https://server/checkout/payment.aspx but IIS responds with a 302 to http://server/checkout/payment.aspx Any clues, as to what could be causing it. I've even tried forcing SSL for the page, but it doesn't work I get 403.4 error. (SSL is required to view this resource.) And if i remove the redirection logic and code the payment page to redirect to its SSL version when the connection is not secure using Request.IsSecureConnection, i end up with an endless redirect loop, simply because IIS still won't serve the secure version without a 302. Any ideas?

    Read the article

  • Duplicate method 'ProcessRequest' in ASPX

    - by Mauricio Scheffer
    I'm trying to code ASP.NET MVC views (WebForms view engine) in F#. I can already write regular ASP.NET WebForms ASPX and it works ok, e.g. <%@ Page Language="F#" %> <% for i in 1..2 do %> <%=sprintf "%d" i %> so I assume I have everything in my web.config correctly set up. However, when I make the page inherit from ViewPage: <%@ Page Language="F#" Inherits="System.Web.Mvc.ViewPage" %> I get this error: Compiler Error Message: FS0442: Duplicate method. The abstract method 'ProcessRequest' has the same name and signature as an abstract method in an inherited type. The problem seems to be this piece of code generated by the F# CodeDom provider: [<System.Diagnostics.DebuggerNonUserCodeAttribute>] abstract ProcessRequest : System.Web.HttpContext -> unit [<System.Diagnostics.DebuggerNonUserCodeAttribute>] default this.ProcessRequest (context:System.Web.HttpContext) = let mutable context = context base.ProcessRequest(context) |> ignore when I change the Page directive to use C# instead, the generated code is: [System.Diagnostics.DebuggerNonUserCodeAttribute()] public new virtual void ProcessRequest(System.Web.HttpContext context) { base.ProcessRequest(context); } which of course works fine and AFAIK is not semantically the same as the generated F# code. I'm using .NET 4.0.30319.1 (RTM) and MVC 2 RTM

    Read the article

  • Can't log in a user in MVC!

    - by devlife
    I have been scratching my head on this for a while now but still can't get it. I'm trying to simply log in a user in an MVC2 application. I have tried everything that I know to try but still can't figure out what I'm doing wrong. Here are a few things that I have tried: FormsAuthentication.SetAuthCookie( emailAddress, rememberMe ); var cookie = FormsAuthentication.GetAuthCookie( emailAddress, rememberMe ); HttpContext.Response.Cookies.Add( cookie ); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( emailAddress, rememberMe, 15 ); FormsIdentity identity = new FormsIdentity( ticket ); GenericPrincipal principal = new GenericPrincipal(identity, new string[0]); HttpContext.User = principal; I'm not sure if any of this is the right thing to do (as it's not working). After setting HttpContext.User = principal then Request.IsAuthenticated == true. However, in Global.asax I have this: HttpCookie authenCookie = Context.Request.Cookies.Get( FormsAuthentication.FormsCookieName ); The only cookie that ever is available is the aspnet session cookie. Any ideas at all would be much appreciated!

    Read the article

  • HttpModule.Init - safely add HttpApplication.BeginRequest handler in IIS7 integrated mode

    - by Paul Smith
    My question is similar but not identical to: http://stackoverflow.com/questions/1123741/why-cant-my-host-softsyshosting-com-support-beginrequest-and-endrequest-event (I've also read the mvolo blog referenced therein) The goal is to successfully hook HttpApplication.BeginRequest in the IHttpModule.Init event (or anywhere internal to the module), using a normal HttpModule integrated via the system.webServer config, i.e. one that doesn't: invade Global.asax or override the HttpApplication (the module is intended to be self-contained & reusable, so e.g. I have a config like this): <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <remove name="TheHttpModule" /> <add name="TheHttpModule" type="Company.HttpModules.TheHttpModule" preCondition="managedHandler" /> So far, any strategy I've tried to attach a listener to HttpApplication.BeginRequest results in one of two things, symptom 1 is that BeginRequest never fires, or symptom 2 is that the following exception gets thrown on all managed requests, and I cannot catch & handle it from user code: Stack Trace: [NullReferenceException: Object reference not set to an instance of an object.] System.Web.PipelineModuleStepContainer.GetEventCount(RequestNotification notification, Boolean isPostEvent) +30 System.Web.PipelineStepManager.ResumeSteps(Exception error) +1112 System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb) +113 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +616 Commenting out app.BeginRequest += new EventHandler(this.OnBeginRequest) in Init stops the exception of course. Init does not reference the Context or Request objects at all. I have tried: Removed all references to HttpContext.Current anywhere in the project (still symptom 1) Tested removing all code from the body of my OnBeginRequest method, to ensure the problem wasn't internal to the method (= exception) Sniffing the stack trace and only calling app.BeginRequest+=... when if the stack isn't started by InitializeApplication (= BeginRequest not firing) Only calling app.BeginRequest+= on the second pass through Init (= BeginRequest not firing) Anyone know of a good approach? Is there some indirect strategy for hooking Application_Start within the module (seems unlikely)? Another event which a) one can hook from a module's constructor or Init method, and b) which is subsequently a safe place to attach BeginRequest event handlers? Thanks much

    Read the article

  • Problem with ASP.NET Authentication

    - by Niels Bosma
    I'm having problem with our login procedure. Some customers complain that they can't login. I can see in our logs that their login is successful and that they are redirected from the login page to the member area. But there somehow the login isn't detected and they are bounced back to the login page. I've asked customers to check if cookies are supported (http://www.html-kit.com/tools/cookietester/) but problem remains even if this test returns true. This is how I've implemented the login procedure (simplyfied): protected void Login(string email, string password) { FormsAuthentication.SignOut(); Guid clientId = /* Validate login by checking email and password, if fails display error otherwise get client id */ FormsAuthentication.SetAuthCookie(clientId.ToString(), true); HttpContext.Current.Response.Redirect("~/Members.aspx"); } On the member page I check for authentication by in Page_Load function: public static void IsAuthenticated() { if (!HttpContext.Current.User.Identity.IsAuthenticated) { HttpContext.Current.Response.Redirect("~/Login.aspx", true); } } Maybe I'm using FormsAuthentication completely wrong? I've asked this before but still haven't been able to figure this out, I'd appreciate any help.

    Read the article

  • System.ArgumentException: Invalid hex character at DecryptAssemblyResource

    - by Radu094
    My webapp is trowing these exceptions intermitently ever since we migrated to Mono + Apache: The error sounds more like a problem reading/processing some assembly, so I was wondering if I should be worried that there might be a problem with the hard-drive? System.ArgumentException: Invalid hex character at System.Web.Configuration.MachineKeySectionUtils.ToHexValue (Char c, Boolean high) [0x00000] in <filename unknown>:0 at System.Web.Configuration.MachineKeySectionUtils.GetBytes (System.String key, Int32 len) [0x00000] in <filename unknown>:0 at System.Web.Handlers.ScriptResourceHandler.GetBytes (System.String val) [0x00000] in <filename unknown>:0 at System.Web.Handlers.ScriptResourceHandler.DecryptAssemblyResource (System.String val, System.String& asmName, System.String& resName) [0x00000] in <filename unknown>:0 at System.Web.Handlers.ScriptResourceHandler.ProcessRequest (System.Web.HttpContext context) [0x00000] in <filename unknown>:0 at System.Web.Handlers.ScriptResourceHandler.System.Web.IHttpHandler.ProcessRequest (System.Web.HttpContext context) [0x00000] in <filename unknown>:0 at System.Web.HttpApplication+<Pipeline>c__Iterator2.MoveNext () [0x00000] in <filename unknown>:0 at System.Web.HttpApplication.Tick () [0x00000] in <filename unknown>:0 Method: Void Application_Error(System.Object, System.EventArgs) at File: at Line Number: 0 Method: Void ProcessError(System.Exception) at File: at Line Number: 0 Method: Void Tick() at File: at Line Number: 0 Method: Void Start(System.Object) at File: at Line Number: 0 Method: Void System.Web.IHttpHandler.ProcessRequest(System.Web.HttpContext) at File: at Line Number: 0 Method: Void Process(System.Web.HttpWorkerRequest) at File: at Line Number: 0 Method: Void RealProcessRequest(System.Object) at File: at Line Number: 0 Method: Void ProcessRequest(System.Web.HttpWorkerRequest) at File: at Line Number: 0 Method: Void ProcessRequest() at File: at Line Number: 0 Method: Void ProcessRequest(Mono.WebServer.MonoWorkerRequest) at File: at Line Number: 0 Method: Void ProcessRequest(Int32, System.String, System.String, System.String, System.String, System.String, Int32, System.String, Int32, System.String, System.String[], System.String[], System.Object) at File: at Line Number: 0 Method: Void InnerRun(System.Object) at File: at Line Number: 0 Method: Void Run(System.Object) at File: at Line Number: 0

    Read the article

  • OutOfMemory during paging

    - by Tony
    Hi I am using ObjectDataSource, ListView, CustomPaging If the total number of rows is too big, I got OutOfMemory exception, it seems that it caused by some array, I don't get it, because total number of rows should never make any array to be filled with elements, the page size do!! This is the logger. ****EXCEPTION # 3 : 4/30/2010 9:43:07 PM System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. --- System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.Web.UI.WebControls.ListView.CreateChildControls() at System.Web.UI.Control.EnsureChildControls() at System.Web.UI.WebControls.ListView.get_Controls() at System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) --- End of inner exception stack trace --- at System.Web.UI.Page.HandleError(Exception e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.default_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\flickrdemo\15752207\c63ea96c\App_Web__8yxn9sb.0.cs:line 0 at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

    Read the article

  • Updated MVC 4 to 5.2.0 via Nuget Site compiles but wont run

    - by hjavaher
    I had the bright idea of updating my perfectly working ASP.Net MVC 4 application to the MVC 5 via nuget, Everything compiles just fine but when I try to run the application I get the following yellow screen of death. Has anyone gotten this or know how to solve it? I've searched for it and couldn't find any solutions. Please let me know if there is any farther information that would help you that I can give you. Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()' to access security critical method 'System.Web.WebPages.Razor.WebPageRazorHost.AddGlobalImport(System.String)' failed. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.MethodAccessException: Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()' to access security critical method 'System.Web.WebPages.Razor.WebPageRazorHost.AddGlobalImport(System.String)' failed. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [MethodAccessException: Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()' to access security critical method 'System.Web.WebPages.Razor.WebPageRazorHost.AddGlobalImport(System.String)' failed.] WebMatrix.WebData.PreApplicationStartCode.Start() +112 [InvalidOperationException: The pre-application start initialization method Start on type WebMatrix.WebData.PreApplicationStartCode threw an exception with the following error message: Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()' to access security critical method 'System.Web.WebPages.Razor.WebPageRazorHost.AddGlobalImport(System.String)' failed..] System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +556 System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +132 System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102 System.Web.Compilation.BuildManager.ExecutePreAppStart() +153 System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516 [HttpException (0x80004005): The pre-application start initialization method Start on type WebMatrix.WebData.PreApplicationStartCode threw an exception with the following error message: Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()' to access security critical method 'System.Web.WebPages.Razor.WebPageRazorHost.AddGlobalImport(System.String)' failed..] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9885060 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

    Read the article

  • Validation of viewstate MAC failed with nested master page

    - by just_name
    After I use a nested master page ,I face the following problem : Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. and sometimes Invalid related information [ViewStateException: Invalid viewstate. Client IP: 127.0.0.1 Port: User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0 ViewState: /wEPDwULLTEzOTY5MjA1ODUPZBYCZg9kFgICAw9kFg4CAQ9kFgJmDxYCHgRocmVmBUZmcm1faXRlbXMyLmFzcHg/c3lzPURGJmdycD0xJmRiPTUmZW1wPTc1NCZmaXJzdFJlcXVlc3Q9dHJ1ZSZMaXN0VHlwZT0xFgICAQ8PFgIeBFRleHQFATFkZAIDDxYCHgVjbGFzcwUGYWN0aXZlFgJmDxYCHwAFRmZybV9pdGVtczIuYXNweD9zeXM9REYmZ3JwPTEmZGI9NSZlbXA9NzU0JmZpcnN0UmVxdWVzdD10cnVlJkxpc3RUeXBlPTIWAgIBDw8WAh8BBQI3OGRkAgUPZBYCZg8WAh8ABUZmcm1faXRlbXMyLmFzcHg/c3lzPURGJmdycD0xJmRiPTUmZW1wPTc1NCZmaXJzdFJlcXVlc3Q9dHJ1ZSZMaXN0VHlwZT0zFgICAQ8PFgIfAQUDODY0ZGQCBw9kFgJmDxYCHwAFRmZybV9pdGVtczIuYXNweD9zeXM9REYmZ3JwPTEmZGI9NSZlbXA9NzU0JmZpcnN0UmVxdWVzdD10cnVlJkxpc3RUeXBlPTQWAgIBDw8WAh8BBQEwZGQCCQ9kFgJmDxYCHwAFP2ZybV9Vc2VyVGFza3MyLmFzcHg/c3lzPURGJmdycD0xJmRiPTUmZW1wPTc1NCZmaXJzdFJlcXVlc3Q9dHJ1ZWQCCw9kFgJmDxYCHwAFN1NlYXJjaC5hc3B4P3N5cz1ERiZncnA9MSZkYj01JmVtcD03NTQmZmlyc3RSZXF1ZXN0PXRydWVkAg8PZBYMAgQPEA8WBh4ORGF0YVZhbHVlRmllbGQFCFRhc2tDb2RlHg1EYXRhVGV4dEZpZWxkBQhUYXNrTmFt...] [HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.] System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +116 System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState) +13 System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +220 System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +5 System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +37 System.Web.UI.HiddenFieldPageStatePersister.Load() +202 System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +106 System.Web.UI.Page.LoadAllState() +43 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3905 System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +262 System.Web.UI.Page.ProcessRequest() +79 System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21 System.Web.UI.Page.ProcessRequest(HttpContext context) +109 ASP.frm_items2_aspx.ProcessRequest(HttpContext context) in c:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\a961040e\19f53d4c\App_Web_frm_items2.aspx.cdcab7d2.nkfrbsfi.0.cs:0 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +399 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +76 I use this Tool to fix this problem but in vain !! I don't know even the root cause of this problem !!

    Read the article

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