Wednesday, 31 August 2016

Object Caching

Caching is the technique for storing frequently used data on the server to fulfill subsequent requests. there are a lots of way to store data in cache. Object Caching is one of them. Object Cache stores data in simple name/value pairs.

To Use this we need to use System.Runtime.Caching namespace. this is introduced in .Net 4.0. 
here I'm going to create a simple example to store data in Object Cache.

first, you need to add a reference of System.Runtime.Caching object in your project.


To add value in Cache, create a function like this

        public void SetCache(object value, string key)
        {
            ObjectCache cache = MemoryCache.Default;
            cache.Add(key, value, DateTime.Now.AddDays(1));
        }

In the above code, the first line is used to reference to the default MemoryCache instance. Using the new .NET Caching runtime, you can have multiple MemoryCaches inside a single application.

In the next line we are adding the object to the cache along with a key. The key allows us to retrieve this when you want.

To Get the Cache object you can create a new function like below

        public string GetCache(string key)
        {
            ObjectCache cache = MemoryCache.Default;
            return (string)cache[key];
        }

You can create the above function more reusable

        static readonly ObjectCache Cache = MemoryCache.Default;

        /// <summary>
        /// get cached data
        /// </summary>
        /// <typeparam name="T">Type of cached data</typeparam>
        /// <param name="key">Name of cached data</param>
        /// <returns>Cached data as type</returns>
        public static T Get<T>(string key) where T : class
        {
            try
            {
                return (T)Cache[key];
            }
            catch
            {
                return null;
            }
        }

I am attaching a little class, which you can easily use in your projects to use Caching.





Continue Reading →

Wednesday, 3 August 2016

Calling WebApi from MVC layer

In this Project you will be able to learn how you can call Web Api functions from MVC Layer project.

Follow the Steps:

1- First Create a new MVC4 Project.
2- In the same solution add a Web Api Project.


3- In the API Project, Add a Employee Model in Model Folder.

 public class EmployeeModel  
   {  
     public int EmpId { get; set; }  
     public string Name { get; set; }  
     public string Address { get; set; }  
   }  

4- In the Values API Controller Replace this function to get Employee data.

   public class ValuesController : ApiController  
   {  
     // GET api/values  
     public IEnumerable<EmployeeModel> Get()  
     {  
       List<EmployeeModel> list = new List<EmployeeModel>();  
       for (int i = 0; i < 10; i++)  
       {  
         EmployeeModel emp = new EmployeeModel();  
         emp.EmpId = i;  
         emp.Name = "Emp" + i;  
         emp.Address = "Delhi" + i;  
         list.Add(emp);  
       }  
       return list;  
     }  
   }  

5- Now Run the Web Api Project.


6- Now come to your MVC Project. Add this key in Web.config file.
<add key="baseurl" value="http://localhost:6763" />

Above Key contains the base url of Web Api.

7- In the Home Controller,  Add the Below Code.

     string apiUrl = ConfigurationManager.AppSettings["baseurl"]+"/api/Values/";  
     HttpClient client;  
     public HomeController()  
     {  
       client = new HttpClient();  
       client.BaseAddress = new Uri(apiUrl);  
       client.DefaultRequestHeaders.Accept.Clear();  
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
     }  

The above Code is required for getting data from Web Api.

8- In the MVC Project, Add a Employee Model in Model Folder.

 public class EmployeeModel  
   {  
     public int EmpId { get; set; }  
     public string Name { get; set; }  
     public string Address { get; set; }  
   }  


9- Now we will write the Code to fetch data from Web Api. For this I am using Index Action method in Home Controller.

  //  
     // GET: /Home/  
     public async Task<ActionResult> Index()  
     {  
       List<EmployeeModel> emp = new List<EmployeeModel>();  
       HttpResponseMessage responseMessage = await client.GetAsync(apiUrl);  
       if (responseMessage.IsSuccessStatusCode)  
       {  
         var responseData = responseMessage.Content.ReadAsStringAsync().Result;  
         emp = JsonConvert.DeserializeObject<List<EmployeeModel>>(responseData);  
       }  
       return View(emp);  
     }  

10- Add/Replace Index View.

 @model IEnumerable<WebApiWithMVC.Models.EmployeeModel>  
 @{  
   ViewBag.Title = "Index";  
 }  
 <h2>Index</h2>  
 <p>  
   @Html.ActionLink("Create New", "Create")  
 </p>  
 <table>  
   <tr>  
     <th>  
       @Html.DisplayNameFor(model => model.EmpId)  
     </th>  
     <th>  
       @Html.DisplayNameFor(model => model.Name)  
     </th>  
     <th>  
       @Html.DisplayNameFor(model => model.Address)  
     </th>  
     <th></th>  
   </tr>  
 @foreach (var item in Model) {  
   <tr>  
     <td>  
       @Html.DisplayFor(modelItem => item.EmpId)  
     </td>  
     <td>  
       @Html.DisplayFor(modelItem => item.Name)  
     </td>  
     <td>  
       @Html.DisplayFor(modelItem => item.Address)  
     </td>  
   </tr>  
 }  
 </table>  

11- Now Debug your Mvc Project. But before running Mvc project make sure your Web Api is running.




12- Please do not forget to share with your techie friends. You can download the complete project here Download

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives