Tuesday, October 19, 2010

How to strip HTML and special character from string.

I have created following function to strip or remove HTML and specail character from string.
Regular Expression for special character:([^\w\+\-\\\/_ ])
Regular Expression for HTML strip:<(.\n)+?>

-------------Code--------------------
public static string StripHTMLAndSpecialChars(string sHTML)
{
string strOutput = StripHTML(sHTML);
System.Text.RegularExpressions.Regex objRegExp = new System.Text.RegularExpressions.Regex(@"([^\w\+\-\\\/_ ])");
//Replace all characters other than ones specified above
strOutput = objRegExp.Replace(strOutput, "");
objRegExp = null;
return strOutput;
}

----------------Function to strip HTML-----------------
public static string StripHTML(string sHTML)
{
string strOutput;
System.Text.RegularExpressions.Regex objRegExp = new System.Text.RegularExpressions.Regex("<(.
\n)+?>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//Replace all HTML tag matches with the empty string
strOutput = objRegExp.Replace(sHTML, "");
objRegExp = null;
return strOutput;
}

-----------------------------

Monday, October 18, 2010

Capature exception or crashes in asp.net application.

we ca capature exception or crashes that are generated




1-you have added try catch blocks and in catch block you can easily get the text of exception like



try



{



}



catch(Exception ex)



{



//insert exception in db or any log file (ex.tostring())





}



2-There are exception that are not handled through try catch block you can easily get those as well



on global_asax there is an event Application_Error you can use it for exception locking





void Application_Error(object sender, EventArgs e)

{

foreach (Exception ex in Context.AllErrors)

// insert in log or db file;



}



3.There is another way you store your Unhandled exception just add an event handler on global.asax



void Application_Start(object sender, EventArgs e)

{



AppDomain.CurrentDomain.UnhandledException +=newUnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

}



void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)

{

// store to (e.ExceptionObject as Exception);



}

Allow hyphens in URL’s using ASP.NET MVC 2

If you wan’t to allow hyphens in your URL’s you will need to change the way the routing works in your Global.asax file.

First create a new class which extends the MvcRouteHandler and place this in the Global.asax file after the main MvcApplication class.

-----------------Changes in Global.asax-----------------------
public class HyphenatedRouteHandler : MvcRouteHandler{

protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
return base.GetHttpHandler(requestContext);
}

}
--------------------------End----------------------
 
Then you need to replace the routes.MapRoute with an equivalent routes.Add specifying the new handler as the MapRoute does not allow you to specify a custom route handler.


routes.Add(
new Route("{controller}/{action}/{id}",
new RouteValueDictionary(
new { controller = "Default", action = "Index", id = "" }),
new HyphenatedRouteHandler())
);

Main advantages of ASP.net MVC.

  • Separation of concerns (SoC) • From a technical standpoint, the organization of code within MVC is very clean, organized and granular, making it easier (hopefully) for a web application to scale in terms of functionality. Promotes great design from a development standpoint.
  • Easier integration with client side tools (rich user interface tools) • More than ever, web applications are increasingly becoming as rich as the applications you see on your desktops. With MVC, it gives you the ability to integrate with such toolkits (such as jQuery) with greater ease and more seamless than in Web Forms.
  • Search Engine Optimization (SEO) Friendly / Stateless • URL's are more friendly to search engines (i.e. mywebapplication.com/users/ 1 - retrieve user with an ID of 1 vs mywebapplication/users/getuser.aspx (id passed in session)). Similarly, since MVC is stateless, this removes the headache of users who spawn multiple web browsers from the same window (session collisions). Along those same lines, MVC adheres to the stateless web protocol rather than 'battling' against it.
  • Works well with developers who need high degree of control • ASP.NET web forms automatically generates much of the raw HTML you see when an page is rendered. This can cause headaches for developers. With MVC, you have complete control over what is rendered and there are no surprises. Even more important, is that the HTML forms typically are much smaller than the Web forms which can equate to a performance boost - something to seriously consider.
  • Test Driven Development (TDD) • With MVC, you can more easily create tests for the web side of things. An additional layer of testing will provide yet another layer of defense against unexpected behavior.

Stop non-HTML file (for example, a downloadable PDF) from appearing in search results


