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?

Friday, October 14, 2011

ASP.NET MVC Overview

 The above diagram shows the relationship between the MVC Framework and the .NET Framework. Observe that the Web Forms and MVC are both built on top of ASP.NET Framework.

                     

Introduction

ASP.NET MVC is one of the methods of developing ASP.NET applications. In this article, we will go through the overview of ASP.NET MVC by creating a simple application.
ASP.NET MVC Framework is Microsoft’s Web Application development framework, the other one being traditional webforms framework.
MVC or Model View Controller is a design pattern that addresses the separation of concerns(Soc) which is the process of identifying and separating the application into distinct parts like UI, Logic and Data Access.
Soc has proven to be useful in the design of web applications. Keeping the view separate from the other parts of the application means that we can easily change the view without affecting the rest of the application.
Similarly, if we want to change the main application logic, we just need to change the controller.
ASP.NET MVC is an implementation of the MVC design pattern. The framework helps Test Driven Development which is a method of development in which Unit Test Cases are written before the rest of the application.
While building web applications, developers can either choose the web forms model or the MVC model depending on the requirements of the application.
An MVC application consists of Model, View and Controller at its core:
  1. Model: Consists of the data access logic and the classes that represent the objects in the application domain (Business Objects)
  2. View: A view contains HTML markup
  3. Controller: Consists of the main application flow logic
Let’s start with creating simple MVC application to understand the basics of the MVC application. We will start by creating a blank ASP.NET MVC application.
Once the web application is created, we will add the functionality to make it work.




Adding the Controller

For adding the controller, we will right click the controllers folder and select Add -> Controller. We will type the name NamesController in controller name dialog.
Note that the Controller name must end with Suffix Controller. Doing so creates a controller with the default code. We have renamed the action as in the following code.



//public class ProductsController : Controller
    //{
    //    //
    //    // GET: /Names/

    //    public ActionResult Electronics()
    //    {
    //        ViewData["Message"] = "Electronics Products Listing";
    //        return View();
    //    }
    //}
Here NamesController is the name of our Controller. It inherits from System.Web.Mvc.Controller Framework class. View is a method defined in the base controller class.
Controller is just a normal class that contains action methods which is a non static public method defined in the Controller class.
A controller action is invoked in response to the requested URL like Products.
We will see later how URLs map to the Actions defined in the controller class.
A controller action always returns an action result which determines the response returned to the browser. In the above code, the action returns viewresult which represents an ASP.NET view.
Few of the actionresults are:
  • ViewResult - Represents the HTML for the view
  • RedirectResult - Represents Redirect to another controller action
  • ContentResult - Represents RAW URL sent to the browser
  • EmptyResult - Represents that no result is returned by the action
Typically, we call the method defined in the base controller class whose return type is the appropriate view instead of directly returning the action result.
To invoke the above action, we just need to type the following in the browser Names/Index.
If we want to add another action to the controller, we just need to add another public method to the controller. We can also specify the name of the view explicitly as:
return View("index");
 
The above code will return the index view instead of returning the default view (which in this case is also index). Now that we have our controller in place, let us create our first view.
View: Views are responsible for rendering the Interface on the browser. To create a view in the controller, we right click on the action and select Add View.



We will leave the default options selected in the create new view dialog. This creates a new view with two content elements. In the first content, we place the content we want to appear in the title, while in the second content we place the content we want to appear in the body of an HTML page. We will replace the second content control with the following:
 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2> <%=ViewData["Message"]  %></h2>
</asp:Content> 
Remember that we have assigned the ViewData property in the Controller’s Index action method. View data is a dictionary object used to pass the information between the controller and the view. Here, we are using the view data property to display the message in the view.

Routing

In traditional web applications, the URL is hardwired with the application code that gets executed or resource that is requested. URL Routing decouples the URL with the application code.
URL ----------> ROUTING ----------> APPLICATION LOGIC
One of the advantages of this decoupling is that it makes the URL more user friendly since we can give more meaningful names to the URL. For example, instead of using something like ListProduct.aspx, we can use simply Products which is more meaningful to the end user.
Routing defines a URL pattern that should match to access the application.
We normally define the routes in the global.asax file since it contains the application life cycle events. By default, routes are defined in the RegisterRoutes method which is called from Application_Start event.
  routes.MapRoute(
  "Default",
                 "{controller}/{action}/{id}",
                 new { controller = "Products", action = "Electronics",
  id = UrlParameter.Optional }
            );
The second parameter in the MapRoute method matches all the URLs that satisfy the above pattern e.g. {Controller}/{Action}/{id} and the appropriate Controllers action method is called for the matched URL.

ASP.NET MVC Model Binding - Part1

Introduction

