Upcoming User Group Speaking : Building Real Time ASP.NET SignalR Application with ASP.NET MVC


Join my first user group speaking after getting Microsoft MVP Award  , You will learn practical implementation of ASP.NET SignalR with real time hands on demo example. For more details read following details

Agenda
 Date : 30-07-2016

Vithal-Wadje-user-group-speaking-Pune-on-ASP.NET-SignalR



Building Real Time ASP.NET SignalR Application with ASP.NET MVC
    • What is SignalR?
    • Why we need ASP.NET SignalR?
    • What today's clients Expect from application ?
    • Supported Clients of SignalR
    • Understanding SignalR Packages
    • Creating SignalR application with ASP.NET MVC for real time database change notification
    • Installing ASP.NET SignalR library.
    • Understanding structure of ASP.NET SignalR application
    • What is hub class ?
    • What is IAppBuilder Interface ?
    • What is service broker in SQL Server ?
    •  Enabling Service broker for real time database change notification
    • Testing Real time database change notification on dashboard using ASP.NET MVC application.
    • Q & A

      Where:


       Knowledge Port AG
      Atre House Second Floor 1284, 
      Shivajinagar, Pune , 
      Maharashtra , India -411005


      Price: Free of cost

      Requirement: Optional to bring your laptop and internet card.

      Date : 30-07-2016
      Time : 1 PM To 2 PM

                                    Join Event







       

      Get Return Value From DataBase Using Dapper ORM

      Sometimes in an  we need to give user acknowledgment of their raised request or transaction reference number instantly from database which is generated against that user request. So for this purpose we need to take return value from stored procedure which is either string or integer or anything as per application requirement. Now in this article we will learn how to get return value from stored procedure using Dapper ORM in ASP.NET MVC with one scenario-based sample MVC application.
      Scenario
       Let's consider ABC housing society provides different services to their flat owners.  Since ABC housing society is very big it's difficult to manage complaints manually of their flat customers, so they decided to build the sample application which covers the following scenario .
      • User can raise the complaint type and short description using Text boxes .
      • The unique ComplaintId need to be generated instantly after raising the complaint to track status.
      • The ComplaintId should be the combination of first four characters of complaint type text and Database auto generated number.
      So based on preceding scenario let's start building application step by step so beginners can also understand .
      Step 1: Create an MVC Application.
       Now let us start with a step by step approach from the creation of a simple MVC application as in the following:
      1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
      2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
      1. As shown in the preceding screenshot, click on Empty template and check MVC option, then click OK. This will create an empty MVC web application.
      Step 2 : Add The Reference of Dapper ORM into Project.

      Now next step is to add the reference of Dapper ORM into our created MVC Project. Here are the steps:
      1. Right click on Solution ,find Manage NuGet Package manager and click on it.
      2. After as shown into the image and type in search box "dapper".
      3. Select Dapper as shown into the image .
      4. Choose version of dapper library and click on install button
       After installing the Dapper library, it will be added into the References of our solution explorer of MVC application such as:

      If wants to learn how to install correct Dapper library , watch my video tutorial using following link,
      I hope you have followed the same steps and installed dapper library.
      Step 3: Create Model Class.
      Now let's create the model class named ComplaintModel.cs by right clicking on model folder as in the following screenshot:
      Note:
      It is not mandatory that Model class should be in Model folder, it is just for better readability you can create this class anywhere in the solution explorer. This can be done by creating different folder name or without folder name or in a separate class library.
      ComplaintModel.cs class code snippet: 

      public class ComplaintModel  
          {   [Display(Name = "Complaint Type")]  
              [Required]  
              public string ComplaintType { get; set; }  
              [Display(Name = "Complaint Description")]  
              [Required]  
              public string ComplaintDesc { get; set; }  
          }
      Step 4 : Create Controller.

      Now let us add the MVC 5 controller as in the following screenshot:

      After clicking on Add button it will show the window. specify the Controller name as Complaint with suffix Controller:
      Note:

      The controller name must be having suffix as 'Controller' after specifying the name of controller.
      Step 5 : Create Table and Stored procedure.

      Now before creating the views let us create the table name ComplaintDetails in database according to store the complaint details:
      I hope you have created the same table structure as shown above. Now create the stored procedures to get the return value  as in the following code snippet:
      Create PROCEDURE AddComplaint  
      (  
      @ComplaintType varchar(100),  
      @ComplaintDesc varchar(150),  
      @ComplaintId varchar(20)=null out  
      )  
      AS  
      BEGIN  
      SET NOCOUNT ON;  
        
      Declare @ComplaintRef varchar(30)  
      --Getting unquie Id  
      select @ComplaintRef=isnull(max(Id),0)+1 from ComplaintDetails  
      --Generating the unique reference number and seeting to output parameter  
      Set @ComplaintId=Upper(LEFT(@ComplaintType,4))+convert(Varchar,@ComplaintRef)  
        
      INSERT INTO [dbo].[ComplaintDetails]  
                 (  
                  [ComplaintId]  
                 ,[ComplaintType]  
                 ,[ComplaintDesc]  
                 )  
           VALUES  
                 (  
                @ComplaintId,  
                @ComplaintType,  
                @ComplaintDesc  
                 )  
      END  
      Run the above script in sql it will generates the stored procedure to get the return value .
      Step 6: Create Repository class.
      Now create Repository folder and Add ComplaintRepo.cs class for database related operations, Now create method in ComplaintRepo.cs to get the output parameter value from stored procedure as in the following code snippet:
      public class ComplaintRepo  
        {  
            SqlConnection con;  
            //To Handle connection related activities  
            private void connection()  
            {  
                string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();  
                con = new SqlConnection(constr);  
            }  
            //To Add Complaint details  
            public string AddComplaint(ComplaintModel Obj)  
            {  
                DynamicParameters ObjParm = new DynamicParameters();  
                ObjParm.Add("@ComplaintType", Obj.ComplaintType);  
                ObjParm.Add("@ComplaintDesc", Obj.ComplaintDesc);  
                ObjParm.Add("@ComplaintId", dbType:DbType.String,direction:ParameterDirection.Output,size:5215585);  
                connection();  
                con.Open();  
                con.Execute("AddComplaint",ObjParm,commandType:CommandType.StoredProcedure);  
                //Getting the out parameter value of stored procedure  
                var ComplaintId = ObjParm.Get<string>("@ComplaintId");  
                con.Close();  
                return ComplaintId;  
        
            }  
        }  
      Note
      1. In the above code we are manually opening and closing connection, however you can directly pass the connection string to the dapper without opening it. Dapper will automatically handle it.
      Step 7: Create Method into the ComplaintController.cs file.

      Now open the ComplaintController.cs and create the following action methods:
      public class ComplaintController : Controller  
         {  
             // GET: complaint  
             public ActionResult AddComplaint()  
             {  
                 return View();  
             }  
             [HttpPost]  
             public ActionResult AddComplaint(ComplaintModel ObjComp)  
             {  
                 try  
                 {  
                     ComplaintRepo Obj = new ComplaintRepo();  
                     //Getting complaintId and assigning   
                     //to ViewBag with custom message to show user  
                     ViewBag.ComplaintId = "Complaint raised successfully, Your complaintId is " + Obj.AddComplaint(ObjComp);  
                 }  
                 catch (Exception)  
                 {  
                     //Assigning custom message to ViewBag to show users, If any error occures.  
                     ViewBag.ComplaintId="Error while raising complaint, Please check details";  
                 }  
                 return View();  
             }  
         }  
      Step 8 : Creating strongly typed view named AddComplaint using ComplaintModel class .
      Right click on View folder of created application and choose add view , select ComplaintModel class and create scaffolding template to create view to raise the user complaints as
       Click on Add button then it will create the view named AddComplaint, Now open the AddComplaint.cshtml view , Then following default code you will see which is generated by MVC scaffolding template as,
      AddComplaint.cshtml  



      @model GetReturnValueUsingDapperInMVC.Models.ComplaintModel   
      @{  
          ViewBag.Title = "www.compilemode.com";  
      }   
      @using (Html.BeginForm())   
      {  
          @Html.AntiForgeryToken()  
            
          <div class="form-horizontal">      
              <hr />  
              @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
              <div class="form-group">  
                  @Html.LabelFor(model => model.ComplaintType, htmlAttributes: new { @class = "control-label col-md-2" })  
                  <div class="col-md-10">  
                      @Html.EditorFor(model => model.ComplaintType, new { htmlAttributes = new { @class = "form-control" } })  
                      @Html.ValidationMessageFor(model => model.ComplaintType, "", new { @class = "text-danger" })  
                  </div>  
              </div>  
        
              <div class="form-group">  
                  @Html.LabelFor(model => model.ComplaintDesc, htmlAttributes: new { @class = "control-label col-md-2" })  
                  <div class="col-md-10">  
                      @Html.EditorFor(model => model.ComplaintDesc, new { htmlAttributes = new { @class = "form-control" } })  
                      @Html.ValidationMessageFor(model => model.ComplaintDesc, "", new { @class = "text-danger" })  
                  </div>  
              </div>  
        
              <div class="form-group">  
                  <div class="col-md-offset-2 col-md-10">  
                      <input type="submit" value="Add Complaint" class="btn btn-primary" />  
                  </div>  
              </div>  
              <div class="form-group">  
                  <div class="col-md-offset-2 col-md-10 text-success">  
                      @ViewBag.ComplaintId  
                  </div>  
              </div>  
          </div>  
      }  
      <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
      <script src="~/Scripts/jquery.validate.min.js"></script>  
      <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 
      After adding model, view , controller and Repository folder our final solution explorer will be look like as follows,

      Now we have done all coding to upload files .
      Step 9 : Now run the application.
      After running the application initial screen will be look like as follows,
      Now click on Add Complaint button without entering the details then the following error message shows which we have defined in model class as
       Now enter the proper details as,

      I hope from all the preceding example we have learned how to get return value from stored procedure using Dapper ORM in ASP.NET MVC with real time scenario based sample MVC application.
      Note:

      • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
      • Configure the database connection in the web.config file depending on your database server location.
      • You can use  DropDownList for complaint types which might be come from master table.
      Summary
      I hope this article is useful for all readers. If you have any suggestions please contact me.
      Read more articles on ASP.NET MVC:

      Multiple Submit Buttons On Single View In ASP.NET MVC

      In ASP.NET MVC applications we need to use multiple submit buttons on single view to achieve certain functionalities, and if we create a view from model that is a strongly typed view, then by default view behavior is submitted and it adds many functionalities. While submitting the form it will fire the validation. Suppose we need to add another submit button on view and I want different functionality for that button, then it will call the same action method as the previous button, which means both buttons will point to the same action method. So by considering this requirement I have decided to write this article to explain how to manage multiple submit buttons on single view. Let's learn step by step so beginners also can understand.
      Scenario
      There many be many scenarios where we need multiple submit buttons on single view but in this example we are considering the scenario in which we have one view from where the user can add the employee details and if the details are not sufficient then the user can save it as a draft. Now let's start creating a simple MVP application to demonstrate the above scenario.
      Step 1: Create an MVC Application.

      Now let us start with a step by step approach from the creation of a simple MVC application as in the following,
      1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
      2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear,

      Step 2: Create Model Class

      Now let us create the model class file named EmployeeModel.cs by right clicking on model folder as in the following screenshot,

      Note

      It is not mandatory that Model class should be in Models folder, it is just for better readability; you can create this class anywhere in the solution explorer. This can be done by creating different folder names or without folder name or in a separate class library.

      EmployeeModel.cs class file code snippet
      using System.ComponentModel.DataAnnotations;  
        
      namespace ManagningMultipleSubmitButtonsInMVC.Models  
      {  
          public class EmployeeModel  
          {  
              [Required]  
              public string Name { get; set; }  
              [Required]  
              public string City { get; set; }  
             
              public string Address { get; set; }  
          }  
      }  
      Step 3: Add Controller Class

      Now let us add the MVC 5 controller as in the following screenshot,

      After clicking on Add button it will show the window. Specify the Controller name as Home with suffix Controller.
      Note

      The controller name must have a suffix as 'Controller' after specifying the name of the controller. Now modify the default code in HomeController.cs class file and create two action methods, after modifying the code will look like as follows,
      HomeController.cs
      using ManagningMultipleSubmitButtonsInMVC.Models;  
      using System.Web.Mvc;  
        
      namespace ManagningMultipleSubmitButtonsInMVC.Controllers  
      {  
          public class HomeController : Controller  
          {  
                
              public ActionResult Employee()  
              {  
                  return View();  
              }  
              [HttpPost]  
              public ActionResult Save(EmployeeModel objSave)  
              {  
        
                  ViewBag.Msg = "Details saved successfully.";  
                  return View();  
              }  
              [HttpPost]  
              public ActionResult Draft(EmployeeModel objDraft)  
              {  
                  ViewBag.Msg = "Details saved as draft.";  
                  return View();  
              }  
        
          }  
      }  
      In the preceding code sample, we have two action methods named Save and Draft Save action method is used to save the records and Draft is used to save the details as draft for saving later.

      Step 4: Create View

      Now let's create strongly typed view named Employee from EmployeeModel class ,

      Click on Add button then it will create the view named Employee, Now open the Employee.cshtml view, then some default code you will see which is generated by MVC scaffolding template, now modify default code to make as per our requirements. After modifying the code it will look like as in the following,
      @model ManagningMultipleSubmitButtonsInMVC.Models.EmployeeModel  
        
      @{  
          ViewBag.Title = "www.compilemode.com";  
      }  
      @using (Html.BeginForm())   
      {  
          @Html.AntiForgeryToken()  
            
          <div class="form-horizontal">  
                
              <hr />  
              @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
              <div class="form-group">  
                  @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
                  <div class="col-md-10">  
                      @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
                      @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })  
                  </div>  
              </div>  
        
              <div class="form-group">  
                  @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
                  <div class="col-md-10">  
                      @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
                      @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })  
                  </div>  
              </div>  
        
              <div class="form-group">  
                  @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
                  <div class="col-md-10">  
                      @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
                      @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })  
                  </div>  
              </div>  
        
              <div class="form-group">  
                  <div class="col-md-offset-2 col-md-12">  
                      <input type="submit" value="Save" class="btn btn-primary" />  
                      <input type="submit" value="Draft" class="btn btn-primary" />  
        
                  </div>  
                    
              </div>  
              <div class="form-group">  
                  <div class="col-md-offset-2 col-md-10">  
                     @ViewBag.Msg  
        
                  </div>  
        
              </div>  
          </div>  
      }  
      <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
      <script src="~/Scripts/jquery.validate.min.js"></script>  
      <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 
      Now after adding the Model, add View and controller into our project. The solution explorer will look like as follows,

      Step 5 : Now run the application and click on any one of the buttons,  it will fire only Save action method as,

      In the preceding screen shot, if we clicked on any one of the buttons it will point to the save action method because we have only one form and two submit buttons, so it's not possible to point to two different buttons on two different action methods usingthe preceding scenario.

      Step 6 :Solution

      There are lots of solutions to solve the preceding issue, we will look at the one which requires the least effort to solve the same scenario:
      • By creating two forms on single view by using html.Action helper class
      • By changing input type submit button of those submit buttons but the model validation will not be fired .
      • By Using javascript or jQuery to submit forms but default validations will not work.
      • By using action name along with name property in submit button.
      • By Using formaction property of submit button,
      So in this article we will use a simple way by formation of name property of submit button:

      In the preceding example we have provided the ActionResult method name in formation property of submit button, now let's update the Employee.cshtml view code; after updating the code; the Employee.cshtml code will look like as follows
      @model ManagningMultipleSubmitButtonsInMVC.Models.EmployeeModel  
        
      @{  
          ViewBag.Title = "www.compilemode.com";  
      }  
      @using (Html.BeginForm("Save","Home",FormMethod.Post))   
      {  
          @Html.AntiForgeryToken()  
            
          <div class="form-horizontal">  
                
              <hr />  
              @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
              <div class="form-group">  
                  @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
                  <div class="col-md-10">  
                      @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
                      @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })  
                  </div>  
              </div>  
        
              <div class="form-group">  
                  @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
                  <div class="col-md-10">  
                      @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
                      @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })  
                  </div>  
              </div>  
        
              <div class="form-group">  
                  @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
                  <div class="col-md-10">  
                      @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
                      @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })  
                  </div>  
              </div>  
        
              <div class="form-group">  
                  <div class="col-md-offset-2 col-md-12">  
        
        
                      <input type="submit" value="Save" formaction="Save"  class="btn btn-primary" />  
        
                      <input type="submit" value="Draft"  formaction="Draft" class="btn btn-primary" />  
        
                  </div>  
                    
              </div>  
              <div class="form-group">  
                  <div class="col-md-offset-2 col-md-10 text-success">  
                      @ViewBag.Msg  
                      
        
                  </div>  
        
              </div>  
          </div>  
      }  
      <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
      <script src="~/Scripts/jquery.validate.min.js"></script>  
      <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
      Step 7: Now let's run the application and click on the save button, then it will fire the save action method as,

      Now click on draft button, it will fire the Draft action method and  show the following message,
       I hope from all the preceding examples we have learned how to use multiple submit buttons on single view in ASP.NET MVC.
      Note
      • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
      Summary
      I hope this article is useful for all readers. If you have any suggestions please contact me.

      jQuery Ajax Get Request with Input Parameters

      In many forum post, I have read one common question that is how to make jQuery Ajax GET request with input parameter in ASP.NET MVC , So by considering above requirement I have decided to write this article.
      Let's consider the scenario we have action method in named Details in Home controller which takes the Id as input parameter .Then jQuery function will be look like as follows.
      $(document).ready(function () {
              $("#btnGetDetails").click(function () {
                  $.ajax({
                      //base address/controller/Action
                      url: 'http://localhost:51163/Home/Details',
                      type: 'GET',
                      data: {
                          //Passing Input parameter
                          id: $('#txtId').val()
                      },
                      success: function (result) {
                         //write something
                      },
                      error: function () {
                          alert("error");
                      }
                  });
                  return false;
              });
          });
      
      Suppose following is the Home controller having action result method named Details which takes id as input parameter.
      HomeController.cs
        public class HomeController : Controller
          {
              
              [HttpGet]
              public ActionResult Details(int id)
              {
              //write logic here to get data
      
              return View();
              }
          }
      Note
      • To work with jQuery we need to reference of jQuery library .You can use following CDN jQuery library from any provider such as Microsoft,Google or jQuery .
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
      To use above jQuery library you need an active internet connection , You can download and use it as offline .You need to be add reference as like below.
      <script src="~/Scripts/jquery-1.10.2.min.js"></script>
      From preceding example we have learned how to make  jQuery Ajax GET request with input parameter in ASP.NET MVC.
      Summary
      I hope this article is useful for all readers, If you have a suggestion related to this article then please contact me.
       To learn ASP.NET MVC step by step please refer following articles

      Creating ASP.NET Web API REST Service Step by Step

      Today's application need to be communicated on all cross platforms to fulfill the need of today's modern application, to fulfill these requirement lots of technologies are invented and they are used as per requirement. The Web API is one of the latest technology to fulfill the requirement of enterprise application.
      Let's learn about it step by step:
      What is ASP.NET Web API
      The ASP.NET Web API is one of the Microsoft open source technology to build the powerful REST Services which will communicate across all platform and devices over HTTP.
      Let us implement it practically by creating one sample application.

      Step 1 :
      Create ASP.NET Web API Service
      1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
      2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template" and provide the Project a name as you wish and click on OK, then the following windows will appear; select empty template and check on Web API as in the following image.


      3. Choose MVC empty application option and click OK.
      4. Now after adding the MVC project, the Solution Explorer will look like the following:


      After creating the ASP.NET Web API project, the preceding folder structure and files are added into the project by default which are same as MVC project, so let us learn about them in brief as in the following:

      • App_Start folder
        This folder contains the application configuration details such as routing, authentication, filtering of URL and so on.
      • Controller
        This folder contains the controller and their methods. The controller is responsible for processing the user request and return output as a view.
      • Models
        This folder contains the entities or properties used to store the input values.
      Step 2 : Create Model Class.

      Right click on Model folder in the created Web API application, give the class name EmpModel or as you wish and click on OK.


      Now write the following code into the EmpModel Class.
      EmpModel.cs
      public class EmpModel  
          {  
              public string Name { get; set; }  
              public string City { get; set; }  
          } 

      Step 3 : Add Web API Controller.

      Right click on Controller folder in the created Web API application and Web API 2 Empty controller as in the following,


      Now click on add and give the class name Home or as you wish and click OK as:



      Now we have added Model class and web API controller class. Let's create the method into the HomeController class as in the following,

      HomeController.cs
      using System;  
      using System.Web.Http;  
        
      namespace CreatingWebAPIService.Controllers  
      {  
          public class HomeController : ApiController  
          {  
              [HttpPost]  
              public bool AddEmpDetails()  
              {  
                  return true;  
                  //write insert logic  
        
              }  
              [HttpGet]  
              public string GetEmpDetails()  
              {  
                  return "Vithal Wadje";  
        
              }  
              [HttpDelete]  
              public string DeleteEmpDetails(string id)  
              {  
                  return "Employee details deleted having Id " + id;  
        
              }  
              [HttpPut]  
              public string UpdateEmpDetails(string Name, String Id)  
              {  
                  return "Employee details Updated with Name " + Name + " and Id " + Id;  
        
              }  
          }  
        
      }  
      In this above code we have created four methods for Insert, Update, Display and delete the records .The above web API controller methods defined with HTTP methods which are the following,
      • GET: Get the resource (Records) from particular source such as SQL database.
      • POST: Used to insert the records into the particular source such as SQL, Oracle database.
      • PUT: Used to modify the resource or records.
      • DELETE : Used to delete the specific resource or record from particular source.
       Step 4: Run the application.
      Now everything is ready lets run the application, it will throw the following error:

       

      The reason of above error is we are not following the url structure which are set into the routing of web API application. The following is the default URL structure of ASP.NET Web API defined into the WebApiConfig.cs file.



      From the above routing structure, we can access the resource using  url format i.e Base url+api+apicontroller. Unlike MVC controller the web controller by default access all the methods just using controller name. Now our service is ready. Let's test it using REST client browser extension because browser only supports Get request directly from URL not others .

      Our REST Service URL will be http://localhost:56290/api/Home which is described as follows,
      • http://localhost:56290: Is the base address of web API service, It can be different as per your server.
      • api: It is the used to differentiate between Web API controller and MVC controller request .
      • Home: This is the Web API controller name.
      Step 5: Testing Web API REST service using REST client.

       Now let us test the application using REST client as:

      POST:



      In the above image Web API REST Service, HTTP POST method returns the 200 Status code means REST service is successfully executed.
      GET Method


      In the above image Web API REST Service, HTTP GET method returns the 200 Status code means REST service is successfully executed and return the XML format output.

      Note
      • The  Web API REST service by default return the output as per browser default message header such as XML or JSON.
      The above XML output return in Firefox browser., Now let's change the browser as IE, then output will return in JSON format as in the following,


      From the above output its clear that output format by default depend on browser message format header.
      Delete Method

      In the above image Web API REST Service, HTTP Delete method returns the 200 Status code means REST service is successfully executed and return the XML format output. I hope from the preceding examples we learned how to create Web API REST Service.

      Note:
      • Download the Zip file of the sample application for a better understanding.
      • In my next article, Introduction ASP.NET Web API we will learn what is Web API REST Service, When and where to use Web API REST Service.
      Summary

      I hope this article is useful for all readers. If you have any suggestions, then please mention it in the comment section.

      Folder Structure of ASP.NET MVC Application

      Day by day ASP.NET MVC becomes the popular framework among the developers because of clean code and folder structure.In this first article of ASP.NET MVC articles series we will understand  folder structure of ASP.NET MVC application.
      Many new developer and students are struggling to learn ASP.NET MVC in quick time and in MVC lots of technologies are used like javascript , jQuery , AngularJs , Typescript ,Dapper ,Entity framework and much more because of this developers and students get confused how to start learning ? , by considering above problem and help students and developers who wants to learn quick about MVC, I have decided to start series of articles on ASP.NET MVC .

       MVC And Convention standard

      ASP.NET MVC applications, by default, depends  heavily on conventions. This allows developers to
      avoid having to configure and specify things that can be inferred based on convention by adding code through Scaffolding .
      For instance, MVC uses a convention-based directory-naming structure when resolving View templates and this convention allows you to omit the location path when referencing views from within a Controller class.
      MVC is designed around some sensible convention-based defaults that can be overridden as needed.
      This concept is commonly referred to as "convention over configuration" which popular concepts of Ruby on Rails programming language.
      The convention over configuration concept implemented in ASP.NET MVC with the help of following main directories
      • Controllers
      • Models
      • Views   
      Key points 
      • Each controller name ends with suffix controller.
      • The single view directory can be used for entire application.
      • By default all directories (folder) created with name of controller name.
      Let's add the ASP.NET MVC application so it will create folder structure under the project solution explorer.
      Step 1 : Create MVC Application To Create Folder structure
      1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
      2. "File", then "New" and click "Project..." then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK .
      The preceding project solution explorer you have seen different folders and files . The preceding folder structure may be different according your MVC project template , So let us learn about major folders in brief as in the following:
      • App_Data
      • App_Start
      • Content
      • Controllers
      • Models
      • views
      • Script
      •  App_Data
      This folder is used to store file based database such as sql server .mdf files or xml files etc.like in following image

      • Controller 
       This folder contains the controller and their methods. The controller is responsible for processing the user request and return output.
      •  Models
      This folder contains the class files for entities or properties used to store the input values.
       You can rename the folder Model and you can give any name as you wish ,its not mandatory that the folder name should be Models however model name is only for better naming conventions . also Model can be created in separate class library project .

      • View
      This folder contains the UI pages including shared page, .CSHTMl, .VBHTML, HTML,aspx pages that show the output to the end user.
      •  Content 
      This folder is used to store files related to design and UI such as CSS files ,images which is require for UI..
      • Script
      This folder contains the Script files such as JavaScript ,jQuery ,AngularJs ,TypeScript etc.


      From preceding example we have learned how the folder structure architectures and use of each folder.
      Note:
      Its not mandatory that you should use above folder structure and naming conventions, You can rename it and  follow different folder structure as you wish.

      To learn more about MVC basic in terms of to understand preceding folder structure practically please refer following videos series.
      MVC Basic Videos.
      Summary
      I hope this article is useful for all readers, if you have a suggestion then please contact me.To learn ASP.NET MVC step by step please refer following articles
      For more MVC article ,please refer www.compilemode.com , MVC section using following link.

        Calendar Control Using Model Class in ASP.NET MVC

        Many times we need to work with calendar control to fulfill business requirements but many times there is lots of scripting involved like jQuery, JavaScript etc. when you wants to work with calendar control .
        MVC is a very powerful framework with a wide range of built in features and to display calendar control without jQuery and javascript we will use the Data Annotation. So let's see step by step so a beginner can also understand .
        Step 1: Create an MVC Application.
        Now let us start with a step by step approach from the creation of a simple MVC application as in the following:
        1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
        2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
         As shown in the preceding screenshot, click on Empty template and check MVC option, then click OK. This will create an empty MVC web application whose Solution Explorer will look like the following:
         Step 3: Create Model Class.
        Now let us create the model class named EmpModel.cs by right clicking on model folder as in the following screenshot:
         Note:
        It is not mandatory that Model class should be in Model folder, it is just for better readability you can create this class anywhere in the solution explorer. This can be done by creating different folder name or without folder name or in a separate class library.
        EmpModel.cs class code snippet:
        using System;  
        using System.ComponentModel.DataAnnotations;  
          
        namespace UsingCalendarControlWithoutScriptInMVC.Models  
        {  
            public class EmpModel  
            {  
                /// <summary>  
                /// DOB datetime data type property   
                /// to display date type control  
                /// </summary>  
                [Display(Name = "Date of Birth")]                 
                [DataType(DataType.Date)]  
                public DateTime ? DOB { get; set; }  
            }  
        }  
        Step 4 : Create Controller.

        Now let us add the MVC 5 controller as in the following screenshot:
         After clicking on Add button it will show the window. specify the Controller name as Home with suffix Controller.
        Note: The controller name must be having suffix as 'Controller' after specifying the name of controller. Now the default code in HomeController.cs will look like as follows,
        using System.Web.Mvc;  
          
        namespace UsingCalendarControlWithoutScriptInMVC.Controllers  
        {  
            public class HomeController : Controller  
            {  
                // GET: Home  
                public ActionResult Index()  
                {  
                    return View();  
                }  
            }  
        }  
        Don't change preceding code of HomeController as we are not going to add additional functionality.
        Step 5 : Create View.
        To create the View , right click on view folder and then click Add view. Now specify the view name as Index or as you wish, choose create scaffolding template and model class EmpModel.cs and click on Add button. 
        After clicking on Add button it will create the Index view having extension .cshtml , Now the following default code is generated into the Index.cshtml as,
        Index.cshtml
        @model UsingCalendarControlWithoutScriptInMVC.Models.EmpModel  
          
        @{  
            ViewBag.Title = "www.compilemode.com";  
        }  
        @using (Html.BeginForm())  
        {  
            @Html.AntiForgeryToken()  
          
            <div class="form-horizontal">  
          
                <hr />  
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
                <div class="form-group">  
                    @Html.LabelFor(model => model.DOB, htmlAttributes: new { @class = "control-label col-md-2" })  
                    <div class="col-md-10">  
                        @Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control" } })  
                        @Html.ValidationMessageFor(model => model.DOB, "", new { @class = "text-danger" })  
                    </div>  
                </div>  
          
          
            </div>  
        }  
        Step 6: Run the Application.
        Now run the application the Index view appears as in the following screenshots. The Calendar UI differs as per browser.
        Microsoft Edge: The calendar control in Microsoft Edge browser will look like as follows,

        The well designed calendar control will be displayed as shown in the preceding image. Now choose the data , then the date will  look like as follows,


        Google Chrome: The calendar control in Google Chrome browser will be look like as follows,
         Now Display only month in calendar,
         Opera: The calendar control in Opera  browser will look like as follows,

        From the preceding examples we have learned how to display calendar control in  ASP.NET MVC without jQuery and javascript.
        Note:
        • Data Annotation Date Data type calendar only support to those browser which are fully capable of HTML 5 date type .
        • IE and Firefox does not support to HTML 5 date type , So this example will not be work on IE and Firefox.
        • This Demo fully works on Google Chrome ,Microsoft Edge , Opera and Safari browser because the support HTML 5 date type.
        • You can customize calendar including date format as per your need.
        • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
        • This application is created completely focusing on beginners.
        Summary
        I hope this article is useful for all readers. If you have any suggestions please contact me.
        Read more articles on ASP.NET MVC:

        www.CodeNirvana.in

        Protected by Copyscape
        Copyright © Compilemode