Tuesday, 2 February 2016

Configure signalr in Mvc using Visual Studio 2012

 Asp.net signalr is used to transfer the data between server and client asynchronously and it is real time communication between server and client.Asp.net signalr maintains persistent connection between server and client. Using signalr we can create multiuser real time applications and chat applications. This is typically required for the real time monitoring applications.Signalr has Hub class to allow the client and server to call methods each other.

The easiest way to setup signalr in mvc is using nugget package manager.
Create sample mvc project name it as SignalRMVC=>Right click on project and click on Manage Nuget Packages and search with signalR now select Microsoft Asp.Net SignalR and click on install,now The SignalR will be successfully installed in your project.

Create one folder name it as Hubs and add one class to this folder and name it as Startup
Please write the following code in Startup class

public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }

The Startup class will be look like as below

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }

Now run the application you will get the following error

The following errors occurred while attempting to load the app.
- No assembly found containing an OwinStartupAttribute.
- No assembly found containing a Startup or [AssemblyName].Startup class.
To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.

or

Cannot create/shadow copy 'WebGrease' when that file already exists.

To resolve this you need to add one key in Appsettings in web.config

<add key="owin:AppStartup" value="SignalRMVC.Hubs.Startup" />

SignalRMVC.Hubs.Startup is namespace of your Startup class
SignalrMVC is project name and Hubs is folder name and Startup calss
Now the run the application it will run successfully.
To check whether Signalr install on your application or not ,go to browser and type “http://localhost:58206/signalr/hubs

/signalr/hubs and you will get





keywords:asp.net signalr setup,signalr setup in mvc ,signalr setup in visal studio,signalr configure in visual studio 2010,signalr configure in visual studio 2012,signalr configure in visual studio 2013,signalr configure in visual studio 2015,configure in signalr in mvc in visual studio 2013,signalr in mvc ,signalr chat application ,signalr application ,signalr 





Wednesday, 6 January 2016

Call Web Api from Mvc Controller



This tutorial will explain how to call a web api from Mvc Controller
Oftenly we will cal web api from Jquery using ajax call but here we call web api from C# using HttpClient library.we call web api’s from Windows application and console application using http client libraries.

So Httpclient libraries are very useful for calling web api from mvc application ,windows application and console application and also windows 8 application.
To enhance the  responsiveness of application we will use Asynchronous programming for that we will use async , await ,Task and  ReadAsync and GetAsync keywords.

Async and Await many methods could not return output immediately, they wait for other asynchronous programs execution. An Async method returns only Void or Task.

Task returns no value if it is void .If a Task<string> returns string value, this is generic type.

The GetAsync method is asynchronous method and it sends http get request , the await keyword is suspends execution until asynchronous method completes, it returns HttpResponseMessage that contains Http response.

If the IsSuccessStatusCode is true the response code contain Json ,the ReadAsync method is deserialize Json object to Users Model and IsSuccessStatusCode property is false it returns error code.

Create a MVC project , add one controller and  Action method to the MVC project and add one view to the corresponding action method ,write the following method.

For fake api  I took this url: http://jsonplaceholder.typicode.com/posts/1

Decorate your attribute with HttpGet Attribute

[HttpGet]
        public async Task<JsonResult> getdata()
        {
            Users user=null;
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                // New code:
                HttpResponseMessage response = await client.GetAsync("posts/1");
                if (response.IsSuccessStatusCode)
                {
                     user = await response.Content.ReadAsAsync<Users>();  
                }
            }

            return Json(user, JsonRequestBehavior.AllowGet);
           
        }
Here Users is Model Class to persist data
public class Users
    {
        public int userId { get; set; }
        public int id { get; set; }
        public string title { get; set; }
        public string body { get; set; }
    }


 In fiddler we will get the following result



  Tags: call api from c#,call web api from C# controller, call web api from Mvc,calling api from C#,
calling api from asp.net,calling api from jquery,call web api  from controller,consume api in C#,consume web api from C#










Saturday, 28 November 2015

Static RadiobuttonList in AngularJs

