<?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>CSharp &#8211; Sibeesh Passion</title>
	<atom:link href="https://sibeeshpassion.com/tag/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>https://sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:17:39 +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>CSharp &#8211; Sibeesh Passion</title>
	<link>https://sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>LINQ Basic To Advanced &#8211; MVC Demo Application</title>
		<link>https://sibeeshpassion.com/linq-basic-to-advanced-mvc-demo-application/</link>
					<comments>https://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>
<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 fetchpriority="high" 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>
<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>
<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>
<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>
<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>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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>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>
<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>[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>
<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>
<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://sibeeshpassion.com/linq-basic-to-advanced-mvc-demo-application/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Programmatically Extract or Unzip Zip,Rar Files And Check</title>
		<link>https://sibeeshpassion.com/programmatically-extract-or-unzip-ziprar-files-and-check/</link>
					<comments>https://sibeeshpassion.com/programmatically-extract-or-unzip-ziprar-files-and-check/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 25 Feb 2016 00:00:22 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Extract Files]]></category>
		<category><![CDATA[HttpFileCollectionBase]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[System.IO.Compression]]></category>
		<category><![CDATA[System.IO.Compression.FileSystem]]></category>
		<category><![CDATA[Unzip Files]]></category>
		<category><![CDATA[Upload in MVC]]></category>
		<category><![CDATA[ZipArchive]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11281</guid>

					<description><![CDATA[In this pose we will see how we can extract or unzip the uploaded files and check for some files in it in a in a programmatic manner. We will use a normal MVC application to work with this demo. We will use Microsoft System.IO.Compression, System.IO.Compression.FileSystem namespaces and the classes, for example ZipArchive, in the namespace for extracting or unzipping the files we upload. Once it is uploaded we will check the same by looping through it. For the client side coding, we uses jQuery. I guess this is enough for the introduction, now we will move on to our [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this pose we will see how we can extract or unzip the uploaded files and check for some files in it in a in a programmatic manner. We will use a normal <a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC</a> application to work with this demo. We will use Microsoft System.IO.Compression, System.IO.Compression.FileSystem namespaces and the classes, for example ZipArchive, in the namespace for extracting or unzipping the files we upload. Once it is uploaded we will check the same by looping through it. For the client side coding, we uses <a href="http://sibeeshpassion.com/category/jQuery/" target="_blank" rel="noopener">jQuery</a>. I guess this is enough for the introduction, now we will move on to our application. Let us create it. I hope you will like this article. </p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here: 	</p>
<li><a href="https://gallery.technet.microsoft.com/Programmatically-Extract-0544debd" target="_blank" rel="noopener">Programmatically Extract or Unzip Zip,Rar Files And Check</a></li>
<p><strong>Background</strong></p>
<p>As you are aware most websites accepts only .zip or any other zipped formats, this is for ensuring that only less amount of data is being uploaded to the server. We can reduce almost 60 percentage of the size if we zipped the same. Now the problem is, how you can validate any zipped item which is uploaded to your site? How can you check for any particular file in that zipped item? For example if you need to find out any files with extension of .sql, .ico or .txt? What if you want to intimate user that the uploaded items does not have any particular file that must be needed? You need to loop through the contents available in it right? This is what we are going to discuss in this post. I had a situation of uploading my old back ups of my personal website (<a href="http://sibeeshpassion.com/" target="_blank" rel="noopener">http://sibeeshpassion.com/</a>) and after uploading I wanted to check whether the uploaded .zip file has .ico file in it. The process we are going to do is listed below.</p>
<li>Create a MVC application</li>
<li>Install jQuery</li>
<li>Create Controller and View</li>
<li>Upload Action Using jQuery</li>
<li>Add System.IO.Compression, System.IO.Compression.FileSystem references</li>
<li>Checks for the file using ZipArchive class</li>
<p><strong>Using the code</strong></p>
<p>Now we will move into the coding part. I hope your MVC application is ready for action 🙂 with all the needed packages. </p>
<p><strong>Create a controller</strong></p>
<p>Now we will create a controller, view with an action in it as follows. </p>
<p>[csharp]<br />
public ActionResult Index()<br />
        {<br />
            return View();<br />
        }<br />
[/csharp]</p>
<p><strong>Update the view</strong></p>
<p>Now in the view, we will add a file upload and other needed elements. </p>
<p>[html]<br />
&lt;input type=&quot;file&quot; name=&quot;FileUpload1&quot; id=&quot;fileUpload&quot; placeholder=&quot;Please select the file&quot; /&gt;&lt;br /&gt;<br />
&lt;input id=&quot;btnUploadFile&quot; type=&quot;button&quot; value=&quot;Upload File&quot; /&gt;<br />
&lt;div id=&quot;message&quot;&gt;&lt;/div&gt;<br />
[/html]</p>
<p><strong>Add the JS references</strong></p>
<p>Add the references as follows.</p>
<p>[html]<br />
&lt;script src=&quot;~/scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/MyScript.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Here <em>MyScript.js</em> is where we are going to write some scripts. </p>
<p><strong>Style the elements (Optional) </strong></p>
<p>You can style your view as follows. This step is absolutely optional, for me the view should not as simple as default one. And to be frank I am not a good designer 🙂</p>
<p>[css]<br />
&lt;style&gt;<br />
    #fileUpload {<br />
        border: 1px solid #ccc;<br />
        padding: 10px;<br />
        border-radius: 5px;<br />
        font-size: 14px;<br />
        font-family: cursive;<br />
        color: blue;<br />
    }</p>
<p>    #btnUploadFile {<br />
        border: 1px solid #ccc;<br />
        padding: 10px;<br />
        border-radius: 5px;<br />
        font-size: 14px;<br />
        font-family: cursive;<br />
        color: blue;<br />
    }</p>
<p>    #message {<br />
        border-radius: 5px;<br />
        font-size: 14px;<br />
        font-family: cursive;<br />
        color: blue;<br />
        margin-top: 15px;<br />
    }<br />
    h2 {<br />
        border-radius: 5px;<br />
        font-size: 20px;<br />
        font-family: cursive;<br />
        color: blue;<br />
        margin-top: 15px;<br />
    }<br />
&lt;/style&gt;<br />
[/css]</p>
<p><strong>Add the upload action in script</strong></p>
<p>Now it is time to create upload action. For that, please go to the script file MyScript.js and do the coding as follows. </p>
<p>[js]<br />
$(document).ready(function () {<br />
    $(&#8216;#btnUploadFile&#8217;).on(&#8216;click&#8217;, function () {<br />
        var data = new FormData();<br />
        var files = $(&quot;#fileUpload&quot;).get(0).files;<br />
        // Add the uploaded image content to the form data collection<br />
        if (files.length &gt; 0) {<br />
            data.append(&quot;UploadedImage&quot;, files[0]);<br />
        }<br />
        // Make Ajax request with the contentType = false, and procesDate = false<br />
        var ajaxRequest = $.ajax({<br />
            type: &quot;POST&quot;,<br />
            url: &quot;Home/Upload&quot;,<br />
            contentType: false,<br />
            processData: false,<br />
            data: data,<br />
            success: function (data) {<br />
                $(&#8216;#message&#8217;).html(data);<br />
            },<br />
            error: function (e)<br />
            {<br />
                console.log(&#8216;Oops, Something went wrong!.&#8217; + e.message);<br />
            }<br />
        });<br />
        ajaxRequest.done(function (xhr, textStatus) {<br />
            // Do other operation<br />
        });<br />
    });<br />
});<br />
[/js]</p>
<p>If you are not aware of uploading and downloading in MVC, I strongly recommend you to have a look here: <a href="http://sibeeshpassion.com/uploading-and-downloading-in-mvc-step-by-step/" target="_blank" rel="noopener">Uploading and Downloading in MVC Step-by-Step</a>. </p>
<p>So we have set Home/Upload as the URL action in our <a href="http://sibeeshpassion.com/tag/jquery-ajax/" target="_blank" rel="noopener">Ajax</a> function right? So we are going to create that action. Go to your controller and create a JsonResult action as follows. </p>
<p>[csharp]<br />
public JsonResult Upload()<br />
        {<br />
            string isValid = checkIsValid(Request.Files);<br />
            return Json(isValid, JsonRequestBehavior.AllowGet);<br />
        }<br />
[/csharp]</p>
<p>So we have done that too, now stop for a while. To work with <em>ZipArchive</em> class you must include the namespace as listed below. </p>
<p>[csharp]<br />
using System.IO.Compression;<br />
[/csharp]</p>
<p>Now you will be shown an error as &#8220;Are you missing an assembly reference?&#8221;. Yes we are. We have not added that references right? So now we are going to add the references for System.IO.Compression and System.IO.Compression.FileSystem. </p>
<p>Right click on Reference in your project and browse for the references. If you uses Visual Studio 2015, the references will be in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6. </p>
<blockquote><p>Please be noted that the folder names will differs according to your framework version</p></blockquote>
<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>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>
<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>
<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>
<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><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/programmatically-extract-or-unzip-ziprar-files-and-check/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Using MVC Grid In MVC</title>
		<link>https://sibeeshpassion.com/using-mvc-grid-in-mvc/</link>
					<comments>https://sibeeshpassion.com/using-mvc-grid-in-mvc/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Fri, 11 Dec 2015 00:00:15 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MVC Grid]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Products]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10981</guid>

					<description><![CDATA[In this post we will see how we can develop a MVC grid in our MVC application. There are so many grids are available in the industries, most of them are useful. Here we are going to use a grid called MVC grid, which uses bootstrap and jQuery. We will create some dynamic data using list first, once it is done, we will send this data to the MVC grid. Sounds good? I hope you will like this article. Download Source Code Using MVC Grid In MVC Background I have been working with the Grid controls for a long long [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will see how we can develop a MVC grid in our <a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC </a>application. There are so many grids are available in the industries, most of them are useful. Here we are going to use a grid called MVC grid, which uses bootstrap and <a href="http://sibeeshpassion.com/category/jQuery/" target="_blank" rel="noopener">jQuery</a>. We will create some dynamic data using list first, once it is done, we will send this data to the MVC grid. Sounds good? I hope you will like this article. </p>
<p><strong>Download Source Code</strong></p>
<li><a href="https://code.msdn.microsoft.com/Using-MVC-Grid-In-MVC-4111f300" target="_blank" rel="noopener">Using MVC Grid In MVC</a></li>
<p><strong>Background</strong></p>
<p>I have been working with the Grid controls for a long long time. So far I have worked with jQX Grid, jQ Grid, jQuery Datatables, Pivot tables, KO grid etc. It is always interesting to work with some controls. I always loved it. recently I worked with MVC grid. So I thought of sharing that experience with you all. </p>
<p><strong>Create a MVC application</strong></p>
<p>First, we will start with creating an MVC application. Open your visual studio, then click File->New->Project. Name your project. </p>
<p><strong>Install MVC Grid</strong></p>
<p>The next step we are going to do is, installing the MVC grid to our project. To install, please right click your solution and click on Manage NuGet packages. </p>
<div id="attachment_10982" style="width: 469px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/11/Select_NuGet_Package.png"><img decoding="async" aria-describedby="caption-attachment-10982" src="http://sibeeshpassion.com/wp-content/uploads/2015/11/Select_NuGet_Package.png" alt="Select NuGet Package" width="459" height="673" class="size-full wp-image-10982" srcset="/wp-content/uploads/2015/11/Select_NuGet_Package.png 459w, /wp-content/uploads/2015/11/Select_NuGet_Package-205x300.png 205w, /wp-content/uploads/2015/11/Select_NuGet_Package-400x586.png 400w, /wp-content/uploads/2015/11/Select_NuGet_Package-409x600.png 409w" sizes="(max-width: 459px) 100vw, 459px" /></a><p id="caption-attachment-10982" class="wp-caption-text">Select NuGet Package</p></div>
<p>Now you can see a new window, please search for MVC grid in the search box. And then click Install. </p>
<div id="attachment_10983" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/11/Install_MVC_Grid_To_Project-e1448285055873.png"><img decoding="async" aria-describedby="caption-attachment-10983" src="http://sibeeshpassion.com/wp-content/uploads/2015/11/Install_MVC_Grid_To_Project-e1448285055873.png" alt="Install_MVC_Grid_To_Project" width="650" height="433" class="size-full wp-image-10983" srcset="/wp-content/uploads/2015/11/Install_MVC_Grid_To_Project-e1448285055873.png 650w, /wp-content/uploads/2015/11/Install_MVC_Grid_To_Project-e1448285055873-300x200.png 300w, /wp-content/uploads/2015/11/Install_MVC_Grid_To_Project-e1448285055873-400x266.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10983" class="wp-caption-text">Install_MVC_Grid_To_Project</p></div>
<p>Once you installed, you can see there is a new reference file has been added(GridMVC), you can also notice that two views are created (_Grig.cshtml,_GridPager.cshtml) and one CSS file and some scripts. Now we will move to our next step.</p>
<p><strong>Dependencies </strong></p>
<p>As I said before, MVC grid uses bootstrap for design. So the next thing we need to is to install bootstrap in our project. For that, go to NuGet packages again and search for bootstrap.</p>
<div id="attachment_10984" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/11/Install_Bootstrap_To_Project-e1448285364634.png"><img decoding="async" aria-describedby="caption-attachment-10984" src="http://sibeeshpassion.com/wp-content/uploads/2015/11/Install_Bootstrap_To_Project-e1448285364634.png" alt="Install_Bootstrap_To_Project" width="650" height="433" class="size-full wp-image-10984" srcset="/wp-content/uploads/2015/11/Install_Bootstrap_To_Project-e1448285364634.png 650w, /wp-content/uploads/2015/11/Install_Bootstrap_To_Project-e1448285364634-300x200.png 300w, /wp-content/uploads/2015/11/Install_Bootstrap_To_Project-e1448285364634-400x266.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10984" class="wp-caption-text">Install_Bootstrap_To_Project</p></div>
<p>You can see some new CSS files and scripts has been added to our project. So the set up has been done. Now what we need to do is to move on the coding part. </p>
<p><strong>Create a controller </strong></p>
<p>Now we can create a new controller, in my case I created a controller &#8216;HomeController&#8217;. In my controller I am going to call a model action which will return some dynamic data. See the code below. </p>
<p>[csharp]<br />
public class HomeController : Controller<br />
    {<br />
        //<br />
        // GET: /Home/</p>
<p>        public ActionResult Index()<br />
        {<br />
            Test t = new Test();<br />
            var myList= t.GetData();<br />
            return View(myList);<br />
        }</p>
<p>    }<br />
[/csharp]</p>
<p>As you can see I am creating an instance of my model Test, now we will create our model class. Shall we?</p>
<p><strong>Create Model </strong></p>
<p>I have create a model class with the name Test. Here I am creating some data dynamically using a for loop and assign those values to a list. Please see the codes below. </p>
<p>[csharp]<br />
namespace AsyncActions.Models<br />
{<br />
    public class Test<br />
    {<br />
        public List&lt;Customer&gt; GetData()<br />
        {<br />
            try<br />
            {<br />
                List&lt;Customer&gt; cst = new List&lt;Customer&gt;();<br />
                for (int i = 0; i &lt; 100; i++)<br />
                {<br />
                    Customer c = new Customer();<br />
                    c.CustomerID = i;<br />
                    c.CustomerCode = &quot;CST&quot; + i;<br />
                    cst.Add(c);<br />
                }<br />
                return cst;<br />
            }<br />
            catch (Exception)<br />
            {<br />
                throw new NotImplementedException();<br />
            }</p>
<p>        }<br />
    }<br />
    public class Customer<br />
    {<br />
        public int CustomerID { get; set; }<br />
        public string CustomerCode { get; set; }<br />
    }<br />
}<br />
[/csharp]</p>
<p>As you can see I am creating a list of type Customer. Is that fine? Now what is pending? Yes, a view.</p>
<p><strong>Create a strongly typed view</strong></p>
<p>Now we are going to create a strongly typed view. </p>
<div id="attachment_10985" style="width: 519px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/11/Create_Strongly_Typed_View.png"><img decoding="async" aria-describedby="caption-attachment-10985" src="http://sibeeshpassion.com/wp-content/uploads/2015/11/Create_Strongly_Typed_View.png" alt="Create_Strongly_Typed_View" width="509" height="502" class="size-full wp-image-10985" srcset="/wp-content/uploads/2015/11/Create_Strongly_Typed_View.png 509w, /wp-content/uploads/2015/11/Create_Strongly_Typed_View-300x296.png 300w, /wp-content/uploads/2015/11/Create_Strongly_Typed_View-400x394.png 400w" sizes="(max-width: 509px) 100vw, 509px" /></a><p id="caption-attachment-10985" class="wp-caption-text">Create_Strongly_Typed_View</p></div>
<blockquote><p>When you create a view as strongly typed view, your view header will be as follows. @model List<AsyncActions.Models.Customer></p></blockquote>
<p>So our view is ready, now we can do some codes in our view to populate our grid. Are you ready? First thing is you need to include the needed references to our view, you can do this in the file called Layout.cshtml. Here I am going to add those references directly to the view.</p>
<p>[html]<br />
&lt;link href=&quot;~/Content/bootstrap-theme.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
&lt;link href=&quot;~/Content/bootstrap.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
&lt;script src=&quot;~/Scripts/jquery-2.1.3.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;link href=&quot;~/Content/Gridmvc.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
&lt;script src=&quot;~/Scripts/gridmvc.min.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p><strong>Add the grid namespace</strong></p>
<p>You can add the grid namespace as follows.</p>
<p>[html]<br />
@using GridMvc.Html<br />
[/html]</p>
<p>Next thing is to add grid implementation.</p>
<p><strong>MVC Grid Implementation</strong></p>
<p>To add a MVC grid as our requirement, you need to add the codes as below. </p>
<p>[csharp]<br />
@Html.Grid(Model).Columns(columns =&gt;<br />
           {<br />
               columns.Add(foo =&gt; foo.CustomerID).Titled(&quot;Customer ID&quot;).SetWidth(50).Sortable(true).Filterable(true);<br />
               columns.Add(foo =&gt; foo.CustomerCode).Titled(&quot;Customer Code&quot;).SetWidth(50).Sortable(true).Filterable(true);<br />
           }).WithPaging(20)</p>
<p>[/csharp]</p>
<p>As you can see we are using the columns Customer.CustomerID and Customer.CustomerCode. </p>
<p><strong>Output</strong></p>
<div id="attachment_10986" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/11/MVC_Grid_With_Dynamic_Data.png"><img decoding="async" aria-describedby="caption-attachment-10986" src="http://sibeeshpassion.com/wp-content/uploads/2015/11/MVC_Grid_With_Dynamic_Data-1024x518.png" alt="MVC_Grid_With_Dynamic_Data" width="634" height="321" class="size-large wp-image-10986" srcset="/wp-content/uploads/2015/11/MVC_Grid_With_Dynamic_Data-1024x518.png 1024w, /wp-content/uploads/2015/11/MVC_Grid_With_Dynamic_Data-300x152.png 300w, /wp-content/uploads/2015/11/MVC_Grid_With_Dynamic_Data-768x389.png 768w, /wp-content/uploads/2015/11/MVC_Grid_With_Dynamic_Data-400x203.png 400w, /wp-content/uploads/2015/11/MVC_Grid_With_Dynamic_Data-1185x600.png 1185w, /wp-content/uploads/2015/11/MVC_Grid_With_Dynamic_Data.png 1918w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-10986" class="wp-caption-text">MVC_Grid_With_Dynamic_Data</p></div>
<p><strong>Add more Grid features</strong></p>
<p><em>To set the paging </em> we can use the option <em>WithPaging(20)</em>.<br />
<em>To add title</em> we can use <em>Titled</em> property.<br />
<em>To set width</em> we can use <em>SetWidth</em> property.<br />
<em>To set sort</em> we can use <em>Sortable</em> property.<br />
<em>To set filter</em> we can use <em>Filterable</em> property.</p>
<p>You can always see the additional options <a href="https://gridmvc.codeplex.com/documentation" target="_blank" rel="noopener">here </a>.</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’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/using-mvc-grid-in-mvc/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Convert Data Reader To Datatable</title>
		<link>https://sibeeshpassion.com/convert-data-reader-to-datatable/</link>
					<comments>https://sibeeshpassion.com/convert-data-reader-to-datatable/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Tue, 17 Nov 2015 09:45:56 +0000</pubDate>
				<category><![CDATA[Microsoft ADOMD]]></category>
		<category><![CDATA[SSAS]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Data reader]]></category>
		<category><![CDATA[Data reader to Data table]]></category>
		<category><![CDATA[Generate table schema]]></category>
		<category><![CDATA[GetSchemaTable]]></category>
		<category><![CDATA[LoadDataRow]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10968</guid>

					<description><![CDATA[In this article we will learn how we can convert Microsoft ADOMD data reader to datatable. As you all know a data reader is the most efficient way for looping through the data. Performance wise a data reader is faster than any of the other way like data adapter and cell set in MDX result. So in few situations you may need to convert this data reader to a data table. Here in this post we will discuss how we can convert it. I hope you will like it. Background For the past few months I have been working with [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we will learn how we can convert Microsoft ADOMD data reader to datatable. As you all know a data reader is the most efficient way for looping through the data. Performance wise a data reader is faster than any of the other way like data adapter and cell set in MDX result. So in few situations you may need to convert this data reader to a data table. Here in this post we will discuss how we can convert it. I hope you will like it.</p>
<p><strong>Background</strong></p>
<p>For the past few months I have been working with Microsoft ADOMD data sources. And I have written some article also that will describe the problems I have encountered so far. If you are new to ADOMD I strongly recommend that read my previous articles that you may find useful when you work with ADOMD data sources. You can find those article links here: <a href="http://sibeeshpassion.com/category/microsoft-adomd/" target="_blank">ADOMD Data Sources </a></p>
<p><strong>Why </strong></p>
<p>You might think, why I am not using other two ways (data adapter and cell set). I will answer it here. I am handling large set of data, so when I use data adapter and cell set it was bit slow to get the output. So I was just checking the performance by using data reader. It was fast enough when I use data reader. So we can order these three as following by performance.</p>
<blockquote><p>Data reader >> Data Adapter >> Cell Set</p></blockquote>
<p><strong>Using the code</strong></p>
<p>The following is the function that does what was explained above.</p>
<p>[csharp]<br />
 #region Convert Datareader toDatatable<br />
        /// &lt;summary&gt;<br />
        /// Convert Datareader toDatatable<br />
        /// &lt;/summary&gt;<br />
        /// &lt;param name=&quot;query&quot;&gt;&lt;/param&gt;<br />
        /// &lt;param name=&quot;myConnection&quot;&gt;&lt;/param&gt;<br />
        public DataTable ConvertDataReaderToDataTable(string query, string myConnection)<br />
        {<br />
            AdomdConnection conn = new AdomdConnection(myConnection);<br />
            try<br />
            {<br />
                try<br />
                {<br />
                    conn.Open();<br />
                }<br />
                catch (Exception)<br />
                {<br />
                }<br />
                using (AdomdCommand cmd = new AdomdCommand(query, conn))<br />
                {<br />
                    AdomdDataReader rdr;<br />
                    cmd.CommandTimeout = connectionTimeout;<br />
                    using (AdomdDataAdapter ad = new AdomdDataAdapter(cmd))<br />
                    {<br />
                        DataTable dtData = new DataTable(&quot;Data&quot;);<br />
                        DataTable dtSchema = new DataTable(&quot;Schema&quot;);<br />
                        rdr = cmd.ExecuteReader();<br />
                        if (rdr != null)<br />
                        {<br />
                            dtSchema = rdr.GetSchemaTable();<br />
                            foreach (DataRow schemarow in dtSchema.Rows)<br />
                            {<br />
                                dtData.Columns.Add(schemarow.ItemArray[0].ToString(), System.Type.GetType(schemarow.ItemArray[5].ToString()));<br />
                            }<br />
                            while (rdr.Read())<br />
                            {<br />
                                object[] ColArray = new object[rdr.FieldCount];<br />
                                for (int i = 0; i &lt; rdr.FieldCount; i++)<br />
                                {<br />
                                    if (rdr[i] != null) ColArray[i] = rdr[i];<br />
                                }<br />
                                dtData.LoadDataRow(ColArray, true);<br />
                            }<br />
                            rdr.Close();<br />
                        }<br />
                        return dtData;<br />
                    }<br />
                }<br />
            }</p>
<p>            catch (Exception)<br />
            {<br />
                throw;<br />
            }<br />
            finally<br />
            {<br />
                conn.Close(false);<br />
            }<br />
        }<br />
        #endregion;<br />
[/csharp]</p>
<p>Here we are creating two data table dtData and dtSchema where dtData is for binding the data and dtSchema is for binding the schema.</p>
<p><em>Creating data tables</em></p>
<p>[csharp]<br />
 DataTable dtData = new DataTable(&quot;Data&quot;);<br />
                        DataTable dtSchema = new DataTable(&quot;Schema&quot;);<br />
[/csharp]</p>
<p><em>Execute data reader</em></p>
<p>Now we will execute the reader as follows.</p>
<p>[csharp]<br />
rdr = cmd.ExecuteReader();<br />
[/csharp]</p>
<p><em>Get the schema</em></p>
<p>To generate the schema, we can call the function GetSchemaTable() which is a part of your data reader.</p>
<blockquote><p>To use this function, you must include Microsoft.AnalysisServices.AdomdClient.dll</p></blockquote>
<p><em>Adding the columns headers to the dtData</em></p>
<p>The next thing is to add the header names to the data table dtData.</p>
<p>[csharp]<br />
foreach (DataRow schemarow in dtSchema.Rows)<br />
                            {<br />
                                dtData.Columns.Add(schemarow.ItemArray[0].ToString(), System.Type.GetType(schemarow.ItemArray[5].ToString()));<br />
                            }<br />
[/csharp]</p>
<p><em>Load the data to dtData </em></p>
<p>To load the data, we are using a function LoadDataRow() which expects an object as parameter. This will find and updates a specific row, if the matching row is not found, it will create an another row with the given values. </p>
<div id="attachment_10969" style="width: 608px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/11/Convert_data_reader_to_data_table.png"><img decoding="async" aria-describedby="caption-attachment-10969" src="http://sibeeshpassion.com/wp-content/uploads/2015/11/Convert_data_reader_to_data_table.png" alt="Convert data reader to data table" width="598" height="150" class="size-full wp-image-10969" srcset="/wp-content/uploads/2015/11/Convert_data_reader_to_data_table.png 598w, /wp-content/uploads/2015/11/Convert_data_reader_to_data_table-300x75.png 300w, /wp-content/uploads/2015/11/Convert_data_reader_to_data_table-400x100.png 400w" sizes="(max-width: 598px) 100vw, 598px" /></a><p id="caption-attachment-10969" class="wp-caption-text">Convert data reader to data table</p></div>
<p>[csharp]<br />
object[] ColArray = new object[rdr.FieldCount];<br />
                                for (int i = 0; i &lt; rdr.FieldCount; i++)<br />
                                {<br />
                                    if (rdr[i] != null) ColArray[i] = rdr[i];<br />
                                }<br />
                                dtData.LoadDataRow(ColArray, true);<br />
[/csharp]</p>
<p><strong>Conclusion</strong></p>
<p>Have you ever gone through this kind of requirement. Did I miss anything that you may think which is needed?. 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-Sharp Corner, Stack Overflow, Asp.Net Forums or Code Project instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I am able to.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/convert-data-reader-to-datatable/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Caching In MVC</title>
		<link>https://sibeeshpassion.com/caching-in-mvc/</link>
					<comments>https://sibeeshpassion.com/caching-in-mvc/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sat, 31 Oct 2015 18:25:25 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Caching In MVC]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[MVC 4]]></category>
		<category><![CDATA[Output Caching]]></category>
		<category><![CDATA[Performance Improvements In MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10877</guid>

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

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/c-sharp-interview-questions-and-answers/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Check a String is Palindrome</title>
		<link>https://sibeeshpassion.com/check-a-string-is-palindrome/</link>
					<comments>https://sibeeshpassion.com/check-a-string-is-palindrome/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 31 May 2015 13:02:21 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Pallindrome]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=2871</guid>

					<description><![CDATA[Introduction This tip covers how we can check a string is palindrome or not. Background Now a day you can expect a question in every Interviews that to write a program to check whether a String is palindrome or not. I thought of sharing my methods two find out the same 🙂 Using the Code We can do it in two ways: By creating char arrays By using string reverse method NB: There are some other methods also, for now I am sharing these two. By creating char arrays [csharp] private static bool chkPallindrome(string strVal) { try { int min [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>This tip covers how we can check a string is palindrome or not.</p>
<p><strong>Background</strong></p>
<p>Now a day you can expect a question in every Interviews that to write a program to check whether a String is palindrome or not. I thought of sharing my methods two find out the same 🙂</p>
<p><strong>Using the Code</strong></p>
<p>We can do it in two ways:</p>
<li>By creating char arrays</li>
<li>By using string reverse method</li>
<p>NB: There are some other methods also, for now I am sharing these two.</p>
<p><strong>By creating char arrays</strong></p>
<p>[csharp]<br />
private static bool chkPallindrome(string strVal)<br />
{<br />
     try<br />
     {<br />
          int min = 0;<br />
          int max = strVal.Length &#8211; 1;<br />
          while (true)<br />
          {<br />
               if (min &gt; max)<br />
               return true;<br />
               char minChar = strVal[min];<br />
               char maxChar = strVal[max];<br />
               if (char.ToLower(minChar) != char.ToLower(maxChar))<br />
               {<br />
                    return false;<br />
               }<br />
               min++;<br />
               max&#8211;;<br />
         }<br />
     }<br />
     catch (Exception)<br />
     {<br />
          throw;<br />
     }<br />
}<br />
[/csharp] </p>
<p><strong>By using string reverse method  </strong><br />
[csharp]<br />
private static void CheckAndDisplay(string strReal)<br />
{<br />
     string strRev;<br />
     char[] tmpChar = strReal.ToCharArray();<br />
     Array.Reverse(tmpChar);<br />
     strRev = new string(tmpChar);<br />
     if (strReal.Equals(strRev, StringComparison.OrdinalIgnoreCase))<br />
     {<br />
          Console.WriteLine(&quot;The string is pallindrome&quot;);<br />
     }<br />
     else<br />
     {<br />
           Console.WriteLine(&quot;The string is not pallindrome&quot;);<br />
     }<br />
     Console.ReadLine();<br />
}<br />
[/csharp]<br />
Please download to see the entire program. I hope it helps someone.</p>
<p><img decoding="async" src="http://www.c-sharpcorner.com/UploadFile/BlogImages/11162014232536PM/output.jpg" alt="" /></p>
<p><strong>Points of Interest</strong></p>
<p>Palindrome, Arrays, Array Manipulations</p>
<p><strong>History</strong></p>
<p>1st version: 16-11-2014</p>
<p>Thank you for reading.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/check-a-string-is-palindrome/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