ASP.NET MVC has many great features. I have been playing around with ASP.NET MVC, and gone through couple of interesting things as part of Model Binding. Here I am putting together all my findings, and explain with a simple example. I am sure this will save a lot of time for people who are out there, looking to understand, how exactly ASP.NET MVC Model binding works.
In ASP.NET MVC, Model Binding is, mapping the HTTP request data directly to Action method parameters and .NET objects (a Model).

Using the Code 

As this is going big, I am splitting this into parts. In this part, I am covering ASP.NET MVC object model binding, Parameter binding using Query String parameters, and controlling Model binding using Bind Attribute.
Below is the code structure:
CodeStructure.JPG
To make it simple, and to concentrate more on Model binding, I am taking a simple example,  which is having Employee Model, and EmployeeController Control, and two Views EmployeeView1, EmployeeView2.
When we run the above code, it displays Employee Add/Edit page (Adding/Editing to database is out of scope for this article), EmployeeView1 view, like below:
EmployeeView1.JPG
'Using Query Strings' link is to demonstrate model binding using Query String parameters, 'Control Model Binding' link is to demonstrate how we can control model binding. Controlling Model Binding gives control on what Model properties can bind with incoming HTTP request.
I have used VS 2008 SP1, ASP.NET MVC 2 for this sample, recommended to use the same version.
Here is how model binding works, for e.g., consider the below request:
 POST: Route Values, Query String Parameters
Route Values decide the controller and the Action method is responsible for handling the request and the Query String Parameters basically map to the Action method parameters, this is explained in detail below. Here is the Employee Model:
public class Employee
{
    [DisplayName("Employee ID")]
    [Required(ErrorMessage = "ID Required")]
    public int EmpId { get; set; }
    [DisplayName("Employee Name")]
    [Required]
    public string EmpName { get; set; }
    [DisplayName("Designation")]
    [Required]
    public string EmpDesignation { get; set; }
    [DisplayName("Department")]
    [Required]
    public string EmpDepartment { get; set; }
    [DisplayName("Salary")]
    [Required]
    public float EmpSalary { get; set; }
}
The above model is decorated with Data Annotations to take care of simple validations. As part of this writing, we will not discuss much on validations.

Binding Style 1: Query String Parameters

Query String Parameters can directly map to the Action method parameters. Consider the below request which corresponds to the action method in the sample.
EmployeeController.cs
-------------------------

public ActionResult UpdateQueryString(int EmpId, string EmpName, 
   string EmpDepartment, string EmpDesignation)
{
    return View("EmployeeView1");
}
The above request directly maps each HTTP query string parameters EmpId, EmpName, EmpDepartment, EmpDesignation to Action method parameters respectively and updates the above EmployeeModel to contain these values. To observe this behavior, the attached sample renders the binded values in the EmployeeView1 view page, once you set the source code, run the application from Visual Studio, and click on the link Using Query Strings ; link. We will observe the updated fields on the view page. Have a look at the below snapshot.
EmployeeView2.JPG
We can generate the above HTTP request by using the HtmlHelper method like below. Observe the provided handy sample for more information.
<%= Html.ActionLink("Using Query Strings", "UpdateQueryString", 
new { EmpId = 1, EmpName = "Nick", EmpDepartment = "IT",
 EmpDesignation = "Director" })%>

Binding Style 2: Object Binding

We see this type of binding in Action methods most of the times. From HTTP request values will be mapped to Model attributes behind the scenes, to make it work we need to follow certain thumb rules. For e.g., consider the below code:
[HttpPost]
public ActionResult Update(Employee employee )
{
    if (!this.ModelState.IsValid)

    ModelState.AddModelError("Employee", "Model is Not Valid");
        return View("EmployeeView1");
}
and the View page contains the following strongly typed way of rendering the fields. For e.g.:
 <%= Html.TextBoxFor(model => model.EmpId) %>
 
The above code automatically binds the strongly typed 'EmpId' entered in the text box to the EmpId of the model (employee) and sends over this to Action method when we submit the form. Consider the below line, instead of strongly typed method like above, we can consider using the below method:
  <%= Html.TextBox("employee.EmpId")%>
Parameter name and property name combination pulls the values from HTTP input. The above method follows the prefix.PropertyName standard. prefix generally if we don't specify, it will be Action parameter name. In the above example, employee is the parameter for action method. Values entered in the EmpId text box will be mapped to EmpId property of the Model.
If we specify the prefix using Bind attribute for the action method like below:
[HttpPost]
public ActionResult UsingPrefix([Bind(Prefix = "emp")]Employee employee)
{
    if (!this.ModelState.IsValid)

    ModelState.AddModelError("Employee", "Employee Not Valid");
        return View("EmployeeView2");
}
then Helper method in the view page should look like below:
<%= Html.TextBox("emp.EmpId")%>
Click the submit button to observe the Object Model binding.