This  article will teach you the basics of Radiobutton list list in AngularJs with Asp.Net Mvc Application.Yo can use Microsoft Visual studio to follow this article.
Create a Sample Asp.Net Mvc application name it as AngularRadioButtonList.the project architecture doesn’t contain any angularjs scripts, so we need to add angularjs scripts from Nuget Packages.

Right click on project “AngularRadioButtonList”=>  select Manage Nuget Package=> on  top right search as angularjs ,you will get Angularjs related frameworks now select Angularjs and click on install.Now angularjs scripts successfully added your scripts Folder.

Angularjs doesn’t have directives to build radiobuttions like ng-options use to build select list.
Now create one mvc controller name it as radio and add one action method index


Add view to inde action method,now include following script from the scripts folder
<script src="~/Scripts/angular.min.js"></script>


See the below example
<script src="~/Scripts/angular.min.js"></script>
<script>
    angular.module('radioExample', [])
      .controller('ExampleController', ['$scope', function ($scope) {
      }]);
</script>

<form name="myForm" ng-app="radioExample">
    <div ng-controller="ExampleController">
        <label>
            <input type="radio" ng-model="country.name" value="India">
            India
        </label><br />
        <label>
            <input type="radio" ng-model="country.name" value="USA">
            USA
        </label><br />
        <label>
            <input type="radio" ng-model="country.name" value="China">
            China
        </label><br />
        <h3>Country = {{country.name | json}}</h3><br />
    </div>
</form>
                             
In the above example we need to include ng-app and ng-controller because ng-app is used to initialize angularjs application,the ng-app directive should be initialzed at root element of the application ,its not mandatory.
ng-controller is a javascript function,it prepares  the model for view. The ng-controller attaches model to the scope.
Radio button in angularjs  has the following aruments.
ngModel,value,ngname, ngchange , ngValue

ngModel : it is a assignable angular expression ,we can assign dynamic data

value: whenever we select ngModel that value will be set to this value 
parameter. value supports only string values.

ngchange: this is like  radiobutton event ,it will execute when input changes

name:it is property name of the form.

ngValue: when radio button is selected ng-model value will be set to this ng-value.we can use it instead of value parameter.

Apart from now select the radio button it will display the selected radiobutton value.
Lets see the output


Tags:Radiobuton list in angularjs ,static radiobuttonlist in angularjs,dynamic radiobuttonlist  in angularjs,radiobuttonlist,angularjs radiobuttonlist ,mvc angularjs radiobutton,radiobuttonlist in angularjs, mvc radiobuton list in angularjs, radiobuttonlist  in angularjs from database


Saturday, 1 August 2015

Web Api CRUD Operations without Repository Using Entity Framework

CRUD stands for Create ,Read, Update and Delete, these are four basic standard database operations . How we implement these CRUD operations in  asp.net web api.
create webapi application
In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.


I will take one sample  Employee table with valid data
create one Employee table in database
Create Table Employee
(
EmployeeID int PRIMARY KEY identity(1,1),
Name varchar(50),
Age int,
Salary int
)
insert into Employee values('sasishekaraya',25,40000)

like this insert 2 more records

create one model name it as Employee

model is an object that represents the data in your application. In ASP.NET Web API, you can use strongly typed CLR objects as models, and they will automatically be serialized to XML or JSON for the client.
           
public class Employee
    {
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public int Salary { get; set; }
    }


The Database context class is Enity framework object.This class contains all collections of entities that map to tables in the database. The controller has to be access this Database context class so that it can perform CRUD operations.

Add database context class

public class DatabaseContext:DbContext
    {
        public DatabaseContext()
            : base("Name=DatabaseContext")
        {
            Database.SetInitializer<DatabaseContext>(null);
        }
        public DbSet<Employee> employee { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Employee>().ToTable("employee");
        }

    }



Install Entiry Framework From Manage NugetPackage

DbSet class is one of most important object in Entity framework.DbSet represents collection of entities.DbSet<TEntity> is generic version.


In web.config

