C# Change my sitemap from ashx to xml - c#

My sitemap is at: http://localhost/scirranew/sitemap.ashx
<%# WebHandler Language="C#" Class="SiteMap" %>
using System;
using System.Web;
public class SiteMap : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/xml";
}
public bool IsReusable {
get {
return false;
}
}
}
As far as I know, google will be OK with this. But I would like it to be a .xml filetype for consistency throughout my site.
I've tried rewriting the URL:
<rewrite url="^~/Sitemap.xml" to="~/SiteMap.ashx" processing="stop"/>
But this doesn't work with the .xml extension.

Instead of using an ashx file, just put the code in an assembly and register the handler in web.config with any extension you like:
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="Sitemap.xml"
type="SiteMap, AssemblyContainingClass" />
</httpHandlers>
</system.web>
</configuration>

Related

Can't use codeblock in control property

The abstract problem: I'm trying to limit user input in text fields to the same as the database length of the column. So I want to set a maxlength attribute on an html input, and the maxlength should be the same as the max length allowed in the database. I could hardcode these constants throughout the frontend, but I'm trying to set that value dynamically.
The problem: telerik RadComboBox won't accept an asp code block to set a property. The exception is as follows:
Parser Error
Description: 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.
Parser Error Message: Cannot create an object of type 'System.Int32' from its string representation '<% Utility.GetColumnMaxLength<Portfolio>(x => x.Title) %>' for the 'MaxLength' property.
I've created a new minimal asp.net project to duplicate the problem. default.aspx source (no .cs code behind):
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TelerikCodeBlock._Default" %>
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<%# Import namespace="TelerikCodeBlock" %>
<%# Import namespace="TelerikCodeBlock.DataModel" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<telerik:RadComboBox ID="txtboxTitle" runat="server" MaxLength="<% Utility.GetColumnMaxLength<Portfolio>(x => x.Title) %>" >
</telerik:RadComboBox>
</asp:Content>
The Utility class has been minimized to the following
namespace TelerikCodeBlock
{
public class Utility
{
public static int GetColumnMaxLength<T>(Expression<Func<T, object>> property)
{
// looks at Entity Framework metadata in real project ...
return 3;
}
}
}
Data model looks like
namespace TelerikCodeBlock.DataModel
{
public class Portfolio
{
public int Id { get; set; }
public string Title { get; set; }
}
}
Possible workaround: using ASP.NET Expressions (the <%$ ... %> code blocks), build a general expression that executes code, as outlined here.
Add a reference to Microsoft.CodeDom.Providers.DotNetCompilerPlatform.
Define the following somewhere:
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using System.Web.UI;
namespace TelerikCodeBlock
{
[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context)
{
return new CodeSnippetExpression(entry.Expression);
}
}
}
And register it in the web.config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" >
<expressionBuilders>
<add expressionPrefix="Code" type="TelerikCodeBlock.CodeExpressionBuilder"/>
</expressionBuilders>
</compilation>
...
Now change the asp control to use the expression code block:
<telerik:RadComboBox ID="txtboxTitle" runat="server" MaxLength="<%$ Code: Utility.GetColumnMaxLength<Portfolio>(x => x.Title) %>" >

Programmatically change the page redirection in web config

Hi i want to change the Page redirection in webconfig programmatically.
i have following code in web config.
<location path="WebForm2.aspx">
<system.webServer>
<httpRedirect enabled="true" destination="http://google.com" httpResponseStatus="Permanent" />
</system.webServer>
</location>
i want to enable or disable the httpredirect programmatically using c#.
please suggest me how to do this.
I've tried the code suggested by Rahul but I wasn't able to change the <location> element of the Web.config programatically.
As an alternative you could write an HttpHandler to intercept the request to the WebForm2.aspx page and redirect the user to another URL:
Handler:
namespace StackOverflowHelp
{
public class RedirectHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
Uri uri = context.Request.Url;
if (uri.AbsolutePath == "/WebForm2.aspx.aspx")
context.Response.Redirect("http://google.com");
}
}
}
Handler registration in the Web.config:
<system.webServer>
<handlers>
<add verb="*" path="WebForm2.aspx"
name="RedirectHandler"
type="StackOverflowHelp.RedirectHandler"/>
</handlers>

IRouteHandler not routing through RouteConfig