Controlling Model Binding

Sometimes, it may not be required to show all the fields in the View, but Model contains more properties than what a View shows. It is a potential candidate for injection attacks. To avoid this, we can control the Model binding from View to Model using the Bind attribute.
public ActionResult BindInclude
    ([Bind(Include = "EmpId,EmpName", Exclude = "EmpSalary")] Employee employee)
        {
            return View("EmployeeView1");
        }
Using the Bind attribute, we can white list Model Properties using Include param name, black list Model Properties using Exclude param name. In the above code, only EmpID, EmpName inputs from HTTP request will be mapped to employee model, if this results in invalid model state because of the validations set, then corresponding validations will fire automatically. I will write in the next part, about Collection binding, Collection binding objects, etc., how to do manual Model binding. I am sure this reading will save a lot of time for readers who are hunting for Model binding.

Disclaimer

This article uses a sample, which is not for direct production deployment. This is to give the reader an idea on how model binding works, it is individual responsibility to follow the necessary best practices while implementing the Model Binding.

Introduction to ASP.NET MVC 3

Introduction

ASP.NET MVC framework follows the well-defined MVC pattern to create a web application. MVC design pattern is used to separate the different parts of the application for more scalability, extensibility and testability purposes.
One of the major challenges with normal web forms is the testability of the business logic. Unit test of code-behind logic is very complex. Also, the extensibility of the application required a lot of re-work on the application. ASP.NET MVC addresses the pain points associated with the traditional web form applications.
In this article, we will discuss about how to create an MVC application and understand the Controller, Views & Models.

MVC

MVC means Model View Controller. Controller takes care of the overall execution of a request. Controller receives the request from the web server and identifies the data requirements. Depending on the data requirements, Controller contacts the corresponding Model. Model will supply the required data, which will be rendered to the UI using a View.
1.png For working with ASP.NET MVC, we can install the Web Platform Installer, which consists of Visual Studio 2010 Express for coding the MVC application, SQL Server Express for storing the data and IIS Express for hosting the application. We can download the Web Platform Installer from Microsoft Web Platform Installer 3.0.

How to Create an ASP.NET MVC Application

Let us start our discussion by creating the first MVC application. File-> New Project and select the ASP.NET MVC 3 Web Application template.
2.png This will open the new ASP.NET MVC 3 Project window.
3.png Select either Empty or Internet Application. Empty will create a blank application. Internet application will create an application with few default pages. For our sample, I will select the Internet Application option.
We can choose to create a test project along with our MVC application from the same window. Also, we can choose the View Engine as ASPX or Razor. ASPX is for backward compatibility.
Our new solution will look like:
4.png We have different folders to hold the Controllers, Views and Models. As we selected Internet Application, our application is a fully functional application. We can run it and see the pages.
5.png It opens a small application with two tabs, Home and about. Also, we have the option to Log On, from where we can register a new User.
When you select the About tab, it goes to the HomeController and returns a View using the About() method. About() is not specified any View name, so the controller will goes to the Views and find the directory corresponding to the HomeController. Here also, it uses the name of the controller to find the corresponding directory. Then, the controller checks whether it contains any view with the name About.
6.png We can specify a View name in the About() method like:
public ActionResult About()
{
    return View("Index");
}
Now, both Home and About display the same content.

Data Passing from Controller to View

Now, let us see how we can pass some information to the View from Controller. There are two ways to pass data from Controller to View.

Using ViewBag

ViewBag is a dynamic object, where we can add any properties dynamically.
For example, if I want to pass some contact information like Name and Contact number to About View from the Home controller, we can define it using the ViewBag as:
public ActionResult About()
{
    ViewBag.ContactPerson = "George MAthew";
    ViewBag.ContactNumber = "91-99444444000";
    return View();
}
This data will be accessed in about.cshtml as:
@{    
   ViewBag.Title = "About Us";
}
<h2>About</h2>
<div>    
      Contact person : @ViewBag.ContactPerson 
      Contact Number : @ViewBag.Contactnumber
</div>
Note that the dynamic properties added are not case sensitive. Also, it won’t throw any exception, in case of a wrong dynamic property reference.
Now, our About tab looks like:
7.png

Using Model

