<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Asp.Net &#8211; Sibeesh Passion</title>
	<atom:link href="https://sibeeshpassion.com/tag/asp-net/feed/" rel="self" type="application/rss+xml" />
	<link>https://sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:23:29 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Asp.Net &#8211; Sibeesh Passion</title>
	<link>https://sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Working With Test Client In Asp Net Web API Help Page</title>
		<link>https://sibeeshpassion.com/working-with-test-client-in-asp-net-web-api-help-page/</link>
					<comments>https://sibeeshpassion.com/working-with-test-client-in-asp-net-web-api-help-page/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Tue, 31 May 2016 00:00:33 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[How to test Web API]]></category>
		<category><![CDATA[Test Web API]]></category>
		<category><![CDATA[Web API Tester]]></category>
		<category><![CDATA[WebApiTestClient]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11654</guid>

					<description><![CDATA[[toc] Introduction In this article we are going to see how we test our API with the help of a package called WebApiTestClient. As you all know, if you create a sample API project you will get a folder HelpPage in Areas. This is for adding the XML description to each controller and actions we use in our API. If you document it well, any one can understand your API, so that you don&#8217;t need to explain what your API will do and what would be the output. If you are new to HelpPage implementation in API, please see here: [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this article we are going to see how we test our API with the help of a package called <em>WebApiTestClient</em>. As you all know, if you create a sample API project you will get a folder HelpPage in Areas. This is for adding the XML description to each controller and actions we use in our API. If you document it well, any one can understand your API, so that you don&#8217;t need to explain what your API will do and what would be the output. If you are new to HelpPage implementation in API, please see here: <a href="http://sibeeshpassion.com/working-with-api-help-page-controller-action-description-in-web-api/" target="_blank" rel="noopener">API help page controller action description in Web API</a>. Here I am going to create a <a href="http://sibeeshpassion.com/category/web-api" target="_blank" rel="noopener">Web API</a> with the help page descriptions in <a href="http://sibeeshpassion.com/category/tools/visual-studio/" target="_blank" rel="noopener">Visual Studio</a> 2015. And once after the project is ready I will install the <em>WebApiTestClient </em> package to my solution. I hope you will like this.</p>
<blockquote><p>Please be noted that this package is not officially released by Microsoft. This is a prototype created by <a href="https://social.msdn.microsoft.com/profile/Yao+-+MSFT" target="_blank" rel="noopener">Yao &#8211; MSFT</a></p></blockquote>
<h2><strong>Download the source code</strong></h2>
<p>You can always download the source code here: <a href="https://code.msdn.microsoft.com/Working-With-Test-Client-9fb65ba9" target="_blank" rel="noopener">API Test Client</a></p>
<h2><strong>Background</strong></h2>
<p>For the past few months, I had been working with API projects. Recently I was asked to create an application to test the API I created so that the testing team can test the API easily. Yes I agree that we have tools like Fiddler and Post Man for the same. Still we thought to create our own. As I started my development, I came to know about the package <em>WebApiTestClient</em> which does what we wanted. Finally we decided to stop developing the application and used this wonderful package. Here I am going to show you how can we use this.</p>
<h2><strong>Prerequisites</strong></h2>
<ul>
<li>Visual Studio With Web API Installed</li>
</ul>
<h2><strong>Things we are going to do</strong></h2>
<p>The following are the tasks we are going to do.</p>
<ul>
<li>Setting up database</li>
<li>Creating an Entity Framework</li>
<li>Creating API controller with the Model Created</li>
<li>Installing <em>WebApiTestClient</em></li>
<li>Configuring <em>WebApiTestClient</em></li>
<li>Testing <em>WebApiTestClient</em></li>
</ul>
<h2><strong>Setting up database</strong></h2>
<p>Here I am going to create a database which I created for my demo purposes, you can always create this database by running the queries mentioned here.</p>
<h3><strong>Create database</strong></h3>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object: Database [TrialsDB] Script Date: 5/12/2016 10:56:41 AM ******/<br />
CREATE DATABASE [TrialsDB]<br />
CONTAINMENT = NONE<br />
ON PRIMARY<br />
( NAME = N&#8217;TrialsDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf&#8217; , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
LOG ON<br />
( NAME = N&#8217;TrialsDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf&#8217; , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECOVERY FULL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_WRITE<br />
GO<br />
[/sql]</p>
<h3><strong>Create table with data</strong></h3>
<p>[sql]<br />
USE [TrialsDB]<br />
GO<br />
/****** Object: Table [dbo].[Product] Script Date: 5/12/2016 10:54:48 AM ******/<br />
SET ANSI_NULLS ON<br />
GO<br />
SET QUOTED_IDENTIFIER ON<br />
GO<br />
CREATE TABLE [dbo].[Product](<br />
[ProductID] [int] NOT NULL,<br />
[Name] [nvarchar](max) NOT NULL,<br />
[ProductNumber] [nvarchar](25) NOT NULL,<br />
[MakeFlag] [bit] NOT NULL,<br />
[FinishedGoodsFlag] [bit] NOT NULL,<br />
[Color] [nvarchar](15) NULL,<br />
[SafetyStockLevel] [smallint] NOT NULL,<br />
[ReorderPoint] [smallint] NOT NULL,<br />
[StandardCost] [money] NOT NULL,<br />
[ListPrice] [money] NOT NULL,<br />
[Size] [nvarchar](5) NULL,<br />
[SizeUnitMeasureCode] [nchar](3) NULL,<br />
[WeightUnitMeasureCode] [nchar](3) NULL,<br />
[Weight] [decimal](8, 2) NULL,<br />
[DaysToManufacture] [int] NOT NULL,<br />
[ProductLine] [nchar](2) NULL,<br />
[Class] [nchar](2) NULL,<br />
[Style] [nchar](2) NULL,<br />
[ProductSubcategoryID] [int] NULL,<br />
[ProductModelID] [int] NULL,<br />
[SellStartDate] [datetime] NOT NULL,<br />
[SellEndDate] [datetime] NULL,<br />
[DiscontinuedDate] [datetime] NULL,<br />
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,<br />
[ModifiedDate] [datetime] NOT NULL<br />
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]<br />
GO<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (1, N&#8217;Adjustable Race&#8217;, N&#8217;AR-5381&#8242;, 0, 0, NULL, 1000, 750, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;694215b7-08f7-4c0d-acb1-d734ba44c0c8&#8242;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (2, N&#8217;Bearing Ball&#8217;, N&#8217;BA-8327&#8242;, 0, 0, NULL, 1000, 750, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;58ae3c20-4f3a-4749-a7d4-d568806cc537&#8242;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (3, N&#8217;BB Ball Bearing&#8217;, N&#8217;BE-2349&#8242;, 1, 0, NULL, 800, 600, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;9c21aed2-5bfa-4f18-bcb8-f11638dc2e4e&#8217;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (4, N&#8217;Headset Ball Bearings&#8217;, N&#8217;BE-2908&#8242;, 0, 0, NULL, 800, 600, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;ecfed6cb-51ff-49b5-b06c-7d8ac834db8b&#8217;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (316, N&#8217;Blade&#8217;, N&#8217;BL-2036&#8242;, 1, 0, NULL, 800, 600, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;e73e9750-603b-4131-89f5-3dd15ed5ff80&#8242;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (317, N&#8217;LL Crankarm&#8217;, N&#8217;CA-5965&#8242;, 0, 0, N&#8217;Black&#8217;, 500, 375, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, N&#8217;L &#8216;, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;3c9d10b7-a6b2-4774-9963-c19dcee72fea&#8217;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (318, N&#8217;ML Crankarm&#8217;, N&#8217;CA-6738&#8242;, 0, 0, N&#8217;Black&#8217;, 500, 375, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, N&#8217;M &#8216;, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;eabb9a92-fa07-4eab-8955-f0517b4a4ca7&#8217;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
[/sql]</p>
<h3>Create application</h3>
<p>Our database is ready, now create a Web API application in visual studio and then entity with the above mentioned database.</p>
<div id="attachment_11556" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Creating-Entity-e1463031313825.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-11556" class="size-large wp-image-11556" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Creating-Entity-1024x542.png" alt="Creating Entity" width="634" height="336" /></a><p id="caption-attachment-11556" class="wp-caption-text">Creating Entity</p></div>
<p>If you don&#8217;t know how to create an entity in your solution, please read that <a href="http://sibeeshpassion.com/web-api-with-angular-js/" target="_blank" rel="noopener">here</a>. I have mentioned the steps to be followed in that article. Once you have created the entity, you are good to go and create a API controller with the entity created. If you do so, The CRUD actions will be created automatically for you. You may need to edit those actions according to your needs.</p>
<div id="attachment_11557" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319.png"><img decoding="async" aria-describedby="caption-attachment-11557" class="size-full wp-image-11557" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319.png" alt="Web API 2 Controller with actions, using Entity Framework" width="650" height="457" srcset="/wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319.png 650w, /wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319-300x211.png 300w, /wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319-400x281.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11557" class="wp-caption-text">Web API 2 Controller with actions, using Entity Framework</p></div>
<p>Select the Model Class, DBContext then name your controller and click OK. I hope a controller with the CRUD actions. Now we can modify that as follows.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Data;<br />
using System.Data.Entity;<br />
using System.Data.Entity.Infrastructure;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Net.Http;<br />
using System.Web.Http;<br />
using System.Web.Http.Description;<br />
using ControllerActionDescriptions.Models;</p>
<p>namespace ControllerActionDescriptions.Controllers<br />
{<br />
public class ProductsController : ApiController<br />
{<br />
private TrialsDBEntities db = new TrialsDBEntities();<br />
#region GetProducts<br />
/// &lt;summary&gt;<br />
/// Get all the products available<br />
/// GET: api/Products<br />
/// &lt;/summary&gt;<br />
public IQueryable&lt;Product&gt; GetProducts()<br />
{<br />
return db.Products;<br />
}<br />
#endregion</p>
<p>#region GetProductWithParameter<br />
/// &lt;summary&gt;<br />
/// Get a single product by id<br />
/// GET: api/Products/5<br />
/// &lt;param name=&#8221;id&#8221;&gt;&lt;/param&gt;<br />
/// &lt;/summary&gt;<br />
[ResponseType(typeof(Product))]<br />
public IHttpActionResult GetProduct(int id)<br />
{<br />
Product product = db.Products.Find(id);<br />
if (product == null)<br />
{<br />
return NotFound();<br />
}</p>
<p>return Ok(product);<br />
}<br />
#endregion<br />
// PUT: api/Products/5<br />
[ResponseType(typeof(void))]<br />
public IHttpActionResult PutProduct(int id, Product product)<br />
{<br />
if (!ModelState.IsValid)<br />
{<br />
return BadRequest(ModelState);<br />
}</p>
<p>if (id != product.ProductID)<br />
{<br />
return BadRequest();<br />
}</p>
<p>db.Entry(product).State = EntityState.Modified;</p>
<p>try<br />
{<br />
db.SaveChanges();<br />
}<br />
catch (DbUpdateConcurrencyException)<br />
{<br />
if (!ProductExists(id))<br />
{<br />
return NotFound();<br />
}<br />
else<br />
{<br />
throw;<br />
}<br />
}</p>
<p>return StatusCode(HttpStatusCode.NoContent);<br />
}</p>
<p>// POST: api/Products<br />
[ResponseType(typeof(Product))]<br />
public IHttpActionResult PostProduct(Product product)<br />
{<br />
if (!ModelState.IsValid)<br />
{<br />
return BadRequest(ModelState);<br />
}</p>
<p>db.Products.Add(product);</p>
<p>try<br />
{<br />
db.SaveChanges();<br />
}<br />
catch (DbUpdateException)<br />
{<br />
if (ProductExists(product.ProductID))<br />
{<br />
return Conflict();<br />
}<br />
else<br />
{<br />
throw;<br />
}<br />
}</p>
<p>return CreatedAtRoute(&#8220;DefaultApi&#8221;, new { id = product.ProductID }, product);<br />
}</p>
<p>// DELETE: api/Products/5<br />
[ResponseType(typeof(Product))]<br />
public IHttpActionResult DeleteProduct(int id)<br />
{<br />
Product product = db.Products.Find(id);<br />
if (product == null)<br />
{<br />
return NotFound();<br />
}</p>
<p>db.Products.Remove(product);<br />
db.SaveChanges();</p>
<p>return Ok(product);<br />
}</p>
<p>protected override void Dispose(bool disposing)<br />
{<br />
if (disposing)<br />
{<br />
db.Dispose();<br />
}<br />
base.Dispose(disposing);<br />
}</p>
<p>private bool ProductExists(int id)<br />
{<br />
return db.Products.Count(e =&gt; e.ProductID == id) &gt; 0;<br />
}<br />
}<br />
}<br />
[/csharp]</p>
<h2><strong>Installing WebApiTestClient</strong></h2>
<p>To install the package, please go to your Package Manage Console from NuGet Package Manager and run the following command.</p>
<p>[csharp]<br />
Install-Package WebApiTestClient<br />
[/csharp]</p>
<p>You can always get the details about the package <a href="https://www.nuget.org/packages/WebApiTestClient" target="_blank" rel="noopener">here</a>.</p>
<p>Once you install the package, you can see some files are added to your Script and Area folder as preceding.</p>
<div id="attachment_11655" style="width: 291px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Script-and-Area-Folder.png"><img decoding="async" aria-describedby="caption-attachment-11655" class="size-full wp-image-11655" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Script-and-Area-Folder.png" alt="Script and Area Folder" width="281" height="780" srcset="/wp-content/uploads/2016/05/Script-and-Area-Folder.png 281w, /wp-content/uploads/2016/05/Script-and-Area-Folder-108x300.png 108w, /wp-content/uploads/2016/05/Script-and-Area-Folder-216x600.png 216w" sizes="(max-width: 281px) 100vw, 281px" /></a><p id="caption-attachment-11655" class="wp-caption-text">Script and Area Folder</p></div>
<h2><strong>Configuring WebApiTestClient</strong></h2>
<p>To configure the WebApiTestClient, please go to the folder Areas-&gt;Views-&gt;Help and then click on Api.cshtml</p>
<div id="attachment_11656" style="width: 272px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Api-Cshtml.png"><img decoding="async" aria-describedby="caption-attachment-11656" class="size-full wp-image-11656" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Api-Cshtml.png" alt="Api Cshtml" width="262" height="232" /></a><p id="caption-attachment-11656" class="wp-caption-text">Api Cshtml</p></div>
<p>This is the view shown when you click on each API in your help page. Now add the preceding code block to that view.</p>
<p>[html]<br />
@Html.DisplayForModel(&#8220;TestClientDialogs&#8221;)<br />
@section Scripts<br />
{<br />
&lt;link href=&#8221;~/Areas/HelpPage/HelpPage.css&#8221; rel=&#8221;stylesheet&#8221; type=&#8221;text/css&#8221; /&gt;<br />
@Html.DisplayForModel(&#8220;TestClientReferences&#8221;)<br />
}<br />
[/html]</p>
<div id="attachment_11657" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Code-Block-e1464327127249.png"><img decoding="async" aria-describedby="caption-attachment-11657" class="size-full wp-image-11657" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Code-Block-e1464327127249.png" alt="Code Block" width="650" height="503" srcset="/wp-content/uploads/2016/05/Code-Block-e1464327127249.png 461w, /wp-content/uploads/2016/05/Code-Block-e1464327127249-300x232.png 300w, /wp-content/uploads/2016/05/Code-Block-e1464327127249-400x310.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11657" class="wp-caption-text">Code Block</p></div>
<h2><strong>Testing WebApiTestClient</strong></h2>
<p>Now run your API application and go to the help page for any controller action, you can see a button called Test API on the bottom. If you click on that you will get a pop where you can test your API action.</p>
<div id="attachment_11658" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-API-Client-Output-e1464327451839.png"><img decoding="async" aria-describedby="caption-attachment-11658" class="size-large wp-image-11658" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-API-Client-Output-1024x451.png" alt="Test API Client Output" width="634" height="279" /></a><p id="caption-attachment-11658" class="wp-caption-text">Test API Client Output</p></div>
<p>Now if you send your request by clicking the send button, you will get an output as follows.</p>
<div id="attachment_11659" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-API-Client-Output-With-Response-e1464327640682.png"><img decoding="async" aria-describedby="caption-attachment-11659" class="size-full wp-image-11659" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-API-Client-Output-With-Response-e1464327640682.png" alt="Test API Client Output With Response" width="650" height="484" srcset="/wp-content/uploads/2016/05/Test-API-Client-Output-With-Response-e1464327640682.png 479w, /wp-content/uploads/2016/05/Test-API-Client-Output-With-Response-e1464327640682-300x223.png 300w, /wp-content/uploads/2016/05/Test-API-Client-Output-With-Response-e1464327640682-400x298.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11659" class="wp-caption-text">Test API Client Output With Response</p></div>
<p>You can always give id parameter as follows.</p>
<div id="attachment_11660" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-Client-With-Parameters-e1464327873548.png"><img decoding="async" aria-describedby="caption-attachment-11660" class="size-full wp-image-11660" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-Client-With-Parameters-e1464327873548.png" alt="Test Client With Parameters" width="650" height="302" srcset="/wp-content/uploads/2016/05/Test-Client-With-Parameters-e1464327873548.png 650w, /wp-content/uploads/2016/05/Test-Client-With-Parameters-e1464327873548-300x139.png 300w, /wp-content/uploads/2016/05/Test-Client-With-Parameters-e1464327873548-400x186.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11660" class="wp-caption-text">Test Client With Parameters</p></div>
<p>You can also give content-length and content-type in your post request as follows.</p>
<div id="attachment_11661" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-Client-With-Post-e1464328070355.png"><img decoding="async" aria-describedby="caption-attachment-11661" class="size-full wp-image-11661" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-Client-With-Post-e1464328070355.png" alt="Test Client With Post" width="650" height="468" srcset="/wp-content/uploads/2016/05/Test-Client-With-Post-e1464328070355.png 496w, /wp-content/uploads/2016/05/Test-Client-With-Post-e1464328070355-300x216.png 300w, /wp-content/uploads/2016/05/Test-Client-With-Post-e1464328070355-400x288.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11661" class="wp-caption-text">Test Client With Post</p></div>
<div id="attachment_11662" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-Client-With-PUT-Request-e1464328191663.png"><img decoding="async" aria-describedby="caption-attachment-11662" class="size-full wp-image-11662" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-Client-With-PUT-Request-e1464328191663.png" alt="Test Client With PUT Request" width="650" height="542" srcset="/wp-content/uploads/2016/05/Test-Client-With-PUT-Request-e1464328191663.png 428w, /wp-content/uploads/2016/05/Test-Client-With-PUT-Request-e1464328191663-300x250.png 300w, /wp-content/uploads/2016/05/Test-Client-With-PUT-Request-e1464328191663-400x334.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11662" class="wp-caption-text">Test Client With PUT Request</p></div>
<h2><strong>References</strong></h2>
<ul>
<li><a href="https://blogs.msdn.microsoft.com/yaohuang1/2012/12/02/adding-a-simple-test-client-to-asp-net-web-api-help-page/" target="_blank" rel="noopener">Sample Test Client</a></li>
<li><a href="https://www.nuget.org/packages/WebApiTestClient" target="_blank" rel="noopener">WebApiTestClient</a></li>
</ul>
<p>Author has already posted the source code in GitHub, please check <a href="https://github.com/yaohuang/WebApiTestClient" target="_blank" rel="noopener">here</a>.</p>
<p>Have a happy coding!.</p>
<h2><strong>Conclusion</strong></h2>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><strong>Your turn. What do you think?</strong></h2>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/working-with-test-client-in-asp-net-web-api-help-page/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Encrypt And Decrypt ConnectionString In Web.Config File</title>
		<link>https://sibeeshpassion.com/encrypt-and-decrypt-connectionstring-in-web-config-file/</link>
					<comments>https://sibeeshpassion.com/encrypt-and-decrypt-connectionstring-in-web-config-file/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 16 May 2016 10:33:46 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[article]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Command Prompt]]></category>
		<category><![CDATA[Decrypt ConnectionString]]></category>
		<category><![CDATA[Encrypt ConnectionString]]></category>
		<category><![CDATA[How To]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11565</guid>

					<description><![CDATA[In this article we are going to see how we can encrypt and secure our connection string in our web config file. As you all know the connection string is the pillar of our data. I mean, without a connection string you just can&#8217;t create an application which does some database actions like retrieving the data, creating the data. We all know that the connection string is placed in the file called web config, so others too. If anyone needs to get the database information of your application, the first place he/she may look at will be the web config [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we are going to see how we can encrypt and secure our connection string in our web config file. As you all know the connection string is the pillar of our data. I mean, without a connection string you just can&#8217;t create an application which does some database actions like retrieving the data, creating the data. We all know that the connection string is placed in the file called web config, so others too. If anyone needs to get the database information of your application, the first place he/she may look at will be the web config file. Am I right? It is always recommend to encrypt the connection string of your application because the data we have there is highly sensitive. It must be secured. Here I am going to show you a demo of how we can do that, You can do the same thing in your Web API project, MVC project, Asp.Net 5 project, or any kind of templates you works with. I hope you will like this.</p>
<p><strong>Background</strong></p>
<p>I used to secure my config file if I am the who starts the project. Here you will get to know how easy the procedure is to encrypt the connection string. There is only a few steps to be followed. I will explain those. </p>
<p><strong>Agenda</strong></p>
<p>The following is the agenda we are going to follow. </p>
<li>Create an empty project, it can be any template(Asp.Net 5, Web API, MVC&#8230;)</li>
<li>Add a connection string</li>
<li>Encrypt the connection string</li>
<li>Decrypt the connection string</li>
<p><strong>Perquisites </strong></p>
<li>Visual Studio</li>
<li>SQL Server</li>
<p><strong>Create an empty project</strong></p>
<p>To create an empty project, go to File->New->New Project->Name the project->Select Empty->Click OK. Hope you get a solution as follows.</p>
<div id="attachment_11566" style="width: 384px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Empty-Solution.png"><img decoding="async" aria-describedby="caption-attachment-11566" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Empty-Solution.png" alt="Empty Solution" width="374" height="285" class="size-full wp-image-11566" srcset="/wp-content/uploads/2016/05/Empty-Solution.png 374w, /wp-content/uploads/2016/05/Empty-Solution-300x229.png 300w" sizes="(max-width: 374px) 100vw, 374px" /></a><p id="caption-attachment-11566" class="wp-caption-text">Empty Solution</p></div>
<p>Now We will connect to a database. To connect, please click on the connect icon in your server explorer window and connect you Local/Server database.</p>
<div id="attachment_11567" style="width: 515px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Connect-to-Database.png"><img decoding="async" aria-describedby="caption-attachment-11567" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Connect-to-Database.png" alt="Connect to Database" width="505" height="873" class="size-full wp-image-11567" srcset="/wp-content/uploads/2016/05/Connect-to-Database.png 505w, /wp-content/uploads/2016/05/Connect-to-Database-174x300.png 174w, /wp-content/uploads/2016/05/Connect-to-Database-400x691.png 400w, /wp-content/uploads/2016/05/Connect-to-Database-347x600.png 347w" sizes="(max-width: 505px) 100vw, 505px" /></a><p id="caption-attachment-11567" class="wp-caption-text">Connect to Database</p></div>
<p><strong>Add a connection string</strong></p>
<p>Now it is time to add our connection string, hope you got your data source of the database we already connected. The connection string property must be placed under configuration tag in your web config file. Here is mine.</p>
<p>[xml]<br />
&lt;connectionStrings&gt;<br />
    &lt;add name=&quot;myConnection&quot; connectionString=&quot;Data Source=SIBEESHVENU\SQLEXPRESS;Initial Catalog=ReportServer$SQLEXPRESS;Integrated Security=True&quot; /&gt;<br />
  &lt;/connectionStrings&gt;<br />
[/xml]</p>
<p>Now we will create a web page and in the page load event we will fetch this connection string and write it as a response. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.UI;<br />
using System.Web.UI.WebControls;</p>
<p>namespace EncryptConnectionString<br />
{<br />
    public partial class Default : System.Web.UI.Page<br />
    {<br />
        protected void Page_Load(object sender, EventArgs e)<br />
        {<br />
            if (!IsPostBack)<br />
            {<br />
                try<br />
                {<br />
                    string myCon = System.Configuration.ConfigurationManager.ConnectionStrings[&quot;myConnection&quot;].ConnectionString;<br />
                    if (myCon != null)<br />
                    {<br />
                        Response.Write(&quot;My connection string is :&quot; + myCon);<br />
                    }<br />
                }<br />
                catch (Exception)<br />
                {</p>
<p>                    throw;<br />
                }<br />
            }<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Please run your page, you will see your connection string in your page.</p>
<div id="attachment_11568" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Connection-string-response-e1463302112567.png"><img decoding="async" aria-describedby="caption-attachment-11568" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Connection-string-response-1024x47.png" alt="Connection string response" width="634" height="29" class="size-large wp-image-11568" /></a><p id="caption-attachment-11568" class="wp-caption-text">Connection string response</p></div>
<p><strong>Encrypt connection string</strong></p>
<p>To start the process, you must open your command window with the admin privilege. Then type the following command.</p>
<p>[csharp]<br />
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319<br />
[/csharp]</p>
<p>This command will narrate you to the framework version folder given. Now right click on your project and click open folder in file explorer and then copy the location. For me it is <em>F:\Visual Studio\EncryptConnectionString\EncryptConnectionString</em>. Now please go back to your command prompt and type the command as follows.</p>
<p>[csharp]<br />
ASPNET_REGIIS -PEF &quot;connectionStrings&quot; &quot;F:\Visual Studio\EncryptConnectionString\EncryptConnectionString&quot;<br />
[/csharp]</p>
<p>Once you click the enter. You will get the output as follows.</p>
<div id="attachment_11569" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Encrypt-ConnectionString-Output-e1463303289891.png"><img decoding="async" aria-describedby="caption-attachment-11569" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Encrypt-ConnectionString-Output-e1463303289891.png" alt="Encrypt ConnectionString Output" width="650" height="422" class="size-full wp-image-11569" srcset="/wp-content/uploads/2016/05/Encrypt-ConnectionString-Output-e1463303289891.png 650w, /wp-content/uploads/2016/05/Encrypt-ConnectionString-Output-e1463303289891-300x195.png 300w, /wp-content/uploads/2016/05/Encrypt-ConnectionString-Output-e1463303289891-400x260.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11569" class="wp-caption-text">Encrypt ConnectionString Output</p></div>
<p>Please be noted that the text <em>connectionStrings</em> is case sensitive. If you don&#8217;t give it as it is, you will get an error as follows.</p>
<p>[csharp]<br />
C:\Windows\Microsoft.NET\Framework\v4.0.30319&gt;ASPNET_REGIIS -PEF &quot;connectionstrings&quot; &quot;F:\Visual Studio\EncryptConnectionString\EncryptConnectionString&quot;<br />
Microsoft (R) ASP.NET RegIIS version 4.0.30319.0<br />
Administration utility to install and uninstall ASP.NET on the local machine.<br />
Copyright (C) Microsoft Corporation.  All rights reserved.<br />
Encrypting configuration section&#8230;<br />
The configuration section &#8216;connectionstrings&#8217; was not found.<br />
Failed!<br />
[/csharp]</p>
<p>So please be careful while you type the commands. Now I am going back to our application and see the config file. Shall we? You can see the connection string is encrypted as follows.</p>
<p>[xml]<br />
&lt;connectionStrings configProtectionProvider=&quot;RsaProtectedConfigurationProvider&quot;&gt;<br />
    &lt;EncryptedData Type=&quot;http://www.w3.org/2001/04/xmlenc#Element&quot;<br />
      xmlns=&quot;http://www.w3.org/2001/04/xmlenc#&quot;&gt;<br />
      &lt;EncryptionMethod Algorithm=&quot;http://www.w3.org/2001/04/xmlenc#tripledes-cbc&quot; /&gt;<br />
      &lt;KeyInfo xmlns=&quot;http://www.w3.org/2000/09/xmldsig#&quot;&gt;<br />
        &lt;EncryptedKey xmlns=&quot;http://www.w3.org/2001/04/xmlenc#&quot;&gt;<br />
          &lt;EncryptionMethod Algorithm=&quot;http://www.w3.org/2001/04/xmlenc#rsa-1_5&quot; /&gt;<br />
          &lt;KeyInfo xmlns=&quot;http://www.w3.org/2000/09/xmldsig#&quot;&gt;<br />
            &lt;KeyName&gt;Rsa Key&lt;/KeyName&gt;<br />
          &lt;/KeyInfo&gt;<br />
          &lt;CipherData&gt;<br />
            &lt;CipherValue&gt;B4B3oZrbpQsYM7Eaq5smukqDj9XUYUCwygBYRG1iasN4ll5W4wAKVCIFCRfvOJGoIXzgqpyjAI30IKf5pnZ/xWqmo3p/wGfOKdMrzd041dt9llLGbxFpLJs0Nkm583PJ1FppXLAy7FOD0YoBVhG/PBtBgLjTQqcXRNbVcgufzuArlv/EH+7lzSNRclXSTMOPMtISF65hPI9ICj9qLx7RBGhVZ6uFZVFteyyuRd2i3D2r7wJfr6KflFkakdxp1OWE2JK4Ldb8kZSwAy3bNaI/qaV9EgIWt9wM6RZO/IrI3kI/bX8JuvirPw3j/+TLDB3MoIgKjSbLpR3GYTm9csPu8g==&lt;/CipherValue&gt;<br />
          &lt;/CipherData&gt;<br />
        &lt;/EncryptedKey&gt;<br />
      &lt;/KeyInfo&gt;<br />
      &lt;CipherData&gt;<br />
        &lt;CipherValue&gt;0n1Y6ScSNZDR4x1sXfK05w9h+pp2OrAEQFQsoAUP5Y/hPsfpJS/7jv21PbPlkYmdCzycM4PGGb0+fuffR3RuL1x0tn7rfyUdA9llTfkyRQKwS9xOmkMsVFXgQDr8P4aXGef1fZPE2gjhcjm/JQToLwsfQZK1gNr4d6cIPFNqKD6wt24F7fuySJPX3OgLb8wXfQMd7ij+JcZzNlnyNHbq/DIjxSpPOnMrC52t06Jj8F8+MsSud9GcijcFB2UhvLVXQwyZ51nEj6Tf36Zbca8bgw==&lt;/CipherValue&gt;<br />
      &lt;/CipherData&gt;<br />
    &lt;/EncryptedData&gt;<br />
  &lt;/connectionStrings&gt;<br />
[/xml]</p>
<p><strong>Decrypt connection string</strong></p>
<p>You can always decrypt the connection string if you want, to decrypt you just need follows the commands as follows in the command prompt.</p>
<p>[csharp]<br />
cd C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319<br />
[/csharp]</p>
<p>Once after you did you the above command you can execute the preceding one.</p>
<p>[csharp]<br />
ASPNET_REGIIS -PDF &quot;connectionStrings&quot; &quot;F:\Visual Studio\EncryptConnectionString\EncryptConnectionString&quot;<br />
[/csharp]</p>
<blockquote><p>The text &#8216;connectionString&#8217; is case sensitive as mentioned above</p></blockquote>
<p>If the command is correct, you can get an output as follows.</p>
<div id="attachment_11573" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Decrypting-connectionString-e1463394161466.png"><img decoding="async" aria-describedby="caption-attachment-11573" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Decrypting-connectionString-e1463394161466.png" alt="Decrypting connectionString" width="650" height="440" class="size-full wp-image-11573" srcset="/wp-content/uploads/2016/05/Decrypting-connectionString-e1463394161466.png 650w, /wp-content/uploads/2016/05/Decrypting-connectionString-e1463394161466-300x203.png 300w, /wp-content/uploads/2016/05/Decrypting-connectionString-e1463394161466-320x218.png 320w, /wp-content/uploads/2016/05/Decrypting-connectionString-e1463394161466-620x420.png 620w, /wp-content/uploads/2016/05/Decrypting-connectionString-e1463394161466-400x271.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11573" class="wp-caption-text">Decrypting connectionString</p></div>
<p>Now if you check your Web config again, you can see the connection string has got encrypted. Have a happy coding!.</p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/encrypt-and-decrypt-connectionstring-in-web-config-file/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Working with API help page controller action description in Web API</title>
		<link>https://sibeeshpassion.com/working-with-api-help-page-controller-action-description-in-web-api/</link>
					<comments>https://sibeeshpassion.com/working-with-api-help-page-controller-action-description-in-web-api/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 12 May 2016 00:00:24 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[API Help Page Description]]></category>
		<category><![CDATA[article]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Enable Region Summary Of Actions]]></category>
		<category><![CDATA[How To]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11555</guid>

					<description><![CDATA[In this article we are going to see how we can enable the API descriptions for the better understanding of how our API controller works and what exactly it is supposed to do. It is recommended that to give the summary and parameter lists and a bit introduction to the service whenever you write any API services. Here I am going to use create a Web API in Visual Studio 2015. I hope you will like this. Download the source code You can always download the source code here: API Help Page Documentation Background Few months back I have hosted [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we are going to see how we can enable the API descriptions for the better understanding of how our API controller works and what exactly it is supposed to do. It is recommended that to give the summary and parameter lists and a bit introduction to the service whenever you write any API services. Here I am going to use create a <a href="http://sibeeshpassion.com/category/web-api" target="_blank" rel="noopener">Web API</a> in <a href="http://sibeeshpassion.com/category/tools/visual-studio/" target="_blank" rel="noopener">Visual Studio</a> 2015. I hope you will like this.</p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here: <a href="https://code.msdn.microsoft.com/Working-with-API-help-page-23eddf9e" target="_blank" rel="noopener">API Help Page Documentation</a></p>
<p><strong>Background</strong></p>
<p>Few months back I have hosted one of my API application to <a href="http://sibeeshpassion.com/category/azure" target="_blank" rel="noopener">Azure</a>. I thought of implementing the document summary for the services(controllers actions) now. And I did, now any one can understand what exactly my service will do by going to the help page of the API application. I will show you a demo of the same. Here we will create a Web API with entity framework. Lets us start then.</p>
<p><strong>Setting up database</strong></p>
<p>Here I am going to create a database which I created for my demo purposes, you can always create this database by running the queries mentioned here.</p>
<p><strong>Create database</strong></p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialsDB]    Script Date: 5/12/2016 10:56:41 AM ******/<br />
CREATE DATABASE [TrialsDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialsDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf&#8217; , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialsDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf&#8217; , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECOVERY FULL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p><strong>Create table with data</strong></p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO<br />
/****** Object:  Table [dbo].[Product]    Script Date: 5/12/2016 10:54:48 AM ******/<br />
SET ANSI_NULLS ON<br />
GO<br />
SET QUOTED_IDENTIFIER ON<br />
GO<br />
CREATE TABLE [dbo].[Product](<br />
	[ProductID] [int] NOT NULL,<br />
	[Name] [nvarchar](max) NOT NULL,<br />
	[ProductNumber] [nvarchar](25) NOT NULL,<br />
	[MakeFlag] [bit] NOT NULL,<br />
	[FinishedGoodsFlag] [bit] NOT NULL,<br />
	[Color] [nvarchar](15) NULL,<br />
	[SafetyStockLevel] [smallint] NOT NULL,<br />
	[ReorderPoint] [smallint] NOT NULL,<br />
	[StandardCost] [money] NOT NULL,<br />
	[ListPrice] [money] NOT NULL,<br />
	[Size] [nvarchar](5) NULL,<br />
	[SizeUnitMeasureCode] [nchar](3) NULL,<br />
	[WeightUnitMeasureCode] [nchar](3) NULL,<br />
	[Weight] [decimal](8, 2) NULL,<br />
	[DaysToManufacture] [int] NOT NULL,<br />
	[ProductLine] [nchar](2) NULL,<br />
	[Class] [nchar](2) NULL,<br />
	[Style] [nchar](2) NULL,<br />
	[ProductSubcategoryID] [int] NULL,<br />
	[ProductModelID] [int] NULL,<br />
	[SellStartDate] [datetime] NOT NULL,<br />
	[SellEndDate] [datetime] NULL,<br />
	[DiscontinuedDate] [datetime] NULL,<br />
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,<br />
	[ModifiedDate] [datetime] NOT NULL<br />
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]<br />
GO<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (1, N&#8217;Adjustable Race&#8217;, N&#8217;AR-5381&#8242;, 0, 0, NULL, 1000, 750, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;694215b7-08f7-4c0d-acb1-d734ba44c0c8&#8242;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (2, N&#8217;Bearing Ball&#8217;, N&#8217;BA-8327&#8242;, 0, 0, NULL, 1000, 750, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;58ae3c20-4f3a-4749-a7d4-d568806cc537&#8242;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (3, N&#8217;BB Ball Bearing&#8217;, N&#8217;BE-2349&#8242;, 1, 0, NULL, 800, 600, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;9c21aed2-5bfa-4f18-bcb8-f11638dc2e4e&#8217;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (4, N&#8217;Headset Ball Bearings&#8217;, N&#8217;BE-2908&#8242;, 0, 0, NULL, 800, 600, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;ecfed6cb-51ff-49b5-b06c-7d8ac834db8b&#8217;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (316, N&#8217;Blade&#8217;, N&#8217;BL-2036&#8242;, 1, 0, NULL, 800, 600, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;e73e9750-603b-4131-89f5-3dd15ed5ff80&#8242;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (317, N&#8217;LL Crankarm&#8217;, N&#8217;CA-5965&#8242;, 0, 0, N&#8217;Black&#8217;, 500, 375, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, N&#8217;L &#8216;, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;3c9d10b7-a6b2-4774-9963-c19dcee72fea&#8217;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (318, N&#8217;ML Crankarm&#8217;, N&#8217;CA-6738&#8242;, 0, 0, N&#8217;Black&#8217;, 500, 375, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, N&#8217;M &#8216;, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;eabb9a92-fa07-4eab-8955-f0517b4a4ca7&#8217;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
[/sql]</p>
<p>Our database is ready, now create a Web API application in visual studio and then entity with the above mentioned database. </p>
<div id="attachment_11556" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Creating-Entity-e1463031313825.png"><img decoding="async" aria-describedby="caption-attachment-11556" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Creating-Entity-1024x542.png" alt="Creating Entity" width="634" height="336" class="size-large wp-image-11556" /></a><p id="caption-attachment-11556" class="wp-caption-text">Creating Entity</p></div>
<p>If you don&#8217;t know how to create an entity in your solution, please read that <a href="http://sibeeshpassion.com/web-api-with-angular-js/" target="_blank" rel="noopener">here</a>. I have mentioned the steps to be followed in that article. Once you have created the entity, you are good to go and create a API controller with the entity created. If you do so, The CRUD actions will be created automatically for you. You may need to edit those actions according to your needs. </p>
<div id="attachment_11557" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319.png"><img decoding="async" aria-describedby="caption-attachment-11557" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319.png" alt="Web API 2 Controller with actions, using Entity Framework" width="650" height="457" class="size-full wp-image-11557" srcset="/wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319.png 650w, /wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319-300x211.png 300w, /wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319-400x281.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11557" class="wp-caption-text">Web API 2 Controller with actions, using Entity Framework</p></div>
<p>Select the Model Class, DBContext then name your controller and click OK. I hope a controller with the CRUD actions like preceding has been generated for you.</p>
<p>[csharp]<br />
 public class ProductsController : ApiController<br />
    {<br />
        private TrialsDBEntities db = new TrialsDBEntities();</p>
<p>        // GET: api/Products<br />
        public IQueryable&lt;Product&gt; GetProducts()<br />
        {<br />
            return db.Products;<br />
        }</p>
<p>        // GET: api/Products/5<br />
        [ResponseType(typeof(Product))]<br />
        public IHttpActionResult GetProduct(int id)<br />
        {<br />
            Product product = db.Products.Find(id);<br />
            if (product == null)<br />
            {<br />
                return NotFound();<br />
            }</p>
<p>            return Ok(product);<br />
        }</p>
<p>        // PUT: api/Products/5<br />
        [ResponseType(typeof(void))]<br />
        public IHttpActionResult PutProduct(int id, Product product)<br />
        {<br />
            if (!ModelState.IsValid)<br />
            {<br />
                return BadRequest(ModelState);<br />
            }</p>
<p>            if (id != product.ProductID)<br />
            {<br />
                return BadRequest();<br />
            }</p>
<p>            db.Entry(product).State = EntityState.Modified;</p>
<p>            try<br />
            {<br />
                db.SaveChanges();<br />
            }<br />
            catch (DbUpdateConcurrencyException)<br />
            {<br />
                if (!ProductExists(id))<br />
                {<br />
                    return NotFound();<br />
                }<br />
                else<br />
                {<br />
                    throw;<br />
                }<br />
            }</p>
<p>            return StatusCode(HttpStatusCode.NoContent);<br />
        }</p>
<p>        // POST: api/Products<br />
        [ResponseType(typeof(Product))]<br />
        public IHttpActionResult PostProduct(Product product)<br />
        {<br />
            if (!ModelState.IsValid)<br />
            {<br />
                return BadRequest(ModelState);<br />
            }</p>
<p>            db.Products.Add(product);</p>
<p>            try<br />
            {<br />
                db.SaveChanges();<br />
            }<br />
            catch (DbUpdateException)<br />
            {<br />
                if (ProductExists(product.ProductID))<br />
                {<br />
                    return Conflict();<br />
                }<br />
                else<br />
                {<br />
                    throw;<br />
                }<br />
            }</p>
<p>            return CreatedAtRoute(&quot;DefaultApi&quot;, new { id = product.ProductID }, product);<br />
        }</p>
<p>        // DELETE: api/Products/5<br />
        [ResponseType(typeof(Product))]<br />
        public IHttpActionResult DeleteProduct(int id)<br />
        {<br />
            Product product = db.Products.Find(id);<br />
            if (product == null)<br />
            {<br />
                return NotFound();<br />
            }</p>
<p>            db.Products.Remove(product);<br />
            db.SaveChanges();</p>
<p>            return Ok(product);<br />
        }</p>
<p>        protected override void Dispose(bool disposing)<br />
        {<br />
            if (disposing)<br />
            {<br />
                db.Dispose();<br />
            }<br />
            base.Dispose(disposing);<br />
        }</p>
<p>        private bool ProductExists(int id)<br />
        {<br />
            return db.Products.Count(e =&gt; e.ProductID == id) &gt; 0;<br />
        }<br />
    }<br />
[/csharp]</p>
<p>Now please run your application and go to the help page. You can see the API help page as follows. </p>
<div id="attachment_11558" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/API-Help-Page-e1463032044742.png"><img decoding="async" aria-describedby="caption-attachment-11558" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/API-Help-Page-e1463032044742.png" alt="API Help Page" width="650" height="524" class="size-full wp-image-11558" srcset="/wp-content/uploads/2016/05/API-Help-Page-e1463032044742.png 650w, /wp-content/uploads/2016/05/API-Help-Page-e1463032044742-300x242.png 300w, /wp-content/uploads/2016/05/API-Help-Page-e1463032044742-400x322.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11558" class="wp-caption-text">API Help Page</p></div>
<p>As you can see &#8216;No documentation available.&#8217; under description of all the service actions. No worries we will try to add some summary to the actions now. So we will change the code as follows.</p>
<p>[csharp]<br />
 #region GetProducts<br />
        /// &lt;summary&gt;<br />
        /// Get all the products available<br />
        /// GET: api/Products<br />
        /// &lt;/summary&gt;<br />
        public IQueryable&lt;Product&gt; GetProducts()<br />
        {<br />
            return db.Products;<br />
        }<br />
        #endregion</p>
<p>        #region GetProductWithParameter<br />
        /// &lt;summary&gt;<br />
        /// Get a single product<br />
        /// GET: api/Products/5<br />
        /// &lt;param name=&quot;id&quot;&gt;&lt;/param&gt;<br />
        /// &lt;/summary&gt;<br />
        [ResponseType(typeof(Product))]<br />
        public IHttpActionResult GetProduct(int id)<br />
        {<br />
            Product product = db.Products.Find(id);<br />
            if (product == null)<br />
            {<br />
                return NotFound();<br />
            }</p>
<p>            return Ok(product);<br />
        }<br />
        #endregion<br />
[/csharp]</p>
<p>Now run your application and see the help page. Still the same result? Hmm, here comes the things we need to do. I will explain that. </p>
<li>Go to Areas\HelpPage\App_Start and click on the file <em>HelpPageConfig.cs</em>.</li>
<li>Uncomment the following line from the static function Register. </li>
<p>[csharp]<br />
config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath(&quot;App_Data/XmlDocument.xml&quot;)));<br />
[/csharp]</p>
<li>Right click on your project and go to properties, then click on Build</li>
<li>Go to Output section and click on XML documentation file and then type <em>~/App_Data/XmlDocument.xml</em> in the given text box. </li>
<li>Save and build your project.</li>
<p>This will create a XML document with the name <em>XmlDocument.xml</em> in App_Data folder. Once it is generated, the summary you have described in your API controller will be listed there. Initially the file will be in excluded state, you may need to include the same to your project when you deploy your API application. For that please follows the below steps. </p>
<li>Click on show all files.</li>
<li>Click on Refresh.</li>
<li>Go to App_Data folder and find XmlDocument.xml.</li>
<li>Right click the file and click Include In Project.</li>
<p>That&#8217;s all. Run your application and see the Help page again. Hope you get the page as follows. </p>
<div id="attachment_11559" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/API-Help-Page-With-Descriptions-e1463033550891.png"><img decoding="async" aria-describedby="caption-attachment-11559" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/API-Help-Page-With-Descriptions-e1463033550891.png" alt="API Help Page With Descriptions" width="650" height="361" class="size-full wp-image-11559" srcset="/wp-content/uploads/2016/05/API-Help-Page-With-Descriptions-e1463033550891.png 650w, /wp-content/uploads/2016/05/API-Help-Page-With-Descriptions-e1463033550891-300x167.png 300w, /wp-content/uploads/2016/05/API-Help-Page-With-Descriptions-e1463033550891-400x222.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11559" class="wp-caption-text">API Help Page With Descriptions</p></div>
<p>Have a happy coding!.</p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/working-with-api-help-page-controller-action-description-in-web-api/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Creating Azure Mobile App With Visual Studio</title>
		<link>https://sibeeshpassion.com/creating-azure-mobile-app-with-visual-studio/</link>
					<comments>https://sibeeshpassion.com/creating-azure-mobile-app-with-visual-studio/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 24 Apr 2016 00:00:46 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Azure Mobile App]]></category>
		<category><![CDATA[Mobile App With Azure And Visual Studio]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[Windows 10]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11507</guid>

					<description><![CDATA[[toc] Introduction In this article we are going to create a mobile application with Azure using Visual Studio. Before you start with make sure that you have some azure credits with you. You can always create new azure free account where you can claim for some free credits Azure free trial . Please be noted that you can get only limited azure credits with the free account. But to get started, that is more than enough. Now we will go and create our application. I hope you will like this. Download the source code You can always download the source [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>In this article we are going to create a mobile application with <a href="http://sibeeshpassion.com/category/azure" target="_blank">Azure</a> using <a href="http://sibeeshpassion.com/category/visual-studio" target="_blank">Visual Studio</a>. Before you start with make sure that you have some azure credits with you. You can always create new azure free account where you can claim for some free credits <a href="https://azure.microsoft.com/en-in/pricing/free-trial/" target="_blank">Azure free trial </a>. Please be noted that you can get only limited azure credits with the free account. But to get started, that is more than enough. Now we will go and create our application. I hope you will like this. </p>
<h3>Download the source code</h3>
<p>You can always download the source code here</p>
<li><a href="https://gallery.technet.microsoft.com/Creating-Azure-Mobile-App-89d3df9f" target="_blank">Azure Mobile App With Visual Studio</a></li>
<h3>Background</h3>
<p>We all know what Azure is. If you are really new to Azure, I strongly recommend you to have a look at <a href="http://sibeeshpassion.com/category/azure" target="_blank">here</a> .To get started, please make sure that you have installed Visual Studio in your machine. You can always download visual studio from <a href="https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx" target="_blank">here</a>. </p>
<h3>Setting Azure Portal </h3>
<p>Login to your Azure portal from <a href="https://portal.azure.com/" target="_blank">Azure Portal</a>. Once you logged in, you can see a dashboard and a menu as follows.</p>
<div id="attachment_11508" style="width: 295px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Microsoft-Azure-Portal-Menu.png"><img decoding="async" aria-describedby="caption-attachment-11508" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Microsoft-Azure-Portal-Menu.png" alt="Microsoft Azure Portal Menu" width="285" height="747" class="size-full wp-image-11508" srcset="/wp-content/uploads/2016/04/Microsoft-Azure-Portal-Menu.png 285w, /wp-content/uploads/2016/04/Microsoft-Azure-Portal-Menu-114x300.png 114w, /wp-content/uploads/2016/04/Microsoft-Azure-Portal-Menu-229x600.png 229w" sizes="(max-width: 285px) 100vw, 285px" /></a><p id="caption-attachment-11508" class="wp-caption-text">Microsoft Azure Portal Menu</p></div>
<p>Now click on New -> Web+Mobile -> Mobile App.</p>
<div id="attachment_11509" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Web-Mobile-Category-In-Azure-Portal-e1460901278999.png"><img decoding="async" aria-describedby="caption-attachment-11509" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Web-Mobile-Category-In-Azure-Portal-1024x886.png" alt="Web Mobile Category In Azure Portal" width="634" height="549" class="size-large wp-image-11509" /></a><p id="caption-attachment-11509" class="wp-caption-text">Web Mobile Category In Azure Portal</p></div>
<p>Now name your mobile application. Select your subscription, it will be automatically selected if you have only one subscription. Please select the subscription accordingly if you have multiple subscriptions. Select or create new resource group. You may be thinking what is this resource group, and what are all the benefits for using it. According to Microsoft, a resource group is a collection of resources so that you can use those accordingly. A resource can be included only in one resource group and it is possible to link the resources in other resource group. Please be noted that you can&#8217;t edit and rename your resource group name. Only option you are allowed is to move your resources to your new resource group. Please see <a href="https://azure.microsoft.com/en-us/documentation/articles/resource-group-move-resources/" target="_blank">Move resources to a new resource group in azure</a> if you need to move your resources. </p>
<p>Now select your service plan or location as per your need. Now click on that link. You can see all the service plans you have used so far, you can select those if you want or you can create a new one. </p>
<div id="attachment_11511" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Available-App-Service-Plan-In-Azure-e1460903507474.png"><img decoding="async" aria-describedby="caption-attachment-11511" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Available-App-Service-Plan-In-Azure-e1460903507474.png" alt="Available App Service Plan In Azure" width="650" height="526" class="size-full wp-image-11511" srcset="/wp-content/uploads/2016/04/Available-App-Service-Plan-In-Azure-e1460903507474.png 650w, /wp-content/uploads/2016/04/Available-App-Service-Plan-In-Azure-e1460903507474-300x243.png 300w, /wp-content/uploads/2016/04/Available-App-Service-Plan-In-Azure-e1460903507474-400x324.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11511" class="wp-caption-text">Available App Service Plan In Azure</p></div>
<p>To create a new one, please click the &#8216;Create new&#8217; option. </p>
<div id="attachment_11512" style="width: 393px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/New-App-Service-Plan-In-Azure.png"><img decoding="async" aria-describedby="caption-attachment-11512" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/New-App-Service-Plan-In-Azure.png" alt="New App Service Plan In Azure" width="383" height="867" class="size-full wp-image-11512" srcset="/wp-content/uploads/2016/04/New-App-Service-Plan-In-Azure.png 383w, /wp-content/uploads/2016/04/New-App-Service-Plan-In-Azure-133x300.png 133w, /wp-content/uploads/2016/04/New-App-Service-Plan-In-Azure-265x600.png 265w" sizes="(max-width: 383px) 100vw, 383px" /></a><p id="caption-attachment-11512" class="wp-caption-text">New App Service Plan In Azure</p></div>
<p>Now select your app service plan, location, pricing tier. When you select the pricing tier, please be cautious because Azure charge you according to your use. Select it according your use. </p>
<div id="attachment_11513" style="width: 396px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/App-Service-Pricing-Tier.png"><img decoding="async" aria-describedby="caption-attachment-11513" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/App-Service-Pricing-Tier.png" alt="App Service Pricing Tier" width="386" height="865" class="size-full wp-image-11513" srcset="/wp-content/uploads/2016/04/App-Service-Pricing-Tier.png 386w, /wp-content/uploads/2016/04/App-Service-Pricing-Tier-134x300.png 134w, /wp-content/uploads/2016/04/App-Service-Pricing-Tier-268x600.png 268w" sizes="(max-width: 386px) 100vw, 386px" /></a><p id="caption-attachment-11513" class="wp-caption-text">App Service Pricing Tier</p></div>
<p>Now this is how you Mobile App service set up looks like. You can always pin your mobile app to your dashboard. </p>
<div id="attachment_11514" style="width: 396px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Mobie-App-Service.png"><img decoding="async" aria-describedby="caption-attachment-11514" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Mobie-App-Service.png" alt="Mobie App Service" width="386" height="864" class="size-full wp-image-11514" srcset="/wp-content/uploads/2016/04/Mobie-App-Service.png 386w, /wp-content/uploads/2016/04/Mobie-App-Service-134x300.png 134w, /wp-content/uploads/2016/04/Mobie-App-Service-268x600.png 268w" sizes="(max-width: 386px) 100vw, 386px" /></a><p id="caption-attachment-11514" class="wp-caption-text">Mobie App Service</p></div>
<p>Once this is done, you will get a notification that your mobile app deployment is succeeded if nothing goes wrong and you can see the app in your dashboard. Now click on the settings of your mobile application and then quick start.</p>
<div id="attachment_11515" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Quick-Start-Option-In-Azure-Mobile-App-e1460905361428.png"><img decoding="async" aria-describedby="caption-attachment-11515" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Quick-Start-Option-In-Azure-Mobile-App-e1460905361428.png" alt="Quick Start Option In Azure Mobile App" width="650" height="581" class="size-full wp-image-11515" srcset="/wp-content/uploads/2016/04/Quick-Start-Option-In-Azure-Mobile-App-e1460905361428.png 399w, /wp-content/uploads/2016/04/Quick-Start-Option-In-Azure-Mobile-App-e1460905361428-300x268.png 300w, /wp-content/uploads/2016/04/Quick-Start-Option-In-Azure-Mobile-App-e1460905361428-400x358.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11515" class="wp-caption-text">Quick Start Option In Azure Mobile App</p></div>
<p>Select Windows(C#) from it. Now you will be asked to complete three actions. </p>
<li>Connect a database</li>
<li>Create a table API</li>
<li>Configure your client application</li>
<h3>Connect a database</h3>
<p>Click on connect a database ( We will create a database first). Click Add and add a data connection as follows. </p>
<div id="attachment_11516" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Data-Connections-In-Azure-Mobile-App-e1460905798522.png"><img decoding="async" aria-describedby="caption-attachment-11516" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Data-Connections-In-Azure-Mobile-App-1024x583.png" alt="Data Connections In Azure Mobile App" width="634" height="361" class="size-large wp-image-11516" /></a><p id="caption-attachment-11516" class="wp-caption-text">Data Connections In Azure Mobile App</p></div>
<p>Now give your database name and pricing tier. For now I am going to select the pricing tier as Basic. You can see 5 DTUs are available for Basic tier. According to Microsoft, The Database Transaction Unit (DTU) is the unit of measure in SQL Database that represents the relative power of databases based on a real-world measure: the database transaction. Please read more <a href="https://azure.microsoft.com/en-us/documentation/articles/sql-database-service-tiers/?rnd=1#understanding-dtus" target="_blank">here</a>.</p>
<p>Did you notice that there is a field called Collation? Basically a collation is a set of rules and regulation we set for the proper use of characters. Like the characters are much different in all the languages, we set the collation accordingly. The default collation for character data in Azure SQL database is <em>SQL_Latin1_General_CP1_CI_AS</em>. You can read about collation <a href="https://azure.microsoft.com/en-in/blog/working-with-collations-in-sql-azure/" target="_blank">here</a>. </p>
<p>Next, set your server and click OK. Once you click OK, you can see the connection strings is being set automatically for you. Creation of data connection may take few minutes. Now we will create a table API. </p>
<h3>Create a table API</h3>
<p>To store the data in your back end. You need a table, isn&#8217;t it? The first option you will see here is select the language for your back end actions. You can select either C# or Node JS. </p>
<blockquote><p>There was a time, that we can do server side actions only by using server side languages like C#,Vb.Net, PhP etc. Now everything changes, we can do server side actions with few set of JavaScript, that is Node JS. </p></blockquote>
<p>Once you select your language you can see a message as &#8220;Once you’ve downloaded your personalized server project, extract it and open in Visual Studio. Right-click the project and select “Publish” to host the code in your mobile backend. The TodoItem table will be created automatically using Entity Framework.&#8221; Now we will do as suggested. </p>
<p>Please open your downloaded project in Visual Studio. Right click the project file then click publish. You can see a window and finish Profile, Connection, Settings steps. </p>
<div id="attachment_11517" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Azure-Mobile-App-preview-e1460909105653.png"><img decoding="async" aria-describedby="caption-attachment-11517" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Azure-Mobile-App-preview-e1460909105653.png" alt="Azure Mobile App preview" width="650" height="519" class="size-full wp-image-11517" srcset="/wp-content/uploads/2016/04/Azure-Mobile-App-preview-e1460909105653.png 447w, /wp-content/uploads/2016/04/Azure-Mobile-App-preview-e1460909105653-300x240.png 300w, /wp-content/uploads/2016/04/Azure-Mobile-App-preview-e1460909105653-400x319.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11517" class="wp-caption-text">Azure Mobile App preview</p></div>
<p>Click publish once you verified the settings. It may take few minutes according to your internet bandwidth. In the meanwhile you can see all the controllers and additional files had been created for us automatically. For example below is the Values controller.</p>
<p>[csharp]<br />
using System.Web.Http;<br />
using System.Web.Http.Tracing;<br />
using Microsoft.Azure.Mobile.Server;<br />
using Microsoft.Azure.Mobile.Server.Config;</p>
<p>namespace SibeeshTasksService.Controllers<br />
{<br />
    // Use the MobileAppController attribute for each ApiController you want to use<br />
    // from your mobile clients<br />
    [MobileAppController]<br />
    public class ValuesController : ApiController<br />
    {<br />
        // GET api/values<br />
        public string Get()<br />
        {<br />
            MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();<br />
            ITraceWriter traceWriter = this.Configuration.Services.GetTraceWriter();</p>
<p>            string host = settings.HostName ?? &quot;localhost&quot;;<br />
            string greeting = &quot;Hello from &quot; + host;</p>
<p>            traceWriter.Info(greeting);<br />
            return greeting;<br />
        }</p>
<p>        // POST api/values<br />
        public string Post()<br />
        {<br />
            return &quot;Hello World!&quot;;<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Now the publish process is completed, you can see a message as follows. </p>
<div id="attachment_11518" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Azure-App-Service-Publish-e1460910331127.png"><img decoding="async" aria-describedby="caption-attachment-11518" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Azure-App-Service-Publish-1024x414.png" alt="Azure App Service Publish" width="634" height="256" class="size-large wp-image-11518" /></a><p id="caption-attachment-11518" class="wp-caption-text">Azure App Service Publish</p></div>
<p>Now please go back to your Azure portal. </p>
<h3>Configure your client application</h3>
<p>It is time to configure our client application now. Download the client application by clicking the link provided. And open the project in Visual Studio. Please install the missing files if it is asked to do so. </p>
<div id="attachment_11520" style="width: 585px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/MIssing-Componenets.png"><img decoding="async" aria-describedby="caption-attachment-11520" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/MIssing-Componenets.png" alt="MIssing Componenets" width="575" height="807" class="size-full wp-image-11520" srcset="/wp-content/uploads/2016/04/MIssing-Componenets.png 575w, /wp-content/uploads/2016/04/MIssing-Componenets-214x300.png 214w, /wp-content/uploads/2016/04/MIssing-Componenets-400x561.png 400w, /wp-content/uploads/2016/04/MIssing-Componenets-428x600.png 428w" sizes="(max-width: 575px) 100vw, 575px" /></a><p id="caption-attachment-11520" class="wp-caption-text">MIssing Componenets</p></div>
<p>Once the installation is done, reload your project and it will be asked to enable developer mode for windows 10. Go ahead and change that in settings. </p>
<p>Now please open the shared project and click on MainPage.cs file, you can see the CRUD operation actions are already created for us. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Text;<br />
using System.Threading.Tasks;<br />
using Microsoft.WindowsAzure.MobileServices;<br />
using Windows.UI.Popups;<br />
using Windows.UI.Xaml;<br />
using Windows.UI.Xaml.Controls;<br />
using Windows.UI.Xaml.Navigation;</p>
<p>// To add offline sync support, add the NuGet package Microsoft.WindowsAzure.MobileServices.SQLiteStore<br />
// to your project. Then, uncomment the lines marked // offline sync<br />
// For more information, see: http://aka.ms/addofflinesync<br />
//using Microsoft.WindowsAzure.MobileServices.SQLiteStore;  // offline sync<br />
//using Microsoft.WindowsAzure.MobileServices.Sync;         // offline sync</p>
<p>namespace SibeeshTasks<br />
{<br />
    sealed partial class MainPage: Page<br />
    {<br />
        private MobileServiceCollection&lt;TodoItem, TodoItem&gt; items;<br />
        private IMobileServiceTable&lt;TodoItem&gt; todoTable = App.MobileService.GetTable&lt;TodoItem&gt;();<br />
        //private IMobileServiceSyncTable&lt;TodoItem&gt; todoTable = App.MobileService.GetSyncTable&lt;TodoItem&gt;(); // offline sync</p>
<p>        public MainPage()<br />
        {<br />
            this.InitializeComponent();<br />
        }</p>
<p>        private async Task InsertTodoItem(TodoItem todoItem)<br />
        {<br />
            // This code inserts a new TodoItem into the database. When the operation completes<br />
            // and Mobile App backend has assigned an Id, the item is added to the CollectionView.<br />
            await todoTable.InsertAsync(todoItem);<br />
            items.Add(todoItem);</p>
<p>            //await SyncAsync(); // offline sync<br />
        }</p>
<p>        private async Task RefreshTodoItems()<br />
        {<br />
            MobileServiceInvalidOperationException exception = null;<br />
            try<br />
            {<br />
                // This code refreshes the entries in the list view by querying the TodoItems table.<br />
                // The query excludes completed TodoItems.<br />
                items = await todoTable<br />
                    .Where(todoItem =&gt; todoItem.Complete == false)<br />
                    .ToCollectionAsync();<br />
            }<br />
            catch (MobileServiceInvalidOperationException e)<br />
            {<br />
                exception = e;<br />
            }</p>
<p>            if (exception != null)<br />
            {<br />
                await new MessageDialog(exception.Message, &quot;Error loading items&quot;).ShowAsync();<br />
            }<br />
            else<br />
            {<br />
                ListItems.ItemsSource = items;<br />
                this.ButtonSave.IsEnabled = true;<br />
            }<br />
        }</p>
<p>        private async Task UpdateCheckedTodoItem(TodoItem item)<br />
        {<br />
            // This code takes a freshly completed TodoItem and updates the database. When the service<br />
            // responds, the item is removed from the list.<br />
            await todoTable.UpdateAsync(item);<br />
            items.Remove(item);<br />
            ListItems.Focus(Windows.UI.Xaml.FocusState.Unfocused);</p>
<p>            //await SyncAsync(); // offline sync<br />
        }</p>
<p>        private async void ButtonRefresh_Click(object sender, RoutedEventArgs e)<br />
        {<br />
            ButtonRefresh.IsEnabled = false;</p>
<p>            //await SyncAsync(); // offline sync<br />
            await RefreshTodoItems();</p>
<p>            ButtonRefresh.IsEnabled = true;<br />
        }</p>
<p>        private async void ButtonSave_Click(object sender, RoutedEventArgs e)<br />
        {<br />
            var todoItem = new TodoItem { Text = TextInput.Text };<br />
            await InsertTodoItem(todoItem);<br />
        }</p>
<p>        private async void CheckBoxComplete_Checked(object sender, RoutedEventArgs e)<br />
        {<br />
            CheckBox cb = (CheckBox)sender;<br />
            TodoItem item = cb.DataContext as TodoItem;<br />
            await UpdateCheckedTodoItem(item);<br />
        }</p>
<p>        protected override async void OnNavigatedTo(NavigationEventArgs e)<br />
        {<br />
            //await InitLocalStoreAsync(); // offline sync<br />
            await RefreshTodoItems();<br />
        }</p>
<p>        #region Offline sync</p>
<p>        //private async Task InitLocalStoreAsync()<br />
        //{<br />
        //    if (!App.MobileService.SyncContext.IsInitialized)<br />
        //    {<br />
        //        var store = new MobileServiceSQLiteStore(&quot;localstore.db&quot;);<br />
        //        store.DefineTable&lt;TodoItem&gt;();<br />
        //        await App.MobileService.SyncContext.InitializeAsync(store);<br />
        //    }<br />
        //<br />
        //    await SyncAsync();<br />
        //}</p>
<p>        //private async Task SyncAsync()<br />
        //{<br />
        //    await App.MobileService.SyncContext.PushAsync();<br />
        //    await todoTable.PullAsync(&quot;todoItems&quot;, todoTable.CreateQuery());<br />
        //}</p>
<p>        #endregion<br />
    }<br />
}<br />
[/csharp]</p>
<p>And following is the XAML file created for our app design.</p>
<p>[xml]<br />
&lt;Page<br />
    x:Class=&quot;SibeeshTasks.MainPage&quot;<br />
    IsTabStop=&quot;false&quot;<br />
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;<br />
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;<br />
    xmlns:local=&quot;using:SibeeshTasks&quot;<br />
    xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;<br />
    xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;<br />
    mc:Ignorable=&quot;d&quot;&gt;</p>
<p>    &lt;Grid Background=&quot;White&quot;&gt;</p>
<p>        &lt;Grid Margin=&quot;50,50,10,10&quot;&gt;<br />
            &lt;Grid.ColumnDefinitions&gt;<br />
                &lt;ColumnDefinition Width=&quot;*&quot; /&gt;<br />
                &lt;ColumnDefinition Width=&quot;*&quot; /&gt;<br />
            &lt;/Grid.ColumnDefinitions&gt;<br />
            &lt;Grid.RowDefinitions&gt;<br />
                &lt;RowDefinition Height=&quot;Auto&quot; /&gt;<br />
                &lt;RowDefinition Height=&quot;*&quot; /&gt;<br />
            &lt;/Grid.RowDefinitions&gt;</p>
<p>            &lt;Grid Grid.Row=&quot;0&quot; Grid.ColumnSpan=&quot;2&quot; Margin=&quot;0,0,0,20&quot;&gt;<br />
                &lt;StackPanel&gt;<br />
                    &lt;TextBlock Foreground=&quot;#0094ff&quot; FontFamily=&quot;Segoe UI Light&quot; Margin=&quot;0,0,0,6&quot;&gt;MICROSOFT AZURE MOBILE SERVICES&lt;/TextBlock&gt;<br />
                    &lt;TextBlock Foreground=&quot;Gray&quot; FontFamily=&quot;Segoe UI Light&quot; FontSize=&quot;45&quot; &gt;SibeeshTasks&lt;/TextBlock&gt;<br />
                &lt;/StackPanel&gt;<br />
            &lt;/Grid&gt;</p>
<p>            &lt;Grid Grid.Row=&quot;1&quot;&gt;<br />
                &lt;StackPanel&gt;</p>
<p>                    &lt;local:QuickStartTask Number=&quot;1&quot; Title=&quot;Insert a TodoItem&quot; Description=&quot;Enter some text below and click Save to insert a new todo item into your database&quot; /&gt;</p>
<p>                    &lt;StackPanel Orientation=&quot;Horizontal&quot; Margin=&quot;72,0,0,0&quot;&gt;<br />
                        &lt;TextBox Name=&quot;TextInput&quot; Margin=&quot;5&quot; MinWidth=&quot;300&quot;&gt;&lt;/TextBox&gt;<br />
                        &lt;Button Name=&quot;ButtonSave&quot; Click=&quot;ButtonSave_Click&quot; IsEnabled=&quot;False&quot;&gt;Save&lt;/Button&gt;<br />
                    &lt;/StackPanel&gt;</p>
<p>                &lt;/StackPanel&gt;<br />
            &lt;/Grid&gt;</p>
<p>            &lt;Grid Grid.Row=&quot;1&quot; Grid.Column=&quot;1&quot;&gt;<br />
                &lt;Grid.RowDefinitions&gt;<br />
                    &lt;RowDefinition Height=&quot;Auto&quot; /&gt;<br />
                    &lt;RowDefinition /&gt;<br />
                &lt;/Grid.RowDefinitions&gt;<br />
                &lt;StackPanel&gt;<br />
                    &lt;local:QuickStartTask Number=&quot;2&quot; Title=&quot;Query and Update Data&quot; Description=&quot;Click refresh below to load the unfinished TodoItems from your database. Use the checkbox to complete and update your TodoItems&quot; /&gt;<br />
                    &lt;Button Margin=&quot;72,0,0,0&quot; Name=&quot;ButtonRefresh&quot; Click=&quot;ButtonRefresh_Click&quot;&gt;Refresh&lt;/Button&gt;<br />
                &lt;/StackPanel&gt;</p>
<p>                &lt;ListView Name=&quot;ListItems&quot; Margin=&quot;62,10,0,0&quot; Grid.Row=&quot;1&quot;&gt;<br />
                    &lt;ListView.ItemTemplate&gt;<br />
                        &lt;DataTemplate&gt;<br />
                            &lt;StackPanel Orientation=&quot;Horizontal&quot;&gt;<br />
                                &lt;CheckBox Name=&quot;CheckBoxComplete&quot; IsChecked=&quot;{Binding Complete, Mode=TwoWay}&quot; Checked=&quot;CheckBoxComplete_Checked&quot; Content=&quot;{Binding Text}&quot; Margin=&quot;10,5&quot; VerticalAlignment=&quot;Center&quot;/&gt;<br />
                            &lt;/StackPanel&gt;<br />
                        &lt;/DataTemplate&gt;<br />
                    &lt;/ListView.ItemTemplate&gt;<br />
                &lt;/ListView&gt;</p>
<p>            &lt;/Grid&gt;</p>
<p>        &lt;/Grid&gt;<br />
    &lt;/Grid&gt;<br />
&lt;/Page&gt;<br />
[/xml]</p>
<p>Now please run your project. Here I am running the app in visual studio. You can always run the same in Windows Emulator. If nothing goes wrong you can see an output as follows. </p>
<div id="attachment_11521" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Azure-Mobile-App-Output-e1460915717240.png"><img decoding="async" aria-describedby="caption-attachment-11521" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Azure-Mobile-App-Output-1024x800.png" alt="Azure Mobile App Output" width="634" height="495" class="size-large wp-image-11521" /></a><p id="caption-attachment-11521" class="wp-caption-text">Azure Mobile App Output</p></div>
<div id="attachment_11522" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Azure-Mobile-App-Output-Inserting-And-Reading-e1460915910597.png"><img decoding="async" aria-describedby="caption-attachment-11522" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Azure-Mobile-App-Output-Inserting-And-Reading-1024x802.png" alt="Azure Mobile App Output Inserting And Reading" width="634" height="497" class="size-large wp-image-11522" /></a><p id="caption-attachment-11522" class="wp-caption-text">Azure Mobile App Output Inserting And Reading</p></div>
<p>Just to make sure that the entries has been inserted and the data is getting from the database we can go back to our Azure portal. We all are humans, we believe things when we see. We all asks for the proof. Isn&#8217;t it? Click on SQL databases from the menu. Now you can see all the databases you have created, click on the database and get the server name, user id and password form the connection string. Once you get it, open your SQL Server Management Studio in your local machine and provide the details you took from the connection string. Now you can see the our Azure SQL database in your local SSMS.</p>
<div id="attachment_11523" style="width: 429px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Connect-Azure-SQL-Database-Through-SSMS.png"><img decoding="async" aria-describedby="caption-attachment-11523" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Connect-Azure-SQL-Database-Through-SSMS.png" alt="Connect Azure SQL Database Through SSMS" width="419" height="916" class="size-full wp-image-11523" srcset="/wp-content/uploads/2016/04/Connect-Azure-SQL-Database-Through-SSMS.png 419w, /wp-content/uploads/2016/04/Connect-Azure-SQL-Database-Through-SSMS-137x300.png 137w, /wp-content/uploads/2016/04/Connect-Azure-SQL-Database-Through-SSMS-400x874.png 400w, /wp-content/uploads/2016/04/Connect-Azure-SQL-Database-Through-SSMS-274x600.png 274w" sizes="(max-width: 419px) 100vw, 419px" /></a><p id="caption-attachment-11523" class="wp-caption-text">Connect Azure SQL Database Through SSMS</p></div>
<p>Now we can query our table and see the data. Right?</p>
<p>[sql]<br />
USE [Tasks]<br />
GO</p>
<p>SELECT [Id]<br />
      ,[Text]<br />
      ,[Complete]<br />
      ,[Version]<br />
      ,[CreatedAt]<br />
      ,[UpdatedAt]<br />
      ,[Deleted]<br />
  FROM [dbo].[TodoItems]<br />
GO<br />
[/sql]</p>
<p>I am sure you will get an result as follows.</p>
<div id="attachment_11524" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Querying-Azure-SQL-Database-In-SSMS-e1460917590108.png"><img decoding="async" aria-describedby="caption-attachment-11524" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Querying-Azure-SQL-Database-In-SSMS-1024x435.png" alt="Querying Azure SQL Database In SSMS" width="634" height="269" class="size-large wp-image-11524" /></a><p id="caption-attachment-11524" class="wp-caption-text">Querying Azure SQL Database In SSMS</p></div>
<p>You can always run this same application in Windows Emulator, Now we will see how we can do that.</p>
<h3>Download Windows Emulator</h3>
<p>Before getting started, you must install Windows Emulator in your machine. You can get the Windows 10 emulator from <a href="https://www.microsoft.com/en-in/download/details.aspx?id=46893" target="_blank">here</a>. Please be noted that there are some sysytem requirements and actions to be taken care of before going to install the emulator. Basically Microsoft emulator works as a virtual machine on Hyper V. You must enable it. </p>
<h3>Enable Hyper-V in Windows</h3>
<p>To enable Hyper-V, go to control panel and select Programs, then click on &#8216;Turn windows feature on or off&#8217; and then select all the items under Hyper-V.</p>
<div id="attachment_11539" style="width: 564px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Enable-Hyper-V-in-Windows.png"><img decoding="async" aria-describedby="caption-attachment-11539" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Enable-Hyper-V-in-Windows.png" alt="Enable Hyper V in Windows" width="554" height="491" class="size-full wp-image-11539" srcset="/wp-content/uploads/2016/04/Enable-Hyper-V-in-Windows.png 554w, /wp-content/uploads/2016/04/Enable-Hyper-V-in-Windows-300x266.png 300w, /wp-content/uploads/2016/04/Enable-Hyper-V-in-Windows-400x355.png 400w" sizes="(max-width: 554px) 100vw, 554px" /></a><p id="caption-attachment-11539" class="wp-caption-text">Enable Hyper V in Windows</p></div>
<p>You may need to restart your system once. There are some additional requirements too.</p>
<h3>System Requirements</h3>
<p>We must enable the following configurations in BIOS.</p>
<li>Hardware-assisted virtualization</li>
<li>Second Level Address Translation (SLAT)</li>
<li>Hardware-based Data Execution Prevention (DEP)</li>
<p>And we need,</p>
<li>4GB or more RAM</li>
<li>OS Windows 8 or higher(Pro edition or higher)</li>
<p>To go to BIOS settings in Windows 10, Just type &#8216;change advanced startup options&#8217; in the start search box. And then click on the Restart under advanced settings. There you will see the BIOS options. Once you are done these procedures, you can go ahead and install Windows Emulator. After you install the emulator you can see an option to run the app in emulator in Visual Studio. </p>
<h3>Run app in Windows emulator</h3>
<p>Please see the option as follows in visual studio. </p>
<div id="attachment_11540" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Emulator-option-in-Visual-studio-e1461419933506.png"><img decoding="async" aria-describedby="caption-attachment-11540" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Emulator-option-in-Visual-studio-e1461419933506.png" alt="Emulator option in Visual studio" width="650" height="82" class="size-full wp-image-11540" srcset="/wp-content/uploads/2016/04/Emulator-option-in-Visual-studio-e1461419933506.png 650w, /wp-content/uploads/2016/04/Emulator-option-in-Visual-studio-e1461419933506-300x38.png 300w, /wp-content/uploads/2016/04/Emulator-option-in-Visual-studio-e1461419933506-400x50.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11540" class="wp-caption-text">Emulator option in Visual studio</p></div>
<p>Now you can run your application in emulator if everything works fine. </p>
<div id="attachment_11541" style="width: 443px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Windows-emulator-output.png"><img decoding="async" aria-describedby="caption-attachment-11541" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Windows-emulator-output.png" alt="Windows emulator output" width="433" height="839" class="size-full wp-image-11541" srcset="/wp-content/uploads/2016/04/Windows-emulator-output.png 184w, /wp-content/uploads/2016/04/Windows-emulator-output-155x300.png 155w, /wp-content/uploads/2016/04/Windows-emulator-output-400x775.png 400w, /wp-content/uploads/2016/04/Windows-emulator-output-310x600.png 310w" sizes="(max-width: 433px) 100vw, 433px" /></a><p id="caption-attachment-11541" class="wp-caption-text">Windows emulator output</p></div>
<p>I guess we are done. Hope you enjoyed reading. I will see you soon with another article. </p>
<h3>Conclusion</h3>
<p>Did I miss anything that you may think which is needed? Did you try Azure yet? Have you ever created any mobile apps? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3>Your turn. What do you think?</h3>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/creating-azure-mobile-app-with-visual-studio/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Caching In Web API</title>
		<link>https://sibeeshpassion.com/caching-in-web-api/</link>
					<comments>https://sibeeshpassion.com/caching-in-web-api/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 24 Mar 2016 00:00:39 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Caching]]></category>
		<category><![CDATA[Caching In Web API]]></category>
		<category><![CDATA[MemoryCache]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11410</guid>

					<description><![CDATA[In this article we will are going to learn how we can use caching in Web API. Normally caching is the process of storing data somewhere for the future requests, in our case we can avoid the unwanted hit to database to get the data if we cache the data somewhere, this way we can make sure that the data is served in a faster manner. Here we are going to see the caching in our Web API controller. If you are new to caching, I have written an article about caching in MVC, please read it here: Caching In [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we will are going to learn how we can use caching in Web API. Normally caching is the process of storing data somewhere for the future requests, in our case we can avoid the unwanted hit to database to get the data if we cache the data somewhere, this way we can make sure that the data is served in a faster manner. Here we are going to see the caching in our Web API controller. If you are new to caching, I have written an article about caching in MVC, please read it here: <a href="http://sibeeshpassion.com/caching-in-mvc/" target="_blank" rel="noopener">Caching In MVC</a>. We will explain caching with the help of <em>System.Runtime.Caching</em> which is given by Microsoft. This DLL is not available in the default references, you may need to add that separately. I will show you how. I am creating this application in Visual Studio 2015. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below. </p>
<li><a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/web-api/" target="_blank" rel="noopener">Web API Tips, Tricks, Blogs</a></li>
<p>Now we will go and create our application. I hope you will like this. </p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here.</p>
<li><a href="https://code.msdn.microsoft.com/Caching-In-Web-API-cb40be30" target="_blank" rel="noopener">Caching In Web API</a></li>
<p><strong>Background</strong></p>
<p>For the past few days I am working with Web API.Here we are going to see a demo of how to use Caching in Web API in our MVC application. We are going to use the DLL <em>System.Runtime.Caching.dll</em>, which you need to add as reference. </p>
<p><strong>Create a MVC application</strong></p>
<p>Click File-> New-> Project then select MVC application. From the following pop up we will select the template as empty and select the core references and folders for MVC. </p>
<div id="attachment_11405" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png"><img decoding="async" aria-describedby="caption-attachment-11405" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png" alt="Empty Template With MVC And Web API Folders" width="650" height="484" class="size-full wp-image-11405" srcset="/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png 650w, /wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206-300x223.png 300w, /wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206-400x298.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11405" class="wp-caption-text">Empty Template With MVC And Web API Folders</p></div>
<p>Once you click OK, a project with MVC like folder structure with core references will be created for you.</p>
<div id="attachment_11362" style="width: 277px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png"><img decoding="async" aria-describedby="caption-attachment-11362" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png" alt="Folder Structure And References For Empty MVC Project" width="267" height="367" class="size-full wp-image-11362" srcset="/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png 267w, /wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project-218x300.png 218w" sizes="(max-width: 267px) 100vw, 267px" /></a><p id="caption-attachment-11362" class="wp-caption-text">Folder Structure And References For Empty MVC Project</p></div>
<p>Once your application is ready, we can add the reference for <em>System.Runtime.Caching</em></p>
<p><strong>Add reference for System.Runtime.Caching</strong></p>
<p>To add the reference, right click on References and click Add reference.</p>
<div id="attachment_11411" style="width: 492px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Add_References_.png"><img decoding="async" aria-describedby="caption-attachment-11411" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Add_References_.png" alt="Add_References" width="482" height="316" class="size-full wp-image-11411" srcset="/wp-content/uploads/2016/03/Add_References_.png 482w, /wp-content/uploads/2016/03/Add_References_-300x197.png 300w, /wp-content/uploads/2016/03/Add_References_-400x262.png 400w" sizes="(max-width: 482px) 100vw, 482px" /></a><p id="caption-attachment-11411" class="wp-caption-text">Add_References</p></div>
<p>Now click on the browse button, and search for <em>System.Runtime.Caching</em></p>
<div id="attachment_11412" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/References_Found_-e1458732611680.png"><img decoding="async" aria-describedby="caption-attachment-11412" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/References_Found_-e1458732611680.png" alt="References_Found_" width="650" height="373" class="size-full wp-image-11412" srcset="/wp-content/uploads/2016/03/References_Found_-e1458732611680.png 650w, /wp-content/uploads/2016/03/References_Found_-e1458732611680-300x172.png 300w, /wp-content/uploads/2016/03/References_Found_-e1458732611680-400x230.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11412" class="wp-caption-text">References_Found_</p></div>
<p>And the click OK, the DLL will be added to your references now. </p>
<p><strong>Using the code</strong></p>
<p>We will set up our database first so that we can create Entity Model for our application later. </p>
<p><strong>Create a database</strong></p>
<p>The following query can be used to create a database in your SQL Server.</p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialsDB]<br />
CREATE DATABASE [TrialsDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialsDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf&#8217; , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialsDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf&#8217; , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECOVERY FULL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p>Now we will create the table we needed. As of now I am going to create the table <em>tblTags </em></p>
<p><strong>Create tables in database</strong></p>
<p>Below is the query to create the table <em>tblTags</em>.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[tblTags]    Script Date: 23-Mar-16 5:01:22 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[tblTags](<br />
	[tagId] [int] IDENTITY(1,1) NOT NULL,<br />
	[tagName] [nvarchar](50) NOT NULL,<br />
	[tagDescription] [nvarchar](max) NULL,<br />
 CONSTRAINT [PK_tblTags] PRIMARY KEY CLUSTERED<br />
(<br />
	[tagId] ASC<br />
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br />
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Can we insert some data to the tables now?</p>
<p><strong>Insert data to table</strong></p>
<p>You can use the below query to insert the data to the table <em>tblTags</em></p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>INSERT INTO [dbo].[tblTags]<br />
           ([tagName]<br />
           ,[tagDescription])<br />
     VALUES<br />
           (&lt;tagName, nvarchar(50),&gt;<br />
           ,&lt;tagDescription, nvarchar(max),&gt;)<br />
GO<br />
[/sql] </p>
<p>Next thing we are going to do is creating a ADO.NET Entity Data Model. </p>
<p><strong>Create Entity Data Model</strong></p>
<p>Right click on your model folder and click new, select ADO.NET Entity Data Model. Follow the steps given. Once you have done the processes, you can see the edmx file and other files in your model folder. Here I gave <em>Dashboard</em> for our Entity data model name. Now you can see a file with edmx extension have been created.<br />
Now will create our Web API controller. </p>
<p><strong>Create Web API Controller</strong></p>
<p>To create a Web API controller, just right click on your controller folder and click Add -> Controller -> Select Web API 2 controller with actions, using Entity Framework.</p>
<div id="attachment_11401" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png"><img decoding="async" aria-describedby="caption-attachment-11401" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png" alt="Web API 2 Controller With Actions Using Entity Framework" width="650" height="448" class="size-full wp-image-11401" srcset="/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png 650w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-300x207.png 300w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-160x110.png 160w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-400x276.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11401" class="wp-caption-text">Web API 2 Controller With Actions Using Entity Framework</p></div>
<p>Now select <em>tblTag (CachingInWebAPI.Models)</em> as our Model class and <em>TrialsDBEntities (CachingInWebAPI.Models)</em> as data context class. </p>
<p>As you can see It has been given the name of our controller as <em>tblTags</em>. Here I am not going to change that, if you wish to change, you can do that.</p>
<p>Now you will be given the following codes in our new Web API controller.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Data;<br />
using System.Data.Entity;<br />
using System.Data.Entity.Infrastructure;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Net.Http;<br />
using System.Web.Http;<br />
using System.Web.Http.Description;<br />
using CachingInWebAPI.Models;</p>
<p>namespace CachingInWebAPI.Controllers<br />
{<br />
    public class tblTagsController : ApiController<br />
    {<br />
        private TrialsDBEntities db = new TrialsDBEntities();</p>
<p>        // GET: api/tblTags<br />
        public IQueryable&lt;tblTag&gt; GettblTags()<br />
        {<br />
            return db.tblTags;<br />
        }</p>
<p>        // GET: api/tblTags/5<br />
        [ResponseType(typeof(tblTag))]<br />
        public IHttpActionResult GettblTag(int id)<br />
        {<br />
            tblTag tblTag = db.tblTags.Find(id);<br />
            if (tblTag == null)<br />
            {<br />
                return NotFound();<br />
            }</p>
<p>            return Ok(tblTag);<br />
        }</p>
<p>        // PUT: api/tblTags/5<br />
        [ResponseType(typeof(void))]<br />
        public IHttpActionResult PuttblTag(int id, tblTag tblTag)<br />
        {<br />
            if (!ModelState.IsValid)<br />
            {<br />
                return BadRequest(ModelState);<br />
            }</p>
<p>            if (id != tblTag.tagId)<br />
            {<br />
                return BadRequest();<br />
            }</p>
<p>            db.Entry(tblTag).State = EntityState.Modified;</p>
<p>            try<br />
            {<br />
                db.SaveChanges();<br />
            }<br />
            catch (DbUpdateConcurrencyException)<br />
            {<br />
                if (!tblTagExists(id))<br />
                {<br />
                    return NotFound();<br />
                }<br />
                else<br />
                {<br />
                    throw;<br />
                }<br />
            }</p>
<p>            return StatusCode(HttpStatusCode.NoContent);<br />
        }</p>
<p>        // POST: api/tblTags<br />
        [ResponseType(typeof(tblTag))]<br />
        public IHttpActionResult PosttblTag(tblTag tblTag)<br />
        {<br />
            if (!ModelState.IsValid)<br />
            {<br />
                return BadRequest(ModelState);<br />
            }</p>
<p>            db.tblTags.Add(tblTag);<br />
            db.SaveChanges();</p>
<p>            return CreatedAtRoute(&quot;DefaultApi&quot;, new { id = tblTag.tagId }, tblTag);<br />
        }</p>
<p>        // DELETE: api/tblTags/5<br />
        [ResponseType(typeof(tblTag))]<br />
        public IHttpActionResult DeletetblTag(int id)<br />
        {<br />
            tblTag tblTag = db.tblTags.Find(id);<br />
            if (tblTag == null)<br />
            {<br />
                return NotFound();<br />
            }</p>
<p>            db.tblTags.Remove(tblTag);<br />
            db.SaveChanges();</p>
<p>            return Ok(tblTag);<br />
        }</p>
<p>        protected override void Dispose(bool disposing)<br />
        {<br />
            if (disposing)<br />
            {<br />
                db.Dispose();<br />
            }<br />
            base.Dispose(disposing);<br />
        }</p>
<p>        private bool tblTagExists(int id)<br />
        {<br />
            return db.tblTags.Count(e =&gt; e.tagId == id) &gt; 0;<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>As we are not going to use only read operation, you can remove other functionalities and keep only <em>Get </em>methods for now.</p>
<p>[csharp]<br />
 // GET: api/tblTags<br />
        public IQueryable&lt;tblTag&gt; GettblTags()<br />
        {<br />
            return db.tblTags;<br />
        }<br />
[/csharp]</p>
<p>So the coding part to fetch the data from database is ready, now we need to check whether our Web API is ready for action!. To check that, you just need to run the URL <em>http://localhost:4832/api/tblTags</em>. Here <em>tblTags</em> is our Web API controller name. I hope you get the data as a result.</p>
<div id="attachment_11413" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png"><img decoding="async" aria-describedby="caption-attachment-11413" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png" alt="Web_API_Result" width="650" height="342" class="size-full wp-image-11413" srcset="/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png 650w, /wp-content/uploads/2016/03/Web_API_Result-e1458733092316-300x158.png 300w, /wp-content/uploads/2016/03/Web_API_Result-e1458733092316-600x315.png 600w, /wp-content/uploads/2016/03/Web_API_Result-e1458733092316-400x210.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11413" class="wp-caption-text">Web_API_Result</p></div>
<p>Now we will start testing our caching. For that please import the namespace <em>System.Runtime.Caching;</em></p>
<p>[csharp]<br />
using System.Runtime.Caching;<br />
[/csharp]</p>
<p>Next we will create an instance of <em>MemoryCache </em>class.</p>
<div id="attachment_11415" style="width: 664px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Tooltip_.png"><img decoding="async" aria-describedby="caption-attachment-11415" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Tooltip_.png" alt="MemoryCache_Tooltip_" width="654" height="102" class="size-full wp-image-11415" srcset="/wp-content/uploads/2016/03/MemoryCache_Tooltip_.png 654w, /wp-content/uploads/2016/03/MemoryCache_Tooltip_-300x47.png 300w, /wp-content/uploads/2016/03/MemoryCache_Tooltip_-400x62.png 400w" sizes="(max-width: 654px) 100vw, 654px" /></a><p id="caption-attachment-11415" class="wp-caption-text">MemoryCache_Tooltip_</p></div>
<p>As you can see there are four possible settings we can set in <em>MemoryCache </em> class.</p>
<div id="attachment_11416" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751.png"><img decoding="async" aria-describedby="caption-attachment-11416" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751.png" alt="MemoryCache_Settings" width="650" height="123" class="size-full wp-image-11416" srcset="/wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751.png 650w, /wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751-300x57.png 300w, /wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751-400x76.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11416" class="wp-caption-text">MemoryCache_Settings</p></div>
<p>Now we can add MemoryCache as follows. </p>
<p>[csharp]<br />
public IQueryable&lt;tblTag&gt; GettblTags()<br />
        {<br />
            var ca = db.tblTags;<br />
            memCache.Add(&quot;tag&quot;, ca, DateTimeOffset.UtcNow.AddMinutes(5));<br />
            return db.tblTags;<br />
        }<br />
[/csharp]</p>
<div id="attachment_11417" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183.png"><img decoding="async" aria-describedby="caption-attachment-11417" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183.png" alt="MemoryCache_Add" width="650" height="70" class="size-full wp-image-11417" srcset="/wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183.png 650w, /wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183-300x32.png 300w, /wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183-400x43.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11417" class="wp-caption-text">MemoryCache_Add</p></div>
<p>Here &#8220;tag&#8221; is my key and &#8220;ca&#8221; is my values and DateTimeOffset.UtcNow.AddMinutes(5) is for setting the cache for five minutes from now. </p>
<p>Shall we check how it works now? To check whether the content has been added to the cache we need to use the Get method, please see the code block below. </p>
<p>[csharp]<br />
var res = memCache.Get(&quot;tag&quot;);<br />
            if (res != null)<br />
            {<br />
                return res;<br />
            }<br />
            else {<br />
                var ca = db.tblTags;<br />
                memCache.Add(&quot;tag&quot;, ca, DateTimeOffset.UtcNow.AddMinutes(5));<br />
                return db.tblTags;<br />
            }<br />
[/csharp]</p>
<p>We will get the cache values in the variable res, remember this values will be there only for five minutes. You can always change that as per need. If the value is not null, we will just return it and do the manipulation and if it is null we will go ahead and fetch the data from database and add the value to cache. Now please run your API by running the URL <em>http://localhost:4832/api/tblTags</em>. </p>
<div id="attachment_11418" style="width: 634px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Cache_Value_Null.png"><img decoding="async" aria-describedby="caption-attachment-11418" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Cache_Value_Null.png" alt="Cache_Value_Null" width="624" height="215" class="size-full wp-image-11418" srcset="/wp-content/uploads/2016/03/Cache_Value_Null.png 624w, /wp-content/uploads/2016/03/Cache_Value_Null-300x103.png 300w, /wp-content/uploads/2016/03/Cache_Value_Null-620x215.png 620w, /wp-content/uploads/2016/03/Cache_Value_Null-400x138.png 400w" sizes="(max-width: 624px) 100vw, 624px" /></a><p id="caption-attachment-11418" class="wp-caption-text">Cache_Value_Null</p></div>
<p>You can see that we are setting the value to memCache as the <em>memCache.Get(&#8220;tag&#8221;)</em> is null. </p>
<div id="attachment_11419" style="width: 606px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Cache_Value_Not_Null.png"><img decoding="async" aria-describedby="caption-attachment-11419" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Cache_Value_Not_Null.png" alt="Cache_Value_Not_Null" width="596" height="215" class="size-full wp-image-11419" srcset="/wp-content/uploads/2016/03/Cache_Value_Not_Null.png 596w, /wp-content/uploads/2016/03/Cache_Value_Not_Null-300x108.png 300w, /wp-content/uploads/2016/03/Cache_Value_Not_Null-400x144.png 400w" sizes="(max-width: 596px) 100vw, 596px" /></a><p id="caption-attachment-11419" class="wp-caption-text">Cache_Value_Not_Null</p></div>
<p>So we just tried to load the same Web API URL within five minutes, so we gets values from <em>memCache.Get(&#8220;tag&#8221;)</em>. Sounds good?</p>
<p>There is an option to remove our cache too, we will see that now. We will use the <em>Remove</em> function for the same. First we will check whether the key is available in the <em>MemoryCache</em>, if it is available we will remove that.</p>
<p>[csharp]<br />
//This is to remove the MemoryCache &#8211; start<br />
                if (memCache.Contains(&quot;tag&quot;))<br />
                {<br />
                    memCache.Remove(&quot;tag&quot;);<br />
                }<br />
                //This is to remove the MemoryCache &#8211; end<br />
[/csharp]</p>
<div id="attachment_11420" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814.png"><img decoding="async" aria-describedby="caption-attachment-11420" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814.png" alt="MemoryCache_Remove" width="650" height="299" class="size-full wp-image-11420" srcset="/wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814.png 650w, /wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814-300x138.png 300w, /wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814-400x184.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11420" class="wp-caption-text">MemoryCache_Remove</p></div>
<p>We have done everything!. That&#8217;s fantastic right? Have a happy coding.</p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Did you try Web API yet? Have you ever wanted to do caching in Web API? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/caching-in-web-api/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Chart Widgets With Server Side Data In MVC Using Angular JS And Web API</title>
		<link>https://sibeeshpassion.com/chart-widgets-with-server-side-data-in-mvc-using-angular-js-and-web-api/</link>
					<comments>https://sibeeshpassion.com/chart-widgets-with-server-side-data-in-mvc-using-angular-js-and-web-api/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 17 Mar 2016 05:33:35 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Angular JS]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Bar Chart]]></category>
		<category><![CDATA[Column Charts]]></category>
		<category><![CDATA[HighChart]]></category>
		<category><![CDATA[HighChart With Angular JS]]></category>
		<category><![CDATA[Line Chart]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Pie Chart]]></category>
		<category><![CDATA[Scatter Chart]]></category>
		<category><![CDATA[Server Error in Application]]></category>
		<category><![CDATA[Spline Chart]]></category>
		<category><![CDATA[The resource cannot be found]]></category>
		<category><![CDATA[Widgets With Server Side Data]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11359</guid>

					<description><![CDATA[In this article we will learn how we can create some client side chart widgets with the data from SQL Server database. We use MVC architecture with Web API and Angular JS to fetch the data and do all the manipulations. I am creating this application in Visual Studio 2015. In this project we covers topic of how to use HighChart with Angular JS. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below. AngularJS Tips, Tricks, Blogs MVC Tips, Tricks, Blogs Web API Tips, Tricks, Blogs Now we will go and create our application. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we will learn how we can create some client side chart widgets with the data from <a href="http://sibeeshpassion.com/category/SQL/" target="_blank" rel="noopener">SQL </a>Server database. We use MVC architecture with Web API and Angular JS to fetch the data and do all the manipulations. I am creating this application in Visual Studio 2015. In this project we covers topic of how to use <a href="http://sibeeshpassion.com/category/products/HighChart/" target="_blank" rel="noopener">HighChart </a>with Angular JS. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below. </p>
<li><a href="http://sibeeshpassion.com/category/angularjs/" target="_blank" rel="noopener">AngularJS Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/web-api/" target="_blank" rel="noopener">Web API Tips, Tricks, Blogs</a></li>
<p>Now we will go and create our application. I hope you will like this. </p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here.</p>
<li><a href="https://code.msdn.microsoft.com/Chart-Widgets-With-Server-70f5cdac" target="_blank" rel="noopener">Widgets With Server Side Data</a></li>
<li><a href="http://sibeeshpassion.com/Download/MyDashboardSQLScript.rar" target="_blank" rel="noopener">SQL Scripts With Insert Queries</a></li>
<p><strong>Background</strong></p>
<p>I am working now in a personal dashboard application in which I uses HighChart products for the chart integration. We can always load the chart widgets with server side data and Angular JS right? Here we will discuss that. We are going to create the preceding charts for our dashboard. </p>
<li>Pie Chart</li>
<li>Spline Chart</li>
<li>Bar Chart</li>
<li>Line Chart</li>
<li>Scatter Chart</li>
<li>Column Chart</li>
<p>Once we are done, this is how our applications output will be. </p>
<div id="attachment_11360" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Chart-Widgets-With-Server-Side-Data-In-MVC-Using-Angular-JS-And-Web-API-Output-e1458121833696.png"><img decoding="async" aria-describedby="caption-attachment-11360" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Chart-Widgets-With-Server-Side-Data-In-MVC-Using-Angular-JS-And-Web-API-Output-1024x875.png" alt="Chart Widgets With Server Side Data In MVC Using Angular JS And Web API Output" width="634" height="542" class="size-large wp-image-11360" /></a><p id="caption-attachment-11360" class="wp-caption-text">Chart Widgets With Server Side Data In MVC Using Angular JS And Web API Output</p></div>
<p><strong>Create a MVC application</strong></p>
<p>Click File-> New-> Project then select MVC application. From the following pop up we will select the template as empty and select the core references and folders for MVC. </p>
<div id="attachment_11361" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MVC-Project-With-Empty-Template-e1458122053871.png"><img decoding="async" aria-describedby="caption-attachment-11361" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MVC-Project-With-Empty-Template-e1458122053871.png" alt="MVC Project With Empty Template" width="650" height="508" class="size-full wp-image-11361" srcset="/wp-content/uploads/2016/03/MVC-Project-With-Empty-Template-e1458122053871.png 650w, /wp-content/uploads/2016/03/MVC-Project-With-Empty-Template-e1458122053871-300x234.png 300w, /wp-content/uploads/2016/03/MVC-Project-With-Empty-Template-e1458122053871-400x313.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11361" class="wp-caption-text">MVC Project With Empty Template</p></div>
<p>Once you click OK, a project with MVC like folder structure with core references will be created for you.</p>
<div id="attachment_11362" style="width: 277px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png"><img decoding="async" aria-describedby="caption-attachment-11362" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png" alt="Folder Structure And References For Empty MVC Project" width="267" height="367" class="size-full wp-image-11362" srcset="/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png 267w, /wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project-218x300.png 218w" sizes="(max-width: 267px) 100vw, 267px" /></a><p id="caption-attachment-11362" class="wp-caption-text">Folder Structure And References For Empty MVC Project</p></div>
<p>Before going to start the coding part, make sure that all the required extensions/references are installed. Below are the required things to start with. </p>
<li>Angular JS</li>
<li>jQuery</li>
<p>You can all the items mentioned above from NuGet. Right click on your project name and select Manage NuGet packages.</p>
<div id="attachment_11235" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png"><img decoding="async" aria-describedby="caption-attachment-11235" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png" alt="Manage NuGet Package Window" width="650" height="432" class="size-full wp-image-11235" srcset="/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png 650w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-300x199.png 300w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-400x266.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11235" class="wp-caption-text">Manage NuGet Package Window</p></div>
<p>Once you have installed those items, please make sure that all the items(jQuery, Angular JS files) are loaded in your scripts folder. </p>
<p><strong>Using the code</strong></p>
<p>As I have said before, we are going to use Angular JS for our client side operations, so it is better to create the Angular JS script files first right? Just to make sure that we have got all the required things :). For that, create a folder named <em>Widget</em> in script folder and right click -> Add -> New Item -> Select AngularJS Module and enter the module name -> Click Add.</p>
<div id="attachment_11363" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Creating-Angular-JS-Modue-In-MVC-Application-e1458122639235.png"><img decoding="async" aria-describedby="caption-attachment-11363" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Creating-Angular-JS-Modue-In-MVC-Application-e1458122639235.png" alt="Creating Angular JS Modue In MVC Application" width="650" height="449" class="size-full wp-image-11363" srcset="/wp-content/uploads/2016/03/Creating-Angular-JS-Modue-In-MVC-Application-e1458122639235.png 650w, /wp-content/uploads/2016/03/Creating-Angular-JS-Modue-In-MVC-Application-e1458122639235-300x207.png 300w, /wp-content/uploads/2016/03/Creating-Angular-JS-Modue-In-MVC-Application-e1458122639235-160x110.png 160w, /wp-content/uploads/2016/03/Creating-Angular-JS-Modue-In-MVC-Application-e1458122639235-400x276.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11363" class="wp-caption-text">Creating Angular JS Modue In MVC Application</p></div>
<p>Follow the same procedure to create Angular JS factory and Angular JS controller. Yes, we have set everything to get started our coding. Now we will create a Web API controller and get the data from database in JSON format. Let&#8217;s start then.</p>
<p><strong>Create Web API Controller</strong></p>
<p>To create a Web API controller, just right click on your controller folder and click Add -> Controller -> Select Web API controller &#8211; Empty ( We will create our own actions later) -> Name the controller (Here I am giving the controller name as Widget).</p>
<p>So our controller is ready, now we need to set up our database so that we can create Entity Model for our application later. </p>
<p><strong>Create a database</strong></p>
<p>The following query can be used to create a database in your SQL Server.</p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialsDB]    Script Date: 16-Mar-16 4:08:15 PM ******/<br />
CREATE DATABASE [TrialsDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialsDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf&#8217; , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialsDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf&#8217; , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECOVERY FULL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p>Now we will create the tables we needed. As of now I am going to create two tables. </p>
<li>SalesOrderDetail</li>
<li>Product</li>
<p>These tables are having relationship by the key <em>ProductID</em>.</p>
<p><strong>Create tables in database</strong></p>
<p>Below is the query to create SalesOrderDetail table in database.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[SalesOrderDetail]    Script Date: 16-Mar-16 4:10:22 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[SalesOrderDetail](<br />
	[SalesOrderID] [int] NOT NULL,<br />
	[SalesOrderDetailID] [int] IDENTITY(1,1) NOT NULL,<br />
	[CarrierTrackingNumber] [nvarchar](25) NULL,<br />
	[OrderQty] [smallint] NOT NULL,<br />
	[ProductID] [int] NOT NULL,<br />
	[SpecialOfferID] [int] NOT NULL,<br />
	[UnitPrice] [money] NOT NULL,<br />
	[UnitPriceDiscount] [money] NOT NULL,<br />
	[LineTotal]  AS (isnull(([UnitPrice]*((1.0)-[UnitPriceDiscount]))*[OrderQty],(0.0))),<br />
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,<br />
	[ModifiedDate] [datetime] NOT NULL,<br />
 CONSTRAINT [PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID] PRIMARY KEY CLUSTERED<br />
(<br />
	[SalesOrderID] ASC,<br />
	[SalesOrderDetailID] ASC<br />
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br />
) ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Now we will create the table Product.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[Product]    Script Date: 16-Mar-16 4:11:29 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[Product](<br />
	[ProductID] [int] NOT NULL,<br />
	[Name] [nvarchar](max) NOT NULL,<br />
	[ProductNumber] [nvarchar](25) NOT NULL,<br />
	[MakeFlag] [bit] NOT NULL,<br />
	[FinishedGoodsFlag] [bit] NOT NULL,<br />
	[Color] [nvarchar](15) NULL,<br />
	[SafetyStockLevel] [smallint] NOT NULL,<br />
	[ReorderPoint] [smallint] NOT NULL,<br />
	[StandardCost] [money] NOT NULL,<br />
	[ListPrice] [money] NOT NULL,<br />
	[Size] [nvarchar](5) NULL,<br />
	[SizeUnitMeasureCode] [nchar](3) NULL,<br />
	[WeightUnitMeasureCode] [nchar](3) NULL,<br />
	[Weight] [decimal](8, 2) NULL,<br />
	[DaysToManufacture] [int] NOT NULL,<br />
	[ProductLine] [nchar](2) NULL,<br />
	[Class] [nchar](2) NULL,<br />
	[Style] [nchar](2) NULL,<br />
	[ProductSubcategoryID] [int] NULL,<br />
	[ProductModelID] [int] NULL,<br />
	[SellStartDate] [datetime] NOT NULL,<br />
	[SellEndDate] [datetime] NULL,<br />
	[DiscontinuedDate] [datetime] NULL,<br />
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,<br />
	[ModifiedDate] [datetime] NOT NULL<br />
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Can we insert some data to the tables now?</p>
<p><strong>Insert data to table</strong></p>
<p>You can use the below query to insert the data to SalesOrderDetail.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>INSERT INTO [dbo].[SalesOrderDetail]<br />
           ([SalesOrderID]<br />
           ,[CarrierTrackingNumber]<br />
           ,[OrderQty]<br />
           ,[ProductID]<br />
           ,[SpecialOfferID]<br />
           ,[UnitPrice]<br />
           ,[UnitPriceDiscount]<br />
           ,[rowguid]<br />
           ,[ModifiedDate])<br />
     VALUES<br />
           (&lt;SalesOrderID, int,&gt;<br />
           ,&lt;CarrierTrackingNumber, nvarchar(25),&gt;<br />
           ,&lt;OrderQty, smallint,&gt;<br />
           ,&lt;ProductID, int,&gt;<br />
           ,&lt;SpecialOfferID, int,&gt;<br />
           ,&lt;UnitPrice, money,&gt;<br />
           ,&lt;UnitPriceDiscount, money,&gt;<br />
           ,&lt;rowguid, uniqueidentifier,&gt;<br />
           ,&lt;ModifiedDate, datetime,&gt;)<br />
GO<br />
[/sql]</p>
<p>and the following query can be used for the table <em>Product</em></p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>INSERT INTO [dbo].[Product]<br />
           ([ProductID]<br />
           ,[Name]<br />
           ,[ProductNumber]<br />
           ,[MakeFlag]<br />
           ,[FinishedGoodsFlag]<br />
           ,[Color]<br />
           ,[SafetyStockLevel]<br />
           ,[ReorderPoint]<br />
           ,[StandardCost]<br />
           ,[ListPrice]<br />
           ,[Size]<br />
           ,[SizeUnitMeasureCode]<br />
           ,[WeightUnitMeasureCode]<br />
           ,[Weight]<br />
           ,[DaysToManufacture]<br />
           ,[ProductLine]<br />
           ,[Class]<br />
           ,[Style]<br />
           ,[ProductSubcategoryID]<br />
           ,[ProductModelID]<br />
           ,[SellStartDate]<br />
           ,[SellEndDate]<br />
           ,[DiscontinuedDate]<br />
           ,[rowguid]<br />
           ,[ModifiedDate])<br />
     VALUES<br />
           (&lt;ProductID, int,&gt;<br />
           ,&lt;Name, nvarchar(max),&gt;<br />
           ,&lt;ProductNumber, nvarchar(25),&gt;<br />
           ,&lt;MakeFlag, bit,&gt;<br />
           ,&lt;FinishedGoodsFlag, bit,&gt;<br />
           ,&lt;Color, nvarchar(15),&gt;<br />
           ,&lt;SafetyStockLevel, smallint,&gt;<br />
           ,&lt;ReorderPoint, smallint,&gt;<br />
           ,&lt;StandardCost, money,&gt;<br />
           ,&lt;ListPrice, money,&gt;<br />
           ,&lt;Size, nvarchar(5),&gt;<br />
           ,&lt;SizeUnitMeasureCode, nchar(3),&gt;<br />
           ,&lt;WeightUnitMeasureCode, nchar(3),&gt;<br />
           ,&lt;Weight, decimal(8,2),&gt;<br />
           ,&lt;DaysToManufacture, int,&gt;<br />
           ,&lt;ProductLine, nchar(2),&gt;<br />
           ,&lt;Class, nchar(2),&gt;<br />
           ,&lt;Style, nchar(2),&gt;<br />
           ,&lt;ProductSubcategoryID, int,&gt;<br />
           ,&lt;ProductModelID, int,&gt;<br />
           ,&lt;SellStartDate, datetime,&gt;<br />
           ,&lt;SellEndDate, datetime,&gt;<br />
           ,&lt;DiscontinuedDate, datetime,&gt;<br />
           ,&lt;rowguid, uniqueidentifier,&gt;<br />
           ,&lt;ModifiedDate, datetime,&gt;)<br />
GO<br />
[/sql] </p>
<p>So let us say, we have inserted the data as follows. If you feel bored of inserting data manually, you can always tun the SQL script file attached which has the insertion queries. Just run that, you will be all OK. If you don&#8217;t know how to generate SQL scripts with data, I strongly recommend you to have a read <a href="http://sibeeshpassion.com/generate-database-scripts-with-data-in-sql-server/" target="_blank" rel="noopener">here</a></p>
<p>Next thing we are going to do is creating a ADO.NET Entity Data Model. </p>
<p><strong>Create Entity Data Model</strong></p>
<p>Right click on your model folder and click new, select ADO.NET Entity Data Model. Follow the steps given. Once you have done the processes, you can see the edmx file and other files in your model folder. Here I gave <em>Dashboard</em> for our Entity data model name. Now you can see a file with edmx extension have been created. If you open that file, you can see as below. </p>
<div id="attachment_11364" style="width: 513px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Entity-Data-Model.png"><img decoding="async" aria-describedby="caption-attachment-11364" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Entity-Data-Model.png" alt="Entity Data Model" width="503" height="669" class="size-full wp-image-11364" srcset="/wp-content/uploads/2016/03/Entity-Data-Model.png 503w, /wp-content/uploads/2016/03/Entity-Data-Model-226x300.png 226w, /wp-content/uploads/2016/03/Entity-Data-Model-400x532.png 400w, /wp-content/uploads/2016/03/Entity-Data-Model-451x600.png 451w" sizes="(max-width: 503px) 100vw, 503px" /></a><p id="caption-attachment-11364" class="wp-caption-text">Entity Data Model</p></div>
<p>Now go back our Web API controller. Please change the code as below.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Net.Http;<br />
using System.Web.Http;<br />
using MyDashboard.Models;<br />
using Newtonsoft.Json;<br />
namespace MyDashboard.Controllers<br />
{<br />
    public class WidgetController : ApiController<br />
    {<br />
        public DashboardEntities de = new DashboardEntities();<br />
        Retriever ret = new Retriever();<br />
        public string getWidgetData()<br />
        {<br />
            var dataList = ret.GetWidgetData(de);<br />
            return dataList;<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Here we have created a new model class <em>Retriever </em> and we have added a method <em>GetWidgetData</em> in that class. Now let us see what I have coded in that.</p>
<p>[csharp]<br />
using Newtonsoft.Json;<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;</p>
<p>namespace MyDashboard.Models<br />
{<br />
    public class Retriever<br />
    {<br />
        public string GetWidgetData(DashboardEntities de)<br />
        {<br />
            try<br />
            {<br />
                using (de)<br />
                {<br />
                    var resList = (from sales in de.SalesOrderDetails<br />
                                  join prod in de.Products<br />
                                  on sales.ProductID equals prod.ProductID<br />
                                  select new<br />
                                  {<br />
                                      ProductName = prod.Name,<br />
                                      QuantityOrdered = sales.OrderQty<br />
                                  });<br />
                    var res = resList.GroupBy(d =&gt; d.ProductName).Select(g =&gt; new<br />
                    {<br />
                        name = g.FirstOrDefault().ProductName,<br />
                        y = g.Sum(s =&gt; s.QuantityOrdered)<br />
                    });<br />
                    return JsonConvert.SerializeObject(res, Formatting.None, new JsonSerializerSettings()<br />
                    {<br />
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore<br />
                    });<br />
                }<br />
            }<br />
            catch (Exception)<br />
            {<br />
                throw new NotImplementedException();<br />
            }</p>
<p>        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Here we are using LINQ to fetch the data, We uses JOIN in the query to find the <em>Name </em> from the table Products. Once the data is ready, we are just do group by the column <em>ProductName</em> and sum of <em>QuantityOrdered</em>. </p>
<p>[csharp]<br />
var res = resList.GroupBy(d =&gt; d.ProductName).Select(g =&gt; new<br />
                    {<br />
                        name = g.FirstOrDefault().ProductName,<br />
                        y = g.Sum(s =&gt; s.QuantityOrdered)<br />
                    });<br />
[/csharp]</p>
<p>So the coding part to fetch the data from database is read, now we need to check whether our Web API is ready for action!. To check that, you just need to run the URL <em>http://localhost:1646/Api/Widget</em>. Here <em>Widget</em> is our Web API controller name. I hope you get the data as a result. If you are getting the error <em>Server Error in &#8216;/&#8217; Application The resource cannot be found</em>, you need to configure your Web API in <em>Global.asax.cs</em>. You got this error just because you created an Empty project with only needed references. So here we need to do his step by our own. No worries, we will do it now. Just change the <em>Global.asax.cs </em>as follows. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.Http;<br />
using System.Web.Mvc;<br />
using System.Web.Routing;</p>
<p>namespace MyDashboard<br />
{<br />
    public class MvcApplication : System.Web.HttpApplication<br />
    {<br />
        protected void Application_Start()<br />
        {<br />
            AreaRegistration.RegisterAllAreas();<br />
            GlobalConfiguration.Configure(WebApiConfig.Register);//This is for setting the configuration<br />
            RouteConfig.RegisterRoutes(RouteTable.Routes);<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Now build your application and run the same URL again, you will get the output as follows. </p>
<div id="attachment_11365" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-Output.png"><img decoding="async" aria-describedby="caption-attachment-11365" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-Output-1024x258.png" alt="Web API Output" width="634" height="160" class="size-large wp-image-11365" srcset="/wp-content/uploads/2016/03/Web-API-Output-1024x258.png 1024w, /wp-content/uploads/2016/03/Web-API-Output-300x75.png 300w, /wp-content/uploads/2016/03/Web-API-Output-768x193.png 768w, /wp-content/uploads/2016/03/Web-API-Output-400x101.png 400w, /wp-content/uploads/2016/03/Web-API-Output.png 1367w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11365" class="wp-caption-text">Web API Output</p></div>
<p>Now we will go back to our angular JS files and consume this Web API. You need to change the scripts in the <em>app.js, controller.js, factory.js</em> as follows.</p>
<p><strong>app.js</strong></p>
<p>[js]<br />
(function () {<br />
    &#8216;use strict&#8217;;<br />
    angular.module(&#8216;WidgetsApp&#8217;, []);<br />
})();<br />
[/js]</p>
<p><strong>controller.js</strong></p>
<p>[js]<br />
(function () {<br />
    &#8216;use strict&#8217;;<br />
    angular<br />
        .module(&#8216;WidgetsApp&#8217;)<br />
        .controller(&#8216;WidgetsController&#8217;, function ($scope, factory) {<br />
            var res = factory.getData();<br />
            var options;<br />
            if (res != undefined) {<br />
                res.then(function (d) {<br />
                    var data = JSON.parse(d.data);</p>
<p>                }, function (error) {<br />
                    console.log(&#8216;Oops! Something went wrong while fetching the data.&#8217;);<br />
                });<br />
            }<br />
        });<br />
})();</p>
<p>[/js]</p>
<p>Once our service is called, we will get the data in return. We will parse the same and store it in a variable for future use.</p>
<p>[js]<br />
var data = JSON.parse(d.data);<br />
[/js]</p>
<p><strong>factory.js</strong></p>
<p>[js]<br />
(function () {<br />
    &#8216;use strict&#8217;;<br />
    angular<br />
        .module(&#8216;WidgetsApp&#8217;)<br />
        .service(&#8216;factory&#8217;, function ($http) {<br />
            this.getData = function () {<br />
                var url = &#8216;Api/Widget&#8217;;<br />
                return $http({<br />
                    type: &#8216;get&#8217;,<br />
                    url: url<br />
                });<br />
            }<br />
        });<br />
})();<br />
[/js]</p>
<p>AS you can see we are just calling our Web API <em>Api/Widget</em> with the help of <a href="http://sibeeshpassion.com/learning-angularjs-http/" target="_blank" rel="noopener">Angular $http.</a></p>
<p>Now we a view to show our data right? Yes, we need a controller too!.</p>
<p><strong>Create a MVC controller</strong></p>
<p>To create a controller, we need to right click on the controller folder, Add &#8211; Controller. I hope you will be given a controller as follows. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.Mvc;</p>
<p>namespace MyDashboard.Controllers<br />
{<br />
    public class HomeController : Controller<br />
    {<br />
        // GET: Home<br />
        public ActionResult Index()<br />
        {<br />
            return View();<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Here <em>Home</em> is our controller name. </p>
<p>Now we need a view right?</p>
<p><strong>Creating a view</strong></p>
<p>To create a view, just right click on your controller name -> Add View -> Add.</p>
<div id="attachment_11366" style="width: 635px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Creating-a-view.png"><img decoding="async" aria-describedby="caption-attachment-11366" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Creating-a-view.png" alt="Creating a view" width="625" height="398" class="size-full wp-image-11366" srcset="/wp-content/uploads/2016/03/Creating-a-view.png 625w, /wp-content/uploads/2016/03/Creating-a-view-300x191.png 300w, /wp-content/uploads/2016/03/Creating-a-view-400x255.png 400w" sizes="(max-width: 625px) 100vw, 625px" /></a><p id="caption-attachment-11366" class="wp-caption-text">Creating a view</p></div>
<p>Now in your view add the needed references.</p>
<p>[html]<br />
&lt;script src=&quot;~/scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/jquery-ui-1.11.4.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-aria.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-route.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/Widgets/app.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/Widgets/controller.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/Widgets/factory.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Once we add the references, we can call our Angular JS controller as follows.</p>
<p>[html]<br />
&lt;div ng-app=&quot;WidgetsApp&quot;&gt;<br />
    &lt;div ng-controller=&quot;WidgetsController&quot;&gt;<br />
    &lt;/div&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p>Now if you run your application, you can see our Web API call works fine and successfully get the data. Next thing we need to do is creating charts with the data we get.</p>
<p><strong>Create chart widgets with the data</strong></p>
<p>As I said, we are going to to create HighChart chart widgets, we need to add a reference to use that plug in.</p>
<p>[html]<br />
&lt;script src=&quot;https://code.highcharts.com/highcharts.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Now create elements where we can load our chart.</p>
<p>[html]<br />
&lt;div ng-app=&quot;WidgetsApp&quot;&gt;<br />
    &lt;div ng-controller=&quot;WidgetsController&quot;&gt;<br />
        &lt;div id=&quot;widgetPie&quot; class=&quot;widget&quot;&gt;Placeholder for chart&lt;/div&gt;<br />
        &lt;div id=&quot;widgetspline&quot; class=&quot;widget&quot;&gt;Placeholder for chart&lt;/div&gt;<br />
        &lt;div id=&quot;widgetBar&quot; class=&quot;widget&quot;&gt;Placeholder for chart&lt;/div&gt;<br />
        &lt;div id=&quot;widgetLine&quot; class=&quot;widget&quot;&gt;Placeholder for chart&lt;/div&gt;<br />
        &lt;div id=&quot;widgetScatter&quot; class=&quot;widget&quot;&gt;Placeholder for chart&lt;/div&gt;<br />
        &lt;div id=&quot;widgetColumn&quot; class=&quot;widget&quot;&gt;Placeholder for chart&lt;/div&gt;<br />
    &lt;/div&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p>You can style your elements as follows if you want, but this is optional.</p>
<p>[css]<br />
&lt;style&gt;<br />
    .widget {<br />
        width: 30%;<br />
        border: 1px solid #ccc;<br />
        padding: 10px;<br />
        margin: 5px;<br />
        border-radius: 3px;<br />
        transition: none;<br />
        -webkit-transition: none;<br />
        -moz-transition: none;<br />
        -o-transition: none;<br />
        cursor: move;<br />
        display: inline-block;<br />
        float:left;<br />
    }<br />
&lt;/style&gt;<br />
[/css]</p>
<p>Go back to our Angular JS controller and add the below codes right after we get the data from server. </p>
<p><strong>Pie Chart</strong></p>
<p>[js]<br />
var data = JSON.parse(d.data);<br />
                    var categories = [];<br />
                    for (var i = 0; i &lt; data.length; i++) {<br />
                        categories.push(data[i].name)<br />
                    }<br />
                    options = new Highcharts.chart(&#8216;widgetPie&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;pie&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Pie Chart&#8217;<br />
                        },<br />
                        plotOptions: {<br />
                            pie: {<br />
                                allowPointSelect: true,<br />
                                cursor: &#8216;pointer&#8217;,<br />
                                dataLabels: {<br />
                                    enabled: false,<br />
                                    format: &#8216;&lt;b&gt;{point.name}&lt;/b&gt;: {point.y:,.0f}&#8217;<br />
                                }<br />
                            }<br />
                        },<br />
                        series: [{<br />
                            name:&#8217;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
[/js]</p>
<p>Now run your application, you can see a pie chart with the data given. </p>
<div id="attachment_11368" style="width: 358px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Pie-Chart-In-MVC-With-Angular-JS-And-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-11368" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Pie-Chart-In-MVC-With-Angular-JS-And-Web-API.png" alt="Pie Chart In MVC With Angular JS And Web API" width="348" height="427" class="size-full wp-image-11368" srcset="/wp-content/uploads/2016/03/Pie-Chart-In-MVC-With-Angular-JS-And-Web-API.png 348w, /wp-content/uploads/2016/03/Pie-Chart-In-MVC-With-Angular-JS-And-Web-API-244x300.png 244w" sizes="(max-width: 348px) 100vw, 348px" /></a><p id="caption-attachment-11368" class="wp-caption-text">Pie Chart In MVC With Angular JS And Web API</p></div>
<p><strong>Column Chart</strong></p>
<p>[js]<br />
options = new Highcharts.chart(&#8216;widgetColumn&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;column&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Column Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
[/js]</p>
<p>Now run your application, you can see a column chart with the data given. </p>
<div id="attachment_11369" style="width: 364px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Column-Chart-In-MVC-With-Angular-JS-And-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-11369" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Column-Chart-In-MVC-With-Angular-JS-And-Web-API.png" alt="Column Chart In MVC With Angular JS And Web API" width="354" height="433" class="size-full wp-image-11369" srcset="/wp-content/uploads/2016/03/Column-Chart-In-MVC-With-Angular-JS-And-Web-API.png 354w, /wp-content/uploads/2016/03/Column-Chart-In-MVC-With-Angular-JS-And-Web-API-245x300.png 245w" sizes="(max-width: 354px) 100vw, 354px" /></a><p id="caption-attachment-11369" class="wp-caption-text">Column Chart In MVC With Angular JS And Web API</p></div>
<p><strong>Bar Chart</strong></p>
<p>[js]<br />
options = new Highcharts.chart(&#8216;widgetBar&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;bar&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Bar Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
[/js]</p>
<p>Now run your application, you can see a Bar chart with the data given. </p>
<div id="attachment_11370" style="width: 362px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Bar-Chart-In-MVC-With-Angular-JS-And-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-11370" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Bar-Chart-In-MVC-With-Angular-JS-And-Web-API.png" alt="Bar Chart In MVC With Angular JS And Web API" width="352" height="431" class="size-full wp-image-11370" srcset="/wp-content/uploads/2016/03/Bar-Chart-In-MVC-With-Angular-JS-And-Web-API.png 352w, /wp-content/uploads/2016/03/Bar-Chart-In-MVC-With-Angular-JS-And-Web-API-245x300.png 245w" sizes="(max-width: 352px) 100vw, 352px" /></a><p id="caption-attachment-11370" class="wp-caption-text">Bar Chart In MVC With Angular JS And Web API</p></div>
<p><strong>Line Chart</strong></p>
<p>[js]<br />
options = new Highcharts.chart(&#8216;widgetLine&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;line&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Line Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
[/js]</p>
<p>Now run your application, you can see a Line chart with the data given. </p>
<div id="attachment_11371" style="width: 364px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Line-Chart-In-MVC-With-Angular-JS-And-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-11371" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Line-Chart-In-MVC-With-Angular-JS-And-Web-API.png" alt="Line Chart In MVC With Angular JS And Web API" width="354" height="436" class="size-full wp-image-11371" srcset="/wp-content/uploads/2016/03/Line-Chart-In-MVC-With-Angular-JS-And-Web-API.png 354w, /wp-content/uploads/2016/03/Line-Chart-In-MVC-With-Angular-JS-And-Web-API-244x300.png 244w" sizes="(max-width: 354px) 100vw, 354px" /></a><p id="caption-attachment-11371" class="wp-caption-text">Line Chart In MVC With Angular JS And Web API</p></div>
<p><strong>Spline Chart</strong></p>
<p>[js]<br />
options = new Highcharts.chart(&#8216;widgetspline&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;spline&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Spline Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
[/js]</p>
<p>Now run your application, you can see a Spline chart with the data given. </p>
<div id="attachment_11372" style="width: 363px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Spline-Chart-In-MVC-With-Angular-JS-And-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-11372" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Spline-Chart-In-MVC-With-Angular-JS-And-Web-API.png" alt="Spline Chart In MVC With Angular JS And Web API" width="353" height="432" class="size-full wp-image-11372" srcset="/wp-content/uploads/2016/03/Spline-Chart-In-MVC-With-Angular-JS-And-Web-API.png 353w, /wp-content/uploads/2016/03/Spline-Chart-In-MVC-With-Angular-JS-And-Web-API-245x300.png 245w" sizes="(max-width: 353px) 100vw, 353px" /></a><p id="caption-attachment-11372" class="wp-caption-text">Spline Chart In MVC With Angular JS And Web API</p></div>
<p><strong>Scatter Chart</strong></p>
<p>[js]<br />
 options = new Highcharts.chart(&#8216;widgetScatter&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;scatter&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Scatter Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
[/js]</p>
<p>Now run your application, you can see a Scatter chart with the data given. </p>
<div id="attachment_11374" style="width: 361px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Scatter-Chart-In-MVC-With-Angular-JS-And-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-11374" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Scatter-Chart-In-MVC-With-Angular-JS-And-Web-API.png" alt="Scatter Chart In MVC With Angular JS And Web API" width="351" height="432" class="size-full wp-image-11374" srcset="/wp-content/uploads/2016/03/Scatter-Chart-In-MVC-With-Angular-JS-And-Web-API.png 351w, /wp-content/uploads/2016/03/Scatter-Chart-In-MVC-With-Angular-JS-And-Web-API-244x300.png 244w" sizes="(max-width: 351px) 100vw, 351px" /></a><p id="caption-attachment-11374" class="wp-caption-text">Scatter Chart In MVC With Angular JS And Web API</p></div>
<p>Now this is how complete code for our controller.js file looks like. </p>
<p>[js]<br />
(function () {<br />
    &#8216;use strict&#8217;;<br />
    angular<br />
        .module(&#8216;WidgetsApp&#8217;)<br />
        .controller(&#8216;WidgetsController&#8217;, function ($scope, factory) {<br />
            var res = factory.getData();<br />
            var options;<br />
            if (res != undefined) {<br />
                res.then(function (d) {<br />
                    var data = JSON.parse(d.data);<br />
                    var categories = [];<br />
                    for (var i = 0; i &lt; data.length; i++) {<br />
                        categories.push(data[i].name)<br />
                    }<br />
                    options = new Highcharts.chart(&#8216;widgetPie&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;pie&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Pie Chart&#8217;<br />
                        },<br />
                        plotOptions: {<br />
                            pie: {<br />
                                allowPointSelect: true,<br />
                                cursor: &#8216;pointer&#8217;,<br />
                                dataLabels: {<br />
                                    enabled: false,<br />
                                    format: &#8216;&lt;b&gt;{point.name}&lt;/b&gt;: {point.y:,.0f}&#8217;<br />
                                }<br />
                            }<br />
                        },<br />
                        series: [{<br />
                            name:&#8217;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
                    options = new Highcharts.chart(&#8216;widgetColumn&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;column&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Column Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
                    options = new Highcharts.chart(&#8216;widgetBar&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;bar&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Bar Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
                    options = new Highcharts.chart(&#8216;widgetLine&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;line&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Line Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
                    options = new Highcharts.chart(&#8216;widgetspline&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;spline&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Spline Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
                    options = new Highcharts.chart(&#8216;widgetScatter&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;scatter&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Scatter Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
                }, function (error) {<br />
                    console.log(&#8216;Oops! Something went wrong while fetching the data.&#8217;);<br />
                });<br />
            }<br />
        });<br />
})();<br />
[/js]</p>
<p>If you have configured all the chart types, we can see the output now 🙂</p>
<p><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Chart-Widgets-In-MVC-With-Angular-JS-And-Web-API-e1458191984345.png"><img decoding="async" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Chart-Widgets-In-MVC-With-Angular-JS-And-Web-API-1024x907.png" alt="Chart Widgets In MVC With Angular JS And Web API" width="634" height="562" class="alignnone size-large wp-image-11375" /></a></p>
<p>We have done everything!. That&#8217;s fantastic right? Have a happy coding.</p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Did you try Web API yet? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/chart-widgets-with-server-side-data-in-mvc-using-angular-js-and-web-api/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>jQuery Datatable With Server Side Data</title>
		<link>https://sibeeshpassion.com/jquery-datatable-with-server-side-data-2/</link>
					<comments>https://sibeeshpassion.com/jquery-datatable-with-server-side-data-2/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 25 Feb 2016 00:00:43 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Angular JS]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Datatable With Server Side]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[jQuery Datatables]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11266</guid>

					<description><![CDATA[Introduction In this article, we will learn how we can work with jQuery Datatables with server-side data. Here we are going to use an MVC application with jQuery and other required packages installed in it. If you are new to MVC, You can always get the tips/tricks/blogs about that here MVC Tips, Tricks, Blogs. jQuery Datatables is a client-side grid control that is lightweight and easy to use. But when it comes to grid control, it must be usable when it supports the server-side loading of data. This control is perfect for that. I guess, it is enough for the [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Introduction</h2>



<p>In this article, we will learn how we can work with jQuery Datatables with server-side data. Here we are going to use an MVC application with jQuery and other required packages installed in it. If you are new to MVC, You can always get the tips/tricks/blogs about that here MVC Tips, Tricks, Blogs. jQuery Datatables is a client-side grid control that is lightweight and easy to use. But when it comes to grid control, it must be usable when it supports the server-side loading of data. This control is perfect for that. I guess, it is enough for the introduction. Now we will start using our grid. I hope you will like this.</p>



<h2 class="wp-block-heading"><strong>Download the source code</strong></h2>



<p>You can always download the source code here:</p>



<ul class="wp-block-list"><li><a href="https://github.com/SibeeshVenu/jQuery-Datatable-With-Server-Side-Data" target="_blank" rel="noreferrer noopener">Datatable With Server-Side Data</a></li></ul>



<h2 class="wp-block-heading"><strong>Create a MVC application</strong></h2>



<p>Click File-&gt; New-&gt; Project then select MVC application. Before going to start the coding part, make sure that all the required extensions/references are installed. Below are the required things to start with.</p>



<ul class="wp-block-list"><li>Datatables Package</li><li>jQuery</li></ul>



<p>You can all the items mentioned above from NuGet. Right-click on your project name and select Manage NuGet packages.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png"><img decoding="async" width="650" height="432" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png" alt="Manage NuGet Package Window" class="wp-image-11235" srcset="/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png 650w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-300x199.png 300w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-400x266.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Manage NuGet Package Window</figcaption></figure>



<p>Once you have installed those items, please make sure that all the items(jQuery, Datatables JS files) are loaded in your scripts folder.</p>



<h2 class="wp-block-heading"><strong>Using the code</strong></h2>



<p>Now let us add the needed references.</p>



<h3 class="wp-block-heading">Include the references in your _Layout.cshtml</h3>



<p>As we have already installed all the packages we need, now we need to add the references, right? After adding the reference, your _Layout.cshtml will looks like below.</p>



<script src="https://gist.github.com/SibeeshVenu/4b71315abf732ca3a929e8750cf13638.js"></script>



<p>Here <em>MyScripts.js</em> is the JavaScript file where we are going to write our own scripts.</p>



<p><em>Add a normal MVC controller</em></p>



<p>Now we will add a normal MVC controller in our app. Once you add that you can see an ActionResult is created for us.</p>



<p><code>public ActionResult Index()<br>{<br>return View();<br>}</code></p>



<p>Right-click on the controller, and click add view, that will create a View for you. Now we will change the view as follows. </p>



<script src="https://gist.github.com/SibeeshVenu/87fa8feefb4bd7fcb9fbc867d8a23921.js"></script>



<p>So we have set the headers and footer for our grid, where we are going to load the grid control in the table <em>myGrid</em>. So far the UI part is done, now it is time to set up our database and entity model. Are you ready?</p>



<h3 class="wp-block-heading"><strong>Create a database</strong></h3>



<p>The following query can be used to create a database in your SQL Server.</p>



<script src="https://gist.github.com/SibeeshVenu/5bf2b19e004f619ebfb1f9e6229ef66b.js"></script>



<p>Now we will create a table 🙂</p>



<h3 class="wp-block-heading"><strong>Create table in database</strong></h3>



<p>Below is the query to create table in database.</p>



<script src="https://gist.github.com/SibeeshVenu/8b4797ecfbcfe5841f9ca85a5ef131c8.js"></script>



<h3 class="wp-block-heading"><strong>Insert data to table</strong></h3>



<p>To insert the data, I will attach a database script file along with the download file, you can either run that or insert some data by using the below query. By the way, if you would like to know how to generate scripts with data in SQL Server, you can check <a rel="noopener noreferrer" href="http://sibeeshpassion.com/generate-database-scripts-with-data-in-sql-server/" target="_blank">here</a>.</p>



<script src="https://gist.github.com/SibeeshVenu/9ad0fcd0e2220a4b2a93d7617716416a.js"></script>



<p>Along with this, we can create a new stored procedure that will fetch the data. Following is the query to create the stored procedure.</p>



<script src="https://gist.github.com/SibeeshVenu/40e2e26f6dd93dbac671fc9c33743ccd.js"></script>



<p>Next thing we are going to do is creating a ADO.NET Entity Data Model.</p>



<h3 class="wp-block-heading"><strong>Create Entity Data Model</strong></h3>



<p>Right-click on your model folder and click new, select ADO.NET Entity Data Model. Follow the steps given. Once you have done the processes, you can see the edmx file and other files in your model folder.</p>



<p>Now we will go back to our controller and add a new JsonResult which can be called via a new jQuery Ajax request. No worries, we will create that Ajax requests later. Once you add the Jsonresult action, I hope your controller will look like this.</p>



<script src="https://gist.github.com/SibeeshVenu/344693e90203b925d34b755e83a2ec8a.js"></script>



<p>Here <em>TrialsDBEntities </em>is our entity class. Please be noted that to use the model classes in your controller, you must add the reference as follows.</p>



<p><code>using jQuery_Datatable_With_Server_Side_Data.Models;</code></p>



<p>I know all you are familiar with this, I am just saying!. Now can we create a function <em>GetSales</em> in our model class <em>Sales </em>?.</p>



<script src="https://gist.github.com/SibeeshVenu/b7b4a55890e969fe518cd30cd24433fb.js"></script>



<p>We uses normal LINQ queries here, and we take only 100 records to load for now. If you don&#8217;t want to use this method you can call our stored procedure which we have created while creating our database. You can call this as explained in the below function.</p>



<script src="https://gist.github.com/SibeeshVenu/f189bb513e93566d140429b4a9836834.js"></script>



<p>Now the only thing pending is to call our controller JsonResult action right? We will do some code in our MyScript.js file.</p>



<script src="https://gist.github.com/SibeeshVenu/5093c34f6a455a758426ac8df2b00118.js"></script>



<p>Here <em>&#8220;dataSrc&#8221;: &#8220;&#8221; </em> should be used if you have a plain <a rel="noopener noreferrer" href="http://sibeeshpassion.com/tag/json/" target="_blank">JSON </a>data. The sample data can be find below.</p>



<script src="https://gist.github.com/SibeeshVenu/a2ae9ec5f56a05ef62f6f911e4918ba3.js"></script>



<p>We have done everything!. Can we see the output now?</p>



<h2 class="wp-block-heading"><strong>Output</strong></h2>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data.png"><img decoding="async" width="1024" height="596" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-1024x596.png" alt="jQuery Datatable With Server Side Data" class="wp-image-11267" srcset="/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-1024x596.png 1024w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-300x175.png 300w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-768x447.png 768w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-400x233.png 400w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-1030x600.png 1030w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data.png 1097w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption>jQuery Datatable With Server Side Data</figcaption></figure>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search.png"><img decoding="async" width="1024" height="379" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-1024x379.png" alt="jQuery Datatable With Server Side Data Search" class="wp-image-11268" srcset="/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-1024x379.png 1024w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-300x111.png 300w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-768x284.png 768w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-400x148.png 400w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search.png 1109w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption>jQuery Datatable With Server Side Data Search</figcaption></figure>



<p>Have a happy coding.</p>



<h2 class="wp-block-heading"><strong>Conclusion</strong></h2>



<p>Did I miss anything that you may think which is needed? Did you use jQuery Datatables in your application? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>



<h2 class="wp-block-heading"><strong>Your turn. What do you think?</strong></h2>



<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/jquery-datatable-with-server-side-data-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Programmatically Extract or Unzip Zip,Rar Files And Check</title>
		<link>https://sibeeshpassion.com/programmatically-extract-or-unzip-ziprar-files-and-check/</link>
					<comments>https://sibeeshpassion.com/programmatically-extract-or-unzip-ziprar-files-and-check/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 25 Feb 2016 00:00:22 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Extract Files]]></category>
		<category><![CDATA[HttpFileCollectionBase]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[System.IO.Compression]]></category>
		<category><![CDATA[System.IO.Compression.FileSystem]]></category>
		<category><![CDATA[Unzip Files]]></category>
		<category><![CDATA[Upload in MVC]]></category>
		<category><![CDATA[ZipArchive]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11281</guid>

					<description><![CDATA[In this pose we will see how we can extract or unzip the uploaded files and check for some files in it in a in a programmatic manner. We will use a normal MVC application to work with this demo. We will use Microsoft System.IO.Compression, System.IO.Compression.FileSystem namespaces and the classes, for example ZipArchive, in the namespace for extracting or unzipping the files we upload. Once it is uploaded we will check the same by looping through it. For the client side coding, we uses jQuery. I guess this is enough for the introduction, now we will move on to our [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this pose we will see how we can extract or unzip the uploaded files and check for some files in it in a in a programmatic manner. We will use a normal <a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC</a> application to work with this demo. We will use Microsoft System.IO.Compression, System.IO.Compression.FileSystem namespaces and the classes, for example ZipArchive, in the namespace for extracting or unzipping the files we upload. Once it is uploaded we will check the same by looping through it. For the client side coding, we uses <a href="http://sibeeshpassion.com/category/jQuery/" target="_blank" rel="noopener">jQuery</a>. I guess this is enough for the introduction, now we will move on to our application. Let us create it. I hope you will like this article. </p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here: 	</p>
<li><a href="https://gallery.technet.microsoft.com/Programmatically-Extract-0544debd" target="_blank" rel="noopener">Programmatically Extract or Unzip Zip,Rar Files And Check</a></li>
<p><strong>Background</strong></p>
<p>As you are aware most websites accepts only .zip or any other zipped formats, this is for ensuring that only less amount of data is being uploaded to the server. We can reduce almost 60 percentage of the size if we zipped the same. Now the problem is, how you can validate any zipped item which is uploaded to your site? How can you check for any particular file in that zipped item? For example if you need to find out any files with extension of .sql, .ico or .txt? What if you want to intimate user that the uploaded items does not have any particular file that must be needed? You need to loop through the contents available in it right? This is what we are going to discuss in this post. I had a situation of uploading my old back ups of my personal website (<a href="http://sibeeshpassion.com/" target="_blank" rel="noopener">http://sibeeshpassion.com/</a>) and after uploading I wanted to check whether the uploaded .zip file has .ico file in it. The process we are going to do is listed below.</p>
<li>Create a MVC application</li>
<li>Install jQuery</li>
<li>Create Controller and View</li>
<li>Upload Action Using jQuery</li>
<li>Add System.IO.Compression, System.IO.Compression.FileSystem references</li>
<li>Checks for the file using ZipArchive class</li>
<p><strong>Using the code</strong></p>
<p>Now we will move into the coding part. I hope your MVC application is ready for action 🙂 with all the needed packages. </p>
<p><strong>Create a controller</strong></p>
<p>Now we will create a controller, view with an action in it as follows. </p>
<p>[csharp]<br />
public ActionResult Index()<br />
        {<br />
            return View();<br />
        }<br />
[/csharp]</p>
<p><strong>Update the view</strong></p>
<p>Now in the view, we will add a file upload and other needed elements. </p>
<p>[html]<br />
&lt;input type=&quot;file&quot; name=&quot;FileUpload1&quot; id=&quot;fileUpload&quot; placeholder=&quot;Please select the file&quot; /&gt;&lt;br /&gt;<br />
&lt;input id=&quot;btnUploadFile&quot; type=&quot;button&quot; value=&quot;Upload File&quot; /&gt;<br />
&lt;div id=&quot;message&quot;&gt;&lt;/div&gt;<br />
[/html]</p>
<p><strong>Add the JS references</strong></p>
<p>Add the references as follows.</p>
<p>[html]<br />
&lt;script src=&quot;~/scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/MyScript.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Here <em>MyScript.js</em> is where we are going to write some scripts. </p>
<p><strong>Style the elements (Optional) </strong></p>
<p>You can style your view as follows. This step is absolutely optional, for me the view should not as simple as default one. And to be frank I am not a good designer 🙂</p>
<p>[css]<br />
&lt;style&gt;<br />
    #fileUpload {<br />
        border: 1px solid #ccc;<br />
        padding: 10px;<br />
        border-radius: 5px;<br />
        font-size: 14px;<br />
        font-family: cursive;<br />
        color: blue;<br />
    }</p>
<p>    #btnUploadFile {<br />
        border: 1px solid #ccc;<br />
        padding: 10px;<br />
        border-radius: 5px;<br />
        font-size: 14px;<br />
        font-family: cursive;<br />
        color: blue;<br />
    }</p>
<p>    #message {<br />
        border-radius: 5px;<br />
        font-size: 14px;<br />
        font-family: cursive;<br />
        color: blue;<br />
        margin-top: 15px;<br />
    }<br />
    h2 {<br />
        border-radius: 5px;<br />
        font-size: 20px;<br />
        font-family: cursive;<br />
        color: blue;<br />
        margin-top: 15px;<br />
    }<br />
&lt;/style&gt;<br />
[/css]</p>
<p><strong>Add the upload action in script</strong></p>
<p>Now it is time to create upload action. For that, please go to the script file MyScript.js and do the coding as follows. </p>
<p>[js]<br />
$(document).ready(function () {<br />
    $(&#8216;#btnUploadFile&#8217;).on(&#8216;click&#8217;, function () {<br />
        var data = new FormData();<br />
        var files = $(&quot;#fileUpload&quot;).get(0).files;<br />
        // Add the uploaded image content to the form data collection<br />
        if (files.length &gt; 0) {<br />
            data.append(&quot;UploadedImage&quot;, files[0]);<br />
        }<br />
        // Make Ajax request with the contentType = false, and procesDate = false<br />
        var ajaxRequest = $.ajax({<br />
            type: &quot;POST&quot;,<br />
            url: &quot;Home/Upload&quot;,<br />
            contentType: false,<br />
            processData: false,<br />
            data: data,<br />
            success: function (data) {<br />
                $(&#8216;#message&#8217;).html(data);<br />
            },<br />
            error: function (e)<br />
            {<br />
                console.log(&#8216;Oops, Something went wrong!.&#8217; + e.message);<br />
            }<br />
        });<br />
        ajaxRequest.done(function (xhr, textStatus) {<br />
            // Do other operation<br />
        });<br />
    });<br />
});<br />
[/js]</p>
<p>If you are not aware of uploading and downloading in MVC, I strongly recommend you to have a look here: <a href="http://sibeeshpassion.com/uploading-and-downloading-in-mvc-step-by-step/" target="_blank" rel="noopener">Uploading and Downloading in MVC Step-by-Step</a>. </p>
<p>So we have set Home/Upload as the URL action in our <a href="http://sibeeshpassion.com/tag/jquery-ajax/" target="_blank" rel="noopener">Ajax</a> function right? So we are going to create that action. Go to your controller and create a JsonResult action as follows. </p>
<p>[csharp]<br />
public JsonResult Upload()<br />
        {<br />
            string isValid = checkIsValid(Request.Files);<br />
            return Json(isValid, JsonRequestBehavior.AllowGet);<br />
        }<br />
[/csharp]</p>
<p>So we have done that too, now stop for a while. To work with <em>ZipArchive</em> class you must include the namespace as listed below. </p>
<p>[csharp]<br />
using System.IO.Compression;<br />
[/csharp]</p>
<p>Now you will be shown an error as &#8220;Are you missing an assembly reference?&#8221;. Yes we are. We have not added that references right? So now we are going to add the references for System.IO.Compression and System.IO.Compression.FileSystem. </p>
<p>Right click on Reference in your project and browse for the references. If you uses Visual Studio 2015, the references will be in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6. </p>
<blockquote><p>Please be noted that the folder names will differs according to your framework version</p></blockquote>
<p><div id="attachment_11282" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Compression_References-e1455888597687.png"><img decoding="async" aria-describedby="caption-attachment-11282" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Compression_References-e1455888597687.png" alt="Compression_References" width="650" height="447" class="size-full wp-image-11282" srcset="/wp-content/uploads/2016/02/Compression_References-e1455888597687.png 650w, /wp-content/uploads/2016/02/Compression_References-e1455888597687-300x206.png 300w, /wp-content/uploads/2016/02/Compression_References-e1455888597687-160x110.png 160w, /wp-content/uploads/2016/02/Compression_References-e1455888597687-400x275.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11282" class="wp-caption-text">Compression_References</p></div></p>
<p>Now we will go back to our controller and write the codes for the function <em>checkIsValid(Request.Files)</em></p>
<p>[csharp]<br />
private string checkIsValid(HttpFileCollectionBase files)<br />
        {<br />
            string isValid = string.Empty;<br />
            try<br />
            {<br />
                foreach (string upload in Request.Files)<br />
                {<br />
                    if (Request.Files[upload].ContentType == &quot;application/octet-stream&quot;) //Content type for .zip is application/octet-stream<br />
                    {<br />
                        if (Request.Files[upload].FileName != &quot;&quot;)<br />
                        {<br />
                            string path = AppDomain.CurrentDomain.BaseDirectory + &quot;/ App_Data / uploads /&quot;;<br />
                            if (!Directory.Exists(path))<br />
                            {<br />
                                // Try to create the directory.<br />
                                DirectoryInfo di = Directory.CreateDirectory(path);<br />
                            }</p>
<p>                            string filename = Path.GetFileName(Request.Files[upload].FileName);<br />
                            string pth = Path.Combine(path, filename);<br />
                            Request.Files[upload].SaveAs(pth);<br />
                            isValid = CheckForTheIcon(pth);<br />
                        }<br />
                    }<br />
                    else<br />
                    {<br />
                        isValid = &quot;Only .zip files are accepted.&quot;;<br />
                    }<br />
                }<br />
                return isValid;<br />
            }<br />
            catch (Exception)<br />
            {<br />
                return &quot;Oops!. Something went wrong&quot;;<br />
            }<br />
        }<br />
[/csharp]</p>
<p>As you can see we are looping through the <em>HttpFileCollectionBase</em> files and checks for the content type first. </p>
<blockquote><p>Please be noted that the content type for the .zip file is application/octet-stream</p></blockquote>
<p>Once the checking is done, we will save the files to a folder, we will send the path to the function <em>CheckForTheIcon(pth)</em>. So our next thing we need to do is to create the function CheckForTheIcon().</p>
<p>[csharp]<br />
  private string CheckForTheIcon(string strPath)<br />
        {<br />
            string result = string.Empty;<br />
            try<br />
            {<br />
                using (ZipArchive za = ZipFile.OpenRead(strPath))<br />
                {<br />
                    foreach (ZipArchiveEntry zaItem in za.Entries)<br />
                    {<br />
                        if (zaItem.FullName.EndsWith(&quot;.ico&quot;, StringComparison.OrdinalIgnoreCase))<br />
                        {<br />
                            result = &quot;Success&quot;;<br />
                        }<br />
                        else<br />
                        {<br />
                            result = &quot;No ico files has been found&quot;;<br />
                        }<br />
                    }<br />
                }<br />
                return result;<br />
            }<br />
            catch (Exception)<br />
            {<br />
                result = &quot;Oops!. Something went wrong&quot;;<br />
                return result;<br />
            }<br />
        }<br />
[/csharp]</p>
<p>As you can see we are looping through each <em>ZipArchive</em> class items and checks for the &#8216;.ico&#8217; file in it. So if there is no error and there is &#8216;.ico&#8217; file in the uploaded item zip item, you will get the message as &#8220;Success: or if it does not contain the &#8216;.ico&#8217; file, you will get the message as &#8220;No ico files has been found&#8221;. </p>
<p>Now it is time to see our output. Please run your application. </p>
<p><strong>Output</strong></p>
<p><div id="attachment_11283" style="width: 638px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/If_you_try_to_upload_not_zipped_item.png"><img decoding="async" aria-describedby="caption-attachment-11283" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/If_you_try_to_upload_not_zipped_item.png" alt="If_you_try_to_upload_not_zipped_item" width="628" height="298" class="size-full wp-image-11283" srcset="/wp-content/uploads/2016/02/If_you_try_to_upload_not_zipped_item.png 628w, /wp-content/uploads/2016/02/If_you_try_to_upload_not_zipped_item-300x142.png 300w, /wp-content/uploads/2016/02/If_you_try_to_upload_not_zipped_item-400x190.png 400w" sizes="(max-width: 628px) 100vw, 628px" /></a><p id="caption-attachment-11283" class="wp-caption-text">If_you_try_to_upload_not_zipped_item</p></div></p>
<p><div id="attachment_11284" style="width: 653px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_does_not_have_ico_file.png"><img decoding="async" aria-describedby="caption-attachment-11284" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_does_not_have_ico_file.png" alt="If_you_try_to_upload_zipped_item_which_does_not_have_ico_file" width="643" height="288" class="size-full wp-image-11284" srcset="/wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_does_not_have_ico_file.png 643w, /wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_does_not_have_ico_file-300x134.png 300w, /wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_does_not_have_ico_file-400x179.png 400w" sizes="(max-width: 643px) 100vw, 643px" /></a><p id="caption-attachment-11284" class="wp-caption-text">If_you_try_to_upload_zipped_item_which_does_not_have_ico_file</p></div></p>
<p><div id="attachment_11285" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_have_ico_file-e1455889647121.png"><img decoding="async" aria-describedby="caption-attachment-11285" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_have_ico_file-e1455889647121.png" alt="If_you_try_to_upload_zipped_item_which_have_ico_file" width="650" height="277" class="size-full wp-image-11285" srcset="/wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_have_ico_file-e1455889647121.png 650w, /wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_have_ico_file-e1455889647121-300x128.png 300w, /wp-content/uploads/2016/02/If_you_try_to_upload_zipped_item_which_have_ico_file-e1455889647121-400x170.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11285" class="wp-caption-text">If_you_try_to_upload_zipped_item_which_have_ico_file</p></div></p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/programmatically-extract-or-unzip-ziprar-files-and-check/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Caching In MVC</title>
		<link>https://sibeeshpassion.com/caching-in-mvc/</link>
					<comments>https://sibeeshpassion.com/caching-in-mvc/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sat, 31 Oct 2015 18:25:25 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Caching In MVC]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[MVC 4]]></category>
		<category><![CDATA[Output Caching]]></category>
		<category><![CDATA[Performance Improvements In MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10877</guid>

					<description><![CDATA[In this post we will discuss about how we can improve the performance of out MVC application by using the technology Caching . Here I am using Visual Studio 2012. As you all know in MVC it is all about actions, so each and every time we are calling some actions according to the users request. For example when ever a use request a view we will call the controller and get the result and bind the data to the view. Isn&#8217;t it? So what if a user is requesting the same view 50 time in 2 minutes? In normal [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will discuss about how we can improve the performance of out MVC application by using the technology <em>Caching </em>. Here I am using Visual Studio 2012. As you all know in MVC it is all about actions, so each and every time we are calling some actions according to the users request. For example when ever a use request a view we will call the controller and get the result and bind the data to the view. Isn&#8217;t it? So what if a user is requesting the same view 50 time in 2 minutes? In normal cases, this won&#8217;t happen, but there are few situations which may be somewhat equal to what I said. In that case it is always recommend to use the most useful thing &#8216;Caching&#8217;. This will make sure that there is no actions which are not required will be happening within a time period. So if a  user already visited the same view within the time periods, the controller action won&#8217;t fire again if user calls the view again. It will return the same view which has been already rendered. Sounds cool? Yes, we will see how we can achieve this!. I hope you will like this.</p>
<p><strong>Background</strong></p>
<p>I am working in a MVC project. As you all know when it comes to performance, our clients will never be satisfied. So we used to everything we have got to improve the performance. One thing we used was Caching. So I thought of writing an article related to that and share wit you all. </p>
<p><strong>What is Caching?</strong></p>
<p>As I said above, it is performance improvement technique where you can get most of. It helps to avoid the unwanted or frequent actions which is already happened just by using Output Caching(In ASP.NET 5 it is ResponseCache). The view which is rendered recently wont fire the controller again if it is in the time limit period, it will just re show the one which is already rendered. It will cache the contents which is returned by the controller action.</p>
<blockquote><p>Imagine that you have a controller which will return your debit/credit transaction from the database. What if the database is normally updating once in a week? Usually when ever a user hits the controller it will hit the DB and fetch the data right? But in this scenario it is not needed to hit the DB again since the data will be same for a week. So we can set the Output Caching so that withing the time interval the controller contents will be in cache so that the view can render the cached data.</p></blockquote>
<p><strong>How to enable Output Caching?</strong></p>
<p>We will create a simple application in Visual Studio first.</p>
<p><div id="attachment_10879" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC-e1446311455769.png"><img decoding="async" aria-describedby="caption-attachment-10879" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC-e1446311455769.png" alt="Caching In MVC" width="650" height="395" class="size-full wp-image-10879" srcset="/wp-content/uploads/2015/10/Caching_In_MVC-e1446311455769.png 650w, /wp-content/uploads/2015/10/Caching_In_MVC-e1446311455769-300x182.png 300w, /wp-content/uploads/2015/10/Caching_In_MVC-e1446311455769-400x243.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10879" class="wp-caption-text">Caching In MVC</p></div></p>
<p><div id="attachment_10880" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_1-e1446311761707.png"><img decoding="async" aria-describedby="caption-attachment-10880" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_1-e1446311761707.png" alt="Caching In MVC" width="650" height="589" class="size-full wp-image-10880" srcset="/wp-content/uploads/2015/10/Caching_In_MVC_1-e1446311761707.png 394w, /wp-content/uploads/2015/10/Caching_In_MVC_1-e1446311761707-300x272.png 300w, /wp-content/uploads/2015/10/Caching_In_MVC_1-e1446311761707-400x362.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10880" class="wp-caption-text">Caching In MVC</p></div></p>
<p>Now we will create a control in our MVC application.</p>
<p><div id="attachment_10881" style="width: 612px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_2.png"><img decoding="async" aria-describedby="caption-attachment-10881" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_2.png" alt="Caching In MVC" width="602" height="392" class="size-full wp-image-10881" srcset="/wp-content/uploads/2015/10/Caching_In_MVC_2.png 602w, /wp-content/uploads/2015/10/Caching_In_MVC_2-300x195.png 300w, /wp-content/uploads/2015/10/Caching_In_MVC_2-400x260.png 400w" sizes="(max-width: 602px) 100vw, 602px" /></a><p id="caption-attachment-10881" class="wp-caption-text">Caching In MVC</p></div></p>
<p>So our controller is ready, now we need to create simple view and after that we will change our Index action in the controller as below.</p>
<p>[csharp]<br />
public ActionResult Index()<br />
        {<br />
            return Content(DateTime.Now.ToString(&quot;T&quot;));<br />
        }<br />
[/csharp]</p>
<p>So we are returning the current time from the controller. Isn&#8217;t it? Now refresh your view frequently, let us say 2 times in 5 minute, what is the output you are getting?</p>
<p><div id="attachment_10882" style="width: 318px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_3.png"><img decoding="async" aria-describedby="caption-attachment-10882" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_3.png" alt="Caching In MVC" width="308" height="131" class="size-full wp-image-10882" srcset="/wp-content/uploads/2015/10/Caching_In_MVC_3.png 308w, /wp-content/uploads/2015/10/Caching_In_MVC_3-300x128.png 300w" sizes="(max-width: 308px) 100vw, 308px" /></a><p id="caption-attachment-10882" class="wp-caption-text">Caching In MVC</p></div></p>
<p><div id="attachment_10883" style="width: 308px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_4.png"><img decoding="async" aria-describedby="caption-attachment-10883" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_4.png" alt="Caching In MVC" width="298" height="168" class="size-full wp-image-10883" /></a><p id="caption-attachment-10883" class="wp-caption-text">Caching In MVC</p></div></p>
<p>So have you noticed it within five minutes we have hit the controller twice? Now here is the magic of output cache. Please change your controller code as follows.</p>
<p>[csharp]<br />
[OutputCache(Duration = 300, VaryByParam = &quot;none&quot;)]<br />
        public ActionResult Index()<br />
        {<br />
            return Content(DateTime.Now.ToString(&quot;T&quot;));<br />
        }<br />
[/csharp]</p>
<blockquote><p>Here we are setting the cache duration as 5 minutes (5*60 seconds)</p></blockquote>
<p>Now if you run and do the same exercise you can notice that the controller will be hit only once in 5 minutes duration. That&#8217;s cool right?</p>
<blockquote><p>Even though it is so cook, there is some limitations too. As the memory becomes low, the cache data will be released. So that there won&#8217;t be cached data.</p></blockquote>
<p>Here in our case, we just used a simple view which returns time from the controller. What if the controller has some database operations, for every user&#8217;s hit we need to go to the database right? So in simple words we can say that the caching is helping to reduce the amount of work done must be performed by our web server and database. </p>
<p><strong>So contents are chached. Where?</strong></p>
<p>Now we will see which are all the locations we can save the cache data. Usually the contents are cached in three locations.</p>
<li>Web server</li>
<li>Proxy server</li>
<li>Web browser</li>
<p>You can always set where you want to save the cached data, whether it is in server, client or both server and client by using location property. By default the location will be &#8216;any&#8217;.</p>
<p><div id="attachment_10884" style="width: 589px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_5.png"><img decoding="async" aria-describedby="caption-attachment-10884" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_5.png" alt="Caching In MVC" width="579" height="332" class="size-full wp-image-10884" srcset="/wp-content/uploads/2015/10/Caching_In_MVC_5.png 579w, /wp-content/uploads/2015/10/Caching_In_MVC_5-300x172.png 300w, /wp-content/uploads/2015/10/Caching_In_MVC_5-400x229.png 400w" sizes="(max-width: 579px) 100vw, 579px" /></a><p id="caption-attachment-10884" class="wp-caption-text">Caching In MVC</p></div></p>
<p>There are few situations that we should not cache in server. Let me explain, suppose we have a controller which will return the country name of the user logged in to our application. Now I am from &#8216;India&#8217; , so when I logged in to the application it will show the country name as India. That&#8217;s correct. Now have cached these data in the server. So what will happen if a user form Ireland logged in to the application? Will it be good if we show India as his/her country? It doesn&#8217;t make any sense right? </p>
<p>[csharp]<br />
[OutputCache(Duration = 10, VaryByParam = &quot;none&quot;)]<br />
        public ActionResult Index()<br />
        {<br />
            User u = new User();<br />
            return Content(u.getUserCountry());<br />
        }<br />
[/csharp]</p>
<blockquote><p>So in short we can say that we should not cache any personalized data in the server.</p></blockquote>
<p>So what is the fix for this? Simple, cache the data in client. To do that we can change our controller as follows.</p>
<p>[csharp]<br />
[OutputCache(Duration = 10, VaryByParam = &quot;none&quot;, Location=OutputCacheLocation.Client, NoStore=true)]<br />
        public ActionResult Index()<br />
        {<br />
            User u = new User();<br />
            return Content(u.getUserCountry());<br />
        }<br />
[/csharp]</p>
<blockquote><p>To use OutputCacheLocation, you must include the namespace using System.Web.UI;</p></blockquote>
<p>Have you noticed that we have set NoStore=true? This is to intimate the proxy server that should not save any copy of these data in server.</p>
<p><strong>Use of VaryByParam property</strong></p>
<p>Now we are going to discuss an another scenario which explain the use of VaryByParam property. Let us say an action called &#8216;GetEmployee&#8217; which will return all the Employees in our company. Now if we click on any employee links, an another view (GetEmployeeDetails) will show with all the details about that employee( Like account details, leave details, personal informations). So if we save the cached view of GetEmployeeDetails, what will happen? For all the employees, it will show the same GetEmployeeDetails view right?</p>
<p>So we will change the controller actions as follows.</p>
<p>[csharp]<br />
 [OutputCache(Duration = 10, VaryByParam = &quot;none&quot;)]<br />
        public ActionResult GetEmployee()<br />
        {<br />
            Employee e = new Employee();<br />
            return Content(e.getEmployees());<br />
        }<br />
[/csharp]</p>
<p>[csharp]<br />
  [OutputCache(Duration = 10, VaryByParam = &quot;empID&quot;)]<br />
        public ActionResult GetEmployeeDetail(int empID)<br />
        {<br />
            Employee e = new Employee();<br />
            return Content(e.getEmployeeDetails(empID));<br />
        }<br />
[/csharp] </p>
<p>The above mentioned implementation will make sure the different Employee Details view are being generated for different users. Sound cool?</p>
<p><strong>Cache Profiles</strong></p>
<p>There is an another way of achieving the caching, that is cache profiles, which is nothing but creating a tag in web.config file and apply that for different controllers. In this way you can have the same cache profile for different controls. And also it is easy to make any changes in the cache profile since it is just a tag in the web.config file. Any changes in cache profile will get applied easily. I found this is the most effective way of caching. We can do the cache profile as follows.</p>
<p>[html]<br />
&lt;caching&gt;<br />
&lt;outputCacheSettings&gt;<br />
    &lt;outputCacheProfiles&gt;<br />
        &lt;add name=&quot;Admin&quot; duration=&quot;86420&quot; varyByParam=&quot;none&quot;/&gt;<br />
    &lt;/outputCacheProfiles&gt;<br />
&lt;/outputCacheSettings&gt;<br />
&lt;/caching&gt;<br />
[/html]</p>
<p>The above cache profile can be used for any admin control action which will be cached for one day (60*60*24). You can simply use this profile as follows.</p>
<p>[csharp]<br />
[OutputCache(CacheProfile=&quot;Admin&quot;)]<br />
[/csharp]</p>
<p>That is all about the Caching. I will come with an another post which explains caching in ASP.NET 5, MVC 6 soon. Thanks for reading. Have a happy coding.</p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Did you try caching yet? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/caching-in-mvc/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>C sharp Interview Questions And Answers</title>
		<link>https://sibeeshpassion.com/c-sharp-interview-questions-and-answers/</link>
					<comments>https://sibeeshpassion.com/c-sharp-interview-questions-and-answers/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sat, 24 Oct 2015 08:06:18 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Interview]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[C sharp Interview Questions And Answers]]></category>
		<category><![CDATA[Career Advice]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Interview Questions For Dot Net]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10839</guid>

					<description><![CDATA[[toc] Introduction In this article, we will discuss the most asked C# interview questions and answers. If you need to know other interview questions and answers, I strongly recommend to follow this link: Interview Questions. Now in this post, we are going to share the interview questions for C# or a Dot Net developer. No matter you are experienced or fresher, it is important that you must aware of these. So please read it carefully. I hope you will like this article. Background C# is one of my favorite programming languages. So I am really happy to share you some [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>[toc]</p>



<h2 class="wp-block-heading">Introduction</h2>



<p>In this article, we will discuss the most asked C# interview questions and answers. If you need to know other interview questions and answers, I strongly recommend to follow this link: <a href="http://sibeeshpassion.com/category/interview/" target="_blank" rel="noopener noreferrer">Interview Questions</a>. Now in this post, we are going to share the interview questions for C# or a Dot Net developer. No matter you are experienced or fresher, it is important that you must aware of these. So please read it carefully. I hope you will like this article.</p>



<h2 class="wp-block-heading">Background</h2>



<p>C# is one of my favorite programming languages. So I am really happy to share you some interview questions related to C#. You can always read my other interview questions here in the below links.</p>



<ul class="wp-block-list"><li><a rel="noopener noreferrer" href="http://sibeeshpassion.com/dot-net-interview-questions-for-experienced-and-fresher/" target="_blank">Interview Questions For Experienced and Beginner .NET Professionals</a></li><li><a rel="noopener noreferrer" href="http://sibeeshpassion.com/infosys-interview-questions-for-dotnet-professionals/" target="_blank">Infosys Interview Questions For DotNet Professionals</a></li><li><a rel="noopener noreferrer" href="http://sibeeshpassion.com/sql-interview-questions-and-answers/" target="_blank">SQL Interview Questions And Answers</a></li><li><a rel="noopener noreferrer" href="http://sibeeshpassion.com/important-ado-net-interview-questions/" target="_blank">Important ADO.NET Interview Questions</a> <p>So shall we now discuss C# interview questions? </p></li></ul>



<h3 class="wp-block-heading">C# Interview Questions   </h3>



<p>What are Abstract Classes? </p>



<p>The purpose of an abstract class is to define some common behavior that can be inherited by multiple sub classes, without implementing the entire class. In C#, the abstract keyword designates both an abstract class and a pure virtual method. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class. </p>



<h4 class="wp-block-heading">Properties </h4>



<ul class="wp-block-list"><li>An abstract class cannot be instantiated.</li><li>It can be inherited.</li><li>It can have method implementations, class members.</li><li>Only abstract classes can have abstract methods.</li></ul>



<h4 class="wp-block-heading">Syntax</h4>



<script src="https://gist.github.com/SibeeshVenu/2fa66bd9f38b408fe13317d502e08dc1.js"></script>



<h4 class="wp-block-heading">What are Abstract methods?Give an example?</h4>



<h5 class="wp-block-heading">Abstract Methods</h5>



<p>Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. (See above example for syntax)</p>



<p>Derived classes of the abstract class must implement all abstract methods.<br>When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method.</p>



<h5 class="wp-block-heading">Example</h5>



<script src="https://gist.github.com/SibeeshVenu/08fb0fe1e57b4c9d8cd46d0caf2bfbe9.js"></script>



<script src="https://gist.github.com/SibeeshVenu/a597cb326601e52f65758c6cffd0047b.js"></script>



<h4 class="wp-block-heading">What is Interface? Explain with an example?</h4>



<p>An interface is useful when you want to be able to use some common functionality of otherwise unrelated classes- they share no implementation details, only the function signatures. In C#, function declarations within an interface are implicitly pure virtual.</p>



<p>An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.</p>



<h5 class="wp-block-heading">Properties</h5>



<p>An interface can be a member of a namespace or a class and can contain signatures of methods, properties, events, indexers.<br>An interface can inherit from one or more base interfaces. A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.</p>



<p><strong>Example</strong><em> </em></p>



<script src="https://gist.github.com/SibeeshVenu/3057b3fcb14f7455c4b039b217876398.js"></script>



<script src="https://gist.github.com/SibeeshVenu/d1815c018ef376231553005f421b0949.js"></script>



<script src="https://gist.github.com/SibeeshVenu/a710e1206ab1aaff58263d1b299c7b7e.js"></script>



<p><em><strong>Calling the metho</strong></em><strong>ds </strong></p>



<script src="https://gist.github.com/SibeeshVenu/e54d38f6d8751c9cf06252657197ab78.js"></script>



<script src="https://gist.github.com/SibeeshVenu/8cec8789031f25287a997b150a7fb6cf.js"></script>



<script src="https://gist.github.com/SibeeshVenu/a415a854c7cb4de11e625650a039327b.js"></script>



<h4 class="wp-block-heading">Explain The Difference Between Abstract Class and Interface ?</h4>



<p>An Abstract class doesn&#8217;t provide full abstraction but an interface does provide full abstraction; i.e. both a declaration and a definition is given in an abstract class but not so in an interface. Using Abstract we cannot achieve multiple inheritances but be using an Interface we can achieve multiple inheritances. We cannot declare a member field in an Interface. We cannot use any access modifier i.e. public, private, protected, internal etc. because within an interface by default everything is public. An Interface member cannot be defined using the keyword static, virtual, abstract or sealed.</p>



<h4 class="wp-block-heading">Explain Generic Collections &amp; Array Lists ?</h4>



<p>Generics allow you to delay the specification of the data type of programming elements in a class or a method until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type. Generic Collections helps us to create flexible type-safe, strong type collections at compile time.</p>



<h5 class="wp-block-heading">Syntax</h5>



<script src="https://gist.github.com/SibeeshVenu/12e01a38f7fe93800ed2d9e28af1d248.js"></script>



<h5 class="wp-block-heading">Namespace</h5>



<script src="https://gist.github.com/SibeeshVenu/0f0b6f01abc509c5a0c1ed44aecb95c2.js"></script>



<h5 class="wp-block-heading">ArrayList</h5>



<p>They are ordered a collection of objects, that can be resized automatically, that has dynamic memory allocation and which can contain different types of data. Arraylist stores its members as objects, so in order to retrieve it, we must type cast it.</p>



<h5 class="wp-block-heading">Syntax and Example</h5>



<script src="https://gist.github.com/SibeeshVenu/8533989c2ec614777133e892986e18ae.js"></script>



<h5 class="wp-block-heading">Namespace</h5>



<script src="https://gist.github.com/SibeeshVenu/8f232eefceb895791b4a5fa193d499f2.js"></script>



<h4 class="wp-block-heading">What are Finalize and Dispose? Can you list down the differences between them?</h4>



<p>Finalizers are run by the Garbage Collection before an object that is eligible for collection is reclaimed. Dispose() is meant for cleaning up unmanaged resources, like network connections, files, handles to OS stuff, &amp;c. It works best in conjunction with the using block where the compiler makes sure that Dispose() will be called immediately once you are done with an object – and also ensures that you cannot work with the object anymore once it&#8217;s disposed of.</p>



<h5 class="wp-block-heading">Dispose() Method</h5>



<ul class="wp-block-list"><li>This dispose method will be used to free unmanaged resources like files, database connection etc.</li><li>To clear unmanaged resources, we need to write code manually to raise dispose() method.</li><li>This Dispose() method belongs to the IDisposable interface.</li><li>If we need to implement this method for any custom classes we need to inherit the class from IDisposable interface.</li><li>It will not show any effect on the performance of the website and we can use this method whenever we want to free objects immediately.</li></ul>



<h5 class="wp-block-heading">Finalize() Method</h5>



<ul class="wp-block-list"><li>This method also free unmanaged resources like database connections, files etc…</li><li>It is automatically raised by garbage collection mechanism whenever the object goes out of scope.</li><li>This method belongs to object class.</li><li>We need to implement this method whenever we have unmanaged resources in our code and make sure these resources will be freed when garbage collection process was done.</li><li>It will show the effect on the performance of the website and it will not suitable to free objects immediately.</li></ul>



<h4 class="wp-block-heading">What is Dependency Injection?How can we implement it?</h4>



<p>Simply put Dependency injection is for decoupling two components. It can be explained by a simple example.</p>



<script src="https://gist.github.com/SibeeshVenu/6f2681e284b50352ed9e2457ef182515.js"></script>



<script src="https://gist.github.com/SibeeshVenu/22b96305a7e43336e28a3109883fce47.js"></script>



<p>Have a look at the code above.</p>



<p>I have an ErrorLogger class that writes an error into database. The method is actually called from another class ApplicationWatcher.<br>In a later stage, if I want to send an email instead of writing into the database, this design will not suffice. I will have created another class that has a method that sends an email and creates its instance in the application watches.</p>



<h4 class="wp-block-heading">What is Data Encapsulation and explain its Implementation?</h4>



<p>To know about the Data encapsulation in C#, I recommend you to read here:<br><a href="http://www.tutorialspoint.com/csharp/csharp_encapsulation.htm" target="_blank" rel="noopener noreferrer">Data Encapsulation and Its Implementation </a><br>That&#8217;s all. Have a great day.</p>



<h3 class="wp-block-heading">Conclusion</h3>



<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>



<h3 class="wp-block-heading">Your turn. What do you think?</h3>



<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/c-sharp-interview-questions-and-answers/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
	</channel>
</rss>
