Monday, October 31, 2011

Logging in MVC Part 5 – The Model and Data Layer

Introduction

This is the 5th article in a series on MVC logging.
Our sample website now has Elmah, NLog, Log4Net and Health monitoring set up and working. Now it is time to start work on our log reporting website by tying them all together.

Preparing the database

ASP.NET Health Monitoring logs a lot of different types of messages but there is no way to differentiate whether a message is just for information purposes or whether it is an error message that may need attention. So to address this issue, let’s create a new table called “aspnet_WebEvent_ErrorCodes” and introduce a column called “Level” which will map each message eventcode to either “Info”, “Error”.
The reason for doing this is so that we have a common “Level” attribute that we can use for all of our logging providers and this will allow us to later on filter all messages by their Log Level. Elmah for example will only be used to log unhandled exceptions so the LogLevel for our Elmah messages will always be “Error”.
Here is the database script necessary to add the new table to our database:
/****** Object:  Table [dbo].[aspnet_WebEvent_ErrorCodes]   
Script Date: 07/29/2010 09:56:45 ******/
IF  EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[aspnet_WebEvent_ErrorCodes]') 
AND type in (N'U'))
DROP TABLE [dbo].[aspnet_WebEvent_ErrorCodes]
GO
/****** Object:  Default [DF_aspnet_WebEvent_ErrorCodes_Level]    
Script Date: 07/29/2010 09:56:45 ******/
IF  EXISTS (SELECT * FROM sys.default_constraints 
WHERE object_id = OBJECT_ID(N'[dbo].[DF_aspnet_WebEvent_ErrorCodes_Level]') 
AND parent_object_id = OBJECT_ID(N'[dbo].[aspnet_WebEvent_ErrorCodes]'))
Begin
IF  EXISTS (SELECT * FROM dbo.sysobjects 
WHERE id = OBJECT_ID(N'[DF_aspnet_WebEvent_ErrorCodes_Level]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[aspnet_WebEvent_ErrorCodes] 
DROP CONSTRAINT [DF_aspnet_WebEvent_ErrorCodes_Level]
END

End
GO

Logging in MVC Part 4 – Log4Net

Introduction

In this article we will quickly add Log4Net into the website so that later on we can decide whether to use Log4Net or NLog to log our custom messages.
Log4Net is a very widely used logger and it is quite likely that you have 3rd party dependencies in your website that already use Log4Net so it can be a good idea to track any messages that it logs.

Log4Net

The steps we need to follow are:
1. Download Log4Net
2. Add a reference to Log4Net
3. Add a table in our database to store the Log4Net logs
4. Modify the web.config file for Log4Net
5. Implement a Log4NetLogger that implements our ILogger interface.

Logging in MVC Part 3 – NLog

Introduction

In the previous article we implemented Health Monitoring into our MVC website.
Now we need to provide a way to log our own custom messages so that we can keep track of important events that occur throughout our website.
For example, you may need to log information before and after a financial transaction has occurred on your eCommerce website.
It is easy to write your own logger but as there are already many established logging frameworks already available for .NET I’ve decided to concentrate on 2 of the most popular ones: Log4Net and NLog.
In this article we will concentrate on setting up NLog and in the next article we will take a look at Log4Net.

NLog

Prior to working on this series I had never ever used NLog - I’ve always used Log4Net. However, after spending some time on Rob Connerys blog and looking at his MVC Storefront series and his MVC starter kit I decided to look at NLog so that I have another logging framework in my utility belt. It’s always good to broaden your knowledge and learn a new skill or master a new toolkit.
So what follows is pretty much exactly what Rob Conery did for his MVC starter kit website. However I have extended the default NLog functionality by including 2 new layout renderers.
Here are the steps we need to take to integrate NLog into our website:
1. Download NLog.
2. Create a table in our database to store the NLog messages.
3. Configure our NLog configuration file.
4. Set up a logging interface for our website.
5. Implement an NLog logger that uses our interface to log messages to the database table in step 2.
6. Add some additional layout renders that we will need for NLog.
Let’s tackle each one in order.

Logging in MVC Part 2 – Health Monitoring

Introduction

This is the second article in a series. The first article showed how to set up ELMAH to run on an MVC website.
The main focus of ELMAH is to log unhandled exceptions but there are many events that it can’t log for us. That is where ASP.NET Health monitoring comes in!

Health Monitoring

To log such things as when a website starts up, shuts down, recompiles etc the best tool to use is ASP.NET Health Monitoring. Health monitoring is closely tied to the ASP.NET runtime and can log many events that happen on your website:
For those not familiar with what Health Monitoring here is a list of events that can be tracked using it:
* Application starts and stops
* Failed logins and unhandled exceptions
* “Heartbeats”
* Successful and failed login attempts through Membership
* Successful and failed URL and ACL authorizations by authenticated users
* Valid and expired forms authentication tickets
* View state validation failures
* Compilation errors
* Configuration errors
* Unhandled exceptions
* Request validation failures
* Anything that causes request to abort
* Requests queued, processing, or rejected
* Specific or periodic monitoring event
* Process start time and more
One of the best articles to get started with Health Monitoring is the official page here:
http://www.asp.net/hosting/tutorials/logging-error-details-with-asp-net-health-monitoring-cs

Logging in MVC Part 1- Elmah

Introduction

Logging is one of the most useful services that every production website should have.
When errors occur on your website you should be notified about them. Whilst you may think you have written perfect code and unit tested everything to the best of your ability errors can and will still happen. The database server may go down, a 3rd party website may be offline, the shared hosting environment of your website may suffer an outage, a previously undetected bug may occur and the list goes on.
Having a great logging system in place allows you to stay on top of errors when they do happen.
In this series we will be building a logging reporting system that will allow you to drill into the various events that get logged on your website.
Before we get started let’s take a look at the finished solution:

and we would also like to see some graphs so we can quickly pinpoint when errors occurred on our website:





Understanding ASP.NET MVC (Model View Controller) Architecture for Beginners

Introduction

This article is intended to provide basic concepts and fundamentals of ASP.NET MVC (Model View Controller) architecture workflow for beginners.
“M” “V” “C” stands for “MODEL” “VIEW” “CONTROLLER”. ASP.NET MVC is an architecture to develop ASP.NET web applications in a different manner than the traditional ASP.NET web development. Web applications developed with ASP.NET MVC are even more SEO (Search Engine) friendly.
Developing ASP.NET MVC application requires Microsoft .NET Framework 3.5 or higher.

MVC Interaction with Browser

Like a normal web server interaction, MVC application also accepts requests and responds to the web browser in the same way.


Asp.net mvc razor loops syntax

Let’s look at following example where we want to list some Employees information using Razor view engine


<ul>
  @foreach(var emp in EmployeeList)
  {
 <li>
  @emp.EmployeeName - (@emp.EmpCode)
 </li>  
  }
</ul>

Controllers and Routers in ASP.NET MVC 3

Introduction

ASP.NET MVC provides a new way of creating web applications which is more extensible and testable. We discussed about ASP.NET MVC in Introduction to ASP.NET MVC 3. Here, we will have a deeper look into the two pillars of ASP.NET MVC – Routers and Controllers.

Routers

One of the main objectives of ASP.NET MVC is Search Engine Optimization (SEO). Search Engines work mainly using URLs. Defining a meaningful and more understandable URL is very important to make our application more search engine friendly.
Routing is the way of constructing meaningful URLs for a web request. As you have already seen, our MVC application URLs are not represented by extensions like .aspx. Instead, the URLs consist of the Controller name and Action name.
Let us first understand how the default routing works. Open the Global.ascx file, and we can see the Application_Start() and RegisterRoute() methods.
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 = UrlParameter.Optional } 
            // Parameter defaults
    );
}
Look at the statement where we map the routing. Our URL formation uses the pattern “{controller}/{action}/{id}", where id is an optional parameter.
new { controller = "Home", action = "Index", id = UrlParameter.Optional } specifies that in case the URL does not specify a Controller, use the Home Controller. Also, in the absence of an Action, it uses the Index action, and the last parameter is Optional.