The first step requires the webmaster to make a change. If you own the site, you'll need to do ONE of the actions listed below. If you don't own the site, contact the webmaster and request that one of these changes be made. (If one of these changes isn't made, you will not be able to use this tool to process your removal request.)
  • If the page no longer exists, make sure that the server returns a 404 (Not Found) or 410 (Gone) HTTP status code. This will tell Google that the page is gone and that it should no longer appear in search results.
  • If the page still exists but you don't want it to appear in search results, use robots.txt to prevent Google from crawling it. Note that in general, even if a URL is disallowed by robots.txt we may still index the page if we find its URL on another site. However, Google won't index the page if it's blocked in robots.txt and there's an active removal request for the page.
  • Alternatively, you can use a noindex meta tag. When we see this tag on a page, Google will completely drop the page from our search results, even if other pages link to it. This is a good solution if you don't have direct access to the site server. (You will need to be able to edit the HTML source of the page).
In addition, if you want a non-HTML file (for example, a downloadable PDF) to be removed from search results, you or the webmaster should ensure that the file is removed from the server. Once it's gone, use the process below to request that the page is completely removed from search results.

If you own the site

  1. Verify your ownership of the site in Webmaster Tools.
  2. On the Webmaster Tools home page, click the site you want.
  3. On the Dashboard, click Site configuration in the left-hand navigation.
  4. Click Crawler access, and then click Remove URL.
  5. Click New removal request.
  6. Type the URL of the page you want removed from search results (not the Google search results URL or cached page URL), and then click Continue. How to find the right URL. Note that the URL is case-sensitive—you will need to submit the URL using exactly the same characters and the same capitalization that the site uses.
  7. Click Remove page from search results and cache.
  8. Select the checkbox to confirm that you have completed the requirements listed in this article, and then click Submit Request.

If you don't own the site

  1. Go to http://www.google.com/webmasters/tools/removals.
  2. If you're not immediately taken to the 'Create a new request' page, click New Removal Request.
  3. Type the URL of the webpage you want removed (not the Google search results URL or cached page URL). Note that the URL is case-sensitive—you will need to submit the URL using exactly the same characters and the same capitalization that the site uses. How to find the right URL. Click Continue.
  4. Click Webmaster has already blocked the page.
  5. Select the checkbox to confirm the requirements listed in this article have been completed, and then click Submit Request.
Source:http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=164734&from=61062&rd=1

6 Ways to stop your content appears in search engines

  1. Use a robots.txt robots exclusion file.
  2. Use “noindex” page meta tags.
  3. Password protect sensitive content.
  4. Nofollow: tell search engines not to spider some or all links on a page.
  5. Don’t link to pages you want to keep out of search engines.
  6. Use X-Robots-Tag in your http headers.

Thursday, October 14, 2010

Custom Authorization With Asp.net MVC

Authorization is a very important and every web project has there own needs and requirements. Full customisation is paramount.
Here I will show you a simple way to customise your authorization.
------------------------------CLASS BODY-----------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace auth
{
    public class AuthoriseUserAttribute : AuthorizeAttribute
    {
        private int _kind;
        private int _accessId;
        public int Kind
        {
            get { return _kind; }

            set { _kind = value; }
        }
        public int AccessId
        {
            get { return _accessId; }

            set { _accessId = value; }
        }
        public enum AuthorizeType
        {
            System_Rights = 0,
            Master_Rights = 1,
            Document_Rights = 2,
            Category_Rights = 3
        }
        public AuthoriseUserAttribute(int Pkind, int PaccessId)
        {
            Kind = Pkind;
            AccessId = PaccessId;
        }
        public AuthoriseUserAttribute(int Pkind, int PaccessId, int userId)
        {
            Kind = Pkind;
            AccessId = PaccessId;
        }
        public AuthoriseUserAttribute(int Pkind)
        {
            Kind = Pkind;
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {

            base.OnAuthorization(filterContext);

        }
/////////////This method is used for all checks////////////////////////
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.User.Identity.IsAuthenticated)   ///First check User is login
                return false;
            if (Kind == Convert.ToInt32(AuthorizeType.Master_Rights) && httpContext.User.Identity.IsAuthenticated)
            {
                ////Check Users Rights if found ok
                return true;
            }
            else
            {
                ///Redirect to no access page
                ///
                return false;
            }
        }

    }
}

----------------------------END CLASS------------------------------------------


----------------------------CUSTOM ATTRIBUTE CALL------------------------
      [AuthoriseUser(0, 1)]
        public ActionResult Index()
        {
            ViewModel.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        [AuthoriseUser(1, 1)]
        public ActionResult About()
        {
            return View();
        }
    }