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