Routing data inside a Controller

We can access routing data inside a Controller using the RouteData object.
public ActionResult Index()
{
    ViewBag.Message = string.Format("{0}---{1}--{2}",
        RouteData.Values["Controller"],
        RouteData.Values["action"],
        RouteData.Values["id"]
        );
            
    return View();
}

Controllers

Now let us create a new Controller and see how we can route to the new Controller using a different routing pattern.
Add a new Controller using Add New Item -> Controller. It adds a new Controller with an Action as Index. For our sample application, we are using a different Action called Verify.
public class SampleController : Controller
{
    //
    // GET: /Sample/
 
    public ActionResult Verify()
    {
        return View();
    }
}
As there are no Views corresponding to SampleController, let us return some text from our Action. For returning any text data from an Action, use the Content class.
public ActionResult Verify()
{
    return Content("Hello From Sample Controller.");
}
Let us run the application. Modify the URL to /sample/verify.








But if we specify /Sample without any Action, we will receive a 404 error. As per the defined routing, if there is no Action specified, it should redirect to the Index action inside the specified Controller. Here, our SampleController doesn’t have any Index action and throws an error.


Adding a new route

For fixing the above issue, let us define a new route called “sample”.
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
                "sample",
                "Sample/{action}",
                new { controller = "Sample", action = "Verify" }
                );

 
    routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", 
                      id = UrlParameter.Optional } // Parameter defaults
            );

}
 