<connectionStrings>
  
  <add name="DataBaseContext" connectionString="Data Source=SQLEXPRESS;Initial Catalog=Sample;Persist Security Info=True;User ID=sa;Password=007" providerName="System.Data.SqlClient" />
  </connectionStrings>

Add a web api controller,it handles the incoming  http requests

Create a controller name it as Employee

In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller.

The Employee API will expose several "read" actions as HTTP GET methods. Each action will correspond to a method in the ProductsController class.

public class EmployeeController : ApiController
    {
        DatabaseContext db = new DatabaseContext();

//This method is used to get Employee Details based on EmployeedID
        public Employee GetEmp(int id)
        {
            var emp = db.employee.FirstOrDefault(p => p.EmployeeID == id);
            return emp;
        }


//This method is used to add Employee to Database
        [HttpPost]                             
        public string AddEmployee(Employee emp)
        {
            db.employee.Add(emp);
            db.SaveChanges();
            return "Success";
        }
Or to post employee details to database
[HttpPost]
        public HttpResponseMessage AddEmployee(Employee emp)
        {
            db.employee.Add(emp);
            db.SaveChanges();
            var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);

            string uri = Url.Link("DefaultApi", new { id = emp.EmployeeID });
            response.Headers.Location = new Uri(uri);
            return response;

        }

Notice that the method return type is now HttpResponseMessage. By returning an HttpResponseMessage instead of a Employee, we can control the details of the HTTP response message, including the status code and the Location header.




//This method is used to get list of employees
        public List<Employee> GetAllEmployees()
        {
            var lstemps = db.employee.ToList();
            return lstemps;
        }
    }


This method is used to Update Employee Details
 //To update Employee Details
        [HttpPut]
        public string UpdateEmployee(Employee emp)
        {
            Employee empdetails = db.employee.Find(emp.EmployeeID);
            empdetails.Age = emp.Age;
            empdetails.Name = emp.Name;
            empdetails.Salary = emp.Salary;           
            db.SaveChanges();
            return "Success";
        }

This method is used to remove Employee Details


// To remove employee Details
        public string DeleteEmployee(int id)
        {
            Employee empdetails = db.employee.Find(id);
            db.employee.Remove(empdetails);
            db.SaveChanges();
            return   "Success";
        }

db.SaveChanges() method is used to save the changes to the database.

Employee Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiCRUD.Models;

namespace WebApiCRUD.Controllers
{
    public class EmployeeController : ApiController
    {
        DatabaseContext db = new DatabaseContext();
        public Employee GetEmp(int id)
        {
            var emp = db.employee.FirstOrDefault(p => p.EmployeeID == id);
            return emp;
        }
        [HttpPost]
        public HttpResponseMessage AddEmployee(Employee emp)
        {
            db.employee.Add(emp);
            db.SaveChanges();
            var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);

            string uri = Url.Link("DefaultApi", new { id = emp.EmployeeID });
            response.Headers.Location = new Uri(uri);
            return response;

        }
        public List<Employee> GetAllEmployees()
        {
            var lstemps = db.employee.ToList();
            return lstemps;
        }

        //To update Employee Details
        [HttpPut]
        public string UpdateEmployee(Employee emp)
        {
            Employee empdetails = db.employee.Find(emp.EmployeeID);
            empdetails.Age = emp.Age;
            empdetails.Name = emp.Name;
            empdetails.Salary = emp.Salary;           
            db.SaveChanges();
            return "Success";
        }
        // To remove employee Details
        public string DeleteEmployee(int id)
        {
            Employee empdetails = db.employee.Find(id);
            db.employee.Remove(empdetails);
            db.SaveChanges();
            return   "Success";
        }

    }
}




Test api

Rightclick on project =>manage nugget package=>search as testclient


we will get A ‘simple Test Client For Asp.Net Web Api’  click on install




Now run the Application




Click on the GetEmployee



click on TestApi





give the id and click on send you will get  the following result



tags:Web api curd operations,create ,update and delete in web api,curd operations web api 2.2 , curd operations in asp.net web api,sample web api application,realtime web api application and curd operations,web api headers and post data, web api employee curd operations,employee web api,employee asp.net web api.