<?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://mail.sibeeshpassion.com/category/asp-net/feed/" rel="self" type="application/rss+xml" />
	<link>https://mail.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Sun, 15 Aug 2021 14:42:15 +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://mail.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Asp.Net Core Windows Service Task Scheduler Daily, Weekly, Monthly</title>
		<link>https://mail.sibeeshpassion.com/asp-net-core-windows-service-task-scheduler-daily-weekly-monthly/</link>
					<comments>https://mail.sibeeshpassion.com/asp-net-core-windows-service-task-scheduler-daily-weekly-monthly/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 12 Aug 2019 19:15:45 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[Asp Net Core Windows Service]]></category>
		<category><![CDATA[Azure Blob Storage]]></category>
		<category><![CDATA[Azure Storage]]></category>
		<category><![CDATA[NLog]]></category>
		<category><![CDATA[NLog in Windows Service]]></category>
		<category><![CDATA[Quartz Scheduler]]></category>
		<category><![CDATA[Quartz Scheduler with Dependency Injection]]></category>
		<category><![CDATA[Windows Service]]></category>
		<category><![CDATA[Windows Service to Upload to Azure]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=13876</guid>

					<description><![CDATA[[toc] Introduction Windows services are a good way for reducing some manual jobs that we have to do in our system. In this article, we are going to write a windows service using Asp.Net core, the jobs of this windows service is given below. Zip the folder and save the file to a particular directory Upload the zipped folder to the Azure blob storage The above mentioned tasks will be running daily, weekly, monthly. We are using Quartz scheduler with Dependency Injection to do this amazing tasks. We are using Nlog for logging the details of our tasks. If you [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>[toc]</p>



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



<p>Windows services are a good way for reducing some manual jobs that we have to do in our system. In this article, we are going to write a windows service using Asp.Net core, the jobs of this windows service is given below.</p>



<ol class="wp-block-list"><li> Zip the folder and save the file to a particular directory </li><li>Upload the zipped folder to the Azure blob storage</li></ol>



<p>The above mentioned tasks will be running daily, weekly, monthly. We are using Quartz scheduler with Dependency Injection to do this amazing tasks. We are using Nlog for logging the details of our tasks. If you think this is something that you are interested at, then you are at the right place, let us develop our PerfectScheduler. </p>



<h2 class="wp-block-heading">Source Code</h2>



<p>The source code of this project is been uploaded to the GitHub, please feel free to fork, star, create pull requests etc. The repository can be found <a href="https://github.com/SibeeshVenu/Perfect-Scheduler"><strong><em>here</em></strong></a>.</p>



<h2 class="wp-block-heading">Creating Perfect Scheduler</h2>



<p>As I mentioned earlier, we are creating a windows service with Asp.Net core, technically there is no straight way to do this, as the Windows Service with Asp.Net core template is not available in Visual Studio.</p>



<figure class="wp-block-image"><img fetchpriority="high" decoding="async" width="649" height="311" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/No-Windows-Service-Project-Template.png" alt="" class="wp-image-13879" srcset="/wp-content/uploads/2019/08/No-Windows-Service-Project-Template.png 649w, /wp-content/uploads/2019/08/No-Windows-Service-Project-Template-300x144.png 300w, /wp-content/uploads/2019/08/No-Windows-Service-Project-Template-425x204.png 425w" sizes="(max-width: 649px) 100vw, 649px" /><figcaption>No Windows Service Project Template</figcaption></figure>



<p> so we will be creating an Asp.Net console application and then install executable file generated as a windows service. </p>



<figure class="wp-block-image"><img decoding="async" width="649" height="212" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Net-Core-Console-Application.png" alt="" class="wp-image-13880" srcset="/wp-content/uploads/2019/08/Net-Core-Console-Application.png 649w, /wp-content/uploads/2019/08/Net-Core-Console-Application-300x98.png 300w, /wp-content/uploads/2019/08/Net-Core-Console-Application-425x139.png 425w" sizes="(max-width: 649px) 100vw, 649px" /><figcaption>.Net Core Console Application</figcaption></figure>



<h3 class="wp-block-heading">Creating an Asp.Net Console Application</h3>



<p>Open Visual Studio and search for the project template Console App(.Net Core) and name the solution as per your convenience, I am naming this project as Perfect Scheduler, as I am thinking that we, the community people can make this windows service perfect by creating many pull requests.</p>



<p> Once you had created the application, let us install all of our dependencies at once, so that we don&#8217;t need to worry about them later. </p>



<figure class="wp-block-image"><img decoding="async" width="650" height="640" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Dependencies.png" alt="" class="wp-image-13881" srcset="/wp-content/uploads/2019/08/Dependencies.png 650w, /wp-content/uploads/2019/08/Dependencies-300x295.png 300w, /wp-content/uploads/2019/08/Dependencies-425x418.png 425w" sizes="(max-width: 650px) 100vw, 650px" /><figcaption>Asp.Net Core Windows Service Dependencies</figcaption></figure>



<h3 class="wp-block-heading">Write the Service</h3>



<p>As we have installed all of our dependencies, let us create our service now. Add a new class with the name BackupService and inherit the same from IHostedService, which is part of Microsoft.Extensions.Hosting namespace.</p>



<p>The IHostedService has two methods in it as follows, so we should implement them in our service class.</p>



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



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



<p>The StartAsync method can be implemented as preceding.</p>



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



<p>As you can see that in the first line of the above code, we are getting the scheduler of Quartz. Let us create a method and return a scheduler then.</p>



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



<p>The next step is to build a service provider so that we can inject our dependencies using Constructor Dependency Injection. By default the Quartz is not doing this, so we have to build the configuration our own.</p>



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



<p>As you can see that we have configured the services for DailyJob, WeeklyJob, MonthlyJob and HelperService. No worries, we will be creating these Classes and Interfaces very soon. </p>



<p>Once we get the Service Provider, we can pass this to our Custom Job Factory, which we will be implementing soon. Now, we can start the scheduler and schedule our jobs, please make sure that you are using different Identity names for both Triggers and Jobs. The samples are given below.</p>



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



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



<p>The StopAsync method can be implemented as follows</p>



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



<h3 class="wp-block-heading">Creating the JobBuilders and TriggerBuilders</h3>



<p>Now we can create the Interfaces and Classes for our Jobs, which are Daily, Weekly, Monthly. To do so, let us create a new folder called Helpers and then create a folder called Interfaces inside.  Below are the Interfaces you need to create then.</p>



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



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



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



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



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



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



<p>Let us also create an Interface for our HelperService.</p>



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



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



<p>The parameter schedule is for determining which job it is, the value of this parameter can be daily, weekly, monthly.</p>



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



<h3 class="wp-block-heading">Create a Custom Job Factory</h3>



<p>To implement the Dependency Injection, we need to create our own custom job factory. Create a class inside the Helper folder as preceding.</p>



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



<h3 class="wp-block-heading">Implement the Job Builder Interfaces</h3>



<p>Now it is time to implement our Daily, Weekly, Monthly job builders. </p>



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



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



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



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



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



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



<p>As you can see that we have configured separate classes for our each jobs with the dependency IHelperService injected via constructor. In the future we should be able to write custom logic for each jobs here as it is in separate classes.</p>



<h3 class="wp-block-heading">Implement HelperService</h3>



<p>Before we start implementing this service let us configure the NLog now as we will be writing logs from this class. </p>



<h4 class="wp-block-heading">Configure NLog</h4>



<p>To configure, NLog, create a new configuration file NLog.config and edit the content as preceding.</p>



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



<p>Now, create a method SetUpNLog() and add the codes as below.</p>



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



<p>Please make sure that you have already added a property ILogger _logger. </p>



<p>We can implement the HelperService as preceding with all the necessary private and public methods.</p>



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



<p>The method PerformService(string schedule) will be called for every schedule and it will make sure that the below tasks are performed.</p>



<ol class="wp-block-list"><li>Zip the folder and save the file to a particular directory</li><li>Upload the zipped file to the Azure blob storage</li></ol>



<p>Here, the values of the the variable and the blob storage container names are same, that is, daily, weekly, monthly. If you are not sure how you can upload a blob to Azure storage account, I strongly recommend you to read my article <a href="https://sibeeshpassion.com/timertrigger-azure-function-to-upload-to-azure-blob-daily/#azure-function-and-azure-blob"><strong><em>here</em></strong></a>.</p>



<p>Remember to set the values for the FolderToZipLocation(To which location the file should be saved), FolderFromZipLocation (From where the files should be taken), StorageConnectionString in the App.config file.</p>



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



<h3 class="wp-block-heading">Setting Up The Program</h3>



<p>As you all know that Program class it the start of our console application, not it is time to call our BackupService from the Program class. Let us edit the code of the Program class as below.</p>



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



<p>If we are running the application locally/debug, we are calling the extension method RunConsoleAsync() or else we call our own custom extension method RunTheServiceAsync(). The line services.AddHostedService() is very important as this is where we register our IHostedService, which is BackupService. Below is the code for our extension method.</p>



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



<p>The ServiceLifetime class is where we override the methods from ServiceBase class. You can find the implementation as follows.</p>



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



<h2 class="wp-block-heading">Creating the Windows Service</h2>



<p>As we have already created the Asp.Net Core console application, now it is time to create a windows service from it. Make sure that you had set the RuntimeIdentifier to win7-x64 and SelfContained to true in the properties of your project, this will make sure that all of your dependencies are being added to your executable file, so that you don&#8217;t need to worry about handling your dependencies manually. You can read more about it <a href="https://docs.microsoft.com/en-us/dotnet/core/deploying/#self-contained-deployments-scd"><strong><em>here</em></strong></a>. To do so, right click on the project and click on Edit Project File. At the end, your csproj file should be similar as preceding.</p>



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



<h3 class="wp-block-heading">Create the Release Configuration</h3>



<p>You should also run the dotnet publish command with the release configuration before you try to install the service, because you need this executable file to install the service.</p>



<p>Open the command prompt with administrator privilege and go to the project root folder using the cd command. Run the command &#8220;dotnet publish &#8211;configuration=release&#8221; .</p>



<p>This will generate everything you wanted. If you run the command correctly, you should see an output as preceding.</p>



<figure class="wp-block-image"><img decoding="async" width="651" height="400" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Dotnet-Publish-Release.png" alt="" class="wp-image-13883" srcset="/wp-content/uploads/2019/08/Dotnet-Publish-Release.png 651w, /wp-content/uploads/2019/08/Dotnet-Publish-Release-300x184.png 300w, /wp-content/uploads/2019/08/Dotnet-Publish-Release-425x261.png 425w" sizes="(max-width: 651px) 100vw, 651px" /><figcaption>Dotnet Publish Release</figcaption></figure>



<p>Now go to the bin folder and then release folder, you should see a folder with the name netcoreapp2.1, inside this folder, there will be a folder win7-x64, this is the folder where your exe file, log file and other items are residing. </p>



<h3 class="wp-block-heading">Install the Service</h3>



<p>To install our Asp.Net console application as a windows service, you can use the sc command. Open the command prompt with administrator privilege and run the preceding command.</p>



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



<p>And then you can start the service by running the command as &#8220;sc start BackupService&#8221;. This should start your service.</p>



<h3 class="wp-block-heading">Giving Permission to the Folders</h3>



<p>Sometimes you may get some permission issue in your service as it doesn&#8217;t have enough permission to read the files form the C drive. To overcome this, you should give enough permission to the user. You can do this by editing the security properties of those folders.</p>



<figure class="wp-block-image"><img decoding="async" width="649" height="412" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Setting-Permission-for-the-Users.png" alt="" class="wp-image-13886" srcset="/wp-content/uploads/2019/08/Setting-Permission-for-the-Users.png 649w, /wp-content/uploads/2019/08/Setting-Permission-for-the-Users-300x190.png 300w, /wp-content/uploads/2019/08/Setting-Permission-for-the-Users-425x270.png 425w" sizes="(max-width: 649px) 100vw, 649px" /><figcaption>Setting Permission for the Users</figcaption></figure>



<p>Do the same for the BackupZip folder as well.</p>



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



<p>If you have run the service correctly, you should see a log file with the name  backupclientlogfile.txt inside your  win7-x64  folder. Once the service is run,  the logs will be written as follows.</p>



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



<p>You can also check your Azure Storage account to check whether the files have uploaded correctly or not.</p>



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



<p>Wow!. Now we have learned,</p>



<ul class="wp-block-list"><li>about Windows Service and Asp.Net Console Application </li><li>about How to create a Windows Service using Asp.Net Core</li><li>about How to use Quartz scheduler</li><li>about How to use NLog in Windows Service</li><li>about How to configure Quartz scheduler to use Dependency Injection</li><li>about How to Zip a folder and save the file</li><li>about How to upload a file to the Azure blob storage</li></ul>



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



<p>Thanks a lot for reading. Did I miss anything that you may think which is needed in this article? Could you find this post as useful? Kindly do not forget to share me your feedback.</p>



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/asp-net-core-windows-service-task-scheduler-daily-weekly-monthly/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>LINQ Basic To Advanced &#8211; MVC Demo Application</title>
		<link>https://mail.sibeeshpassion.com/linq-basic-to-advanced-mvc-demo-application/</link>
					<comments>https://mail.sibeeshpassion.com/linq-basic-to-advanced-mvc-demo-application/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 15 May 2017 16:09:40 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[LINQ Queries]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=12365</guid>

					<description><![CDATA[[toc] Introduction Here, in this post we are going to a see some LINQ queries, which covers both basics and advanced. LINQ queries are introduced few years back to offer a consistent way for working with data across many datasources and formats. In LINQ queries, you will always work with objects, which makes it simple to write. I hope you would have already written lots of LINQ queries already, if you haven&#8217;t, I strongly reccommend you to read this blog where you can find the answer for, why do we need to use LINQ?. Here I am going to create [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>Here, in this post we are going to a see some <a href="http://sibeeshpassion.com/tag/LINQ" target="_blank" rel="noopener noreferrer">LINQ</a> queries, which covers both basics and advanced. LINQ queries are introduced few years back to offer a consistent way for working with data across many datasources and formats. In LINQ queries, you will always work with objects, which makes it simple to write. I hope you would have already written lots of LINQ queries already, if you haven&#8217;t, I strongly reccommend you to read this <a href="https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/concepts/linq/introduction-to-linq-queries" target="_blank" rel="noopener">blog </a> where you can find the answer for, why do we need to use LINQ?. Here I am going to create a <a href="http://sibeeshpassion.com/category/mvc/">MVC</a> demo application. I hope you will like this. Now let&#8217;s begin.</p>
<h3>Download Source Code</h3>
<li><a href="https://code.msdn.microsoft.com/LINQ-Basic-To-Advanced-MVC-cc3b8254" target="_blank" rel="noopener">LINQ_B_To_A</a></li>
<h3>Background</h3>
<p>Whenever I get a chance to write some server side codes in <a href="http://sibeeshpassion.com/category/csharp/" target="_blank" rel="noopener">C#</a>, I always write it using LINQ. And few weeks back, I was assigned to a training programme where my job was to teach LINQ, hence this post covers the the queries I have written for the training programme. Hope you will find it useful.</p>
<h3>Using the code</h3>
<p>A LINQ query can be written in two ways.</p>
<li>Query Syntax</li>
<li>Method Chain or Using dot(.) operator</li>
<p>There are so many articles available in the Internet on the topic LINQ, but most of them dont cover the differences of writing the queries in two possible ways, the motive of this article is to write the queries in both ways, so that you can understand the differnces.</p>
<p>As I mentioned, we are going to create an MVC application, we need to create it first and then configure the entity. Let&#8217;s go and do that.</p>
<h4>Create a database</h4>
<p>To get started with we need to configure our database first. To do so, either you can download the Wild World Importers from <a href="https://github.com/Microsoft/sql-server-samples/releases/tag/wide-world-importers-v1.0" target="_blank" rel="noopener">here</a> or you can run the script file included in the downlaod link above. </p>
<p>Once after you created the database, you can create your MVC application and Entity Data Model in it. </p>
<h4>Configuring MVC application with Entity Data Model</h4>
<p>By this time, I hope you would have configured your MVC application with Entity Data Model. Now it is time to create a controller and Entity object. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Data.Entity;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.Mvc;<br />
using System.Windows.Forms;<br />
using LINQ_B_to_A.Models;<br />
namespace LINQ_B_to_A.Controllers<br />
{<br />
    public class HomeController : Controller<br />
    {<br />
        // GET: Home</p>
<p>        public MyDataModel DtContext { get; set; } = new MyDataModel();<br />
    }<br />
}<br />
[/csharp]</p>
<p>Now we can write some LINQ queries as everything is set to get started.</p>
<h4>Setting up the Index view with possible actions</h4>
<p>This is just to call the actions we are going write. Let&#8217;s see the Index page now. </p>
<p>[html]<br />
@{<br />
    ViewBag.Title = &quot;Index&quot;;<br />
    Layout = &quot;~/Views/Shared/_Layout.cshtml&quot;;<br />
}</p>
<p>&lt;h2&gt;Index&lt;/h2&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;LoadAll&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Load All &#8211; Query Expression&quot;/&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;JoinWithWhere&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Join With Where&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;LeftJoin&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Left Join&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;DistinctSample&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Distinct Sample&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;EqualsSamples&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Equals Sample&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;NotEqualsSamples&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Not Equals&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;PagingQueries&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Paging Queries&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;MathQueries&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Math Queries&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;StringQueries&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;String Queries&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;SelectMany&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Select Many&quot; /&gt;<br />
[/html]</p>
<p><div id="attachment_12367" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Index-View-e1494741059608.png"><img decoding="async" aria-describedby="caption-attachment-12367" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Index-View-e1494741059608.png" alt="LINQ Basic to Advanced Index View" width="634" height="197" class="size-full wp-image-12367" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Index-View-e1494741059608.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Index-View-e1494741059608-300x93.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Index-View-e1494741059608-400x124.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12367" class="wp-caption-text">LINQ Basic to Advanced Index View</p></div></p>
<h4>Normal Select Query With StartWith and Take</h4>
<p>Let&#8217;s have a look at the preceding query.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Linq query with Select<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult LoadAll()<br />
        {<br />
            var loadAllData = (from d in DtContext.Cities where d.CityName.StartsWith(&quot;C&quot;) select d).Take(10);</p>
<p>            //Method Chain Format<br />
            var loadAllData1 = DtContext.Cities.Where(d =&gt; d.CityName.StartsWith(&quot;C&quot;)).Take(10);</p>
<p>            return PartialView(loadAllData);<br />
        }<br />
[/csharp]</p>
<p>As you can see, we are just fetching the data from Cities in both ways. And we are using StartWith as a filter, which actually looks for the city names which starts with the letter C, and finally we are taking 10 elements from it. The first query is the &#8220;Query syntax&#8221; and the second one is &#8220;Method chain&#8221;. Personally I like the second way. How about you?</p>
<p>[html]<br />
@model IQueryable&lt;LINQ_B_to_A.Models.City&gt;<br />
&lt;style&gt;<br />
    dd, dt, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    dd {<br />
        background-color: #a9a9a9<br />
    }<br />
    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;<br />
&lt;dd&gt;City Names&lt;/dd&gt;<br />
@foreach (var ctyObj in Model)<br />
{<br />
    &lt;dt&gt;@ctyObj.CityName&lt;/dt&gt;<br />
}<br />
&lt;pre&gt;<br />
        public ActionResult LoadAll()<br />
        {<br />
            var loadAllData = (from d in DtContext.Cities where d.CityName.StartsWith(&quot;C&quot;) select d).Take(10);</p>
<p>            //Method Chain Format<br />
            var loadAllData1 = DtContext.Cities.Where(d =&gt; d.CityName.StartsWith(&quot;C&quot;)).Take(10);</p>
<p>            return PartialView(loadAllData);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>We are ready to see our first query in action now. </p>
<p>Let&#8217;s creat a partial view now to show the data we fetched. <a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Normal-Select-Query-With-StartsWith-and-Take-e1494741383811.png"><img decoding="async" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Normal-Select-Query-With-StartsWith-and-Take-e1494741383811.png" alt="LINQ Basic to Advanced Normal Select Query With StartsWith and Take" width="634" height="400" class="alignnone size-full wp-image-12368" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Normal-Select-Query-With-StartsWith-and-Take-e1494741383811.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Normal-Select-Query-With-StartsWith-and-Take-e1494741383811-300x189.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Normal-Select-Query-With-StartsWith-and-Take-e1494741383811-400x252.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a></p>
<h4>JOIN Query</h4>
<p>To write a join, the query would be as preceding.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Linq query with join and where<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult JoinWithWhere()<br />
        {<br />
            var loadAllData = (from oOrders in DtContext.Orders<br />
                               join oOrderLines in DtContext.OrderLines<br />
                               on oOrders.OrderID equals oOrderLines.OrderID<br />
                               orderby oOrders.OrderID<br />
                               select new OrderAndOrderLines()<br />
                               {<br />
                                   OrderId = oOrders.OrderID,<br />
                                   Description = oOrderLines.Description,<br />
                                   Quantity = oOrderLines.Quantity<br />
                               }).Take(10);<br />
            //Method Chain Format<br />
            var asMethodChain = DtContext.Orders.Join(DtContext.OrderLines, oOrders =&gt; oOrders.OrderID,<br />
                    oOrderLines =&gt; oOrderLines.OrderID,<br />
                    (oOrders, oOrderLines) =&gt; new { oOrders, oOrderLines })<br />
                .OrderBy(@o =&gt; @o.oOrders.OrderID)<br />
                .Select(@s =&gt; new OrderAndOrderLines()<br />
                {<br />
                    OrderId = @s.oOrders.OrderID,<br />
                    Description = @s.oOrderLines.Description,<br />
                    Quantity = @s.oOrderLines.Quantity<br />
                }).Take(10);</p>
<p>            return PartialView(loadAllData);<br />
        }<br />
[/csharp]</p>
<p>In the above query we are just joining the tables Order and OrderLines with OrderID and to select we are using an another custom model OrderAndOrderLines. </p>
<p>[csharp]<br />
namespace LINQ_B_to_A.Models<br />
{<br />
    public partial class OrderAndOrderLines<br />
    {<br />
        public int OrderId { get; set; }<br />
        public string Description { get; set; }<br />
        public int? Quantity { get; set; }<br />
    }<br />
}<br />
[/csharp]</p>
<p>The view can be written as follows.</p>
<p>[html]<br />
@model IEnumerable&lt;LINQ_B_to_A.Models.OrderAndOrderLines&gt;<br />
&lt;style&gt;<br />
    td, th, thead,pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    caption {<br />
        background-color: #a9a9a9<br />
    }<br />
    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;</p>
<p>&lt;table&gt;<br />
    &lt;caption&gt;Order Details&lt;/caption&gt;<br />
    &lt;tr&gt;<br />
        &lt;th&gt;Order ID&lt;/th&gt;<br />
        &lt;th&gt;Description&lt;/th&gt;<br />
        &lt;th&gt;Quantity&lt;/th&gt;<br />
    &lt;/tr&gt;<br />
    @foreach (var @item in Model)<br />
    {<br />
        &lt;tr&gt;<br />
            &lt;td&gt;@item.OrderId&lt;/td&gt;<br />
            &lt;td&gt;@item.Description&lt;/td&gt;<br />
            &lt;td&gt;@item.Quantity&lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    }<br />
&lt;/table&gt;<br />
&lt;pre&gt;<br />
     public ActionResult JoinWithWhere()<br />
        {<br />
            var loadAllData = (from oOrders in DtContext.Orders<br />
                               join oOrderLines in DtContext.OrderLines<br />
                               on oOrders.OrderID equals oOrderLines.OrderID<br />
                               orderby oOrders.OrderID<br />
                               select new OrderAndOrderLines()<br />
                               {<br />
                                   OrderId = oOrders.OrderID,<br />
                                   Description = oOrderLines.Description,<br />
                                   Quantity = oOrderLines.Quantity<br />
                               }).Take(10);<br />
            //Method Chain Format<br />
            var asMethodChain = DtContext.Orders.Join(DtContext.OrderLines, oOrders =&gt; oOrders.OrderID,<br />
                    oOrderLines =&gt; oOrderLines.OrderID,<br />
                    (oOrders, oOrderLines) =&gt; new { oOrders, oOrderLines })<br />
                .OrderBy(o =&gt; o.oOrders.OrderID)<br />
                .Select(s =&gt; new OrderAndOrderLines()<br />
                {<br />
                    OrderId = s.oOrders.OrderID,<br />
                    Description = s.oOrderLines.Description,<br />
                    Quantity = s.oOrderLines.Quantity<br />
                }).Take(10);</p>
<p>            return PartialView(loadAllData);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>Once you run the action you can see the result as follows. </p>
<p><div id="attachment_12369" style="width: 1654px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Join-With-Where-e1494742473978.png"><img decoding="async" aria-describedby="caption-attachment-12369" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Join-With-Where-e1494742473978.png" alt="LINQ Basic to Advanced Join With Where" width="1644" height="821" class="size-full wp-image-12369" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Join-With-Where-e1494742473978.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Join-With-Where-e1494742473978-300x150.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Join-With-Where-e1494742473978-400x200.png 400w" sizes="(max-width: 1644px) 100vw, 1644px" /></a><p id="caption-attachment-12369" class="wp-caption-text">LINQ Basic to Advanced Join With Where</p></div></p>
<h4>Left JOIN Query</h4>
<p>To write a Left join, the query would be as preceding.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Linq query with Left Join<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult LeftJoin()<br />
        {<br />
            var loadAllData = (from oOrder in DtContext.Orders<br />
                               join oOrderLine in DtContext.OrderLines<br />
                               on oOrder.OrderID equals oOrderLine.OrderID<br />
                               into lftOrder<br />
                               from afterJoined in lftOrder.DefaultIfEmpty()<br />
                               orderby oOrder.OrderID descending<br />
                               select new OrderAndOrderLines()<br />
                               {<br />
                                   OrderId = oOrder.OrderID,<br />
                                   Description = afterJoined.Description<br />
                               }).Take(10).ToList();<br />
            //Method Chain Format<br />
            var lftJoinMethodChain = (DtContext.Orders.GroupJoin(DtContext.OrderLines,<br />
                    oOrder =&gt; oOrder.OrderID, oOrderLine =&gt; oOrderLine.OrderID,<br />
                    (oOrder, lftJoin) =&gt; new { oOrder, lftJoin })<br />
                .SelectMany(@sm =&gt; @sm.lftJoin.DefaultIfEmpty(), (@sm, afterJoin) =&gt; new { @sm, afterJoin })<br />
                .OrderByDescending(@o =&gt; @o.sm.oOrder.OrderID)<br />
                .Select(@s =&gt; new OrderAndOrderLines()<br />
                {<br />
                    OrderId = @s.sm.oOrder.OrderID,<br />
                    Description = @s.afterJoin.Description<br />
                })).Take(10).ToList();</p>
<p>            return PartialView(loadAllData);<br />
        }<br />
[/csharp]</p>
<p>In the above query we are just joining the tables Order and OrderLines with OrderID and to select we are using an another custom model OrderAndOrderLines as our previous query. The differences you could find here are, using an &#8216;into&#8217; and &#8216;DefaultIfEmpty&#8217; statements. The DefaultIfEmpty is making sure that it returns empty if there is no appropriate rows found in the second table. </p>
<p>The view can be written as follows.</p>
<p>[html]<br />
@model IEnumerable&lt;LINQ_B_to_A.Models.OrderAndOrderLines&gt;<br />
&lt;style&gt;<br />
    td, th, thead, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    caption {<br />
        background-color: #a9a9a9<br />
    }<br />
    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;</p>
<p>&lt;table&gt;<br />
    &lt;caption&gt;Order Details&lt;/caption&gt;<br />
    &lt;tr&gt;<br />
        &lt;th&gt;Order ID&lt;/th&gt;<br />
        &lt;th&gt;Description&lt;/th&gt;<br />
        &lt;th&gt;Quantity&lt;/th&gt;<br />
    &lt;/tr&gt;<br />
    @foreach (var @item in Model)<br />
    {<br />
        &lt;tr&gt;<br />
            &lt;td&gt;@item.OrderId&lt;/td&gt;<br />
            &lt;td&gt;@item.Description&lt;/td&gt;<br />
            &lt;td&gt;@item.Quantity&lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    }<br />
&lt;/table&gt;<br />
&lt;pre&gt;<br />
    public ActionResult LeftJoin()<br />
        {<br />
            var loadAllData = (from oOrder in DtContext.Orders<br />
                               join oOrderLine in DtContext.OrderLines<br />
                               on oOrder.OrderID equals oOrderLine.OrderID<br />
                               into lftOrder<br />
                               from afterJoined in lftOrder.DefaultIfEmpty()<br />
                               orderby oOrder.OrderID descending<br />
                               select new OrderAndOrderLines()<br />
                               {<br />
                                   OrderId = oOrder.OrderID,<br />
                                   Description = afterJoined.Description<br />
                               }).Take(10).ToList();<br />
            //Method Chain Format<br />
            var lftJoinMethodChain = (DtContext.Orders.GroupJoin(DtContext.OrderLines,<br />
                    oOrder =&gt; oOrder.OrderID, oOrderLine =&gt; oOrderLine.OrderID,<br />
                    (oOrder, lftJoin) =&gt; new { oOrder, lftJoin })<br />
                .SelectMany(sm =&gt; sm.lftJoin.DefaultIfEmpty(), (sm, afterJoin) =&gt; new { sm, afterJoin })<br />
                .OrderByDescending(o =&gt; o.sm.oOrder.OrderID)<br />
                .Select(s =&gt; new OrderAndOrderLines()<br />
                {<br />
                    OrderId = s.sm.oOrder.OrderID,<br />
                    Description = s.afterJoin.Description<br />
                })).Take(10).ToList();</p>
<p>            return PartialView(loadAllData);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>Once you run the action you can see the result as follows. </p>
<p><div id="attachment_12370" style="width: 1658px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Left-Join-e1494742942417.png"><img decoding="async" aria-describedby="caption-attachment-12370" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Left-Join-e1494742942417.png" alt="LINQ Basic to Advanced Left Join" width="1648" height="820" class="size-full wp-image-12370" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Left-Join-e1494742942417.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Left-Join-e1494742942417-300x149.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Left-Join-e1494742942417-400x199.png 400w" sizes="(max-width: 1648px) 100vw, 1648px" /></a><p id="caption-attachment-12370" class="wp-caption-text">LINQ Basic to Advanced Left Join</p></div></p>
<p>As you can see in the image, the order id 200000 doesn&#8217;t has any appropriate rows in the second table, so it shows as empty.</p>
<h4>Distinct Query</h4>
<p>The below query shows how we can write simple distinct query.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Linq query Distinct sample<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult DistinctSample()<br />
        {<br />
            var distictSample = (from oOrder in DtContext.OrderLines<br />
                                 select oOrder.Description).Distinct().Take(10).ToList();</p>
<p>            //Method Chain Format<br />
            var distictAsMethodChain = (DtContext.OrderLines.Select(oOrder =&gt; oOrder.Description)).Distinct().Take(10).ToList();</p>
<p>            return PartialView(distictSample);<br />
        }<br />
[/csharp]</p>
<p>In the above query we use Distinct to make sure that only distict items are selected from the result. The view can be written as follows.</p>
<p>[html]<br />
@model  List&lt;string&gt;<br />
&lt;style&gt;<br />
    dd, dt, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    dd {<br />
        background-color: #a9a9a9<br />
    }</p>
<p>    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;<br />
&lt;dd&gt;Order Descriptions&lt;/dd&gt;<br />
@foreach (var orderLinesyObj in Model)<br />
{<br />
    &lt;dt&gt;@orderLinesyObj&lt;/dt&gt;<br />
}<br />
&lt;pre&gt;<br />
    public ActionResult DistinctSample()<br />
        {<br />
            var distictSample = (from oOrder in DtContext.OrderLines<br />
                                 select oOrder.Description).Distinct().Take(10).ToList();</p>
<p>            //Method Chain Format<br />
            var distictAsMethodChain = (DtContext.OrderLines.Select(oOrder =&gt; oOrder.Description)).Distinct().Take(10).ToList();</p>
<p>            return PartialView(distictSample);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>Once you run the action you can see the result as follows.</p>
<p><div id="attachment_12371" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Distinct-Query-e1494743542508.png"><img decoding="async" aria-describedby="caption-attachment-12371" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Distinct-Query-e1494743542508.png" alt="LINQ Basic to Advanced Distinct Query" width="634" height="372" class="size-full wp-image-12371" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Distinct-Query-e1494743542508.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Distinct-Query-e1494743542508-300x176.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Distinct-Query-e1494743542508-400x235.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12371" class="wp-caption-text">LINQ Basic to Advanced Distinct Query</p></div></p>
<h4>Equals and Not Equals Queries</h4>
<p>We can write the equals and not equals query as preceding.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Linq query Equals sample<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult EqualsSamples()<br />
        {<br />
            var objEquals = (from objCity in DtContext.Cities<br />
                             where objCity.CityName.Equals(&quot;Troy&quot;)<br />
                             select objCity).Take(2);<br />
            //Method Chain Format<br />
            var objEquals1 = DtContext.Cities.Where(d =&gt; d.CityName.Equals(&quot;Troy&quot;)).Take(2);</p>
<p>            return PartialView(&quot;OperatorSamples&quot;, objEquals);<br />
        }</p>
<p>        /// &lt;summary&gt;<br />
        /// Linq query Not Equals sample<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult NotEqualsSamples()<br />
        {<br />
            var objNotEquals = (from objCity in DtContext.Cities<br />
                                where objCity.CityName != &quot;Troy&quot;<br />
                                select objCity).Take(5);</p>
<p>            var objNotEquals1 = (from objCity in DtContext.Cities<br />
                                 where !objCity.CityName.Equals(&quot;Troy&quot;)<br />
                                 select objCity).Take(5);</p>
<p>            //Method Chain Format<br />
            var objNotEquals2 = DtContext.Cities.Where(d =&gt; d.CityName != &quot;Troy&quot;).Take(2);</p>
<p>            var objNotEquals3 = DtContext.Cities.Where(d =&gt; !d.CityName.Equals(&quot;Troy&quot;)).Take(2);</p>
<p>            return PartialView(&quot;OperatorSamples&quot;, objNotEquals);<br />
        }<br />
[/csharp]</p>
<p>The view can be written as follows.</p>
<p>[html]<br />
@model IQueryable&lt;LINQ_B_to_A.Models.City&gt;<br />
&lt;style&gt;<br />
    td, th, thead, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    caption {<br />
        background-color: #a9a9a9<br />
    }</p>
<p>    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;</p>
<p>    &lt;table&gt;<br />
        &lt;caption&gt;City Details&lt;/caption&gt;<br />
        &lt;tr&gt;<br />
            &lt;th&gt;City ID&lt;/th&gt;<br />
            &lt;th&gt;City Name&lt;/th&gt;<br />
            &lt;th&gt;City Location&lt;/th&gt;<br />
        &lt;/tr&gt;<br />
@foreach (var @item in Model)<br />
{<br />
    &lt;tr&gt;<br />
    &lt;td&gt;@item.CityID&lt;/td&gt;<br />
    &lt;td&gt;@item.CityName&lt;/td&gt;<br />
    &lt;td&gt;@item.Location&lt;/td&gt;<br />
    &lt;/tr&gt;<br />
}<br />
    &lt;/table&gt;<br />
&lt;caption&gt;Equals Oerator&lt;/caption&gt;<br />
&lt;pre&gt;<br />
    public ActionResult EqualsSamples()<br />
        {<br />
            var objEquals = (from objCity in DtContext.Cities<br />
                                       where objCity.CityName.Equals(&quot;Troy&quot;)<br />
                                       select objCity).Take(2);<br />
            //Method Chain Format<br />
            var objEquals1 = DtContext.Cities.Where(d =&gt; d.CityName.Equals(&quot;Troy&quot;)).Take(2);</p>
<p>            return PartialView(&quot;OperatorSamples&quot;, objEquals);<br />
        }</p>
<p>        public ActionResult NotEqualsSamples()<br />
        {<br />
            var objNotEquals = (from objCity in DtContext.Cities<br />
                where objCity.CityName != &quot;Troy&quot;<br />
                select objCity).Take(5);</p>
<p>            var objNotEquals1 = (from objCity in DtContext.Cities<br />
                where !objCity.CityName.Equals(&quot;Troy&quot;)<br />
                select objCity).Take(5);</p>
<p>            //Method Chain Format<br />
            var objNotEquals2 = DtContext.Cities.Where(d =&gt; d.CityName != &quot;Troy&quot;).Take(2);</p>
<p>            var objNotEquals3 = DtContext.Cities.Where(d =&gt; !d.CityName.Equals(&quot;Troy&quot;)).Take(2);</p>
<p>            return PartialView(&quot;OperatorSamples&quot;, objNotEquals);<br />
        }</p>
<p>        public ActionResult PagingQueries()<br />
        {<br />
            var objNotEquals = (from objCity in DtContext.Cities<br />
                where objCity.CityName != &quot;Troy&quot;<br />
                orderby objCity.CityName ascending<br />
                select objCity).Skip(5).Take(5);</p>
<p>            //Method Chain Format<br />
            var objNotEquals2 = DtContext.Cities.Where(d =&gt; d.CityName != &quot;Troy&quot;).Skip(5).Take(5);</p>
<p>            return PartialView(&quot;OperatorSamples&quot;, objNotEquals);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>Once you run the action you can see the result as follows.</p>
<p><div id="attachment_12372" style="width: 1622px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Equals-and-Not-Equals-e1494744042305.png"><img decoding="async" aria-describedby="caption-attachment-12372" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Equals-and-Not-Equals-e1494744042305.png" alt="LINQ Basic to Advanced Equals and Not Equals" width="1612" height="560" class="size-full wp-image-12372" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Equals-and-Not-Equals-e1494744042305.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Equals-and-Not-Equals-e1494744042305-300x104.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Equals-and-Not-Equals-e1494744042305-400x139.png 400w" sizes="(max-width: 1612px) 100vw, 1612px" /></a><p id="caption-attachment-12372" class="wp-caption-text">LINQ Basic to Advanced Equals and Not Equals</p></div></p>
<h4>LINQ Paging Queries</h4>
<p>Paging queries are always important as we work in some grid controls, with LINQ those are very easy. Let&#8217;s see one of that query. </p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Linq Paging Queries<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult PagingQueries()<br />
        {<br />
            var objNotEquals = (from objCity in DtContext.Cities<br />
                                where objCity.CityName != &quot;Troy&quot;<br />
                                orderby objCity.CityName ascending<br />
                                select objCity).Skip(5).Take(5);</p>
<p>            //Method Chain Format<br />
            var objNotEquals2 = DtContext.Cities.Where(d =&gt; d.CityName != &quot;Troy&quot;).Skip(5).Take(5);</p>
<p>            return PartialView(&quot;OperatorSamples&quot;, objNotEquals);<br />
        }<br />
[/csharp]</p>
<p>Once you run the action you can see the result as follows.</p>
<p><div id="attachment_12373" style="width: 1611px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Paging-Queries-e1494744396637.png"><img decoding="async" aria-describedby="caption-attachment-12373" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Paging-Queries-e1494744396637.png" alt="LINQ Basic to Advanced Paging Queries" width="1601" height="862" class="size-full wp-image-12373" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Paging-Queries-e1494744396637.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Paging-Queries-e1494744396637-300x161.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Paging-Queries-e1494744396637-400x215.png 400w" sizes="(max-width: 1601px) 100vw, 1601px" /></a><p id="caption-attachment-12373" class="wp-caption-text">LINQ Basic to Advanced Paging Queries</p></div></p>
<h4>LINQ Math Queries</h4>
<p>Here we are going to write the possible Math functions in our LINQ query.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Math Queries<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult MathQueries()<br />
        {<br />
            var objMath = (from objInv in DtContext.InvoiceLines<br />
                           where objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15<br />
                           orderby objInv.InvoiceLineID descending<br />
                           select new MathClass()<br />
                           {<br />
                               Actual = objInv.ExtendedPrice,<br />
                               Round = Math.Round(objInv.ExtendedPrice),<br />
                               Floor = Math.Floor(objInv.ExtendedPrice),<br />
                               Ceiling = Math.Ceiling(objInv.ExtendedPrice),<br />
                               Abs = Math.Abs(objInv.ExtendedPrice)<br />
                           }).Take(10);</p>
<p>            //Method Chain Format<br />
            var objMath2 = DtContext.InvoiceLines<br />
                .Where(objInv =&gt; objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15)<br />
                .OrderByDescending(o =&gt; o.InvoiceLineID)<br />
                .Select(objInv =&gt; new MathClass()<br />
                {<br />
                    Actual = objInv.ExtendedPrice,<br />
                    Round = Math.Round(objInv.ExtendedPrice),<br />
                    Floor = Math.Floor(objInv.ExtendedPrice),<br />
                    Ceiling = Math.Ceiling(objInv.ExtendedPrice),<br />
                    Abs = Math.Abs(objInv.ExtendedPrice)<br />
                }).Take(10);</p>
<p>            return PartialView(&quot;MathQueries&quot;, objMath);<br />
        }<br />
[/csharp]</p>
<p>As you can see we have written most of the possible Math functions in our query and selecting with a custome model MathClass.</p>
<p>[csharp]<br />
namespace LINQ_B_to_A.Models<br />
{<br />
    public partial class MathClass<br />
    {<br />
        public decimal Actual { get; set; }<br />
        public decimal Round { get; set; }<br />
        public decimal Floor { get; set; }<br />
        public decimal Ceiling { get; set; }<br />
        public decimal Abs { get; set; }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Let&#8217;s see the view now. </p>
<p>[html]</p>
<p>@model IQueryable&lt;LINQ_B_to_A.Models.MathClass&gt;<br />
&lt;style&gt;<br />
    td, th, thead, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    caption {<br />
        background-color: #a9a9a9<br />
    }</p>
<p>    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;</p>
<p>&lt;table&gt;<br />
    &lt;caption&gt;Math Operators&lt;/caption&gt;<br />
    &lt;tr&gt;</p>
<p>    &lt;/tr&gt;<br />
    @foreach (var @item in Model)<br />
    {<br />
        &lt;tr&gt;<br />
            &lt;td&gt;Actual: @item.Actual&lt;/td&gt;<br />
            &lt;td&gt;Round: @item.Round&lt;/td&gt;<br />
            &lt;td&gt;Floor: @item.Floor&lt;/td&gt;<br />
            &lt;td&gt;Ceiling: @item.Ceiling&lt;/td&gt;<br />
            &lt;td&gt;Abs: @item.Abs&lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    }<br />
&lt;/table&gt;<br />
&lt;pre&gt;<br />
    public ActionResult MathQueries()<br />
        {<br />
            var objMath = (from objInv in DtContext.InvoiceLines<br />
                          where objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15<br />
                          orderby objInv.InvoiceLineID descending<br />
                          select new MathClass()<br />
                          {<br />
                              Actual = objInv.ExtendedPrice,<br />
                              Round = Math.Round(objInv.ExtendedPrice),<br />
                              Floor = Math.Floor(objInv.ExtendedPrice),<br />
                              Ceiling = Math.Ceiling(objInv.ExtendedPrice),<br />
                              Abs = Math.Abs(objInv.ExtendedPrice)<br />
                          }).Take(10);</p>
<p>            //Method Chain Format<br />
            var objMath2 = DtContext.InvoiceLines<br />
                .Where(objInv =&gt; objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15)<br />
                .OrderByDescending(o =&gt; o.InvoiceLineID)<br />
                .Select(objInv =&gt; new MathClass()<br />
                {<br />
                    Actual = objInv.ExtendedPrice,<br />
                    Round = Math.Round(objInv.ExtendedPrice),<br />
                    Floor = Math.Floor(objInv.ExtendedPrice),<br />
                    Ceiling = Math.Ceiling(objInv.ExtendedPrice),<br />
                    Abs = Math.Abs(objInv.ExtendedPrice)<br />
                }).Take(10);</p>
<p>            return PartialView(&quot;MathQueries&quot;, objMath);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>See the result now.</p>
<p><div id="attachment_12374" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Math-Queries-e1494744783496.png"><img decoding="async" aria-describedby="caption-attachment-12374" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Math-Queries-e1494744783496.png" alt="LINQ Basic to Advanced Math Queries" width="634" height="673" class="size-full wp-image-12374" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Math-Queries-e1494744783496.png 336w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Math-Queries-e1494744783496-283x300.png 283w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Math-Queries-e1494744783496-400x425.png 400w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Math-Queries-e1494744783496-565x600.png 565w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12374" class="wp-caption-text">LINQ Basic to Advanced Math Queries</p></div></p>
<h4>LINQ String Queries</h4>
<p>As we saw the Math queries, here we are going to write the possible String functions in our LINQ query.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// String Queries<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult StringQueries()<br />
        {<br />
            var objString = (from objInv in DtContext.InvoiceLines<br />
                             where objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15<br />
                             orderby objInv.InvoiceLineID descending<br />
                             select new StringClass()<br />
                             {<br />
                                 Actual = objInv.Description,<br />
                                 Insert = objInv.Description.Insert(2, &quot;sibeeshpassion&quot;),<br />
                                 Remove = objInv.Description.Remove(1, 1),<br />
                                 Substring = objInv.Description.Substring(2, 3),<br />
                                 ToLower = objInv.Description.ToLower(),<br />
                                 ToUpper = objInv.Description.ToUpper(),<br />
                                 TrimEnd = objInv.Description.TrimEnd(),<br />
                                 TrimStart = objInv.Description.TrimStart()<br />
                             }).Take(2);</p>
<p>            //Method Chain Format<br />
            var objString2 = DtContext.InvoiceLines<br />
                .Where(objInv =&gt; objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15)<br />
                .OrderByDescending(o =&gt; o.InvoiceLineID)<br />
                .Select(objInv =&gt; new StringClass()<br />
                {<br />
                    Actual = objInv.Description,<br />
                    Insert = objInv.Description.Insert(2, &quot;sibeeshpassion&quot;),<br />
                    Remove = objInv.Description.Remove(1, 1),<br />
                    Substring = objInv.Description.Substring(2, 3),<br />
                    ToLower = objInv.Description.ToLower(),<br />
                    ToUpper = objInv.Description.ToUpper(),<br />
                    TrimEnd = objInv.Description.TrimEnd(),<br />
                    TrimStart = objInv.Description.TrimStart()<br />
                }).Take(2);</p>
<p>            return PartialView(&quot;StringQueries&quot;, objString);<br />
        }<br />
[/csharp]</p>
<p>As you can see, here we are using a custom model StringClass.</p>
<p>[csharp]<br />
namespace LINQ_B_to_A.Models<br />
{<br />
    public partial class StringClass<br />
    {<br />
        public string Actual { get; set; }<br />
        public string Insert { get; set; }<br />
        public string Remove { get; set; }<br />
        public string Substring { get; set; }<br />
        public string ToUpper { get; set; }<br />
        public string ToLower { get; set; }<br />
        public string TrimStart { get; set; }<br />
        public string TrimEnd { get; set; }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Let&#8217;s see the view now. </p>
<p>[html]</p>
<p>@model IQueryable&lt;LINQ_B_to_A.Models.StringClass&gt;<br />
&lt;style&gt;<br />
    td, th, thead, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    caption {<br />
        background-color: #a9a9a9<br />
    }</p>
<p>    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;</p>
<p>&lt;table&gt;<br />
    &lt;caption&gt;String Operators&lt;/caption&gt;<br />
    &lt;tr&gt;</p>
<p>    &lt;/tr&gt;<br />
    @foreach (var @item in Model)<br />
    {<br />
        &lt;tr&gt;<br />
            &lt;td&gt;Actual: @item.Actual&lt;/td&gt;<br />
            &lt;td&gt;Insert: @item.Insert&lt;/td&gt;<br />
            &lt;td&gt;Remove: @item.Remove&lt;/td&gt;<br />
            &lt;td&gt;Substring: @item.Substring&lt;/td&gt;<br />
            &lt;td&gt;ToLower: @item.ToLower&lt;/td&gt;<br />
            &lt;td&gt;ToUpper: @item.ToUpper&lt;/td&gt;<br />
            &lt;td&gt;TrimEnd: @item.TrimEnd&lt;/td&gt;<br />
            &lt;td&gt;TrimStart: @item.TrimStart&lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    }<br />
&lt;/table&gt;<br />
&lt;pre&gt;<br />
        public ActionResult StringQueries()<br />
        {<br />
            var objString = (from objInv in DtContext.InvoiceLines<br />
                where objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15<br />
                orderby objInv.InvoiceLineID descending<br />
                select new StringClass()<br />
                {</p>
<p>                    Actual = objInv.Description,<br />
                    Insert = objInv.Description.Insert(2,&quot;sibeeshpassion&quot;),<br />
                    Remove = objInv.Description.Remove(1,1),<br />
                    Substring = objInv.Description.Substring(2,3),<br />
                    ToLower = objInv.Description.ToLower(),<br />
                    ToUpper = objInv.Description.ToUpper(),<br />
                    TrimEnd = objInv.Description.TrimEnd(),<br />
                    TrimStart = objInv.Description.TrimStart()<br />
                }).Take(2);</p>
<p>            //Method Chain Format<br />
            var objString2 = DtContext.InvoiceLines<br />
                .Where(objInv =&gt; objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15)<br />
                .OrderByDescending(o =&gt; o.InvoiceLineID)<br />
                .Select(objInv =&gt; new StringClass()<br />
                {<br />
                    Actual = objInv.Description,<br />
                    Insert = objInv.Description.Insert(2, &quot;sibeeshpassion&quot;),<br />
                    Remove = objInv.Description.Remove(1, 1),<br />
                    Substring = objInv.Description.Substring(2, 3),<br />
                    ToLower = objInv.Description.ToLower(),<br />
                    ToUpper = objInv.Description.ToUpper(),<br />
                    TrimEnd = objInv.Description.TrimEnd(),<br />
                    TrimStart = objInv.Description.TrimStart()<br />
                }).Take(2);</p>
<p>            return PartialView(&quot;StringQueries&quot;, objString);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>Now see the result.</p>
<p><div id="attachment_12375" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-String-Queries-e1494745369956.png"><img decoding="async" aria-describedby="caption-attachment-12375" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-String-Queries-e1494745369956.png" alt="LINQ Basic to Advanced String Queries" width="634" height="300" class="size-full wp-image-12375" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-String-Queries-e1494745369956.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-String-Queries-e1494745369956-300x142.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-String-Queries-e1494745369956-400x189.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12375" class="wp-caption-text">LINQ Basic to Advanced String Queries</p></div></p>
<h4>SelectMany Query</h4>
<p>A SelectMany query flattern the result to a single dimentional collection, so to loop through the result we just need only one loop. </p>
<p><div id="attachment_12377" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-Tooltip-e1494746794913.png"><img decoding="async" aria-describedby="caption-attachment-12377" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-Tooltip-e1494746794913.png" alt="LINQ Basic to Advanced SelectMany Tooltip" width="634" height="104" class="size-full wp-image-12377" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-Tooltip-e1494746794913.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-Tooltip-e1494746794913-300x49.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-Tooltip-e1494746794913-400x66.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12377" class="wp-caption-text">LINQ Basic to Advanced SelectMany Tooltip</p></div></p>
<p>If you use the normal Select, you will be getting a list of lists, thus you will have to use two loops to get the datas.</p>
<p><div id="attachment_12378" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Select-Tooltip-e1494746906690.png"><img decoding="async" aria-describedby="caption-attachment-12378" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Select-Tooltip-e1494746906690.png" alt="LINQ Basic to Advanced Select Tooltip" width="634" height="83" class="size-full wp-image-12378" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Select-Tooltip-e1494746906690.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Select-Tooltip-e1494746906690-300x39.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Select-Tooltip-e1494746906690-400x52.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12378" class="wp-caption-text">LINQ Basic to Advanced Select Tooltip</p></div></p>
<p>[csharp]<br />
 /// &lt;summary&gt;<br />
        /// Linq query with SelectMany<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult SelectMany()<br />
        {<br />
            var selectMany = DtContext.Orders.SelectMany(order =&gt; order.Invoices).Take(10);<br />
            var select = DtContext.Orders.Select(order =&gt; order.Invoices).Take(10);<br />
            return PartialView(&quot;SelectMany&quot;, selectMany);<br />
        }<br />
[/csharp]</p>
<p>Let&#8217;s see the view now. </p>
<p>[html]<br />
@model IQueryable&lt;LINQ_B_to_A.Models.Invoice&gt;<br />
&lt;style&gt;<br />
    td, th, thead, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    caption {<br />
        background-color: #a9a9a9<br />
    }</p>
<p>    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;</p>
<p>&lt;table&gt;<br />
    &lt;caption&gt;Invoice Details&lt;/caption&gt;<br />
    &lt;tr&gt;<br />
        &lt;th&gt;Order ID&lt;/th&gt;<br />
        &lt;th&gt;Invoice ID&lt;/th&gt;<br />
        &lt;th&gt;Invoice Date&lt;/th&gt;<br />
    &lt;/tr&gt;<br />
    @foreach (var @item in Model)<br />
    {<br />
        &lt;tr&gt;<br />
            &lt;td&gt;@item.OrderID&lt;/td&gt;<br />
            &lt;td&gt;@item.InvoiceID&lt;/td&gt;<br />
            &lt;td&gt;@item.InvoiceDate&lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    }<br />
&lt;/table&gt;<br />
&lt;caption&gt;Select Many&lt;/caption&gt;<br />
&lt;pre&gt;<br />
     /// &lt;summary&gt;<br />
        /// Linq query with SelectMany<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult SelectMany()<br />
        {<br />
            var selectMany = DtContext.Orders.SelectMany(order =&gt; order.Invoices).Take(10);<br />
            var select = DtContext.Orders.Select(order =&gt; order.Invoices).Take(10);<br />
            return PartialView(&quot;SelectMany&quot;, selectMany);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>Now see the result.</p>
<p>That&#8217;s all for today, I will come with another set of LINQ queries in the next part. Till then, bye.</p>
<p><div id="attachment_12379" style="width: 952px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-e1494747140197.png"><img decoding="async" aria-describedby="caption-attachment-12379" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-e1494747140197.png" alt="LINQ Basic to Advanced SelectMany" width="942" height="597" class="size-full wp-image-12379" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-e1494747140197.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-e1494747140197-300x190.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-e1494747140197-400x254.png 400w" sizes="(max-width: 942px) 100vw, 942px" /></a><p id="caption-attachment-12379" class="wp-caption-text">LINQ Basic to Advanced SelectMany</p></div></p>
<h3>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>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://mail.sibeeshpassion.com/linq-basic-to-advanced-mvc-demo-application/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>WCF Service Unit Tests Using NUnit With Rhino Mocks And Entity Framework</title>
		<link>https://mail.sibeeshpassion.com/wcf-service-unit-tests-using-nunit-with-rhino-mocks-and-entity-framework/</link>
					<comments>https://mail.sibeeshpassion.com/wcf-service-unit-tests-using-nunit-with-rhino-mocks-and-entity-framework/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 20 Nov 2016 13:58:15 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[NUnit Tests]]></category>
		<category><![CDATA[NUnit With Rhino Mocks]]></category>
		<category><![CDATA[Rhino Mocks]]></category>
		<category><![CDATA[WCF]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11929</guid>

					<description><![CDATA[In this post we will see how we can write unit test cases for our WCF Service with a framework called NUnit. We will also be covering how to mock our dependencies in our test, here we wil be using Rhino Mocks. I am going to use Visual Studio 2015 for the development. I hope you will like this article. Download source code WCF_NUnit_Tests_Rhino_Mocks.zip Background As a developer, we all writes lots of codes in our day to day life. Am I right? It is more important to check whether the codes we have written works well. So for that [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will see how we can write unit test cases for our <a href="http://sibeeshpassion.com/category/WCF-Service/" target="_blank" rel="noopener">WCF Service</a> with a framework called NUnit. We will also be covering how to mock our dependencies in our test, here we wil be using Rhino Mocks. I am going to use <a href="http://sibeeshpassion.com/category/visual-studio/" target="_blank" rel="noopener">Visual Studio</a> 2015 for the development. I hope you will like this article. </p>
<p><strong>Download source code</strong></p>
<li>
<a href="https://code.msdn.microsoft.com/WCF-Service-Unit-Tests-f1fcedff" target="_blank" rel="noopener">WCF_NUnit_Tests_Rhino_Mocks.zip</a>
</li>
<p><strong>Background</strong></p>
<p>As a developer, we all writes lots of codes in our day to day life. Am I right? It is more important to check whether the codes we have written works well. So for that we developer usually do unit testing, few developers are doing a manual testing to just check whether the functionality is working or not. I would say that it is wrong. In a TDD (Test Driven Development) unit testing is very important, where we actually writes the test cases before we start our coding. Let us see what exactly the &#8220;Unit Tesing&#8221; is. </p>
<p><strong>Unit Testing</strong></p>
<p>Unit testing is the process of testing a unit, it can be a class, a block of codde, function, a property. We can easily test our units independently. In <a href="http://sibeeshpassion.com/category/asp-net/">dot net</a> we have so many frameworks to do unit testing. But here we are going to use NUnit which I found very easy to write tests. </p>
<blockquote><p>If you have Resharper installed in your machine, it will be more easier to execute and debug your tests. Here I am using Resharper in my Visual Studio, so the screenshots will be based on that. Thank you</p></blockquote>
<p>Now it is time to set up our project and start our coding.</p>
<p><strong>Setting up the project</strong></p>
<p>To get started, please create an empty project in your Visual Studio. </p>
<p><div id="attachment_11904" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Empty_Project-e1475921231766.png"><img decoding="async" aria-describedby="caption-attachment-11904" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Empty_Project-e1475921231766.png" alt="empty_project" width="650" height="507" class="size-full wp-image-11904" srcset="/wp-content/uploads/2016/10/Empty_Project-e1475921231766.png 458w, /wp-content/uploads/2016/10/Empty_Project-e1475921231766-300x234.png 300w, /wp-content/uploads/2016/10/Empty_Project-e1475921231766-400x312.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11904" class="wp-caption-text">empty_project</p></div></p>
<p>Now, we will add a <a href="http://sibeeshpassion.com/category/WCF-Service/" target="_blank" rel="noopener">WCF Service</a> as follows. </p>
<p><div id="attachment_11930" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Create_a_wcf_service.png"><img decoding="async" aria-describedby="caption-attachment-11930" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Create_a_wcf_service-1024x709.png" alt="create_a_wcf_service" width="634" height="439" class="size-large wp-image-11930" srcset="/wp-content/uploads/2016/11/Create_a_wcf_service-1024x709.png 1024w, /wp-content/uploads/2016/11/Create_a_wcf_service-300x208.png 300w, /wp-content/uploads/2016/11/Create_a_wcf_service-768x532.png 768w, /wp-content/uploads/2016/11/Create_a_wcf_service-160x110.png 160w, /wp-content/uploads/2016/11/Create_a_wcf_service-400x277.png 400w, /wp-content/uploads/2016/11/Create_a_wcf_service-866x600.png 866w, /wp-content/uploads/2016/11/Create_a_wcf_service.png 1178w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11930" class="wp-caption-text">create_a_wcf_service</p></div></p>
<p>Once you are done, you can see two files, an Interface(IMyService) and a class (MyService) with .svc extension. If you are completely new to WCF service, I strongly recommend you to read some basics <a href="https://msdn.microsoft.com/en-us/library/bb386386.aspx" target="_blank" rel="noopener">here</a>.</p>
<p>Now, it is time to set up our database and insert some data. </p>
<p><strong>Creating database</strong></p>
<p>Here I am creating a database with name &#8220;TrialDB&#8221;, you can always create a DB by running the query given below. </p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialDB]    Script Date: 20-11-2016 03:54:53 PM ******/<br />
CREATE DATABASE [TrialDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB.mdf&#8217; , SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB_log.ldf&#8217; , SIZE = 8192KB , MAXSIZE = 2048GB , FILEGROWTH = 65536KB )<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET COMPATIBILITY_LEVEL = 130<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET RECOVERY SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET TARGET_RECOVERY_TIME = 60 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DELAYED_DURABILITY = DISABLED<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET QUERY_STORE = OFF<br />
GO</p>
<p>USE [TrialDB]<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET PARAMETER_SNIFFING = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET QUERY_OPTIMIZER_HOTFIXES = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p><strong>Create a table and insert data in database</strong></p>
<p>To create a table, you can run the query below.</p>
<p>[sql]<br />
USE [TrialDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[Course]    Script Date: 20-11-2016 03:57:30 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[Course](<br />
	[CourseID] [int] NOT NULL,<br />
	[CourseName] [nvarchar](50) NOT NULL,<br />
	[CourseDescription] [nvarchar](100) NULL,<br />
 CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED<br />
(<br />
	[CourseID] 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 can insert few data to our newly created table. </p>
<p>[sql]<br />
USE [TrialDB]<br />
GO</p>
<p>INSERT INTO [dbo].[Course]<br />
           ([CourseID]<br />
           ,[CourseName]<br />
           ,[CourseDescription])<br />
     VALUES<br />
           (1<br />
           ,&#8217;C#&#8217;<br />
           ,&#8217;Learn C# in 7 days&#8217;)<br />
 INSERT INTO [dbo].[Course]<br />
           ([CourseID]<br />
           ,[CourseName]<br />
           ,[CourseDescription])<br />
     VALUES<br />
           (2<br />
           ,&#8217;Asp.Net&#8217;<br />
           ,&#8217;Learn Asp.Net in 7 days&#8217;)<br />
INSERT INTO [dbo].[Course]<br />
           ([CourseID]<br />
           ,[CourseName]<br />
           ,[CourseDescription])<br />
     VALUES<br />
           (3<br />
           ,&#8217;SQL&#8217;<br />
           ,&#8217;Learn SQL in 7 days&#8217;)<br />
INSERT INTO [dbo].[Course]<br />
           ([CourseID]<br />
           ,[CourseName]<br />
           ,[CourseDescription])<br />
     VALUES<br />
           (4<br />
           ,&#8217;JavaScript&#8217;<br />
           ,&#8217;Learn JavaScript in 7 days&#8217;)<br />
GO<br />
[/sql]</p>
<p>So our data is ready, that means we are all set to write our service and tests. Now go to your solution and create an entity data model. </p>
<p><div id="attachment_11931" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Entity_Framework-e1479637932362.png"><img decoding="async" aria-describedby="caption-attachment-11931" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Entity_Framework-e1479637932362.png" alt="entity_framework" width="634" height="686" class="size-full wp-image-11931" srcset="/wp-content/uploads/2016/11/Entity_Framework-e1479637932362.png 330w, /wp-content/uploads/2016/11/Entity_Framework-e1479637932362-277x300.png 277w, /wp-content/uploads/2016/11/Entity_Framework-e1479637932362-400x433.png 400w, /wp-content/uploads/2016/11/Entity_Framework-e1479637932362-555x600.png 555w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11931" class="wp-caption-text">entity_framework</p></div></p>
<p>So entity is also been created. Now please open your interface and that is where we start our coding. We can change the interface as follows. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Runtime.Serialization;<br />
using System.ServiceModel;<br />
using System.Text;</p>
<p>namespace WCF_NUnit_Tests_Rheno_Mocks<br />
{<br />
    [ServiceContract]<br />
    public interface IMyService<br />
    {<br />
        [OperationContract]<br />
        Course GetCourseById(int courseId);<br />
        [OperationContract]<br />
        List&lt;Course&gt; GetAllCourses();<br />
    }<br />
}<br />
[/csharp]</p>
<p>Here we have created two operations, one to get a course by id and one to retrieve all the courses as a list. Now please go and implement these two operations in our service file. You can modify that class as follows. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Runtime.Serialization;<br />
using System.ServiceModel;<br />
using System.Text;</p>
<p>namespace WCF_NUnit_Tests_Rheno_Mocks<br />
{<br />
    public class MyService : IMyService<br />
    {<br />
        private static MyEntity _myContext;<br />
        private static IMyService _myIService;</p>
<p>        public MyService()<br />
        {</p>
<p>        }</p>
<p>        public MyService(IMyService myIService)<br />
        {<br />
            _myContext = new MyEntity();<br />
            _myIService = myIService;<br />
        }<br />
        public Course GetCourseById(int courseId)<br />
        {<br />
            var crse = _myContext.Courses.FirstOrDefault(dt =&gt; dt.CourseID == courseId);<br />
            return crse;<br />
        }</p>
<p>        public List&lt;Course&gt; GetAllCourses()<br />
        {<br />
            var courses = (from dt in _myContext.Courses select dt).ToList();<br />
            return courses;<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>In the above code, as you can see we are creating two constructor one is without parameter and other is with parameter, and we are having IMyService as a parameter. In this way we can achieve the dependency injection when we write tests for our unit. So what we need to do all is, just pass the dependency, in this case it is IMyService.</p>
<blockquote><p>In software engineering, dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. Source: WikiPedia</p></blockquote>
<p>If you need to know more on dependency injection, please read <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection" target="_blank" rel="noopener">here</a>. Now we will build and check whether our service is working fine or not. Please press CTRL+F5.</p>
<p><div id="attachment_11932" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Invoking_WCF_Service.png"><img decoding="async" aria-describedby="caption-attachment-11932" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Invoking_WCF_Service-e1479645357913.png" alt="invoking_wcf_service" width="634" height="403" class="size-full wp-image-11932" srcset="/wp-content/uploads/2016/11/Invoking_WCF_Service-e1479645357913.png 634w, /wp-content/uploads/2016/11/Invoking_WCF_Service-e1479645357913-300x191.png 300w, /wp-content/uploads/2016/11/Invoking_WCF_Service-e1479645357913-400x254.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11932" class="wp-caption-text">invoking_wcf_service</p></div></p>
<p>As our services are ready, we can now create the tests for those operations. For that we can create a new class library in our project and name it <em>UnitTest.Service</em>. Please add a class <em>MyServiceTests</em> in the class library where we can add our tests. And please do not forget to add our application reference too. </p>
<p><div id="attachment_11939" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Add_project_reference-e1479647898141.png"><img decoding="async" aria-describedby="caption-attachment-11939" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Add_project_reference-e1479647898141.png" alt="add_project_reference" width="634" height="438" class="size-full wp-image-11939" srcset="/wp-content/uploads/2016/11/Add_project_reference-e1479647898141.png 634w, /wp-content/uploads/2016/11/Add_project_reference-e1479647898141-300x207.png 300w, /wp-content/uploads/2016/11/Add_project_reference-e1479647898141-160x110.png 160w, /wp-content/uploads/2016/11/Add_project_reference-e1479647898141-400x276.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11939" class="wp-caption-text">add_project_reference</p></div></p>
<p><strong>Installing and configuring NUnit</strong></p>
<p>Now we can install NUnit to our test project from NuGet Package. Once you add the package, you will be able to add the preceding namespace in our <em>MyServiceTests</em> class.</p>
<p>[csharp]<br />
using NUnit.Framework;<br />
[/csharp]</p>
<p>In NUnit we have so many attributes that can be used for different purposes, but now we are going to use only four among them.</p>
<li>TestFixture</li>
<p><div id="attachment_11934" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/TestFixture_In_NUnit-e1479646568966.png"><img decoding="async" aria-describedby="caption-attachment-11934" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/TestFixture_In_NUnit-e1479646568966.png" alt="testfixture_in_nunit" width="634" height="191" class="size-full wp-image-11934" srcset="/wp-content/uploads/2016/11/TestFixture_In_NUnit-e1479646568966.png 634w, /wp-content/uploads/2016/11/TestFixture_In_NUnit-e1479646568966-300x90.png 300w, /wp-content/uploads/2016/11/TestFixture_In_NUnit-e1479646568966-400x121.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11934" class="wp-caption-text">testfixture_in_nunit</p></div></p>
<li>OneTimeSetUp</li>
<p><div id="attachment_11935" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit.png"><img decoding="async" aria-describedby="caption-attachment-11935" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit-1024x283.png" alt="one_time_setup_attribute_in_nunit" width="634" height="175" class="size-large wp-image-11935" srcset="/wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit-1024x283.png 1024w, /wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit-300x83.png 300w, /wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit-768x212.png 768w, /wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit-400x110.png 400w, /wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit.png 1337w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11935" class="wp-caption-text">one_time_setup_attribute_in_nunit</p></div></p>
<p>In previous versions, we were using <em>TestFixtureSetUp</em>, as the TestFixtureSetUp is obsolete, now we are using <em>OneTimeSetUp</em></p>
<p><div id="attachment_11937" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/TestFixtureSetUp_attribute_is_obsolete-e1479646895142.png"><img decoding="async" aria-describedby="caption-attachment-11937" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/TestFixtureSetUp_attribute_is_obsolete-e1479646895142.png" alt="testfixturesetup_attribute_is_obsolete" width="634" height="213" class="size-full wp-image-11937" srcset="/wp-content/uploads/2016/11/TestFixtureSetUp_attribute_is_obsolete-e1479646895142.png 634w, /wp-content/uploads/2016/11/TestFixtureSetUp_attribute_is_obsolete-e1479646895142-300x101.png 300w, /wp-content/uploads/2016/11/TestFixtureSetUp_attribute_is_obsolete-e1479646895142-400x134.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11937" class="wp-caption-text">testfixturesetup_attribute_is_obsolete</p></div></p>
<li>TearDown</li>
<p>This attribute is used to identify a method that is called immediately after each tests, it will be called even if there is any error, this is the place we can dispose our objects. </p>
<li>Test</li>
<p>This attribute is used to make a method callable from NUnit test runner. This can not be inherited. </p>
<p>Now we can see all these attributes in action. So let us write some tests, but the real problem is we need to mock the IMyService right as the parameterized constructor of the class <em>MyService </em> expecting it. Remember, we have discussed about setting up our services in the way which can be injected the dependencies? No worries, we can install Rhino Mock for that now. </p>
<p><div id="attachment_11938" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1.png"><img decoding="async" aria-describedby="caption-attachment-11938" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1-1024x573.png" alt="rhino_mocks_in_nuget_package" width="634" height="355" class="size-large wp-image-11938" srcset="/wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1-1024x573.png 1024w, /wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1-300x168.png 300w, /wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1-768x429.png 768w, /wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1-400x224.png 400w, /wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1-1073x600.png 1073w, /wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1.png 1486w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11938" class="wp-caption-text">rhino_mocks_in_nuget_package</p></div></p>
<p>So we can add the tests are dependencies as follows in our test class.</p>
<p>[csharp]<br />
using NUnit.Framework;<br />
using Rhino.Mocks;<br />
using WCF_NUnit_Tests_Rhino_Mocks;</p>
<p>namespace UnitTest.Service<br />
{<br />
    [TestFixture]<br />
    public class MyServiceTests<br />
    {<br />
        private static MyService _myService;<br />
        private IMyService _myIservice;<br />
        [OneTimeSetUp]<br />
        public void SetUp()<br />
        {<br />
            _myIservice = MockRepository.GenerateMock&lt;IMyService&gt;();<br />
            _myService = new MyService(_myIservice);</p>
<p>        }</p>
<p>        [TearDown]<br />
        public void Clean()<br />
        {</p>
<p>        }</p>
<p>        [Test(Description = &quot;A test to check whether the returned value is null&quot;)]<br />
        public void GetCourseById_Return_NotNull_Pass()<br />
        {<br />
            //Set Up<br />
            var crs = new Course<br />
            {<br />
                CourseID = 1,<br />
                CourseName = &quot;C#&quot;,<br />
                CourseDescription = &quot;Learn course in 7 days&quot;<br />
            };<br />
            _myIservice.Stub(dt =&gt; dt.GetCourseById(1)).IgnoreArguments().Return(crs);</p>
<p>            //Act<br />
            crs = _myService.GetCourseById(1);</p>
<p>            //Assert<br />
            Assert.IsNotNull(crs,&quot;The returned value is null&quot;);<br />
        }</p>
<p>        [Test(Description = &quot;A test to check we get all the courses&quot;)]<br />
        public void GetAllCourses_Return_List_Count_Pass()<br />
        {<br />
            //Act<br />
            var crs = _myService.GetAllCourses();</p>
<p>            //Assert<br />
            Assert.AreEqual(4, crs.Count,&quot;The count of retrieved data doesn&#8217;t match&quot;);<br />
            _myIservice.VerifyAllExpectations();<br />
        }</p>
<p>    }<br />
}<br />
[/csharp]</p>
<p>As you can see we have mocked our IMyService as follows. </p>
<p>[csharp]<br />
_myIservice = MockRepository.GenerateMock&lt;IMyService&gt;();<br />
[/csharp]</p>
<p><div id="attachment_11940" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Generate_Mock_With_Rhino.png"><img decoding="async" aria-describedby="caption-attachment-11940" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Generate_Mock_With_Rhino-1024x247.png" alt="generate_mock_with_rhino" width="634" height="153" class="size-large wp-image-11940" srcset="/wp-content/uploads/2016/11/Generate_Mock_With_Rhino-1024x247.png 1024w, /wp-content/uploads/2016/11/Generate_Mock_With_Rhino-300x72.png 300w, /wp-content/uploads/2016/11/Generate_Mock_With_Rhino-768x185.png 768w, /wp-content/uploads/2016/11/Generate_Mock_With_Rhino-400x97.png 400w, /wp-content/uploads/2016/11/Generate_Mock_With_Rhino.png 1131w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11940" class="wp-caption-text">generate_mock_with_rhino</p></div></p>
<p>And, in the test <em>GetCourseById_Return_NotNull_Pass</em> we have also used a method called <em>Stub</em>. Stub actually tell the mock object to perform a certain action when a matching method is called, and it doesn&#8217;t create an expectation for the same. So you might be thinking, how can we create an expectation? For that we have a method called <em>Expect</em>.</p>
<p><div id="attachment_11941" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Expect_In_Rhino_Mock.png"><img decoding="async" aria-describedby="caption-attachment-11941" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Expect_In_Rhino_Mock-e1479648794975.png" alt="expect_in_rhino_mock" width="634" height="149" class="size-full wp-image-11941" srcset="/wp-content/uploads/2016/11/Expect_In_Rhino_Mock-e1479648794975.png 634w, /wp-content/uploads/2016/11/Expect_In_Rhino_Mock-e1479648794975-300x71.png 300w, /wp-content/uploads/2016/11/Expect_In_Rhino_Mock-e1479648794975-400x94.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11941" class="wp-caption-text">expect_in_rhino_mock</p></div></p>
<p>It is always recommended to verify your expectation when you use <em>Expect</em> as we used it in our test <em>GetAllCourses_Return_List_Count_Pass</em>.</p>
<p>[csharp]<br />
_myIservice.VerifyAllExpectations();<br />
[/csharp]</p>
<p>As I already said, I am using Resharper, we have so many shortcuts to run our tests, now if you right click on your <em>TestFixture</em>. You can see a run all option as preceding.</p>
<p><div id="attachment_11942" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Run_all_test_option_in_Resharper-e1479649326532.png"><img decoding="async" aria-describedby="caption-attachment-11942" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Run_all_test_option_in_Resharper-e1479649326532.png" alt="run_all_test_option_in_resharper" width="634" height="574" class="size-full wp-image-11942" srcset="/wp-content/uploads/2016/11/Run_all_test_option_in_Resharper-e1479649326532.png 394w, /wp-content/uploads/2016/11/Run_all_test_option_in_Resharper-e1479649326532-300x272.png 300w, /wp-content/uploads/2016/11/Run_all_test_option_in_Resharper-e1479649326532-400x362.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11942" class="wp-caption-text">run_all_test_option_in_resharper</p></div></p>
<blockquote><p>As I was getting an error as &#8220;No connection string named &#8216;Entity&#8217; could be found in the application config file.&#8221; when I run the tests, I was forced to install the entity framework in my test project and also add a new config file with the connection string like we have in our web config file. </p></blockquote>
<p>If everything goes fine and you don&#8217;t have any errors, I am sure you will get a screen as preceding. </p>
<p><div id="attachment_11943" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/NUnit_Output.png"><img decoding="async" aria-describedby="caption-attachment-11943" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/NUnit_Output-1024x288.png" alt="nunit_output" width="634" height="178" class="size-large wp-image-11943" srcset="/wp-content/uploads/2016/11/NUnit_Output-1024x288.png 1024w, /wp-content/uploads/2016/11/NUnit_Output-300x84.png 300w, /wp-content/uploads/2016/11/NUnit_Output-768x216.png 768w, /wp-content/uploads/2016/11/NUnit_Output-400x112.png 400w, /wp-content/uploads/2016/11/NUnit_Output.png 1206w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11943" class="wp-caption-text">nunit_output</p></div></p>
<p>Happy coding!.</p>
<p><strong>See also</strong></p>
<li><a href="https://msdn.microsoft.com/en-us/library/ms182532.aspx" target="_blank" rel="noopener">Walkthrough: Creating and Running Unit Tests for Managed Code</a></li>
<li><a href="https://www.nunit.org/" target="_blank" rel="noopener">NUnit</a></li>
<li><a href="https://www.hibernatingrhinos.com/oss/rhino-mocks" target="_blank" rel="noopener">Rhino Mocks</a></li>
<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’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://mail.sibeeshpassion.com/wcf-service-unit-tests-using-nunit-with-rhino-mocks-and-entity-framework/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Encrypt And Decrypt ConnectionString In Web.Config File</title>
		<link>https://mail.sibeeshpassion.com/encrypt-and-decrypt-connectionstring-in-web-config-file/</link>
					<comments>https://mail.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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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://mail.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://mail.sibeeshpassion.com/working-with-api-help-page-controller-action-description-in-web-api/</link>
					<comments>https://mail.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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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://mail.sibeeshpassion.com/working-with-api-help-page-controller-action-description-in-web-api/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Web API With HttpClient Or Consume Web API From Console Application</title>
		<link>https://mail.sibeeshpassion.com/web-api-with-httpclient-or-consume-web-api-from-console-application/</link>
					<comments>https://mail.sibeeshpassion.com/web-api-with-httpclient-or-consume-web-api-from-console-application/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 28 Mar 2016 00:00:37 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[AspNet]]></category>
		<category><![CDATA[HttpClient]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Web API And HttpClient]]></category>
		<category><![CDATA[Web API In Console Application]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11424</guid>

					<description><![CDATA[In this article, we are going to learn how we can call Web API using HttpClient. Normally we call a Web API either from a jQuery Ajax or from Angular JS right? Recently I came across a need of calling our Web API from the server-side itself. Here I am going to use two Visual Studio applications. One is our normal Web API application in which I have a Web API controller and actions, another one is a console application where I consume my Web API. Sounds good? I am using Visual Studio 2015. You can always get the tips/tricks/blogs [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this article, we are going to learn how we can call Web API using HttpClient. Normally we call a Web API either from a jQuery Ajax or from Angular JS right? Recently I came across a need of calling our Web API from the server-side itself. Here I am going to use two Visual Studio applications. One is our normal Web API application in which I have a Web API controller and actions, another one is a console application where I consume my Web API. Sounds good? I am using Visual Studio 2015. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below.</p>



<ul class="wp-block-list"><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></ul>



<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>



<ul class="wp-block-list"><li><a href="https://github.com/SibeeshVenu/WebAPI-HttpClient" target="_blank" rel="noreferrer noopener">Web API Application and Consumer</a></li></ul>



<p><strong>Background</strong></p>



<p>We all use Web API in our applications to implement HTTP services. HTTP services are much simpler than ever if we use Web API. But the fact is, the benefits of a Web API is not limited to that. Previously we use WCF services instead of Web API, where we were working with endpoints and all. Here I am going to explain an important feature of a Web API that we can call Web API from our server itself instead of using an Ajax Call. That is pretty cool, right? Now we will create our application.</p>



<p>First, we will create our Web API application.</p>



<p><strong>Creating Web API application</strong></p>



<p>Click File-&gt; New-&gt; Project then select MVC application. We will select the template as empty from the following pop-up and select the core references and folders for MVC.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png"><img decoding="async" width="650" height="484" 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" class="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><figcaption>Empty Template With MVC And Web API Folders</figcaption></figure>



<p>Once you click OK, a project with MVC like folder structure with core references will be created for you.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png"><img decoding="async" width="267" height="367" 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" class="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><figcaption>Folder Structure And References For Empty MVC Project</figcaption></figure>



<p><strong>Using the code</strong></p>



<p>We will set up our database first so that we can create an 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>



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



<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 the database</strong></p>



<p>Below is the query to create the table <em>tblTags</em>.</p>



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



<p>Can we insert some data into the tables now?</p>



<p><strong>Insert data to the table</strong></p>



<p>You can use the below query to insert the data to the table <em>tblTags</em></p>



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



<p>The next thing we are going to do is creating an 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 Dashboard for our Entity data model name. Now you can see a file with an edmx extension has 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 -&gt; Controller -&gt; Select Web API 2 controller with actions, using Entity Framework.</p>



<figure class="wp-block-image 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" width="650" height="448" 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" class="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><figcaption>Web API 2 Controller With Actions Using Entity Framework</figcaption></figure>



<p>Now select <em>tblTag (WebAPIWithHttpClient.Models)</em> as our Model class and <em>TrialsDBEntities (WebAPIWithHttpClient.Models)</em> as data context class. This time we will select controller with async actions.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-Controller-With-Async-Actions.png"><img decoding="async" width="593" height="233" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-Controller-With-Async-Actions.png" alt="Web API Controller With Async Actions" class="wp-image-11425" srcset="/wp-content/uploads/2016/03/Web-API-Controller-With-Async-Actions.png 593w, /wp-content/uploads/2016/03/Web-API-Controller-With-Async-Actions-300x118.png 300w, /wp-content/uploads/2016/03/Web-API-Controller-With-Async-Actions-400x157.png 400w" sizes="(max-width: 593px) 100vw, 593px" /></a><figcaption>Web API Controller With Async Actions</figcaption></figure>



<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>



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



<p>As you can see, we have actions for,</p>



<ul class="wp-block-list"><li>Get</li><li>Post</li><li>Put</li><li>Delete</li></ul>



<p>So the coding part to fetch the data from the 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:7967/api/tbltags</em>. Here <em>tblTags</em> is our Web API controller name. I hope you get the data as a result.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png"><img decoding="async" width="650" height="342" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png" alt="Web_API_Result" class="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><figcaption>Web_API_Result</figcaption></figure>



<p>As of now, our Web API application is ready, and we have just tested whether it is working or not. Now we can move on to create a console application where we can consume this Web API with the help of HttpClient. So shall we do that?</p>



<p><strong>Create Console Application To Consume Web API</strong></p>



<p>To create a console application, Click File -&gt; New -&gt; Click Windows -&gt; Select Console application -&gt; Name your application -&gt; OK</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Console-Application-e1458836504170.png"><img decoding="async" width="650" height="396" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Console-Application-e1458836504170.png" alt="Console Application" class="wp-image-11426" srcset="/wp-content/uploads/2016/03/Console-Application-e1458836504170.png 650w, /wp-content/uploads/2016/03/Console-Application-e1458836504170-300x183.png 300w, /wp-content/uploads/2016/03/Console-Application-e1458836504170-400x244.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Console Application</figcaption></figure>



<p>I hope now you have a class called Program. cs with the below codes.</p>



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



<p>Now we will start our coding, We will create a class called <em>tblTag </em>with some properties so that we can use those when we need them.</p>



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



<p>To get started using the class <em>HttpClient</em>, you must import the namespace as follows.</p>



<pre class="wp-block-code"><code>using System.Net.Http;</code></pre>



<p>Once you have imported the namespaces, we will set our HttpClient and the properties as follows.</p>



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



<p>As you can see we are just giving the base address of our API and setting the response header. Now we will create an async action to get the data from our database by calling our Web API.</p>



<p><strong>Get operation using HttpClient</strong></p>



<pre class="wp-block-code"><code>MyAPIGet(cons).Wait();</code></pre>



<p>Following is the definition of the <em>MyAPIGet </em>function.</p>



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



<p>Here <em>res.EnsureSuccessStatusCode();</em> ensure that it throws errors if we get any. If you don&#8217;t need to throw the errors, please remove this line of code. If the async call is a success, the value in <em>IsSuccessStatusCode</em> will be true.</p>



<p>Now when you run the above code, there are chances to get an error as follows.</p>



<p><em>Error CS1061 &#8216;HttpContent&#8217; does not contain a definition for &#8216;ReadAsAsync&#8217; and no extension method &#8216;ReadAsAsync&#8217; accepting a first argument of type &#8216;HttpContent&#8217; could be found (are you missing a using directive or an assembly reference?)</em></p>



<p>This is just because the <em>ReadAsAsync</em> is a part of <em>System.Net.Http.Formatting.dll</em> which we have not added to our application as a reference yet. Now we will do that? Sounds OK?</p>



<p>Just right click on the references and click add reference -&gt; Click browse -&gt; search for <em>System.Net.Http.Formatting.dll</em> &#8211; Click OK</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Add-References-e1458838521697.png"><img decoding="async" width="650" height="447" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Add-References-e1458838521697.png" alt="Add References" class="wp-image-11427" srcset="/wp-content/uploads/2016/03/Add-References-e1458838521697.png 650w, /wp-content/uploads/2016/03/Add-References-e1458838521697-300x206.png 300w, /wp-content/uploads/2016/03/Add-References-e1458838521697-160x110.png 160w, /wp-content/uploads/2016/03/Add-References-e1458838521697-400x275.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Add References</figcaption></figure>



<p>Please add <em>Newtonsoft.Json</em> also. Now let us run our project and see our output.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Get_Output1-e1458882223957.png"><img decoding="async" width="650" height="328" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Get_Output1-e1458882223957.png" alt="Web_API_Consumer_Get_Output" class="wp-image-11429" srcset="/wp-content/uploads/2016/03/Web_API_Consumer_Get_Output1-e1458882223957.png 650w, /wp-content/uploads/2016/03/Web_API_Consumer_Get_Output1-e1458882223957-300x151.png 300w, /wp-content/uploads/2016/03/Web_API_Consumer_Get_Output1-e1458882223957-400x202.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Web_API_Consumer_Get_Output</figcaption></figure>



<p>Now shall we create a function for updating the record? Yes, we are going to create a function with the &#8216;Put&#8217; request. Please copy and paste the preceding code for that.</p>



<p><strong>Put operation using HttpClient</strong></p>



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



<p>As you can see, we are updating the record as below once we get the response from <em>await cons.GetAsync(&#8220;api/tblTags/2&#8221;)</em> .</p>



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



<p>Again, run your application and check whether the tag name has been changed to &#8216;New Tag&#8217;.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Put_Output-e1458882875423.png"><img decoding="async" width="650" height="328" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Put_Output-e1458882875423.png" alt="Web_API_Consumer_Put_Output" class="wp-image-11430" srcset="/wp-content/uploads/2016/03/Web_API_Consumer_Put_Output-e1458882875423.png 650w, /wp-content/uploads/2016/03/Web_API_Consumer_Put_Output-e1458882875423-300x151.png 300w, /wp-content/uploads/2016/03/Web_API_Consumer_Put_Output-e1458882875423-400x202.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Web_API_Consumer_Put_Output</figcaption></figure>



<p>Now did you see that your tag name has been changed? If yes, we are ready to go for our next operation. Are you ready?</p>



<p><strong>Delete operation using HttpClient</strong></p>



<p>We will follow the same procedure for delete operation too. Please see the code for the delete operation below.</p>



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



<p>To delete a record we uses <em> res = await cons.DeleteAsync(&#8220;api/tblTags/2&#8221;);</em> method. Now run your application and see the result.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Delete_Output-e1458883191973.png"><img decoding="async" width="650" height="328" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Delete_Output-e1458883191973.png" alt="Web_API_Consumer_Delete_Output" class="wp-image-11431" srcset="/wp-content/uploads/2016/03/Web_API_Consumer_Delete_Output-e1458883191973.png 650w, /wp-content/uploads/2016/03/Web_API_Consumer_Delete_Output-e1458883191973-300x151.png 300w, /wp-content/uploads/2016/03/Web_API_Consumer_Delete_Output-e1458883191973-400x202.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Web_API_Consumer_Delete_Output</figcaption></figure>



<p>What action is pending now? Yes, it is Post.</p>



<p><strong>Post-operation using HttpClient</strong></p>



<p>Please add the below function to your project for the post-operation.</p>



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



<p>We are just creating a new tblTag and assign some values, once the object is ready we are calling the method PostAsJsonAsync as follows.</p>



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



<p>As you have noticed, I have not provided the <em>tagId</em> in the object, do you know why? I have already set Identity Specification with Identity Increment 1 in my table tblTags in the SQL database.</p>



<p>Now we will see the output. Shall we?</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Post_Output-e1458883741126.png"><img decoding="async" width="650" height="328" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Post_Output-e1458883741126.png" alt="Web_API_Consumer_Post_Output" class="wp-image-11432" srcset="/wp-content/uploads/2016/03/Web_API_Consumer_Post_Output-e1458883741126.png 650w, /wp-content/uploads/2016/03/Web_API_Consumer_Post_Output-e1458883741126-300x151.png 300w, /wp-content/uploads/2016/03/Web_API_Consumer_Post_Output-e1458883741126-400x202.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Web_API_Consumer_Post_Output</figcaption></figure>



<p>We have done everything!. That&#8217;s fantastic right? Have a happy coding.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>You can always use WebClient also for this requirement, that I will share in an another article.</p></blockquote>



<p><strong>Conclusion</strong></p>



<p>Did I miss anything that you may think is needed? Did you try Web API yet? Have you ever wanted to call a Web API from the server itself or any console application? Could you find this post 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://mail.sibeeshpassion.com/web-api-with-httpclient-or-consume-web-api-from-console-application/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Caching In Web API</title>
		<link>https://mail.sibeeshpassion.com/caching-in-web-api/</link>
					<comments>https://mail.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>
<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>
<p>Once you click OK, a project with MVC like folder structure with core references will be created for you.</p>
<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>
<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>
<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>
<p>Now click on the browse button, and search for <em>System.Runtime.Caching</em></p>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<p>As you can see there are four possible settings we can set in <em>MemoryCache </em> class.</p>
<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>
<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>
<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>
<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>
<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>
<p>You can see that we are setting the value to memCache as the <em>memCache.Get(&#8220;tag&#8221;)</em> is null. </p>
<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>
<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>
<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>
<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://mail.sibeeshpassion.com/caching-in-web-api/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Angular JS AutoComplete In MVC With Web API</title>
		<link>https://mail.sibeeshpassion.com/angular-js-autocomplete-in-mvc-with-web-api/</link>
					<comments>https://mail.sibeeshpassion.com/angular-js-autocomplete-in-mvc-with-web-api/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 24 Mar 2016 00:00:33 +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[Angular JS AutoComplete]]></category>
		<category><![CDATA[AutoComplete]]></category>
		<category><![CDATA[Autocomplete With Web API]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11393</guid>

					<description><![CDATA[In this article we will learn how we can create Angular JS autoComplete text box 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. 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. I hope you will like this. Download the source code You can always download [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we will learn how we can create Angular JS autoComplete text box 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. 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/Angular-JS-AutoComplete-In-96a92c45" target="_blank" rel="noopener">Angular JS Autocomplete In MVC</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>For the past few days I am experiment few things in Angular JS. Here we are going to see a demo of how to use Angular JS autocomplete in MVC with Web API to fetch the data from database. Once we are done, this is how our applications output will be. </p>
<p><div id="attachment_11394" style="width: 435px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_.png"><img decoding="async" aria-describedby="caption-attachment-11394" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_.png" alt="Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_" width="425" height="266" class="size-full wp-image-11394" srcset="/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_.png 425w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_-300x188.png 300w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_-400x250.png 400w" sizes="(max-width: 425px) 100vw, 425px" /></a><p id="caption-attachment-11394" class="wp-caption-text">Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_</p></div></p>
<p><div id="attachment_11395" style="width: 437px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_.png"><img decoding="async" aria-describedby="caption-attachment-11395" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_.png" alt="Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_" width="427" height="361" class="size-full wp-image-11395" srcset="/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_.png 427w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_-300x254.png 300w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_-400x338.png 400w" sizes="(max-width: 427px) 100vw, 427px" /></a><p id="caption-attachment-11395" class="wp-caption-text">Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_</p></div></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>
<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>
<p>Once you click OK, a project with MVC like folder structure with core references will be created for you.</p>
<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>
<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>
<p><div id="attachment_11407" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Manage-NuGet-Package-Window-e1458712083925.png"><img decoding="async" aria-describedby="caption-attachment-11407" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Manage-NuGet-Package-Window-1024x407.png" alt="Manage NuGet Package Window" width="634" height="252" class="size-large wp-image-11407" /></a><p id="caption-attachment-11407" class="wp-caption-text">Manage NuGet Package Window</p></div></p>
<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 I am going to create a script file called <em>Home.js</em> in which we will write our scripts. Sounds good? 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>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>Products </em></p>
<p><strong>Create tables in database</strong></p>
<p>Below is the query to create the table Product.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[Product]<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 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 run 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>
<p><div id="attachment_11400" style="width: 274px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Entity-Data-Model-Product-Table.png"><img decoding="async" aria-describedby="caption-attachment-11400" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Entity-Data-Model-Product-Table.png" alt="Entity Data Model Product Table" width="264" height="663" class="size-full wp-image-11400" srcset="/wp-content/uploads/2016/03/Entity-Data-Model-Product-Table.png 264w, /wp-content/uploads/2016/03/Entity-Data-Model-Product-Table-119x300.png 119w, /wp-content/uploads/2016/03/Entity-Data-Model-Product-Table-239x600.png 239w" sizes="(max-width: 264px) 100vw, 264px" /></a><p id="caption-attachment-11400" class="wp-caption-text">Entity Data Model Product Table</p></div></p>
<p>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>
<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>
<p>Now select <em>Product (AngularJSAutocompleteInMVCWithWebAPI.Models)</em> as our Model class and <em>TrialsDBEntities (AngularJSAutocompleteInMVCWithWebAPI.Models)</em> as data context class. </p>
<p><div id="attachment_11402" style="width: 635px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Model-Class-And-Data-Context-Class.png"><img decoding="async" aria-describedby="caption-attachment-11402" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Model-Class-And-Data-Context-Class.png" alt="Model Class And Data Context Class" width="625" height="267" class="size-full wp-image-11402" srcset="/wp-content/uploads/2016/03/Model-Class-And-Data-Context-Class.png 625w, /wp-content/uploads/2016/03/Model-Class-And-Data-Context-Class-300x128.png 300w, /wp-content/uploads/2016/03/Model-Class-And-Data-Context-Class-400x171.png 400w" sizes="(max-width: 625px) 100vw, 625px" /></a><p id="caption-attachment-11402" class="wp-caption-text">Model Class And Data Context Class</p></div></p>
<p>As you can see It has been given the name of our controller as <em>Products</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 AngularJSAutocompleteInMVCWithWebAPI.Models;</p>
<p>namespace AngularJSAutocompleteInMVCWithWebAPI.Controllers<br />
{<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 />
}<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.</p>
<p>[csharp]<br />
 // GET: api/Products<br />
        public IQueryable&lt;Product&gt; GetProducts()<br />
        {<br />
            return db.Products;<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:9038/api/products</em>. Here <em>products</em> is our Web API controller name. I hope you get the data as a result.</p>
<p><div id="attachment_11403" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-Result-e1458710180875.png"><img decoding="async" aria-describedby="caption-attachment-11403" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-Result-e1458710180875.png" alt="Web API Result" width="650" height="588" class="size-full wp-image-11403" srcset="/wp-content/uploads/2016/03/Web-API-Result-e1458710180875.png 650w, /wp-content/uploads/2016/03/Web-API-Result-e1458710180875-300x271.png 300w, /wp-content/uploads/2016/03/Web-API-Result-e1458710180875-400x362.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11403" class="wp-caption-text">Web API Result</p></div></p>
<p>Now we will go back to our angular JS file and consume this Web API. You need to change the scripts in the <em>Home.js</em> as follows.</p>
<p>[js]<br />
(function () {<br />
    &#8216;use strict&#8217;;<br />
    angular<br />
        .module(&#8216;MyApp&#8217;, [&#8216;ngMaterial&#8217;, &#8216;ngMessages&#8217;, &#8216;material.svgAssetsCache&#8217;])<br />
        .controller(&#8216;AutoCompleteCtrl&#8217;, AutoCompleteCtrl);<br />
    function AutoCompleteCtrl($http, $timeout, $q, $log) {<br />
        var self = this;<br />
        self.simulateQuery = true;<br />
        self.products = loadAllProducts($http);<br />
        self.querySearch = querySearch;<br />
        function querySearch(query) {<br />
            var results = query ? self.products.filter(createFilterFor(query)) : self.products, deferred;<br />
            if (self.simulateQuery) {<br />
                deferred = $q.defer();<br />
                $timeout(function () { deferred.resolve(results); }, Math.random() * 1000, false);<br />
                return deferred.promise;<br />
            } else {<br />
                return results;<br />
            }<br />
        }<br />
        function loadAllProducts($http) {<br />
            var allProducts = [];<br />
            var url = &#8221;;<br />
            var result = [];<br />
            url = &#8216;api/products&#8217;;<br />
            $http({<br />
                method: &#8216;GET&#8217;,<br />
                url: url,<br />
            }).then(function successCallback(response) {<br />
                allProducts = response.data;<br />
                angular.forEach(allProducts, function (product, key) {<br />
                    result.push(<br />
                        {<br />
                            value: product.Name.toLowerCase(),<br />
                            display: product.Name<br />
                        });<br />
                });<br />
            }, function errorCallback(response) {<br />
                console.log(&#8216;Oops! Something went wrong while fetching the data. Status Code: &#8216; + response.status + &#8216; Status statusText: &#8216; + response.statusText);<br />
            });<br />
            return result;<br />
        }<br />
        function createFilterFor(query) {<br />
            var lowercaseQuery = angular.lowercase(query);<br />
            return function filterFn(product) {<br />
                return (product.value.indexOf(lowercaseQuery) === 0);<br />
            };</p>
<p>        }<br />
    }<br />
})();<br />
[/js]</p>
<p>Here <em>MyApp</em> is our module name and <em>AutoCompleteCtrl</em> is our controller name. The function  <em>loadAllProducts</em> is for loading the products from database using <a href="http://sibeeshpassion.com/learning-angularjs-http/" target="_blank" rel="noopener">$http in Angular JS</a>. </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. We will loop through the same using <em>angular.forEach</em> and format as needed.</p>
<p>[js]<br />
angular.forEach(allProducts, function (product, key) {<br />
                    result.push(<br />
                        {<br />
                            value: product.Name.toLowerCase(),<br />
                            display: product.Name<br />
                        });<br />
                });<br />
[/js]</p>
<p>The function <em>querySearch</em> will be called when ever user search for any particular products. This we will call from the view as follows. </p>
<p>[html]<br />
md-items=&quot;item in ctrl.querySearch(ctrl.searchText)&quot;<br />
[/html]</p>
<p>Now we need 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 AngularJSAutocompleteInMVCWithWebAPI.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>
<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>
<p>Now in your view add the needed references.</p>
<p>[html]<br />
&lt;script src=&quot;~/scripts/angular.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-route.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-aria.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-animate.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-messages.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-material.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/svg-assets-cache.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/Home.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Once we add the references, we can call our Angular JS controller and change the view code as follows.</p>
<p>[html]<br />
&lt;div ng-controller=&quot;AutoCompleteCtrl as ctrl&quot; layout=&quot;column&quot; ng-cloak=&quot;&quot; class=&quot;autocompletedemoBasicUsage&quot; ng-app=&quot;MyApp&quot; style=&quot;width: 34%;&quot;&gt;<br />
    &lt;md-content class=&quot;md-padding&quot;&gt;<br />
        &lt;form ng-submit=&quot;$event.preventDefault()&quot;&gt;<br />
            &lt;md-autocomplete md-no-cache=&quot;false&quot; md-selected-item=&quot;ctrl.selectedItem&quot; md-search-text=&quot;ctrl.searchText&quot; md-items=&quot;item in ctrl.querySearch(ctrl.searchText)&quot; md-item-text=&quot;item.display&quot; md-min-length=&quot;0&quot; placeholder=&quot;Search for products here!.&quot;&gt;<br />
                &lt;md-item-template&gt;<br />
                    &lt;span md-highlight-text=&quot;ctrl.searchText&quot; md-highlight-flags=&quot;^i&quot;&gt;{{item.display}}&lt;/span&gt;<br />
                &lt;/md-item-template&gt;<br />
                &lt;md-not-found&gt;<br />
                    No matching &quot;{{ctrl.searchText}}&quot; were found.<br />
                &lt;/md-not-found&gt;<br />
            &lt;/md-autocomplete&gt;<br />
        &lt;/form&gt;<br />
    &lt;/md-content&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p>Here <em>md-autocomplete</em> will cache the result we gets from database to avoid the unwanted hits to the database. This we can disable/enable by the help of <em>md-no-cache</em>. Now if you run your application, you can see our Web API call works fine and successfully get the data. But the page looks clumsy right? For this you must add a style sheet <em>angular-material.css</em>.</p>
<p>[html]<br />
&lt;link href=&quot;~/Content/angular-material.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
[/html]</p>
<p>Now run your page again, I am sure you will get the output as follows. </p>
<p><strong>Output</strong></p>
<p><div id="attachment_11394" style="width: 435px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_.png"><img decoding="async" aria-describedby="caption-attachment-11394" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_.png" alt="Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_" width="425" height="266" class="size-full wp-image-11394" srcset="/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_.png 425w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_-300x188.png 300w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_-400x250.png 400w" sizes="(max-width: 425px) 100vw, 425px" /></a><p id="caption-attachment-11394" class="wp-caption-text">Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_</p></div></p>
<p><div id="attachment_11395" style="width: 437px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_.png"><img decoding="async" aria-describedby="caption-attachment-11395" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_.png" alt="Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_" width="427" height="361" class="size-full wp-image-11395" srcset="/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_.png 427w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_-300x254.png 300w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_-400x338.png 400w" sizes="(max-width: 427px) 100vw, 427px" /></a><p id="caption-attachment-11395" class="wp-caption-text">Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_</p></div></p>
<p>We have done everything!. That&#8217;s fantastic right? Have a happy coding.</p>
<p><em>Reference</em></p>
<li><a href="https://material.angularjs.org" target="_blank" rel="noopener">Angular JS Materials</a></li>
<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://mail.sibeeshpassion.com/angular-js-autocomplete-in-mvc-with-web-api/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Chart Widgets With Server Side Data In MVC Using Angular JS And Web API</title>
		<link>https://mail.sibeeshpassion.com/chart-widgets-with-server-side-data-in-mvc-using-angular-js-and-web-api/</link>
					<comments>https://mail.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>
<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>
<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>
<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>
<p>Once you click OK, a project with MVC like folder structure with core references will be created for you.</p>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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://mail.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>Programmatically Extract or Unzip Zip,Rar Files And Check</title>
		<link>https://mail.sibeeshpassion.com/programmatically-extract-or-unzip-ziprar-files-and-check/</link>
					<comments>https://mail.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://mail.sibeeshpassion.com/programmatically-extract-or-unzip-ziprar-files-and-check/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>
