Wednesday, September 7, 2011

URL Rewriting in ASP.NET using global.asax and web.config

URL rewriting is very important for search engines like google, yahoo, etc. as we know website getting most of the traffic from search engines.


Here I am explaining 2 way to rewrite URL in asp.net.
URL rewrining using web.config and URL rewriting using global.asax


URL rewrining using web.config:
URL rewriting in web.config is only use for small number of pages. Here you have to rewrite every page manually in web.config. I am writing sample code for 4 urls.
xml version="1.0"?>
<configuration>
<urlMappings enabled="true">
 <add url="~/About-company.aspx"
   mappedUrl="~/index.aspx?id=1" />
 <add url="~/About-products.aspx"
   mappedUrl="~/index.aspx?id=2" />
 <add url="~/Contact-us.aspx" 
   mappedUrl="~/index.aspx?id=3" />
 <add url="~/our-team.aspx" 
   mappedUrl="~/index.aspx?id=4" />
 urlMappings>
. . .
configuration>



URL rewriting using global.aspx:


This very simple way and very use full. In this way we can rewrite N number of pages and there is no need extra server configuration. Only you have to use Application_BeginRequest event. Inside this event use Context.RewritePath method to set which URL will execute internally in code behind. Here is the code:

void Application_BeginRequest(object sender, EventArgs e)
{
 
// Get the current path
 
string CurrentURL_Path = Request.Path.ToLower();

 
if (CurrentURL_Path.StartsWith("/news/"))
 {
   CurrentURL_Path = CurrentURL_Path.Trim("/");
   
string NewsID = CurrentPath.Substring(CurrentPath.IndexOf("/"));
   
HttpContext MyContext = HttpContext.Current;
   MyContext.RewritePath(
"/news-show.aspx?News=" +  NewsID);
 }
}


In next article i will write about URL rewriting using HttpModule.

Wednesday, July 27, 2011

Url Routing MVC TUTORIAL

This tutorial covers an introduction to the MVC pattern using Visual Basic. It also includes a brief overview of the URL routing assumptions that are a foundation to the implementation of the pattern. A sample application is created to demonstrate the fundamentals of this new web-application model. Implementing business rules and testing is also covered. Finally, the use of two alternative view engines, Silverlight and XML Literals, is coverd.




What is ASP.NET MVC? 80 minute technical video for developers, building NerdDinner

Tuesday, June 21, 2011

Overview of ASP.NET MVC Routing

In this tutorial, we introduce an important feature of all ASP.NET applications ASP.NET MVC Routing call. The ASP.NET routing module is responsible for assigning incoming requests particular browser MVC controller actions. At the end of this tutorial, you will understand how the standard routing table maps requests to controller actions.

Using the default route table

When you create a new ASP.NET MVC, the application is configured to use ASP.NET Routing. ASP.NET routing is configured in two places.

First, ASP.NET routing is enabled on the file from the Web application configuration (Web.config file). There are four sections in the configuration file that are relevant for routing: the system.web section. httpModules, section system.web.httpHandlers, system.webserver.modules section and section system.webserver.handlers. Be careful not to delete these sections, because without these sections routing no longer work.

Second, and most importantly, a routing table is created in the application's Global.asax file. The Global.asax file is a special file that contains event handlers for the events of the life cycle of the ASP.NET application. The routing table is created during the application start event.

The file in Listing 1 contains the default Global.asax file for an ASP.NET MVC application.


Listing 1 - Global.asax.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801

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

}

protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}



When an MVC application first starts, the method Application_Start () is called. This method in turn calls the RegisterRoutes () method. The RegisterRoutes () creates the routing table.

The routing table contains a single default route (default name). The default route maps the first part of a URL for a driver name, the second segment of the URL of a controller action, and the third segment with a parameter named id.

Imagine you enter the following URL into the address bar of your browser:

/ Home/Index/3

Maps of the default route this URL for the following parameters:

controller = Home

action = index

id = 3

When you request the URL / Home/Index/3, the code runs as follows:

HomeController.Index (3)

The default route includes defaults for all three parameters. Failure to provide a driver, then the default parameters of the controller to the brokerage. Failure to provide an action, the default parameters of action for the value index. Finally, failure to provide an identifier, the id parameter defaults to an empty string.

Here are some examples of how the default route maps URLs to controller actions. Imagine you enter the following URL into the address bar of your browser:

/ Home

Because the default the default path, entering this URL will cause the index () class in Schedule 2 HomeController called.


Listing 2 - HomeController.cs

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index(string id)
{
return View();
}
}
}

In Listing 2, the class includes a method called HomeController Index () that accepts one parameter named ID. The URL / Home causes the index () to call an empty string as the parameter id.

Due to the way the MVC framework invokes the actions of the driver, the URL / Home also matches the index () HomeController class in Listing 3.


Listing 3 - HomeController.cs (Index action with no parameter)

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}