Now we may need to pass some data to our new Controller from a URL, like the id parameter in the default routing. For that, define a new parameter in the routing.
routes.MapRoute(
                "sample",
                "Sample/{username}",
                new { controller = "Sample", action = "Verify" }
                );
The value can be accessed either using the RouteData object or through a parameter to the Verify action.
public ActionResult Verify(string username)
{
    return Content(username);
}
Note that the URL consists of only the Controller and the parameter.


Again, you will receive a 404 error when we omit the parameter value.


For solving this issue, we need to specify the default value for the username parameter either in the Route mapping or in the Controller.
In the route map, specify the parameter as optional.
routes.MapRoute(
                "sample",
                "Sample/{username}",
                new { controller = "Sample", action = "Verify", 
                      username=UrlParameter.Optional }
                );
Inside the Controller, specify the default value for the parameter.
public ActionResult Verify(string username="all")
{
    return Content(username);
}

Conclusion

We had a quick discussion on how routing works in ASP.NET MVC and how we can customize the same. We will discuss more about Views, Styles, Action results, etc., in the next article.

Basic Steps Of SEO

Introduction

What is SEO(Search Engine Optimizatio)?

SEO is the process of optimizing a website by improving on site and off site aspect in order to increase the traffic, your sites receives from search engine.

SEO aim to index and improve ranking for the webpages which are most relevent to the keywords searched.

SEO will make site search engine friendly so that our potential customers can find us very easily when surfing the web.

SEO is also called as organic or natural results because we do not have to pay to search engine to get listed in search engine database and to archive high ranking on desired keywords.


Background

Why a company or a website need SEO?

Major traffic on a web sites are coming from well-known search engine like Yahoo, Google and MSN. if you will not submit your site in search engine then your site would not be found on search engine result pages so when visitors use search enginee, they can't find your site whether your site provide best content, product or services. your company van miss the valuable chance available on the website through search engine. so, search engine is the basic method of navigation for almost all internet users.

Once you will submit your site in search engine, after your site must be optimized for search engine to improve rankings on desired keywords.

Site will be optimized mainly through 2 factors. i.e Onpage Optimization and offpage Optimization.
Why a website can't get top rankings without SEO help?

