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();
        }
    }

   

Saturday, January 30, 2010

Localization Overview

Globalization is the first step in the process of creating a world-ready application. In this step, the application's executable code is written. A truly global application should be culture-neutral and language-neutral. Therefore, you should focus attention on creating an application that will be able to support localized user interfaces and regional data for all users. Note that although a globalized application has this flexibility, the globalization process itself does not involve translating the user interface. Instead, you should strive to create an application with functionality that works equally well for users from all cultures and regions your application supports.

For each localized version of your application, add a new satellite assembly that contains the localized user interface block translated into the appropriate language for the target culture. The code block for all cultures should remain the same. The combination of a localized version of the user interface block with the code block produces a localized version of your application.

Kinds of Resources in the Hierarchy

  • At the top of the hierarchy sit the fallback resources for your default culture, for example English ("en"). These are the only resources that do not have their own file; they are stored in the main assembly.
  • Below the fallback resources are the resources for any neutral cultures. A neutral culture is associated with a language but not a region. For example, French ("fr") is a neutral culture. (Note that the fallback resources are also for a neutral culture, but a special one.)
  • Below those are the resources for any specific cultures. A specific culture is associated with a language and a region. For example, French Canadian ("fr-CA") is a specific culture.
Localization Best Practices
  • Move all localizable resources to separate resource-only DLLs. Localizable resources include user interface elements, such as strings, error messages, dialog boxes, menus, and embedded object resources.
  • Do not hardcode strings or user interface resources.
  • Do not put nonlocalizable resources into the resource-only DLLs. This causes confusion for translators.
  • Do not use composite strings that are built at run time from concatenated phrases. Composite strings are difficult to localize because they often assume an English grammatical order that does not apply to all languages.
  • Avoid ambiguous constructs such as "Empty Folder" where the strings can be translated differently depending on the grammatical roles of the string components. For example, "empty" can be either a verb or an adjective, which can lead to different translations in languages such as Italian or French.
  • Avoid using images and icons that contain text in your application. They are expensive to localize.
  • Allow plenty of room for the length of strings to expand in the user interface. In some languages, phrases can require 50-75 percent more space than they need in other languages.
  • Use the System.Resources..::.ResourceManager class to retrieve resources based on culture.
  • Use Visual Studio 2008 to create Windows Forms dialog boxes, so that they can be localized using the Windows Forms Resource Editor (Winres.exe). Do not code Windows Forms dialog boxes by hand.
  • Arrange for professional localization (translation).

Thursday, January 28, 2010

From DataGrid to Gridview Web Server Controls

The GridView control is the successor to the DataGrid control. Like the DataGrid control, the GridView control was designed to display data in an HTML table. When bound to a data source, the DataGrid and GridView controls each display a row from a DataSource as a row in an output table.

Differences between the GridView control and the DataGrid control include:
  • Different custom-paging support.
  • Different event models.

Both the DataGrid and GridView controls are derived from the WebControl class. Although it has a similar object model to that of the DataGrid control, the GridView control also has a number of new features and advantages over the DataGrid control, which include:
Richer design-time capabilities.
  • Improved data source binding capabilities.
  • Automatic handling of sorting, paging, updates, and deletes.
  • Additional column types and design-time column operations.
  • A Customized pager user interface (UI) with the PagerTemplate property.
Improved Design-Time Capabilities

Sorting, paging, and in-place editing of data requires additional coding when using the DataGrid control. The GridView control enables you to add sorting, paging, and editing capabilities without writing any code. Instead, you can automate these tasks, along with other common tasks such as data binding to a data source, by setting properties on the control.

If you are working in a designer, such as Microsoft Visual Studio, you can take advantage of designer features built into the GridView control. The GridView control includes support for a smart tag panel that provides a convenient interface for performing common tasks, such as setting properties and launching template editing.


Typically a DataSet control, a DbDataReader control, or a collection, such as an Array, an ArrayList, or some other class in the System.Collections namespace, is assigned to the DataSource property of either the DataGrid control or the GridView control. The DataGrid control and the GridView control can bind any object that implements the IEnumerable or IListSource interface.

While the DataGrid control can declaratively bind a DataSourceControl control, it can do so only for data selection. Sorting, paging, updates, and deletions must be coded manually. The GridView control supports a DataSourceID property that takes any object that implements the IDataSource interface and can, therefore, take advantage of the data source control's sorting, paging, updating, and deleting capabilities, for example, the SqlDataSource control.
Additional Column Types

The GridView control supports the following column types: BoundField, HyperLinkField, ButtonField, CommandField ImageField, and CheckBoxField.
Built-In and Custom Paging Support

The DataGrid control requires additional coding for paging. The GridView control automatically supports paging by setting the PagerSettings property. The PagerSettings property supports four modes: Numeric (default), NextPrevious, NumericFirstLast, and NextPreviousFirstLast. The Numeric mode displays numbered page links instead of "next/prev" links, and the NumericFirstLast option adds first and last page links. The GridView control's PagerStyle property can be used to set styles and the position of the pager.

Additionally, you can customize the pager buttons for the GridView control using a PagerTemplate.

Custom paging support in the GridView is supplied by the bound data source control as opposed to the AllowCustomPaging mechanism supplied by the DataGrid control.
Expanded Event Model

The DataGrid and the GridView controls have different event models.