I have a IRouteHander class which I use to resize images on the fly and add expire headers to them, Recently I moved to MVC5 and now updating my code. I tried to register the same route for that class in RouteConfig.cs
routes.Add(new Route("Image/{w}/{h}/{src}", new ThumbImageRouteHandler()));
but this route isn't working anymore like it was on MVC3 and giving 404 error in MVC5. Is there anything I am missing here? this route leads to
public class ThumbImageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
HttpHanler httpHandler = new HttpHanler();
return httpHandler;
}
public class HttpHanler : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
//Do something
}
}
}
}
Please help me fixing this issue. Thanks
After research I found out that I need to add a line in webconfig in order to make it work, here's how.
<system.webServer>
<handlers>
<add name="ApiURIs-ISAPI-Integrated-4.0-Image" path="/Image/*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Because IRouteHandler is generating re-sized images with a dynamic path, and IIS thinks this is the actual path to a directory because of dot(.) in the link and it thinks it's an extension, which is actually not. So we have to add a handler in Web.Config to make it work.

How can I turn customErrors mode on ASP.NET MVC4?

I am very new to ASP.NET MVC4 and am taking a course on the topic. I have a very minor issue with error handling. When the instructor adds <customErrors mode = "On"/> to the web.config file in the <system.web> tag, he is redirected to the friendly error page (instead of the stack trace).
When I make this change, I am still directed to the stack trace "yellow page of death".
Since I am making a concerted effort to understand this as thoroughly as possible, I thought I'd ask here. Why does turning <customErrors mode="On"/> work for the instructor and not me?
Here is my <system.web> tag:
<system.web>
<customErrors mode="On"/>
<httpHandlers>
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
</system.web>
And here is my Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace OdeToFood
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
}
And finally, my FilterConfig.cs
using System.Web;
using System.Web.Mvc;
namespace OdeToFood
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
I currently have the default view Error.cshtml.
I also tried
<customErrors mode="On" defaultRedirect="Error"/>
and
<customErrors mode="On" defaultRedirect="~/Error.cshtml"/>
I am using this code to force the error:
public class CuisineController : Controller
{
//
// GET: /Cuisine/
public ActionResult Search(string name = "french")
{
throw new Exception("Something terrible has happened");
var message = Server.HtmlEncode(name);
return Content(message);
}
}
}
As you can tell, I'm very new to this so my apologies if this is a frivolous question but I am trying to learn as best I can.
You still need to make an error page. For example,
Web.config
<system.web>
...
<customErrors defaultRedirect="~/Common/Error" mode="On"/>
</system.web>
CommonController
public class CommonController : Controller
{
// Error
public ActionResult Error()
{
this.Response.StatusCode = 503;
this.Response.TrySkipIisCustomErrors = true;
return View();
}
}
~/Views/Shared/Error.cshtml
#{
ViewBag.Title = "Error";
}
<h2>#ViewBag.Title</h2>
<p>
Error ...
</p>

MVC4 Hiding links with a custom AuthorizeAttribute

I've been digging around for a while now trying to figure out how to use my custom AuthorizeAttribute class in my view to show and hide links. I'm transitioning from IsInRole to the custom AuthorizeAttribute because I want the end user to select which groups are authorized to perform certain tasks. Up to this point I've been using:
#{ if (HttpContext.Current.User.IsInRole("UserMgr"))
{ Html.ActionLink("Edit", "Edit", new { id = item.pkRecID }); }
}
Where UserMgr is a domain group. (this does work but is not what I need to do)
I then created a custom AuthorizeAttribute class:
public class isAuthorized : AuthorizeAttribute
{
public string Access { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
string[] aszList = Access.Split(',');
if (!authorized)
{
// The user is not authenticated
return false;
}
var user = httpContext.User;
if (user.IsInRole("Admin"))
return true;
var rd = httpContext.Request.RequestContext.RouteData;
var id = rd.Values["id"] as string;
if (string.IsNullOrEmpty(id))
{
// Now id was specified => we do not allow access
return false;
}
foreach (string szGroup in aszList) // check to see if user is in group
{
if (user.IsInRole(szGroup))
{
return true;
}
}
return false;
}
This works in my controller to block access to functions but how do I hide links in my views using this function?
Thanks!
You could create an extension method, so you can apply it on the MvcHtmlStrings in your Cshtml file
Example:
public static IHtmlString If(this IHtmlString value, bool evaluation)
{
return evaluation ? value : MvcHtmlString.Empty;
}
Then on your html Element you can use it like this:
#Html.ActionLink("Reports", "Index", "Report").If(User.IsInRole("SuperAdmin"))
UPDATE
Steps:
Create a new static class in your project.
Add the suggested extension method to the newly created class.
To make this static class available in all cshtml views go to the webconfig located in the Views folder.
Again pay attention so that the web config is in the views folder, do NOT edit the one thats at the root of your app.
There add the namespace where your static class is located just like in the example below.
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="YourApplication.Utils"/> <!-- THIS IS THE EXAMPLE ON HOW TO INSERT THE NAMESPACE THAT CONTAINS YOUR STATIC CLASS -->
<add namespace="Microsoft.Web.Helpers"/>
</namespaces>
</pages>
</system.web.webPages.razor>
I cant explain it better then this.

Categories