When u submit your site in search engine, it will be stored in search engine database. nowadays online business is becoming very competitive so there will be lots of sites related to your site in search engine database then how can your site get high rankings without SEO help.

Every search engines are using their algorithm to giving a ranking priority to the websites. however there will be a limit that how search engines are working, so right step can create a great traffic of visitors at your site and wrong step can down rankings of your site in search engine results pages(SERPs).
There are two types :
Onpage Optimization
Offpage Optimization
What is Off Page Optimization: -

Off Page Optimization is one of the main factor of Search Engine algorithm. Off Page Optimization means that have an effect on web page listing in SERPs (Search Engine Result Pages). These factors are off site in which you or the coding on your site can not control them. All the things are depend on other sites. Google gives more emphasis on Off Page Optimization.

Off-page optimisation (off-page SEO) is what can be done off the pages of a website to maximise its performance in the search engines for target keywords related to the on-page content and keywords in off-page direct-links.


Off Page Optimization Factors: -

1. Web site URL submission in search engine: -
First of all you have to submit your website url in search engine database. URL submission in search engine are free of cost. When you submit your site in search engine, it will be stored in search engine database. If you will not submit your site in search engine, then search engine would not find it and it will be listed in SERPS. Search Engine may take some time(maximum 8 days) to listed your site in search engine database.

2. Web directory submission or Web promotion: -
Web directory is not like search engine and does not display list of website based on keywords. web directory list the websites by category and subcategory. web directories allows website owners to submit their website in their web directory.
There are thounds of web Free web directories and Paid web directories in which you can submit your site into proper category or related category and promote your website in world wide web. You need Title, Keywords, Description, URL, and E-ID to submit your site in web directory.

3. Web Building: -
The process of getting maximum links from related, equality and high page rank site to get high page rank and to get high rankings in SERPs.
Link building can be done by three ways:-
1. One way link
2. Two Way Link
3. Three Way Link

4. Blog Creation and Submission: -
If you have specific and unique content related to your site, you can create blog related to your site. You can keep back link of your site in blog so that it will create great traffic at your site and it will be One Way link for your site.
You can submit your blog into thousand of free and paid blog submission sites and it will increase popularity of your site and create targeted traffic at your site. You can keep important information about your site, so if visitors likes your content then it will create potential traffic for your site.

5. Press Release and Submission: -
You can write press release about your site or about your new product, after that you can submit your press release to different press release submission site and news publishing sites so it will make popular your site or new products and it will create a targeted traffic to your site.

6. Article Creation and Submission: -
You can create a unique article related to your site and there are so many sites willing to accept well-written articles. By writing articles, it can generate lots of targeted traffic to your site.

7. RSS (Really Simple Syndication) Feed:
RSS feed is used to publish frequently updated content to the subscriber users of your site. If your site has RSS feed and any user will subscribe in RSS feed than that user will get the update of your site when you update your site. So it will create a great traffic of old visitors at your site. When you update any content in your site, you will not need to promote the new content. It will automatically update to the subscribed users.
On Page Optimization: -

Every Search Engines are using their own algorithm and onpage optimization is also an important factor of search engine's algorithm. onpage optimization means we have to optimize some factor in our web site to make site search engine friendly.

On Page Optimization's Factor: -

1. Keywords: -
Keywords is one of the main factor of on page optimization. People are using phrase or request to get information from website. That phrase or request is called keyword.
If you want to build new web site then you have to make some keyword research related to your site. From keyword research you can get list of keyword related to your site which are used by visitors in search engine. You can select keyword research by some following steps.

=> Brainstorming: -
Brainstorming means you have to identify your customers mind that means which keywords they are finding in search engine to find information, product or services your sites offers.

=> Customer Survey: -
You can make customer survey from past and potentional customers about keywords. From customer survey you can increase your keyword list and you can find potentional keywords.