The index () method in Listing 3 does not accept any parameters. The URL / Home will make the index () to be called. The URL / Home/Index/3 also invokes this method (the ID is ignored).

The URL / Home also matches the index () HomeController class in Listing 4.


Listing 4 - HomeController.cs (Index action with nullable parameter)

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index(int? id)
{
return View();
}
}
}



In Listing 4, the method index () has an integer parameter. Because the parameter is nullable (can be set to zero), the index () can be called without causing an error.

Finally, invoking the index () method in Listing 5 to the URL / Home causes an exception as the parameter identification is not a parameter accepts null values. If you try to invoke the method index () then the error is show.


The URL / Home/Index/3 other hand, works very well with the controller action index List 5. Application / Home/Index/3 makes the method index () is called with a parameter ID that has the value 3.

Summary

The aim of this tutorial is to provide a brief introduction to ASP.NET Routing. We examined the routing table by default you get with a new ASP.NET MVC. He has learned default route maps URLs to controller actions.

Thursday, May 26, 2011

Seven Tips and Tricks Programming WPF

The Internet has much to offer in any topic and there is much to learn, but where to start? I realized many years ago, when I got intrigued by the Windows Presentation Foundation (WPF), short write-ups that help you acquire additional knowledge, which when combined can provide solutions to the bigger picture. This article provides a list of tips I learned a year ago, while scanning for simple solutions to big problems. javascript:void(0)


Use the list Visibility.Collapsed vs Visibility.Hidden 
The collapsed value ensures that the element is not involved in the design and gives you a zero height and width. The latter causes the element to continue to participate in the design. 


Reduce CPU consumption for animations to WPF 
As you know, WPF animations are based on 60 frames per second. You can reduce this to a lower optimal rate, resulting in less CPU usage. Use the timeline. DesiredFrameRateProperty to change the default, set to a lower value as 15, and then changes according to the smoothness you want.











Timeline.DesiredFrameRateProperty.OverrideMetadata(
                typeof(Timeline),
                new FrameworkPropertyMetadata { DefaultValue = 15 }



);





Default of Culture of the application for the Culture of the client machine 


WPF elements expose a property of language that can be used to map language as any culture. When this property is applied to a window, applies to all items it contains. See the sample code that applies the language of contemporary culture. The start function in the application class is an ideal place to implement this change through the application.









protected override void OnStartup(StartupEventArgs e)
{
FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(System.Globalization.CultureInfo.CurrentCulture.IetfLanguageTag)));



base.OnStartup(e);
}









Use StaticResource StaticResource vs DynamicResource are evaluated only once and only for the purpose. Dynamic resources assessment because each time they are requested by the control, and hence make the request to perform slower. Although this is a deferred execution time search makes sense if the action will not change 


The use of WPF Performance Suite to the profile of WPF applications 
WPF Performance Suite is available in the Windows SDK and is composed of a few important profiling tools that allow you to analyze the requests and provide information on the optimizations that can be applied. You can download from the Microsoft website. 


The driller and tools of Visual Profiler profiles give much information and also indicate potential bottlenecks in implementation. This suite is part of the Microsoft Windows SDK for Windows 7 and Vista. NET Framework 3. 5 SP1. 


Avoid design errors with the help of DesignerProperties. Method GetIsInDesignMode 
Most designers often break the "Could not create an instance" error. Although this is due to some unhandled exception occurs in the constructor's control, may not require the code execution at design time.






public SampleControlConstructor()
{
    InitializeComponent();
    if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
    {
        //place your code here.
    }
}




Use IsMouseDirectlyOver event to determine the exact mouse movement. 
The event IsMouseOver respond to mouse movement within a control or their children. 


IsMouseDirectlyOver use the event to determine if the mouse movement on the control and not their containers. This is useful for building the triggers specific change in mouse movement. 

Tuesday, May 24, 2011

Bind jQuery event handlers for this object CoffeeScript


Bind jQuery event handlers for this object CoffeeScript 

Friends have told me that the rich domain objects rarely does so using jQuery to improve performance in web pages. I myself have always loved dynamic JavaScript as a language rich first and something for the second DOM. So most of my client-side JavaScript is an object-oriented robust approach similar to Ruby. This is the main reason they have used Prototype.js for so long.

Since both jQuery and Rails CoffeeScript announced as the default in version 3.1, I decided it was time to start learning them. I had always known that jQuery linked keyword is in the event handlers to the DOM object. Something you are totally confused and unacceptable for someone working on their own objects to encapsulate behavior. Today I found two ways to deal with my problem, one way and one way CoffeeScript jQuery. First a code example.


class MyObject
  
  constructor: ->
    @myDomElement = $('#myDomElement')
    @._initBehavior


  handler: (event) ->
    console.log(this)
    false


  _initBehavior: ->
    $(window).resize @handler


jQuery ->
  window.myObject = new MyObject();