The DataGrid control raises single events for operations, while the GridView control is capable of both pre-operation and post-operation events. The GridView control supports the Sorting event that occurs when a field is sorted. Note that this sorting event occurs before the GridView control automatically handles the sort operation, giving you the opportunity to examine or change the SortExpression property, or cancel this operation by setting the Cancel property to true on the passed event arguments.

The GridView control supports the Sorted event that occurs after the GridView control completes the sort operation, giving you the opportunity to change or format the result of the sort operation. In comparison, the DataGrid control supports the SortCommand event that occurs when a column is sorted. Similarly, the GridView control supports RowUpdating and RowUpdated events that occur before and after the GridView control has automatically handled the update operation. In comparison, the DataGrid control supports the UpdateCommand event that occurs when the Update button is clicked for an item in the grid.


Wednesday, January 27, 2010

How Web Resources work

Web Resources rely on a special handler that is named WebResource.axd, which is designed to retrieve assembly resources and serve them to the Web browser. The handler type for WebResource.axd is AssemblyResourceLoader.

When a request comes in from the client for WebResource.axd, the handler looks for the Web Resource identifier in the QueryString method of the Request object. Based on the value of the Web Resource identifier, the handler then tries to load the assembly that contains this resource. If this operation is successful, the handler will then look for the assembly attribute and load the resource stream from the assembly. Finally, the handler will grab the data from the resource stream and send it to the client together with the content type that you specify in the assembly attribute.

The URL for WebResource.axd looks like the following:
WebResource.axd?d=SbXSD3uTnhYsK4gMD8fL84_mHPC5jJ7lfdnr1_WtsftZiUOZ6IXYG8QCXW86UizF0&t=632768953157700078

The format of this URL is WebResource.axd?d=encrypted identifier&t=time stamp value. The "d" stands for the requested Web Resource. The "t" is the timestamp for the requested assembly, which can help in determining if there have been any changes to the resource.
Delving into the code
In my example, I have developed a COM control that is consumed by an ASP.NET Web application to demonstrate this new feature.
COM control for the Web Resource
For creating and embedding a Web Resource, I have developed a COM control (SimpleControl). It has the following embedded resources:

* Two image files that are named smallFail.gif and smallSuccess.gif. These image files are used for rollover effects in the control and are consumed within the control code.
* An HTML file that is named Help.htm. This file does not contain much text and is just for demonstration.
* One JavaScript file that is named MyScript.js. This file contains some JavaScript code which also demonstrates the substitution feature to get a reference to another embedded resource within the same assembly.
* One .css file that is named MyStyleSheet.css. This style sheet is then consumed directly from the ASP.NET Web application.

In this article, I will discuss the parts that are required for Web Resources.
Embedding the Web Resources
First, you have to make sure that all the static files that are added to the Web Control Library project in Microsoft Visual Studio 2005 are embedded resources. To embed these resources, all that you have to do is add these files to Visual Studio and then modify the properties of these files so that the build action is set to Embedded Resource.

After you have done this, you also have to make sure that these resources have been referenced by the WebResource assembly attribute in the AssemblyInfo.cs
he WebResource assembly attribute has three parameters as follows:

* Web Resource: The name of the resource that is embedded in the assembly
* ContentType: The MIME file type for the resource
* PerformSubstitution: A Boolean value that determines whether other Web Resource URLs that are referenced in this resource are parsed and replaced with the full path of the resource

Fetching the Web Resources
For getting the Web Resource, I have used the GetWebResourceUrl method, which is a method of the ClientScriptManager class that is typically used for managing client-side scripts. This method returns a URL reference to the server-side resource that is embedded in an assembly. The GetWebResourceUrl method accepts the following two parameters:

* Type: The type of the server-side resource
* Resource Name: The name of the server-side resource

To use this method, first you have to create an instance of the ClientScriptManager class and get the type of the class as shown below.
ClientScriptManager cs = Page.ClientScript;
Type rsType = this.GetType();

ASP.NET MapPath

MapPath is used to resolve virtual paths and physical paths. You run the ASP.NET development server on your local machine, but the paths on it are not the same as they are on your server. Here we use MapPath to find physical paths and file locations, using the C# programming language.

What is MapPath?
First, in ASP.NET the ~ tilde indicates the root of a virtual path. We need the tilde because otherwise ASP.NET can't figure out if a path is absolute or relative. Let's look at some virtual paths and what they might map to.

Virtual paths: ~/App_Data/test.xml
~/
~/Mapfile.txt

Physical paths: C:\Website\Files\test.xml
C:\Website\Default.aspx
C:\Website\Mapfile.txt
Virtual hosts security

Here we note that if you are using a virtual shared host, there may be problems in your code related to file permissions and security checks. The problem may not be MapPath at all. In fact, MapPath is very simple and unless you have a typo in the argument, it won't cause you any problems

Difference of Server.MapPath and Page.MapPath

both map a virtual path to a physical one..

Page.MapPath: -

Retrieves the physical path that a virtual path, either absolute or relative, or an application-relative path maps to..

Server.MapPath: -

Each file on a Web server has two ways of being accessed - through a virtual path and through a physical path. The virtual path is the path one would enter into their browser's Address bar, for example:

http://www.yourserver.com/someDirectory/someFile.asp

The bold part of the URL above is referred to as the virtual path. The physical path is the actual drive, directory, and filename of a particular file on the Web server. For example, on your computer, if you run Windows 9X, your Win.ini file's physical path is C:\WINDOWS\WIN.INI (assuming you installed Windows on your C: drive).