=> Keyword research tool: -
There are many keyword research tool available for free on the internet. There are well known keyword research tool that are wordtracker(it use it's own database) and overture(it use yahoo's database). In keyword research tool, you have to just enter your main keyword of the page, KW research tool will return all the main keywords related to your entered keyword that means related to your site. It will also return the competition of every keywords.

=>keyword selection: -
You can get list of related keywords from keyword research tool, after that you have to select right keywords from that list. you can select right keywords from some intellegent process that means which keyword will give you high conversion rate, which keyword will give you expected traffic at your site.

=>Finalize the keywords and implete keywords: -
After passing from all intellegent process, you can get list of keywords so after that you have to implete those keywords in your site and based on that keywords you can write best and unique content for your site so that content will become search engine friendly.
From selecting right keywords your site can get top ranking in the search engine results. and from selecting wrong keywords your site may never seen in search engine result pages.


2. Title: -
Title is also an important factor of search engine. Title means summery of the page. it should contain all the major keywords of the page. Title should be specific and unique because it will be displayed at the search engine result pages so from title any visitors will get idea about the page and about the site. Title should be like it must attract to visitors to select the title and to visit your website.


3. Meta Description: -
Description will be displayed at the search engine result pages under title so it is also an important factor of on page optimization.


4. ALT Tags: -
Alt tag means alternative. Google and other search engine can not read images. they can read only coding of the page. so we should use Alt tag on images. From Alt tag search engine can read what the image is about.


5. Content: -
All the major keywords are used frequently in the content in a natural way. All the main keywords should be highlighted by making them bold, italic or underline. By highlighting the keywords, we will indicate to search engine about the keywords. Content must be unique it should not be duplicate otherwise it will hurt your search engine rankings.
All the major search engines like Goggle, Yahoo and MSN gives more
emphasis on the content. If you have good keyword list, best title contains the main keywords and the unique content based on the selected keywords than your site may get the top rankings in the search engine.


6. Keyword Density: -
Keyword density means how many times your keywords are repeating in the content in a natural way. So when the spiders will come on our site to crawl, they can find the keywords easily that is searched by the user in search engine. Some times people are doing keyword stuffing to maintain the keyword density but it is bad for search engine. If you have 100 words in one paragraph and if 4 words from 100 words are your main keyword than it is called 4% keyword density. Generally 5 to 6% keyword density should be maintained in the content.


7. Headings: -
Our main keywords should be used as a Heading. So that it will be very useful for search engine and visitors of the site. You can use the HTML Tags H1 to H6 to make the headings in the content. H1 can be used for main heading and main keyword and than h2 to h6 tags are used for subheadings and other useful keywords. By headings you can indicate the search engine and your visitors about the keywords.

8. Sitemap :-
Sitemap is very useful for visitors and search engines both. Because visitor can reach at any page of the site within two clicks. Sitemap should be at the top of site so when visitor will come, he can go directly at the sitemap and from sitemap visitor can go directly at any page of the site.

It is also helpful to search engine because when spiders will crawl that sitemap link at that time it will crawl all the pages of our site. So it can be also useful to your site.


9. Google Sitemap: -
The above sitemap was general for visitors and all the search engines. You can also create a sitemap for Google. Google sitemap is created in XML. If you have google sitemap in your site than google can easily crawl all the internal page links of your site. You can use the online tools that can create a XML based sitemap for google.


10. Robot.txt: -
When you do not want to crawl any file or image by search engine spiders than you can create robots.txt file and in that file you can mention the files, images which you don't want to crawl by the search engine spiders.
In Off page Optimization:
1. One way link
2. Two Way Link
3. Three Way Link
And how are they useful in getting high rankings in SERPs?

In On Page Optimization:
Which are the Keyword research tools mostly used?
On what basis we should finalize the keywords and implement keywords?
How is ALT Tags used?
How do the Spiders decide if the Keyword Density is under guidelines or not? Are there any standards defined for this activity?
Twitter Bird Gadget