Here is a simple class using methods CoffeeScript. Is initialized with a static property this.myDomElement a DOM element on the page with the id "myDomElement." Then, you assign an event handler to the event of resizing the window and records this on the road. Simple things, the only problem is that the registered object will not be an instance of MyObject, but the raw DOM element, in this case the window object. One way to fix this is to use jQuery function as a proxy for


_initBehavior: ->
  $(window).resize jQuery.proxy(@handler,this)




This works but seems a little tedious for me and can clog up your initialization code of the event. The other way is to use the arrow operator CoffeeScript fat. An extract from the project page explains it well.

The fat arrow => can be used both to define a function, and linked to the current value of this, on the spot. This is useful when using callback libraries based on how Prototype or jQuery, to create a repeater function to pass each, or the event handler functions for use with link. Created with the arrow functions of fat are able to access the properties where they are defined. 
So all we have to do is change - of> = for any of our callbacks or event handlers, and now this is our own object and not the DOM element. Hot Damn! 


class MyObject
  
  constructor: ->
    @myDomElement = $('#myDomElement')
    @._initBehavior


  handler: (event) =>
    console.log(this)
    false


  _initBehavior: ->
    $(window).resize @handler


jQuery ->
  window.myObject = new MyObject();




Monday, May 23, 2011

Adding a Controller


Adding a Controller

MVC stands for model-view-controller. MVC is a pattern for developing applications that are well architected and easy to maintain. MVC-based applications contain:
  • Controllers: Classes that handle incoming requests to the application, retrieve model data, and then specify view templates that return a response to the client.
  • Models: Classes that represent the data of the application and that use validation logic to enforce business rules for that data.
  • Views: Template files that your application uses to dynamically generate HTML responses.
We'll be covering all these concepts in this tutorial series and show you how to use them to build an application.
Let's begin by creating a controller class. In Solution Explorer, right-click the Controllers folder and then select Add Controller.
Name your new controller "HelloWorldController". Leave the default template as Empty controller and clickAdd.
AddHelloWorldController
Notice in Solution Explorer that a new file has been created named HelloWorldController.cs. The file is open in the IDE.
Inside the public class HelloWorldController block, create two methods that look like the following code. The controller will return a string of HTML as an example.
using System.Web;
using System.Web.Mvc; 
 namespace MvcMovie.Controllers { 
    public class HelloWorldController : Controller 
    { 
        // 
        // GET: /HelloWorld/ 
 
        public string Index() 
        { 
            return "This is my default action..."; 
        } 
 
        // 
        // GET: /HelloWorld/Welcome/ 
 
        public string Welcome() 
        { 
            return "This is the Welcome action method..."; 
        } 
    } }
Your controller is named HelloWorldController and the first method above is named Index. Let’s invoke it from a browser. Run the application (press F5 or Ctrl+F5). In the browser, append "HelloWorld" to the path in the address bar. (For example, in the illustration below, it's http://localhost:43246/HelloWorld.) The page in the browser will look like the following screenshot. In the method above, the code returned a string directly. You told the system to just return some HTML, and it did!
ASP.NET MVC invokes different controller classes (and different action methods within them) depending on the incoming URL. The default mapping logic used by ASP.NET MVC uses a format like this to determine what code to invoke:
/[Controller]/[ActionName]/[Parameters]
The first part of the URL determines the controller class to execute. So /HelloWorld maps to theHelloWorldController class. The second part of the URL determines the action method on the class to execute. So /HelloWorld/Index would cause the Index method of the HelloWorldController class to execute. Notice that we only had to browse to /HelloWorld and the Index method was used by default. This is because a method named Index is the default method that will be called on a controller if one is not explicitly specified.
Browse to http://localhost:xxxx/HelloWorld/Welcome. The Welcome method runs and returns the string "This is the Welcome action method...". The default MVC mapping is /[Controller]/[ActionName]/[Parameters]. For this URL, the controller is HelloWorld and Welcome is the action method. You haven't used the[Parameters] part of the URL yet.
Let's modify the example slightly so that you can pass some parameter information from the URL to the controller (for example, /HelloWorld/Welcome?name=Scott&numtimes=4). Change your Welcome method to include two parameters as shown below. Note that the code uses the C# optional-parameter feature to indicate that the numTimes parameter should default to 1 if no value is passed for that parameter.
public string Welcome(string name, int numTimes = 1) {
     return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes);
}
Run your application and browse to the example URL (http://localhost:xxxx/HelloWorld/Welcome?name=Scott&numtimes=4). You can try different values for name and numtimes in the URL. The system automatically maps the named parameters from the query string in the address bar to parameters in your method.
In both these examples the controller has been doing the "VC" portion of MVC — that is, the view and controller work. The controller is returning HTML directly. Ordinarily you don't want controllers returning HTML directly, since that becomes very cumbersome to code. Instead we'll typically use a separate view template file to help generate the HTML response. Let's look next at how we can do this.

Related link