Search Results

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

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

  • Reporting services 2008: ReportExecution2005.asmx does not exist

    - by Shimrod
    Hi everyone, I'm trying to generate a report directly from the code (to send it by mail after). I make this in a windows service. So here is what I'm doing: Dim rview As New ReportViewer() Dim reportServerAddress As String = "http://server/Reports_client" rview.ServerReport.ReportServerUrl = New Uri(reportServerAddress) Dim paramList As New List(Of Microsoft.Reporting.WinForms.ReportParameter) paramList.Add(New Microsoft.Reporting.WinForms.ReportParameter("param1", t.Value)) paramList.Add(New Microsoft.Reporting.WinForms.ReportParameter("CurrentDate", Date.Now)) Dim reportsDirectory As String = "AppName.Reports" Dim reportPath As String = String.Format("/{0}/{1}", reportsDirectory, reportName) rview.ServerReport.ReportPath = reportPath rview.ServerReport.SetParameters(paramList) 'This is where I get the exception Dim mimeType, encoding, extension, deviceInfo As String Dim streamids As String() Dim warnings As Microsoft.Reporting.WinForms.Warning() deviceInfo = "<DeviceInfo><SimplePageHeaders>True</SimplePageHeaders></DeviceInfo>" Dim format As String = "PDF" Dim bytes As Byte() = rview.ServerReport.Render(format, deviceInfo, mimeType, encoding, extension, streamids, warnings) When debugging this code, I can see it throws a MissingEndpointException where I make the SetParameters(paramList) with this message: The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version. Looking in the server's log file, I can see this: ui!ReportManager_0-8!878!06/02/2010-11:34:36:: Unhandled exception: System.Web.HttpException: The file '/Reports_client/ReportExecution2005.asmx' does not exist. at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath) at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath) at System.Web.UI.WebServiceParser.GetCompiledType(String inputFile, HttpContext context) at System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) I didn't find any resource on the web that fits my problem. Does anyone have a clue ? I'm able to view the reports from a web application, so I'm sure the server is running. Thanks in advance.

    Read the article

  • How to Loop through LINQ results (VB.NET)

    - by rockinthesixstring
    I've got some code to try and loop through LINQ results, but it doesn't seem to be working. HERE'S THE CODE Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest ' the page contenttype is plain text' HttpContext.Current.Response.ContentType = "text/plain" ' store the querystring as a variable' Dim qs As Nullable(Of Integer) = Integer.TryParse(HttpContext.Current.Request.QueryString("ID"), Nothing) ' use the RegionsDataContext' Using RegionDC As New DAL.RegionsDataContext 'create a (q)uery variable' Dim q As Object ' if the querystring PID is not blank' ' then we want to return results based on the PID' If Not qs Is Nothing Then ' that fit within the Parent ID' q = (From r In RegionDC.bt_Regions _ Where r.PID = qs _ Select r.Region).ToArray ' now we loop through the array' ' and write out the ressults' For Each item As DAL.bt_Region In q HttpContext.Current.Response.Write(item.Region & vbCrLf) Next End If End Using End Sub HERE'S THE ERROR Public member 'Region' on type 'String' not found. 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.MissingMemberException: Public member 'Region' on type 'String' not found. Source Error: Line 33: ' and write out the ressults Line 34: For Each item In q Line 35: HttpContext.Current.Response.Write(item.Region & vbCrLf) Line 36: Next Line 37: Source File: E:\Projects\businesstrader\App_Code\Handlers\RegionsAutoComplete.vb Line: 35 Stack Trace: [MissingMemberException: Public member 'Region' on type 'String' not found.] Microsoft.VisualBasic.CompilerServices.Container.GetMembers(String& MemberName, Boolean ReportErrors) +509081 Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack) +222 BT.Handlers.RegionsAutoComplete.ProcessRequest(HttpContext context) in E:\Projects\businesstrader\App_Code\Handlers\RegionsAutoComplete.vb:35 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75 Can anyone tell me what I'm doing wrong?

    Read the article

  • ASP.net MVC HttpException strange file not found

    - by Paddy
    I'm running asp.net MVC site on IIS6 - I've edited my routing to look like the following: routes.MapRoute( "Default", "{controller}.aspx/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); routes.MapRoute( "Root", "", new { controller = "Home", action = "Index", id = "" } ); So all my urls now contain .aspx (as per one of the solutions from Phil Haack). Now, I catch all unhandled exceptions using Elmah, and for almost every page request, I get the following error caught by Elmah, that I never see on the front end (everything works perfectly): System.Web.HttpException: The file '/VirtualDirectoryName/Home.aspx' does not exist. System.Web.HttpException: The file '/VirtualDirectoryName/Home.aspx' does not exist. at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath) at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean noAssert) at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp, Boolean noAssert) at System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) at System.Web.UI.PageHandlerFactory.System.Web.IHttpHandlerFactory2.GetHandler(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) There is a Home controller, and it should be found, but I'm not sure a) where this is being called from, and b) why I don't see this error on the front end. Any ideas? Edited with answer: I think the answer for this can be found in this question: http://stackoverflow.com/questions/34194/asp-net-mvc-on-iis6

    Read the article

  • Is HttpContextWrapper all that....useful?

    - by bakasan
    I've been going through the process of cleaning up our controller code to make each action as testable. Generally speaking, this hasn't been too difficult--where we have opportunity to use a fixed object, like say FormsAuthentication, we generally introduce some form of wrapper as appropriate and be on our merry way. For reasons not particularly germaine to this conversation, when it came to dealing with usage of HttpContext, we decided to use the newly created HttpContextWrapper class rather than inventing something homegrown. One thing we did introduce was the ability to swap in a HttpContextWrapper (like say, for unit testing). This was wholly inspired by the way Oren Eini handles unit testing with DateTimes (see article, a pattern we also use) public static class FooHttpContext { public static Func<HttpContextWrapper> Current = () => new HttpContextWrapper(HttpContext.Current); public static void Reset() { Current = () => new HttpContextWrapper(HttpContext.Current); } } Nothing particularly fancy. And it works just fine in our controller code. The kicker came when we go to write unit tests. We're using Moq as our mocking framework, but alas var context = new Mock<HttpContextWrapper>() breaks since HttpContextWrapper doesn't have a parameterless ctor. And what does it take as a ctor parameter? A HttpContext object. So I find myself in a catch 22. I'm using the prescribed way to decouple HttpContext--but I can't mock a value in because the original HttpContext object was sealed and therefore difficult to test. I can map HttpContextBase, which both derive from--but that doesn't really get me what I'm after. Am I just missing the point somewhere with regard to HttpContextWrapper? I can find ways to work around the issue, but we are kind of fond of remaining consistent in decoupling using the Function delegate pattern--but it seems like we're not fully grokking intent of the wrapper.

    Read the article

  • HTTPS Redirect Causing Error "Server cannot append header after HTTP headers have been sent"

    - by Chad
    I need to check that our visitors are using HTTPS. In BasePage I check if the request is coming via HTTPS. If it's not, I redirect back with HTTPS. However, when someone comes to the site and this function is used, I get the error: System.Web.HttpException: Server cannot append header after HTTP headers have been sent. at System.Web.HttpResponse.AppendHeader(String name, String value) at System.Web.HttpResponse.AddHeader(String name, String value) at Premier.Payment.Website.Generic.BasePage..ctor() Here is the code I started with: // If page not currently SSL if (HttpContext.Current.Request.ServerVariables["HTTPS"].Equals("off")) { // If SSL is required if (GetConfigSetting("SSLRequired").ToUpper().Equals("TRUE")) { string redi = "https://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString() + HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"].ToString() + "?" + HttpContext.Current.Request.ServerVariables["QUERY_STRING"].ToString(); HttpContext.Current.Response.Redirect(redi.ToString()); } } I also tried adding this above it (a bit I used in another site for a similar problem): // Wait until page is copletely loaded before sending anything since we re-build HttpContext.Current.Response.BufferOutput = true; I am using c# in .NET 3.5 on IIS 6. enter code here

    Read the article

  • Moq: Unable to cast to interface

    - by Pickels
    Hello, earlier today I asked this question. So since moq creates it's own class from an interface I wasn't able to cast it to a different class. So it got me wondering what if I created a ICustomPrincipal and tried to cast to that. This is how my mocks look: var MockHttpContext = new Mock<HttpContextBase>(); var MockPrincipal = new Mock<ICustomPrincipal>(); MockHttpContext.SetupGet(h => h.User).Returns(MockPrincipal.Object); In the method I am trying to test the follow code gives the error(again): var user = (ICustomPrincipal)httpContext.User; The error is the following: Unable to cast object of type 'IPrincipalProxy4081807111564298854aabfc890edcc8' to type 'MyProject.Web.ICustomPrincipal'. I guess I still need some practice with interfaces and moq but shouldn't I be able to cast the class that moq created back to ICustomPrincipal? I know httpContext.User returns an IPrincipal so maybe something gets lost there? Well if anybody can help me I would appreciate that. Pickels Edit: As requested the full code of the method I am testing. It's still not finished but this is what I have so far: public bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } var user = (ICustomPrincipal)httpContext.User; if (!user.Identity.IsAuthenticated) { return false; } return true; }

    Read the article

  • Need help with creating PDF from HTML using itextsharp

    - by Steven
    I'm trying to crate a PDF out of a HTML page. The CMS I'm using is EPiServer. This is my code so far: protected void Button1_Click(object sender, EventArgs e) { naaflib.pdfDocument(CurrentPage); } public static void pdfDocument(PageData pd) { //Extract data from Page (pd). string intro = pd["MainIntro"].ToString(); // Attribute string mainBody = pd["MainBody"].ToString(); // Attribute // makae ready HttpContext HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/pdf"; // Create PDF document Document pdfDocument = new Document(PageSize.A4, 80, 50, 30, 65); //PdfWriter pw = PdfWriter.GetInstance(pdfDocument, HttpContext.Current.Response.OutputStream); PdfWriter.GetInstance(pdfDocument, HttpContext.Current.Response.OutputStream); pdfDocument.Open(); pdfDocument.Add(new Paragraph(pd.PageName)); pdfDocument.Add(new Paragraph(intro)); pdfDocument.Add(new Paragraph(mainBody)); pdfDocument.Close(); HttpContext.Current.Response.End(); } This outputs the content of the article name, intro-text and main body. But it does not pars HTML which is in the article text and there is no layout. I've tried having a look at http://itextsharp.sourceforge.net/tutorial/index.html without becomming any wiser. Any pointers to the right direction is greatly appreciated :)

    Read the article

  • ASP.NET MVC 2.0 + Implementation of a IRouteHandler does not fire

    - by Peter
    Can anybody please help me with this as I have no idea why public IHttpHandler GetHttpHandler(RequestContext requestContext) is not executing. In my Global.asax.cs I have public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); routes.Add("ImageRoutes", new Route("Images/{filename}", new CustomRouteHandler())); } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); } } //CustomRouteHandler implementation is below public class CustomRouteHandler : IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { // IF I SET A BREAK POINT HERE IT DOES NOT HIT FOR SOME REASON. string filename = requestContext.RouteData.Values["filename"] as string; if (string.IsNullOrEmpty(filename)) { // return a 404 HttpHandler here } else { requestContext.HttpContext.Response.Clear(); requestContext.HttpContext.Response.ContentType = GetContentType(requestContext.HttpContext.Request.Url.ToString()); // find physical path to image here. string filepath = requestContext.HttpContext.Server.MapPath("~/logo.jpg"); requestContext.HttpContext.Response.WriteFile(filepath); requestContext.HttpContext.Response.End(); } return null; } } Can any body tell me what I'm missing here. Simply public IHttpHandler GetHttpHandler(RequestContext requestContext) does not fire. I havn't change anything in the web.config either. What I'm missing here? Please help.

    Read the article

  • httpHandler - subfolder issue

    - by Patto
    Hi, I am trying to redirect my old typepad blog to my new blog (permanent 301 redirect) that runs with wordpress. The new blog will also be on a new server. the old Blog had the following structure: http://subdomain.domain.com/weblog/year/month/what-ever-article.html The new Blog looks like this: http://www.domain.com/Blog/year/month/what-ever-article.html I am using an http handler that I found online and tried to work with it: public class MyHttpModule :IHttpModule { public MyHttpModule() { // // TODO: Add constructor logic here // } #region IHttpModule Members public void Dispose() { } public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } void context_BeginRequest(object sender, EventArgs e) { string oldURL = System.Web.HttpContext.Current.Request.Url.ToString(); string newURL = String.Empty; //oldURL = if (oldURL.ToString().ToLower().IndexOf("articles") >= 0 || System.Web.HttpContext.Current.Request.Url.ToString().ToLower().IndexOf("weblog") >= 0) { newURL = oldURL.Replace("subdomain.domain.com/weblog", "www.domain.com/Blog/index.php"); if (newURL.ToLower().Contains("subdomain")) { newURL = "http://www.domain.com/Blog"; } } else { newURL = "http://www.domain.com/Blog"; } System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.StatusCode = 301; System.Web.HttpContext.Current.Response.AddHeader("Location", newURL); System.Web.HttpContext.Current.Response.End(); } #endregion } To use this code, I put the handler into the web.config <httpModules> <add name="MyHttpModule" type="MyHttpModule, App_Code"/> </httpModules> The issue that I have is that when I want to redirect from the http://subdomain.domain.com/weblog/year/month/what-ever-article.html, I get an error that the folder would not exist. Is there any way to change my script or add an catch all to the web.config that forwards the URL to my script? When I use "http://subdomain.domain.com/weblog/year/month/what-ever-article.html" in oldURL string, then the redirect works just fine... so I must have some IIS or web.config settings wrong. Thanks in advance, Patrick

    Read the article

  • ASP.NET MVC 2.0 + Implementation of a IRouteHandler goes not fire

    - by Peter
    Can anybody please help me with this as I have no idea why public IHttpHandler GetHttpHandler(RequestContext requestContext) is not executing. In my Global.asax.cs I have public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); routes.Add("ImageRoutes", new Route("Images/{filename}", new CustomRouteHandler())); } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); } } //CustomRouteHandler implementation is below public class CustomRouteHandler : IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { // IF I SET A BREAK POINT HERE IT DOES NOT HIT FOR SOME REASON. string filename = requestContext.RouteData.Values["filename"] as string; if (string.IsNullOrEmpty(filename)) { // return a 404 HttpHandler here } else { requestContext.HttpContext.Response.Clear(); requestContext.HttpContext.Response.ContentType = GetContentType(requestContext.HttpContext.Request.Url.ToString()); // find physical path to image here. string filepath = requestContext.HttpContext.Server.MapPath("~/logo.jpg"); requestContext.HttpContext.Response.WriteFile(filepath); requestContext.HttpContext.Response.End(); } return null; } } Can any body tell me what I'm missing here. Simply public IHttpHandler GetHttpHandler(RequestContext requestContext) does not fire. I havn't change anything in the web.config either. What I'm missing here? Please help.

    Read the article

  • Clearing Session in Global Application_Error

    - by Zarigani
    Whenever an unhandled exception occurs on our site, I want to: Send a notification email Clear the user's session Send the user to a error page ("Sorry, a problem occurred...") The first and last I've had working for a long time but the second is causing me some issues. My Global.asax.vb includes: Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) ' Send exception report Dim ex As System.Exception = Nothing If HttpContext.Current IsNot Nothing AndAlso HttpContext.Current.Server IsNot Nothing Then ex = HttpContext.Current.Server.GetLastError End If Dim eh As New ErrorHandling(ex) eh.SendError() ' Clear session If HttpContext.Current IsNot Nothing AndAlso HttpContext.Current.Session IsNot Nothing Then HttpContext.Current.Session.Clear() End If ' User will now be sent to the 500 error page (by the CustomError setting in web.config) End Sub When I run a debug, I can see the session being cleared, but then on the next page the session is back again! I eventually found a reference that suggests that changes to session will not be saved unless Server.ClearError is called. Unfortunately, if I add this (just below the line that sets "ex") then the CustomErrors redirect doesn't seem to kick in and I'm left with a blank page? Is there a way around this?

    Read the article

  • Custom authentication module inheriting IHttpModule issue.

    - by Chandan Khatwani
    LoginPage.aspx:- protected void Button1_Click(object sender, EventArgs e) { Context.Items["Username"] = txtUserId.Text; Context.Items["Password"] = txtPassword.Text; // FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Context.Items["Username"].ToString(), DateTime.Now, DateTime.Now.AddMinutes(10), true, "users", FormsAuthentication.FormsCookiePath); // Encrypt the cookie using the machine key for secure transport string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName, // Name of auth cookie hash); // Hashed ticket // Set the cookie's expiration time to the tickets expiration time if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; Response.Cookies.Add(cookie); Response.Redirect("Default.aspx"); } Global.asax file:- void Application_AuthenticateRequest(object sender, EventArgs e) { if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.IsAuthenticated) { if (HttpContext.Current.User.Identity is FormsIdentity) { FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; // Get the stored user-data, in this case, our roles string userData = ticket.UserData; string[] roles = userData.Split(','); HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles); Response.Write(HttpContext.Current.User.Identity.Name); Response.Redirect("Default.aspx"); } } } } I get the following error after signing in This webpage has a redirect loop. The webpage at http://localhost:1067/Default.aspx has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.

    Read the article

  • Web Apps vs Web Services: 302s and 401s are not always good Friends

    - by Your DisplayName here!
    It is not very uncommon to have web sites that have web UX and services content. The UX part maybe uses WS-Federation (or some other redirect based mechanism). That means whenever an authorization error occurs (401 status code), this is picked by the corresponding redirect module and turned into a redirect (302) to the login page. All is good. But in services, when you emit a 401, you typically want that status code to travel back to the client agent, so it can do error handling. These two approaches conflict. If you think (like me) that you should separate UX and services into separate apps, you don’t need to read on. Just do it ;) If you need to mix both mechanisms in a single app – here’s how I solved it for a project. I sub classed the redirect module – this was in my case the WIF WS-Federation HTTP module and modified the OnAuthorizationFailed method. In there I check for a special HttpContext item, and if that is present, I suppress the redirect. Otherwise everything works as normal: class ServiceAwareWSFederationAuthenticationModule : WSFederationAuthenticationModule {     protected override void OnAuthorizationFailed(AuthorizationFailedEventArgs e)     {         base.OnAuthorizationFailed(e);         var isService = HttpContext.Current.Items[AdvertiseWcfInHttpPipelineBehavior.DefaultLabel];         if (isService != null)         {             e.RedirectToIdentityProvider = false;         }     } } Now the question is, how do you smuggle that value into the HttpContext. If it is a MVC based web service, that’s easy of course. In the case of WCF, one approach that worked for me was to set it in a service behavior (dispatch message inspector to be exact): public void BeforeSendReply( ref Message reply, object correlationState) {     if (HttpContext.Current != null)     {         HttpContext.Current.Items[DefaultLabel] = true;     } } HTH

    Read the article

  • Google Hybrid OpenID+OAuth with dotnetopenauth

    - by Max Favilli
    I have spent probably more than 10 hours in the last two days trying to understand how to implement user login with Google Hybrid OpenID+OAuth (Federated Login) To trigger the authorization request I use: InMemoryOAuthTokenManager tm = new InMemoryOAuthTokenManager( ConfigurationManager.AppSettings["googleConsumerKey"], ConfigurationManager.AppSettings["googleConsumerSecret"]); using (OpenIdRelyingParty openid = new OpenIdRelyingParty()) { Realm realm = HttpContext.Current.Request.Url.Scheme + Uri.SchemeDelimiter + ConfigurationManager.AppSettings["googleConsumerKey"] + "/"; IAuthenticationRequest request = openid.CreateRequest(identifier, Realm.AutoDetect, new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/OAuth/google")); var authorizationRequest = new AuthorizationRequest { Consumer = ConfigurationManager.AppSettings["googleConsumerKey"], Scope = "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/plus.me", }; request.AddExtension(authorizationRequest); request.AddExtension(new ClaimsRequest { Email = DemandLevel.Request, Gender = DemandLevel.Require }); request.RedirectToProvider(); } To retrieve the accesstoken I use: using (OpenIdRelyingParty openid = new OpenIdRelyingParty()) { IAuthenticationResponse authResponse = openid.GetResponse(); if (authResponse != null) { switch (authResponse.Status) { case AuthenticationStatus.Authenticated: HttpContext.Current.Trace.Write("AuthenticationStatus", "Authenticated"); FetchResponse fr = authResponse.GetExtension<FetchResponse>(); InMemoryOAuthTokenManager tm = new InMemoryOAuthTokenManager(ConfigurationManager.AppSettings["googleConsumerKey"], ConfigurationManager.AppSettings["googleConsumerSecret"]); ServiceProviderDescription spd = new ServiceProviderDescription { spd.RequestTokenEndpoint = new DotNetOpenAuth.Messaging.MessageReceivingEndpoint("https://accounts.google.com/o/oauth2/token", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest); spd.AccessTokenEndpoint = new DotNetOpenAuth.Messaging.MessageReceivingEndpoint("https://accounts.google.com/o/oauth2/token", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest); spd.UserAuthorizationEndpoint = new DotNetOpenAuth.Messaging.MessageReceivingEndpoint("https://accounts.google.com/o/oauth2/auth?access_type=offline", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest); spd.TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }; WebConsumer wc = new WebConsumer(spd, tm); AuthorizedTokenResponse accessToken = wc.ProcessUserAuthorization(); if (accessToken != null) { HttpContext.Current.Trace.Write("accessToken", accessToken.ToString()); } else { } break; case AuthenticationStatus.Canceled: HttpContext.Current.Trace.Write("AuthenticationStatus", "Canceled"); break; case AuthenticationStatus.Failed: HttpContext.Current.Trace.Write("AuthenticationStatus", "Failed"); break; default: break; } } } Unfortunatelly I get AuthenticationStatus.Authenticated but wc.ProcessUserAuthorization() is null. What am I doing wrong? Thanks a lot for any help.

    Read the article

  • IIS 7 - The virtual path 'null' maps to another application, which is not allowed

    - by Miro
    I have run into issue when set up IIS 7 Farm for Load balancing. Add 4 server to IIS Farm with appropriate ports(8080,8081,8082,8083). Also add Inbound rule for IIS Farm. The Tomcat instances listens these ports. When i'm opening url(which i set on inbound rule), i got the following exception: The virtual path 'null' maps to another application, which is not allowed. 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: [ArgumentException: The virtual path 'null' maps to another application, which is not allowed.] System.Web.CachedPathData.GetVirtualPathData(VirtualPath virtualPath, Boolean permitPathsOutsideApp) +8839122 System.Web.HttpContext.GetFilePathData() +36 System.Web.HttpContext.GetConfigurationPathData() +26 System.Web.Configuration.RuntimeConfig.GetConfig(HttpContext context) +43 System.Web.Configuration.CustomErrorsSection.GetSettings(HttpContext context, Boolean canThrow) +41 System.Web.HttpResponse.ReportRuntimeError(Exception e, Boolean canThrow, Boolean localExecute) +101 System.Web.HttpContext.ReportRuntimeErrorIfExists(RequestNotificationStatus& status) +538 How can i solve this issue?

    Read the article

  • Static classes and/or singletons -- How many does it take to become a code smell?

    - by Earlz
    In my projects I use quite a lot of static classes. These are usually classes that naturally seem to fit into a single-instance type of thing. Many times I use static classes and recently I've started using some singletons. How many of these does it take to become a code smell? For instance, in my recent project which has a lot of static classes is an Authentication library for ASP.Net. I use a static class for a helper class that fixes ASP.Net error codes so it can be used like CustomErrorsFixer.Fix(Context); Or my authentication class itself is a static class //in global.asax's begin_application Authentication.SomeState="blah"; Authentication.SomeOption=true; //etc //in global.asax's begin_request Authentication.Authenticate(); When are static or singleton classes bad to use? Am I doing it wrong, or am I just in a project that by definition has very little per-instance state associated with it? The only per-instance state I have is stored in HttpContext.Current.Items like so: /// <summary> /// The current user logged in for the HTTP request. If there is not a user logged in, this will be null. /// </summary> public static UserData CurrentUser{ get{ return HttpContext.Current.Items["fscauth_currentuser"] as UserData; //use HttpContext.Current as a little place to persist static data for this request } private set{ HttpContext.Current.Items["fscauth_currentuser"]=value; } }

    Read the article

  • Behind ASP.NET MVC Mock Objects

    - by imran_ku07
       Introduction:           I think this sentence now become very familiar to ASP.NET MVC developers that "ASP.NET MVC is designed with testability in mind". But what ASP.NET MVC team did for making applications build with ASP.NET MVC become easily testable? Understanding this is also very important because it gives you some help when designing custom classes. So in this article i will discuss some abstract classes provided by ASP.NET MVC team for the various ASP.NET intrinsic objects, including HttpContext, HttpRequest, and HttpResponse for making these objects as testable. I will also discuss that why it is hard and difficult to test ASP.NET Web Forms.      Description:           Starting from Classic ASP to ASP.NET MVC, ASP.NET Intrinsic objects is extensively used in all form of web application. They provide information about Request, Response, Server, Application and so on. But ASP.NET MVC uses these intrinsic objects in some abstract manner. The reason for this abstraction is to make your application testable. So let see the abstraction.           As we know that ASP.NET MVC uses the same runtime engine as ASP.NET Web Form uses, therefore the first receiver of the request after IIS and aspnet_filter.dll is aspnet_isapi.dll. This will start the application domain. With the application domain up and running, ASP.NET does some initialization and after some initialization it will call Application_Start if it is defined. Then the normal HTTP pipeline event handlers will be executed including both HTTP Modules and global.asax event handlers. One of the HTTP Module is registered by ASP.NET MVC is UrlRoutingModule. The purpose of this module is to match a route defined in global.asax. Every matched route must have IRouteHandler. In default case this is MvcRouteHandler which is responsible for determining the HTTP Handler which returns MvcHandler (which is derived from IHttpHandler). In simple words, Route has MvcRouteHandler which returns MvcHandler which is the IHttpHandler of current request. In between HTTP pipeline events the handler of ASP.NET MVC, MvcHandler.ProcessRequest will be executed and shown as given below,          void IHttpHandler.ProcessRequest(HttpContext context)          {                    this.ProcessRequest(context);          }          protected virtual void ProcessRequest(HttpContext context)          {                    // HttpContextWrapper inherits from HttpContextBase                    HttpContextBase ctxBase = new HttpContextWrapper(context);                    this.ProcessRequest(ctxBase);          }          protected internal virtual void ProcessRequest(HttpContextBase ctxBase)          {                    . . .          }             HttpContextBase is the base class. HttpContextWrapper inherits from HttpContextBase, which is the parent class that include information about a single HTTP request. This is what ASP.NET MVC team did, just wrap old instrinsic HttpContext into HttpContextWrapper object and provide opportunity for other framework to provide their own implementation of HttpContextBase. For example           public class MockHttpContext : HttpContextBase          {                    . . .          }                     As you can see, it is very easy to create your own HttpContext. That's what did the third party mock frameworks like TypeMock, Moq, RhinoMocks, or NMock2 to provide their own implementation of ASP.NET instrinsic objects classes.           The key point to note here is the types of ASP.NET instrinsic objects. In ASP.NET Web Form and ASP.NET MVC. For example in ASP.NET Web Form the type of Request object is HttpRequest (which is sealed) and in ASP.NET MVC the type of Request object is HttpRequestBase. This is one of the reason that makes test in ASP.NET WebForm is difficult. because their is no base class and the HttpRequest class is sealed, therefore it cannot act as a base class to others. On the other side ASP.NET MVC always uses a base class to give a chance to third parties and unit test frameworks to create thier own implementation ASP.NET instrinsic object.           Therefore we can say that in ASP.NET MVC, instrinsic objects are of type base classes (for example HttpContextBase) .Actually these base classes had it's own implementation of same interface as the intrinsic objects it abstracts. It includes only virtual members which simply throws an exception. ASP.NET MVC also provides the corresponding wrapper classes (for example, HttpRequestWrapper) which provides a concrete implementation of the base classes in the form of ASP.NET intrinsic object. Other wrapper classes may be defined by third parties in the form of a mock object for testing purpose.           So we can say that a Request object in ASP.NET MVC may be HttpRequestWrapper or may be MockRequestWrapper(assuming that MockRequestWrapper class is used for testing purpose). Here is list of ASP.NET instrinsic and their implementation in ASP.NET MVC in the form of base and wrapper classes. Base Class Wrapper Class ASP.NET Intrinsic Object Description HttpApplicationStateBase HttpApplicationStateWrapper Application HttpApplicationStateBase abstracts the intrinsic Application object HttpBrowserCapabilitiesBase HttpBrowserCapabilitiesWrapper HttpBrowserCapabilities HttpBrowserCapabilitiesBase abstracts the HttpBrowserCapabilities class HttpCachePolicyBase HttpCachePolicyWrapper HttpCachePolicy HttpCachePolicyBase abstracts the HttpCachePolicy class HttpContextBase HttpContextWrapper HttpContext HttpContextBase abstracts the intrinsic HttpContext object HttpFileCollectionBase HttpFileCollectionWrapper HttpFileCollection HttpFileCollectionBase abstracts the HttpFileCollection class HttpPostedFileBase HttpPostedFileWrapper HttpPostedFile HttpPostedFileBase abstracts the HttpPostedFile class HttpRequestBase HttpRequestWrapper Request HttpRequestBase abstracts the intrinsic Request object HttpResponseBase HttpResponseWrapper Response HttpResponseBase abstracts the intrinsic Response object HttpServerUtilityBase HttpServerUtilityWrapper Server HttpServerUtilityBase abstracts the intrinsic Server object HttpSessionStateBase HttpSessionStateWrapper Session HttpSessionStateBase abstracts the intrinsic Session object HttpStaticObjectsCollectionBase HttpStaticObjectsCollectionWrapper HttpStaticObjectsCollection HttpStaticObjectsCollectionBase abstracts the HttpStaticObjectsCollection class      Summary:           ASP.NET MVC provides a set of abstract classes for ASP.NET instrinsic objects in the form of base classes, allowing someone to create their own implementation. In addition, ASP.NET MVC also provide set of concrete classes in the form of wrapper classes. This design really makes application easier to test and even application may replace concrete implementation with thier own implementation, which makes ASP.NET MVC very flexable.

    Read the article

  • DataContractJsonSerializer ReadObject Exception

    - by Dan Appleyard
    I am following the accepted answer of ASP.NET MVC How to pass JSON object from View to Controller as Parameter. Like the original question, I have a simple POCO. Everthing works fine for me up until the DataContractJsonSerializer.ReadObject method. I am getting the following exception: Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''. Public Overrides Sub OnActionExecuting(ByVal filterContext As ActionExecutingContext) If filterContext.HttpContext.Request.ContentType.Contains("application/json") Then Dim s As System.IO.Stream = filterContext.HttpContext.Request.InputStream Dim o = New DataContractJsonSerializer(RootType).ReadObject(s) filterContext.ActionParameters(Param) = o Else Dim xmlRoot = XElement.Load(New StreamReader(filterContext.HttpContext.Request.InputStream, filterContext.HttpContext.Request.ContentEncoding)) Dim o As Object = New XmlSerializer(RootType).Deserialize(xmlRoot.CreateReader) filterContext.ActionParameters(Param) = o End If End Sub Any ideas? Thanks

    Read the article

  • ASP.NET GZip Encoding Caveats

    - by Rick Strahl
    GZip encoding in ASP.NET is pretty easy to accomplish using the built-in GZipStream and DeflateStream classes and applying them to the Response.Filter property.  While applying GZip and Deflate behavior is pretty easy there are a few caveats that you have watch out for as I found out today for myself with an application that was throwing up some garbage data. But before looking at caveats let’s review GZip implementation for ASP.NET. ASP.NET GZip/Deflate Basics Response filters basically are applied to the Response.OutputStream and transform it as data is written to it through the ASP.NET Response object. So a Response.Write eventually gets written into the output stream which if a filter is also written through the filter stream’s interface. To perform the actual GZip (and Deflate) encoding typically used by Web pages .NET includes the GZipStream and DeflateStream stream classes which can be readily assigned to the Repsonse.OutputStream. With these two stream classes in place it’s almost trivially easy to create a couple of reusable methods that allow you to compress your HTTP output. In my standard WebUtils utility class (from the West Wind West Wind Web Toolkit) created two static utility methods – IsGZipSupported and GZipEncodePage – that check whether the client supports GZip encoding and then actually encodes the current output (note that although the method includes ‘Page’ in its name this code will work with any ASP.NET output). /// <summary> /// Determines if GZip is supported /// </summary> /// <returns></returns> public static bool IsGZipSupported() { string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"]; if (!string.IsNullOrEmpty(AcceptEncoding) && (AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate"))) return true; return false; } /// <summary> /// Sets up the current page or handler to use GZip through a Response.Filter /// IMPORTANT: /// You have to call this method before any output is generated! /// </summary> public static void GZipEncodePage() { HttpResponse Response = HttpContext.Current.Response; if (IsGZipSupported()) { string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"]; if (AcceptEncoding.Contains("deflate")) { Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter, System.IO.Compression.CompressionMode.Compress); Response.Headers.Remove("Content-Encoding"); Response.AppendHeader("Content-Encoding", "deflate"); } else { Response.Filter = new System.IO.Compression.GZipStream(Response.Filter, System.IO.Compression.CompressionMode.Compress); Response.Headers.Remove("Content-Encoding"); Response.AppendHeader("Content-Encoding", "gzip"); } } } As you can see the actual assignment of the Filter is as simple as: Response.Filter = new DeflateStream(Response.Filter, System.IO.Compression.CompressionMode.Compress); which applies the filter to the OutputStream. You also need to ensure that your response reflects the new GZip or Deflate encoding and ensure that any pages that are cached in Proxy servers can differentiate between pages that were encoded with the various different encodings (or no encoding). To use this utility function now is trivially easy: In any ASP.NET code that wants to compress its Response output you simply use: protected void Page_Load(object sender, EventArgs e) { WebUtils.GZipEncodePage(); Entry = WebLogFactory.GetEntry(); var entries = Entry.GetLastEntries(App.Configuration.ShowEntryCount, "pk,Title,SafeTitle,Body,Entered,Feedback,Location,ShowTopAd", "TEntries"); if (entries == null) throw new ApplicationException("Couldn't load WebLog Entries: " + Entry.ErrorMessage); this.repEntries.DataSource = entries; this.repEntries.DataBind(); } Here I use an ASP.NET page, but the above WebUtils.GZipEncode() method call will work in any ASP.NET application type including HTTP Handlers. The only requirement is that the filter needs to be applied before any other output is sent to the OutputStream. For example, in my CallbackHandler service implementation by default output over a certain size is GZip encoded. The output that is generated is JSON or XML and if the output is over 5k in size I apply WebUtils.GZipEncode(): if (sbOutput.Length > GZIP_ENCODE_TRESHOLD) WebUtils.GZipEncodePage(); Response.ContentType = ControlResources.STR_JsonContentType; HttpContext.Current.Response.Write(sbOutput.ToString()); Ok, so you probably get the idea: Encoding GZip/Deflate content is pretty easy. Hold on there Hoss –Watch your Caching Or is it? There are a few caveats that you need to watch out for when dealing with GZip content. The fist issue is that you need to deal with the fact that some clients don’t support GZip or Deflate content. Most modern browsers support it, but if you have a programmatic Http client accessing your content GZip/Deflate support is by no means guaranteed. For example, WinInet Http clients don’t support GZip out of the box – it has to be explicitly implemented. Other low level HTTP clients on other platforms too don’t support GZip out of the box. The problem is that your application, your Web Server and Proxy Servers on the Internet might be caching your generated content. If you return content with GZip once and then again without, either caching is not applied or worse the wrong type of content is returned back to the client from a cache or proxy. The result is an unreadable response for *some clients* which is also very hard to debug and fix once in production. You already saw the issue of Proxy servers addressed in the GZipEncodePage() function: // Allow proxy servers to cache encoded and unencoded versions separately Response.AppendHeader("Vary", "Content-Encoding"); This ensures that any Proxy servers also check for the Content-Encoding HTTP Header to cache their content – not just the URL. The same thing applies if you do OutputCaching in your own ASP.NET code. If you generate output for GZip on an OutputCached page the GZipped content will be cached (either by ASP.NET’s cache or in some cases by the IIS Kernel Cache). But what if the next client doesn’t support GZip? She’ll get served a cached GZip page that won’t decode and she’ll get a page full of garbage. Wholly undesirable. To fix this you need to add some custom OutputCache rules by way of the GetVaryByCustom() HttpApplication method in your global_ASAX file: public override string GetVaryByCustomString(HttpContext context, string custom) { // Override Caching for compression if (custom == "GZIP") { string acceptEncoding = HttpContext.Current.Response.Headers["Content-Encoding"]; if (string.IsNullOrEmpty(acceptEncoding)) return ""; else if (acceptEncoding.Contains("gzip")) return "GZIP"; else if (acceptEncoding.Contains("deflate")) return "DEFLATE"; return ""; } return base.GetVaryByCustomString(context, custom); } In a page that use Output caching you then specify: <%@ OutputCache Duration="180" VaryByParam="none" VaryByCustom="GZIP" %> To use that custom rule. It’s all Fun and Games until ASP.NET throws an Error Ok, so you’re up and running with GZip, you have your caching squared away and your pages that you are applying it to are jamming along. Then BOOM, something strange happens and you get a lovely garbled page that look like this: Lovely isn’t it? What’s happened here is that I have WebUtils.GZipEncode() applied to my page, but there’s an error in the page. The error falls back to the ASP.NET error handler and the error handler removes all existing output (good) and removes all the custom HTTP headers I’ve set manually (usually good, but very bad here). Since I applied the Response.Filter (via GZipEncode) the output is now GZip encoded, but ASP.NET has removed my Content-Encoding header, so the browser receives the GZip encoded content without a notification that it is encoded as GZip. The result is binary output. Here’s what Fiddler says about the raw HTTP header output when an error occurs when GZip encoding was applied: HTTP/1.1 500 Internal Server Error Cache-Control: private Content-Type: text/html; charset=utf-8 Date: Sat, 30 Apr 2011 22:21:08 GMT Content-Length: 2138 Connection: close ?`I?%&/m?{J?J??t??` … binary output striped here Notice: no Content-Encoding header and that’s why we’re seeing this garbage. ASP.NET has stripped the Content-Encoding header but left our filter intact. So how do we fix this? In my applications I typically have a global Application_Error handler set up and in this case I’ve been using that. One thing that you can do in the Application_Error handler is explicitly clear out the Response.Filter and set it to null at the top: protected void Application_Error(object sender, EventArgs e) { // Remove any special filtering especially GZip filtering Response.Filter = null; … } And voila I get my Yellow Screen of Death or my custom generated error output back via uncompressed content. BTW, the same is true for Page level errors handled in Page_Error or ASP.NET MVC Error handling methods in a controller. Another and possibly even better solution is to check whether a filter is attached just before the headers are sent to the client as pointed out by Adam Schroeder in the comments: protected void Application_PreSendRequestHeaders() { // ensure that if GZip/Deflate Encoding is applied that headers are set // also works when error occurs if filters are still active HttpResponse response = HttpContext.Current.Response; if (response.Filter is GZipStream && response.Headers["Content-encoding"] != "gzip") response.AppendHeader("Content-encoding", "gzip"); else if (response.Filter is DeflateStream && response.Headers["Content-encoding"] != "deflate") response.AppendHeader("Content-encoding", "deflate"); } This uses the Application_PreSendRequestHeaders() pipeline event to check for compression encoding in a filter and adjusts the content accordingly. This is actually a better solution since this is generic – it’ll work regardless of how the content is cleaned up. For example, an error Response.Redirect() or short error display might get changed and the filter not cleared and this code actually handles that. Sweet, thanks Adam. It’s unfortunate that ASP.NET doesn’t natively clear out Response.Filters when an error occurs just as it clears the Response and Headers. I can’t see where leaving a Filter in place in an error situation would make any sense, but hey - this is what it is and it’s easy enough to fix as long as you know where to look. Riiiight! IIS and GZip I should also mention that IIS 7 includes good support for compression natively. If you can defer encoding to let IIS perform it for you rather than doing it in your code by all means you should do it! Especially any static or semi-dynamic content that can be made static should be using IIS built-in compression. Dynamic caching is also supported but is a bit more tricky to judge in terms of performance and footprint. John Forsyth has a great article on the benefits and drawbacks of IIS 7 compression which gives some detailed performance comparisons and impact reviews. I’ll post another entry next with some more info on IIS compression since information on it seems to be a bit hard to come by. Related Content Built-in GZip/Deflate Compression in IIS 7.x HttpWebRequest and GZip Responses © Rick Strahl, West Wind Technologies, 2005-2011Posted in ASP.NET   IIS7  

    Read the article

  • COMException when trying to use a Library

    - by sarkie
    Hi Guys, I have an ASP.net WebService which uses a Library, this has a dependency on some third party .dlls. If I add a reference to the Library to my webservice, I get a COMException and I can't load the site. I thought it may be to do with aspnet user credentials, so I have tried impersonating and using processModel in machine.config but nothing seems to work. The .dlls are for communicating with hardware so I am not even using them on the server just other parts of the library, is there any way I can fix this? I'm running on Windows XP Pro SP3 with Visual 2008 SP1 and .net 3.5. I am thinking the only way of fixing it, is to split up the library into hardware and non-hardware based. Cheers, Sarkie The specified procedure could not be found. (Exception from HRESULT: 0x8007007F) 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.Runtime.InteropServices.COMException: The specified procedure could not be found. (Exception from HRESULT: 0x8007007F) 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: [COMException (0x8007007f): The specified procedure could not be found. (Exception from HRESULT: 0x8007007F)] [FileLoadException: A procedure imported by 'OBIDISC4NETnative, Version=0.0.0.0, Culture=neutral, PublicKeyToken=900ed37a7058e4f2' could not be loaded.] System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +0 System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +43 System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +127 System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +142 System.Reflection.Assembly.Load(String assemblyString) +28 System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +46 [ConfigurationErrorsException: A procedure imported by 'OBIDISC4NETnative, Version=0.0.0.0, Culture=neutral, PublicKeyToken=900ed37a7058e4f2' could not be loaded.] System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +613 System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +203 System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +105 System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +178 System.Web.Compilation.WebDirectoryBatchCompiler..ctor(VirtualDirectory vdir) +163 System.Web.Compilation.BuildManager.BatchCompileWebDirectoryInternal(VirtualDirectory vdir, Boolean ignoreErrors) +53 System.Web.Compilation.BuildManager.BatchCompileWebDirectory(VirtualDirectory vdir, VirtualPath virtualDir, Boolean ignoreErrors) +175 System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) +83 System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +261 System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +101 System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +83 System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath) +10 System.Web.UI.WebServiceParser.GetCompiledType(String inputFile, HttpContext context) +43 System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +180 System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +102 System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +193 System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +93 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 -------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:2.0.50727.3082; ASP.NET Version:2.0.50727.3082

    Read the article

  • controller path not found for static images? asp.net mvc routing issue?

    - by rksprst
    I have an image folder stored at ~/Content/Images/ I am loading these images via <img src="/Content/Images/Image.png" /> Recently, the images aren't loading and I am getting the following errors in my error log. What's weird is that some images load fine, while others do not load. Anyone have any idea what is wrong with my routes? Am I missing an ignore route for the /Content/ folder? I am also getting the same error for favicon.ico and a bunch of other image files... <Fatal> -- 3/25/2010 2:32:38 AM -- System.Web.HttpException: The controller for path '/Content/Images/box_bottom.png' could not be found or it does not implement IController. at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(Type controllerType) at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) at System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) My current routes look like this: routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); routes.MapRoute( "ControllerDefault", // Route name "{controller}/project/{projectid}/{action}/{searchid}", // URL with parameters new { controller = "Listen", action = "Index", searchid = "" } // Parameter defaults ); Thanks!

    Read the article

  • Ninject woes... 404 error problems

    - by jbarker7
    We are using the beloved Ninject+Ninject.Web.Mvc with MVC 2 and are running into some problems. Specifically dealing with 404 errors. We have a logging service that logs 500 errors and records them. Everything is chugging along just perfectly except for when we attempt to enter a non-existent controller. Instead of getting the desired 404 we end up with a 500 error: Cannot be null Parameter name: service [ArgumentNullException: Cannot be null Parameter name: service] Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional) +188 Ninject.ResolutionExtensions.TryGet(IResolutionRoot root, Type service, IParameter[] parameters) +15 Ninject.Web.Mvc.NinjectControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +36 System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +68 System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +118 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +46 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +63 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +13 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8679426 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 I did some searching and found some similar issues, but those 404 issues seem to be unrelated. Any help here would be great. Thanks! Josh

    Read the article

  • How to invalidate a single data item in the .net cache in VB

    - by Craig
    I have the following .NET VB code to set and read objects in cache on a per user basis (i.e. a bit like session) '' Public Shared Sub CacheSet(ByVal Key As String, ByVal Value As Object) Dim userID As String = HttpContext.Current.User.Identity.Name HttpContext.Current.Cache(Key & "_" & userID) = Value End Sub Public Shared Function CacheGet(ByVal Key As Object) Dim returnData As Object = Nothing Dim userID As String = HttpContext.Current.User.Identity.Name returnData = HttpContext.Current.Cache(Key & "_" & userID) Return returnData End Function I use these functions to hold user data that I don't want to access the DB for all the time. However, when the data is updated, I want the cached item to be removed so it get created again. How do I make an Item I set disappear or set it to NOTHING or NULL? Craig

    Read the article

  • Postback problem when using URL Rewrite and 404.aspx

    - by salle55
    I'm using URL rewrite on my site to get URLs like: http://mysite.com/users/john instead of http://mysite.com/index.aspx?user=john To achive this extensionless rewrite with IIS6 and no access to the hosting-server I use the "404-approach". When a request that the server can't find, the mapped 404-page is executed, since this is a aspx-page the rewrite can be performed (I can setup the 404-mapping using the controlpanel on the hosting-service). This is the code in Global.asax: protected void Application_BeginRequest(object sender, EventArgs e) { string url = HttpContext.Current.Request.Url.AbsolutePath; if (url.Contains("404.aspx")) { string[] urlInfo404 = Request.Url.Query.ToString().Split(';'); if (urlInfo404.Length > 1) { string requestURL = urlInfo404[1]; if (requestURL.Contains("/users/")) { HttpContext.Current.RewritePath("~/index.aspx?user=" + GetPageID(requestURL)); StoreRequestURL(requestURL); } else if (requestURL.Contains("/picture/")) { HttpContext.Current.RewritePath("~/showPicture.aspx?pictureID=" + GetPageID(requestURL)); StoreRequestURL(requestURL); } } } } private void StoreRequestURL(string url) { url = url.Replace("http://", ""); url = url.Substring(url.IndexOf("/")); HttpContext.Current.Items["VirtualUrl"] = url; } private string GetPageID(string requestURL) { int idx = requestURL.LastIndexOf("/"); string id = requestURL.Substring(idx + 1); id = id.Replace(".aspx", ""); //Only needed when testing without the 404-approach return id; } And in Page_Load on my masterpage I set the correct URL in the action-attribute on the form-tag. protected void Page_Load(object sender, EventArgs e) { string virtualURL = (string)HttpContext.Current.Items["VirtualUrl"]; if (!String.IsNullOrEmpty(virtualURL)) { form1.Action = virtualURL; } } The rewrite works fine but when I perform a postback on the page the postback isn't executed, can this be solved somehow? The problem seems to be with the 404-approach because when I try without it (and loses the extensionless-feature) the postback works. That is when I request: http://mysite.com/users/john.aspx Can this be solved or is there any other solution that fulfil my requirements (IIS6, no serveraccess/ISAPI-filter and extensionless).

    Read the article

  • OAuth Consumer request for token from ServiceProvider returns InternalServerError

    - by chridam
    I'm playing around with DevDefined.OAuth - an OAuth consumer and provider implementation for .Net http://code.google.com/p/devdefined-tools/wiki/OAuth and on launching the ExampleConsumerSite project after configuring the service endpoints on my IIS 7 web server, I'm receiving the following error: 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.Exception: Request for uri: http://localhost%3A8080/RequestToken.aspx?oauth%5Fcallback=oob&oauth%5Fnonce=94efde0b-dd45-4cee-8253-7496cef0b877&oauth%5Fconsumer%5Fkey=key&oauth%5Fsignature%5Fmethod=PLAINTEXT&oauth%5Ftimestamp=1252512419&oauth%5Fversion=1.0&oauth%5Ftoken=&oauth%5Fsignature=secret%2526 failed. status code: InternalServerError An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Source Error: [HttpException]: 'RequestToken' is not allowed here because it does not extend class 'System.Web.UI.Page'. at System.Web.UI.TemplateParser.ProcessError(String message) at System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) at System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) [HttpParseException]: 'RequestToken' is not allowed here because it does not extend class 'System.Web.UI.Page'. at System.Web.UI.TemplateParser.ProcessException(Exception ex) at System.Web.UI.TemplateParser.ParseStringInternal(String text, Encoding fileEncoding) at System.Web.UI.TemplateParser.ParseString(String text, VirtualPath virtualPath, Encoding fileEncoding) [HttpParseException]: 'RequestToken' is not allowed here because it does not extend class 'System.Web.UI.Page'. at System.Web.UI.TemplateParser.ParseString(String text, VirtualPath virtualPath, Encoding fileEncoding) at System.Web.UI.TemplateParser.ParseReader(StreamReader reader, VirtualPath virtualPath) at System.Web.UI.TemplateParser.ParseFile(String physicalPath, VirtualPath virtualPath) at System.Web.UI.TemplateParser.ParseInternal() at System.Web.UI.TemplateParser.Parse() at System.Web.UI.TemplateParser.Parse(ICollection referencedAssemblies, VirtualPath virtualPath) at System.Web.Compilation.BaseTemplateBuildProvider.get_CodeCompilerType() at System.Web.Compilation.BuildProvider.GetCompilerTypeFromBuildProvider(BuildProvider buildProvider) at System.Web.Compilation.BuildProvidersCompiler.ProcessBuildProviders() at System.Web.Compilation.BuildProvidersCompiler.PerformBuild() at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean noAssert) at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp, Boolean noAssert) at System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) at System.Web.UI.PageHandlerFactory.System.Web.IHttpHandlerFactory2.GetHandler(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) I've noticed the oauth_token GET parameter is empty. On tracing this, the error source is from the line 12 of Default.aspx.cs page: IToken requestToken = session.GetRequestToken(); protected void oauthRequest_Click(object sender, EventArgs e) { OAuthSession session = CreateSession(); IToken requestToken = session.GetRequestToken(); if (string.IsNullOrEmpty(requestToken.Token)) { throw new Exception("The request token was null or empty"); } Session[requestToken.Token] = requestToken; string callBackUrl = "http://localhost:" + HttpContext.Current.Request.Url.Port + "/Callback.aspx"; string authorizationUrl = session.GetUserAuthorizationUrlForToken(requestToken, callBackUrl); Response.Redirect(authorizationUrl, true); } While I'm not sure if this has to do with configuring the service endpoints but I'm running the consumer project from VS2008 and hosting the service on IIS. Please advice.

    Read the article

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