Now, let us see how we can pass data using a Model. Define a Model class and specify the required properties. Our sample Model class looks like:
namespace SampleApp.Models
{
    public class ContactAddress   
    {
       public string Address { get; set; }
       public string City { get; <br />set; }
       public string Country { get; set; }
    }
}
Now, let us construct the Model in Controller and pass the same to our View:
public ActionResult About()
{
    var address = new ContactAddress()
    {
        Address = "Lane 21, Gachibowli",
        City = "Hyderabad",
        Country = "India"
    };
    
    return View(address);
}
Now, we will use the same in our View. In View, we have another object called Model, which holds the dynamic properties like ViewBag. We can extract the model properties using Model.
@{
    ViewBag.Title = "About Us";
}
<h2>About</h2>
<div>
  Contact Address: @Model.Address, @Model.City, @Model.Country
</div>
Now, our About tab looks like:
8.png Notice that there is no intellisense support for the Model properties. We can define the type of the expected model on top of the View, which will gives the Intellisense support for the Model object.
9.png

Conclusion

In this article, we discussed about the ASP.NET MVC framework, how to create a basic MVC application and discussed about the Controller to View communication. We have a lot more to discuss in MVC like the Content folder holding all images and styles, Scripts folder with jQuery scripts and MVC detail. We will discuss the topics in detail later.

Integration of .Net Application With SAP

Introduction.

Integration of .Net Application With SAP Using ERPConnect. You can use following ways to connect SAP system
  1. RFC (Function Call)
  2. BAPI
  3. Idoc
  4. SAP Queries
  5. Special Classes etc many more

What is SAP .Net Connector

  • SAP product. Based on Microsoft .NET Technology
  • Interact with SAP via RFC/SOAP
  • Fully integrated with Visual Studio.NET
  • Managed Code
  • Generates C# Proxy Classes for any .NET application integrations
  • Supports RFC and SOAP
  • Supports qRFC, tRFC
  • Supports asynchronous SOAP calls
  • RFC client or RFC server

Brief About ERPConnect

ð ERPConnect.net is a lean .NET assembly that lets you develop robust SAP interfaces without a great degree of effort and most of all, without an elaborate infrastructure or any additional middleware.
ð Supports RFC and SOAP, therefore integrates itself in any modern SAP NetWeaver architecture
ð Also suitable for use on mobile devices
ð ERPConnect.net also offers a range of special classes to efficiently, securely and stably handle even the most exotic requirements of SAP interface programming
ð Read SAP tables directly through RFC

Resources Required

  • SAP .Net Connector: ERPConnect
  • SAP Server Details
    • name/IP of the SAP server
    • System Number
    • User name
    • Password
    • Language
    • Client

Using the code

First install ERPConnect in the dev environment. After installing ERPConnect, goto Add References block in the application, locate the ERPConnect.dll and hit add.Once the ERPConnect.dll is added to the reference folder. you can add following to the xyz.cs file Now its all upto you. You can implement as you wish.In the code belo I am using the concept of Special Classes.

Block of code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Odbc;
using ERPConnect;
using ERPConnect.Utils;
using ERPConnect.Queries;
 
namespace SAP1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//licence
   ERPConnect.LIC.SetLic(); //Not Required in case of trial version but is 
must in case of licenced version

//creating the connection object
R3Connection con = new R3Connection("SAP Server IP/Name", System Number,  
"UserName", "PWDl", "Language", "Client");

//open the connection
con.Open();

DataTable dt = new DataTable();
ReadTable rt = new ReadTable(con);

rt.TableName = "SAP Table Name";
rt.AddField("FieldName");
rt.AddField("FieldName");


rt.Run();
dt = rt.Result;
dataGridView1.DataSource = dt; // displays the result in gridview
}
catch (Exception ex)
{
 textBox1.Text = ex.Message;
}

}
}
}

How To Download Torrent File using IDM

Yes… Its possible. Even when for the first time i thought of it, it was a day dream for me !
However, I got to know about this essential and important trick and i feel that everybody should be aware of this much needed downloading trick.
Also its very very simple to operate. Just you need to follow the steps below.
And before you begin, first click on the like button below and feel free to send this as well to ur friends/groups/pages.

Steps:

1. First of all , you have to download the torrent file(.torrent) which you want to download.

2. Then just go to the website www.torcache.net and upload the torrent file that you have just downloaded and click on the cache! button.

torcache How To Download Torrent File using IDM

3. This will give you a new torrent file . You just have to copy the link of the new torrent file from the opened window.

4. Then go to the website www.torrific.com and create an account there(in case you don’t have) and login to your account. Then paste the address of the new torrent obtained in step 3 and click on Get button.

torrific How To Download Torrent File using IDM

5. Now you will get the list of available files present in that torrent file. Then click on the initiate bittorrent transmission button. This will give the full option to download the file. Just click on any link and you can see the download manager-IDM popping out for downloading the file.
Now enjoy the ultimate Speed of IDM for downloading torrents too…
Twitter Bird Gadget