tag:blogger.com,1999:blog-55711841030232598712024-02-20T21:54:01.506-08:00C# and .NET step by step with interview questions Shivprasad KoiralaC# and .NET step by step with interview questionsShivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.comBlogger628125tag:blogger.com,1999:blog-5571184103023259871.post-57524392870225385842021-03-17T12:12:00.004-07:002021-03-17T12:27:53.943-07:00Angular Interview Questions with Answers<p>Below is video covering 25 most important Angular Interview Questions and Answers do refer the same: -</p>
<iframe width="500" height="315" src="https://www.youtube.com/embed/-jeoyDJDsSM" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0Mumbai, Maharashtra, India19.0759837 72.8776559-9.2342501361788472 37.721405899999993 47.386217536178847 108.0339059tag:blogger.com,1999:blog-5571184103023259871.post-54778496791266061352021-03-17T09:04:00.002-07:002021-03-17T11:16:04.284-07:00C# Interview Questions and Answers<p>Below is video covering 30 most important C# Interview Questions and Answers do refer the same: -</p>
<iframe width="500" height="315" src="https://www.youtube.com/embed/BKynEBPqiIM" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0Mumbai, Maharashtra, India19.0759837 72.8776559-24.84327493098024 2.5651558999999935 62.995242330980233 143.19015589999998tag:blogger.com,1999:blog-5571184103023259871.post-58050222335519305492021-03-17T04:54:00.004-07:002021-03-17T05:19:06.328-07:00ASP.NET MVC Interview Questions with answers<p>Below is video covering 25 most important ASP.NET MVC Interview Questions and Answers do refer the same: -</p>
<iframe width="500" height="315" src="https://www.youtube.com/embed/pXmMdmJUC0g" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0Mumbai, Maharashtra, India19.0759837 72.8776559-9.2342501361788472 37.721405899999993 47.386217536178847 108.0339059tag:blogger.com,1999:blog-5571184103023259871.post-51909821993734344672019-09-20T02:43:00.000-07:002021-03-17T04:55:27.317-07:00Learn Python Step by Step<div dir="ltr" style="text-align: left;" trbidi="on">
<iframe width="500" height="315" src="https://www.youtube.com/embed/KjJ7WzEL-es" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0Mumbai, Maharashtra, India19.0759837 72.87765590000003618.5957917 72.232208900000032 19.556175699999997 73.52310290000004tag:blogger.com,1999:blog-5571184103023259871.post-9123496017770427162018-11-20T23:10:00.001-08:002018-11-20T23:27:43.557-08:00Concurrency VS Parallelism.<h3><a href="#Actual Parallelism VS feel of Parallelism">Actual Parallelism VS feel of Parallelism</a><br></h3>
<h3><a href="#Why a feel of parallelism and why not actual?">Why a feel of parallelism and why not actual?</a><br></h3>
<h3><a href="#Concurrency is about design, parallelism is about hardware’s">Concurrency is about design, parallelism is about hardware’s</a><br></h3>
<h3><a href="#Concluding">Concluding</a><br></h3>
<h3><a href="#Further readings">Further readings</a><br></h3>
</br>
<h2><a name="Actual Parallelism VS feel of Parallelism">Actual Parallelism VS feel of Parallelism</a></h2>
<p>Technical vocabulary in IT industry are sometimes very confusing and “Concurrency” and “Parallelism” is one of them. Many developers think “Concurrency and parallelism means executing at the same time” which is right 50% but with one big difference:-</p>
<ul><li>Concurrency gives you a feel of parallelism and parallelism as the name implies is actual parallelism.</li></ul>
<p><b>Feel of parallelism</b> means you execute <b>multiple tasks on the same core</b> and the core switches context between tasks and serves them. You can also term this has time
slicing / over lapping time period because your single core is just dedicating some time to one task and then some time to other.</p>
<p><b>Actual parallelism</b> means you execute <b>multiple task on multiple cores</b> parallely.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-blM9pWD9gNQzaFYzvPI1_-lUYFTRiW2DIdsbmQA1-heE4vnyn23qMOBersaRyP8V6gX9k69EU7B6qzzjOleHyM7768Ok5abX2bMWD70z5SS8HDIAmtHbZT7a6QPmR5h0OhqWTtHhtQ/s1600/1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-blM9pWD9gNQzaFYzvPI1_-lUYFTRiW2DIdsbmQA1-heE4vnyn23qMOBersaRyP8V6gX9k69EU7B6qzzjOleHyM7768Ok5abX2bMWD70z5SS8HDIAmtHbZT7a6QPmR5h0OhqWTtHhtQ/s1600/1.jpg" data-original-width="372" data-original-height="374" /></a></div>
<p>Note: - “Concurrency is a broader term and Parallelism is subset of it”.</p>
<p>Mapping to the real world the left image depicts parallelism the right image depicts concurrency.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEisrqUxRiZywFIc99pih8mJqIwuNsJUjdICG2JiXftnbrl-8z8pnDASk-JDRptqriOr723TS_EolfmzkLPGoiLcQy0cSIOfp18iigdlMBUXVEJHvdSj-qLorPramS5nT0o0K_Fk0bq5Uw/s1600/2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEisrqUxRiZywFIc99pih8mJqIwuNsJUjdICG2JiXftnbrl-8z8pnDASk-JDRptqriOr723TS_EolfmzkLPGoiLcQy0cSIOfp18iigdlMBUXVEJHvdSj-qLorPramS5nT0o0K_Fk0bq5Uw/s1600/2.jpg" data-original-width="459" data-original-height="243" /></a></div>
<h2><a name="Why a feel of parallelism and why not actual?">Why a feel of parallelism and why not actual?</a></h2>
<table border="1" width="105%">
<tbody>
<tr>
<td valign="top" width="417">
<p>In order to achieve actual parallelism we need dedicated cores, separate memory and so on.<br>We need MORE RESOURCES.</p>
<p>Let’s say we want to show a progress bar for some task completed. Now we really do not want to have separate cores allocated to display the progress.</p>
</td>
<td valign="top"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjS6NKUrvx91HcH5T-EGUUgMMQLWxm3Sxb-xWlUubZbFMDCM9sE0FpiZuMY-OcT7Dp8ZhiTZrj2ZPVzG-FviDpzhprZC8JxEN_u1eYUp-dxw4QWzAwPxVL0y6vVRHj6Q-8i2hyphenhyphendl9KC8Q/s1600/3.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjS6NKUrvx91HcH5T-EGUUgMMQLWxm3Sxb-xWlUubZbFMDCM9sE0FpiZuMY-OcT7Dp8ZhiTZrj2ZPVzG-FviDpzhprZC8JxEN_u1eYUp-dxw4QWzAwPxVL0y6vVRHj6Q-8i2hyphenhyphendl9KC8Q/s1600/3.jpg" data-original-width="321" data-original-height="143"/ ></a></div></td>
</tr>
</tbody>
</table>
<p>We do not want PERFORMANCE here we want that physiologically the end user feels both tasks are happening simultaneously.</p>
<p>We want to just beat the human eye capability of 100 FPS and give an illusion of parallelism without stressing our computer resources. But let’s say we want to
process big excel files with million records then yes we would love to have actual parallelism to achieve performance.</p>
<h2><a name="Concurrency is about design, parallelism is about hardware’s">Concurrency is about design, parallelism is about hardware’s</a></h2>
<p>In order to achieve concurrency we need to compose our application logic independently. For instance let’s say you want to process employee data where you want to
increment the salary by x% and bonus by x%.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9MgsOSzil3Rle6BbcE4BBRqUFARv0wSa72EhozcSzSZamQhAMLvh_qlTDmujpwoHvbkDj1oX61tP9zIWBVnWv6CnW88CYS1d8y8StE2zHGl7qOEOSNjwghguSQLPzfOlIsc5vAbhONQ/s1600/4.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9MgsOSzil3Rle6BbcE4BBRqUFARv0wSa72EhozcSzSZamQhAMLvh_qlTDmujpwoHvbkDj1oX61tP9zIWBVnWv6CnW88CYS1d8y8StE2zHGl7qOEOSNjwghguSQLPzfOlIsc5vAbhONQ/s1600/4.jpg" data-original-width="476" data-original-height="257" /></a></div>
<p>So you can decompose the application in to logical units by following different designs:-</p>
<p><b>Design 1</b></p>
<ul><li>Divide data in to 50% size each.</li>
<li>Process each 50% as separate unit.</li></ul>
<p><b>Design 2</b></p>
<ul><li>Process bonus calculation as separate unit.</li>
<li>Process salary calculation as separate unit.</li></ul>
<p><b>Design 3</b></p>
<ul><li>Divide data in to 50% size each.</li>
<li>For every 50% data process bonus calculation separately and salary calculation separately.</li></ul>
<p>There can be many such designs and combination. So when you say your application is supporting concurrency your application should be composed in to small
independent units.</p>
<p>Now you take these units and run on one core (Concurrency) or you run on multiple cores (Parallelism). So concurrency is about design while on parallelism we talk
more from hardware perspective, 2 core, 3 cores and so on.</p>
<p>If you try to run every concurrent code as parallel you have resource starvation unnecessarily. So ask yourself do you want an illusion (concurrent) or do you
performance (parallel).</p>
<h2><a name="Concluding">Concluding</a></h2>
<table border="1" width="105%">
<tr>
<td width="267"></td>
<td width="189"><b>Concurrency</b></td>
<td width="189"><b>Parallelism</b></td>
</tr>
<tr>
<td width="267"><b>Basic definition</b></td>
<td width="189">Executing multiple task on same core using overlapping or time slicing.</td>
<td>Executing multiple tasks on different core.</td>
</tr>
<tr>
<td width="267"><b>Goal</b></td>
<td width="189">Feeling of parallelism without stressing out resources.</td>
<td>Actual parallelism for performance.</td>
</tr>
<tr>
<td width="267"><b>Perspective</b></td>
<td width="189">Software design: - Composition of independently executing computations in a co-operative fashion.</td>
<td>Hardware: - Executing computation parallel.</td>
</tr>
<tr>
<td width="267"><b>Resource utilization</b></td>
<td width="189">Light</td>
<td>Heavy</td>
</tr>
</table>
<ul><li>Parallelism is a subset of concurrency.</li>
<li>Concurrency enables parallelism.</li>
<li>Concurrency is more about software design while parallelism is more about hardware’s.</li>
<li>Concurrency gives an illusion of parallelism while parallelism is about performance.</li>
<li>Concurrency just needs one core while parallelism needs at least 2 cores.</li>
</ul>
<h2><a name="Further readings">Further readings</a></h2>
<p>Concurrency is not parallelism by Rob pike <a target="_blank" href="https://www.youtube.com/watch?v=cN_DpYBzKso">https://www.youtube.com/watch?v=cN_DpYBzKso</a></p>
<p>Nice discussion on concurrency and parallelism</p>
<a target="_blank" href="https://stackoverflow.com/questions/1897993/what-is-the-difference-between-concurrent-programming-and-parallel-
programming">https://stackoverflow.com/questions/1897993/what-is-the-difference-between-concurrent-programming-and-parallel-programming</a>
<div><a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a></div>
Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-82189296034858104072018-06-11T00:17:00.000-07:002018-06-11T00:18:18.704-07:00bin vs obj folders in C#.<p>When we compile C# programs you would see 2 folders “bin” and “obj”. In this article we will try to understand the difference and importance of these folders.</p>
<p>Both these folders have compiled IL code, but the question comes is why not just one folder and why two folders?.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKvwHIMEhyphenhyphenlThjILiNZBemSJl0i9bj0AUy3JUu4f1YAVWDJNNCQc9hyU-3vaZpdXJ01z0eiDKWTLZO0_SpBHLdrQ2bg6xPSDhWKc6b_a0G1E47d4_lFg-cTkL_Yy2i2CCCWi9LiiNQkg/s1600/1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKvwHIMEhyphenhyphenlThjILiNZBemSJl0i9bj0AUy3JUu4f1YAVWDJNNCQc9hyU-3vaZpdXJ01z0eiDKWTLZO0_SpBHLdrQ2bg6xPSDhWKc6b_a0G1E47d4_lFg-cTkL_Yy2i2CCCWi9LiiNQkg/s1600/1.jpg" data-original-width="364" data-original-height="380" /></a></div>
<p>We have two folders because the compilation process goes through two steps compiling and linking. See the below diagram.</p>
<ul><li>In compiling phase every code file is compiled in to individual compiled units. So if you have two code files two independent compiled codes will be generated.</li>
<li>In linking phase all these compiled code files are linked and compiled in to single unit assembly which can be a DLL or EXE.</li>
</ul>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvxiIh8ql3tkS3T733DCLLi7VzDnseH-2fK8zr856oVkNRybYyRVPAZMZvUCIzNA-ezkLXXkFeiJpTEIJLGyNHuqWWpuNiunYgd3hfZd9FsHGW8QG5ufGgwUsuCmNK44HQW9BYjAFTgQ/s1600/2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvxiIh8ql3tkS3T733DCLLi7VzDnseH-2fK8zr856oVkNRybYyRVPAZMZvUCIzNA-ezkLXXkFeiJpTEIJLGyNHuqWWpuNiunYgd3hfZd9FsHGW8QG5ufGgwUsuCmNK44HQW9BYjAFTgQ/s400/2.jpg" width="400" height="183" data-original-width="593" data-original-height="271" /></a></div>
<p>If you compare both the folders ( see below image) you will find more files in “obj” folder as compared to “bin” folder. We have more files in “obj” folder because it creates seperate compiled code files for each source code file.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhToUScLdEbD0gJw_SSfZJ2ZCoEYtRnqZfEWkg9bZu4l93AZ2nTh3uzwj8LkYFB6uT7Oq1ZFC7PV-ckpTmH8fFsqkdAHBoO-DQ9QhQxSXWPC1Sf7KM0Vmo8fav4tR8zhDO1aBGqCnjkzw/s1600/3.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhToUScLdEbD0gJw_SSfZJ2ZCoEYtRnqZfEWkg9bZu4l93AZ2nTh3uzwj8LkYFB6uT7Oq1ZFC7PV-ckpTmH8fFsqkdAHBoO-DQ9QhQxSXWPC1Sf7KM0Vmo8fav4tR8zhDO1aBGqCnjkzw/s400/3.jpg" width="400" height="162" data-original-width="602" data-original-height="244" /></a></div>
<p>So the next question which comes to our mind why do we need compiling in two phase, why not just do it one go. By doing the two phase compiling we achieve <b>incremental or conditional compiling</b>.</p>
<p>When we work with big projects we will have lot of code files and we would like to only compile those code files which have changed. In the “obj” folder we have entry of each code file compilation. So we can know from the same which files exactly have changed , thus making compiling fast.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEifOBvlAqKzSCNOmzTuIDdRCN5K9WwgmOn-WzxVkr9CbvAlZMWYqQgl_auzER8kMiEA2yqjUMtwMFxAGlhSpK6GnD63wTjYhf2s_FCBw0U5cR5uaqBzpc14As-xz-a7HX4jbQ6ibp45MA/s1600/4.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEifOBvlAqKzSCNOmzTuIDdRCN5K9WwgmOn-WzxVkr9CbvAlZMWYqQgl_auzER8kMiEA2yqjUMtwMFxAGlhSpK6GnD63wTjYhf2s_FCBw0U5cR5uaqBzpc14As-xz-a7HX4jbQ6ibp45MA/s400/4.jpg" width="400" height="169" data-original-width="602" data-original-height="255" /></a></div>
<p>In summary in “obj” folder have compiled files for each source code file and in “bin” folder we have a single unit which links all individually compiled code files.</p>
<p>Below is 10 minutes youtube video which demonstrates how these both folders look like and how incremental compilation happens.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://www.youtube.com/embed/vjHage_2g4Y" target="_blank" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6dDoSviQZt_796VYH-mtXAG8IdyeuG-uwtfDHJVIAAN0_fX9Yna7-jWuoVpxXK-vBNOFiVHjT4JxpkPAm6fnBYlaOG08aV2KnHdTzcvwIUyl4EaJv3XlmdMdvhIWJtGtZkTP9NhbJBg/s640/5.jpg" width="500" height="278" data-original-width="1333" data-original-height="579" /></a></div>
<div><a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a></div>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-971571171296644302017-11-03T04:57:00.000-07:002017-11-03T04:57:23.003-07:00What is the best project folder structure for Angular projects?<p>There no straight answer to this as every project is different, developers are of different mindset and architecture have their own though process. </p>
<p>But whatever it is you will end up with some kind of nearby folder structure for angular as shown below:-</p>
<ul><li>You will need two root folders one for the server code and the other for client code. The client code folder sometimes is also named as “app”.</li>
<li>If you have a big project then inside in the client folder you can create sub folder which represent modules of your project. Normally developers divide project in modules for better management so these subfolders represent those modules.</li>
<li>In this those module folder you can have separate folder for component, model, module and routing.</li>
<li>A common folder is also needed where in you can push your common utilities like common pipes, filters, http components, injectables and so on.</li>
<li>Server folder will have its own folder structure depending on whether you are doing ASP.NET or JSP or PHP. In this discussion we will restrict only to client side angular folder structure.</li>
</ul>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgo30dUZsOYLO0_ZwNyvz6kMYhJrgESLEXrVdpGmP3v8XrE6WCMESG-tL2O5IVlkcj_OiUKQjJhbQodNwlfgjLCsDfovm5lMdNhPxw5vDD7MX8zEZkSsZVHHGepj2X9pyxma4dnf3MOQ/s1600/1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgo30dUZsOYLO0_ZwNyvz6kMYhJrgESLEXrVdpGmP3v8XrE6WCMESG-tL2O5IVlkcj_OiUKQjJhbQodNwlfgjLCsDfovm5lMdNhPxw5vDD7MX8zEZkSsZVHHGepj2X9pyxma4dnf3MOQ/s1600/1.jpg" data-original-width="319" data-original-height="418" /></a></div>
<p>This question was raised in our Mumbai angular training of 86th batch <a target="_blank" href="http://stepbystepschools.net/">http://stepbystepschools.net/</a></p>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-81368038407666953102017-08-21T06:02:00.001-07:002017-09-03T21:27:46.865-07:00What is package-lock.json file in Node NPM? (Learn Angular Step by Step)<div dir="ltr" style="text-align: left;" trbidi="on">
When you are doing development in Angular, Node NPM is your tool for package management. In simple words we have a “package.json” file and all dependencies are listed inside it. When you are doing NPM you will always find “package-lock.json” file.
<br />
<br>So in this <a target="_blank" href="http://www.learnangularjs.net/">Angular tutorial</a> we will unleash the importance of this lock file.<br />
<br />
To understand the importance of lock lets understand how software versioning works.<br />
<br />
Most software versions follow semantic versioning. In semantic versioning, versions are divided in to three distinct numbers as shown in the image below.<br />
<br />
<table>
<tbody>
<tr>
<td valign="top" width="455">The first number is termed as “major version” , second “minor version” and third “revision”.<br />
<br />
<b>Major version: -</b> Any increment in major version is an indication that there are breaking changes in the software functionality. It’s very much possible that the old code will not work with these changes and have to be tested properly.<br />
<br />
<b>Minor version: -</b> This version is incremented when we add new features but the old code still works.<br />
<br />
<b>Revision:-</b> This version is incremented when we are just doing bug fixes. So there are no new functionalities added, no breaking changes and back ward compatible with old code .</td>
<td valign="top"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhM7z0h3c361W_jTA3lkddBCRMES0sx2bWP3DxWE4bLdOzqAd1mfavRshg6Tiuf2mEpYo9e2eCK0GJyeftQvv4Whr7vwxYcb880EEIxeH9g7pTQsUDUmBj2a9Xrcw3b4eW9PLxs7v5AtA/s1600/1.jpg" />
</td>
</tr>
</tbody>
</table>
<br />
<table>
<tbody>
<tr>
<td valign="top" width="355">NPM follows semantic versioning but it also has some more special characters like “^”, “~”, “>” and so on. They dictate how NPM get latest should behave for Major and Minor versions.<br />
<br />
For these formats 3 formats are very primary let’s understand each them.<br />
<br />
Exact (1.6.5) , Major/Minor ( ^1.6.5) or Minor(~1.6.5).</td>
<td valign="top"><img height="91" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjktQcnBC3qig_eBGr_-xQLZ9YBdSAGVvfCFI1bJ3IYle8w8sQ0rRt9WnrIppRDHhzIZw3qlBTBPXpwJv7lCc8x2AIQUQDfp61cc22GHwwtojQ-V7mt0T8F2tJTQhy0WSFb-fFlP_mQQ/s200/2.jpg" width="200" />
</td>
</tr>
</tbody>
</table>
<br />
<table>
<tbody>
<tr>
<td valign="top" width="379"><b>Exact (1.6.5): -</b> This will do a get latest of exact version 1.6.5 not more or not less. If that version is not available it will throw up an exception.<br />
<br />
<b>Major/Minor(^1.6.5): -</b> The carrot sign will get minimum 1.6.5 and if there are any higher MINOR / REVISION versions it will get that. It WILL NEVER GET HIGHER MAJOR VERSIONS. So if 1.6.5 has 1.6.7 it will get that, if it has 1.7.7 it will that , but if it as 2.0 it will NOT get that.<br />
<br />
<b>Minimum or lower (~1.6.5): -</b> The tilde sign will get HIGHER REVISIONS. For if 1.6.5 has 1.6.7 it will get that , but if it has 1.7.5 it will not be installed , if it has 2.0 it will not be installed.</td>
<td valign="top"><img height="151" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgRqezqN-MU_nkr08SJKhw0Xe2grHEyod0yLZ9XN9nbVRKex-0W8X_tyq8Fb_lpWhxKEdnttvdFZkU6M3RSFd5tKIQhu9tumDbnyEuWFIbBBWlO0KobT0cKjevj2vynfL40l265R30PnQ/s200/3.jpg" width="200" />
</td>
</tr>
</tbody>
</table>
<br />
As discussed in the previous sections package.json has “^” and “~” versioning mechanism. Now suppose in your package.json you have mentioned "jquery": "^3.1.0"and Jquery has a new version “3.2.1”. So in actual it will install or in other words LOCK DOWN to “3.2.1”.<br />
<br />
So in package.json you will have “^3.1.0” but actually you will be using “3.2.1”. This entry of actual version is present in “package-lock.json”. So package lock files have the EXACT versions which are used in your code.<br />
<br />
Below is the image snapshot of both the files.<br />
<br />
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUf7zAgtxFPR-KsbADg99wPPvyYf2-JTRbpK4RczJH5cSd0gwKlUdTyTEvdGQYSKueTf_fjfcOvBgu0XQMzHWohOF8iYCLfRZa9XaNBaDTw_M3-BmDHrQua7nLW-I2zqK1gXEwnXC_Jg/s320/4.jpg" />
<br />
<br />
Do not miss our Learn Angular Step by Step in 8 hours video training series: -<br />
<br />
<div align="center">
<a href="https://www.blogger.com/null"><iframe allowfullscreen="" frameborder="0" height="360" src="https://www.youtube.com/embed/oMgvi-AV-eY?ecver=2" width="480"></iframe></a>
</div>
<div align="center">
<br /></div>
<div align="center">
OR</div>
<br />
You can also catch me teaching Angular in Mumbai at Andheri at <a href="http://stepbystepschools.net/?page_id=622" target="_blank">http://stepbystepschools.net/?page_id=622</a>.
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a></div>
Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-39434315974361304642016-07-11T07:22:00.000-07:002016-07-13T03:13:03.670-07:00== VS Equals in C#<h2>Contents</h2>
<p><a href="#Introduction">Introduction</a></p>
<p><a href="#Point_1_:-_Comparison_on_the_basis_of_Equality">Point 1 :- Comparison on the basis of Equality</a></p>
<p><li><a href="#Scenario_1:-_Value_type_comparison">Scenario 1:- Value type comparison</a></li>
<li><a href="#Scenario_2:-_Reference_types_comparison">Scenario 2:- Reference types comparison</a></li>
<li><a href="#Scenario_3:-_String_comparison,_interning_and_object_type_casting">Scenario 3:- String comparison, interning and object type casting</a></li></p>
<p><a href="#Point_2_:-_Compile_time_VS_RunTime">Point 2 :- Compile time VS RunTime</a></p>
<p><a href="#Point_3_:-_The_NULL_Situation">Point 3 :- The NULL Situation</a></p>
<p><a href="#When_to_use_what_:-_Technical_comparison_VS_Semantical_comparison">When to use what :- Technical comparison VS Semantical comparison</a></p>
<p><a href="#The_Full_Picture">The Full Picture</a></p>
<h1><a name="Introduction">Introduction</a></h1>
<p>To compare equality between variables C# has provided two ways of doing comparison “==” and an overloaded method “equals()”. Most of the developers use “==” and “Equals” is hardly discussed.</p>
<p>So in this small note we will discuss about differences between them and when to use what.</p>
<h1><a name="Point_1_:-_Comparison_on_the_basis_of_Equality">Point 1 :- Comparison on the basis of Equality</a></h1>
<p>Answering to the point “There is no difference between equality comparison using “==” and “Equals()”, <b>except when you are comparing “String” comparison.</b></p>
<p>The common comparison Rule :-Whenever youare comparing variables they are either value types or reference types. When values types are compared they are compared on the basis of “Content” when reference types are compared they are compared on the basis of “Reference”(memory location) and not “Content”.</p>
<p>The above rule is respected by both “==” and “Equals”.</p>
<h2><a name="Scenario_1:-_Value_type_comparison">Scenario 1:- Value type comparison</a></h2>
<p>When you compare value types / primitive data types ( int , double etc) either by using “==” or “Equals” it’s always based on content. In the below code you can see both comparison methods will show as “true”.</p>
<pre>int i = 10;
int y = 10;
Console.WriteLine(i == y); // true
Console.WriteLine(i.Equals(y)); // true
</pre>
<h2><a name="Scenario_2:-_Reference_types_comparison">Scenario 2:- Reference types comparison</a></h2>
<p>Now when you compare objects they are compared on the basis of reference (internal memory pointer). Below obj and obj1 comparison either through “==” or “Equals” will be false. So in the below code even though both the object have property name as “Shiv” still it shows unequal. Because the comparison is based on internal memory reference which is different for “obj” and “obj1”.</p>
<pre>Customerobj = newCustomer();
obj.Name = "Shiv";
Customer obj1 = newCustomer();
obj1.Name = "Shiv";
Console.WriteLine(obj == obj1); // false
Console.WriteLine(obj.Equals(obj1)); // false
</pre>
<p>But the below code will display true as the pointer points to same object.</p>
<pre>Customerobj = newCustomer();
obj.Name = "Shiv";
Customer obj1 = obj;
Console.WriteLine(obj == obj1); // true
Console.WriteLine(obj.Equals(obj1)); // true
</pre>
<h2><a name="Scenario_3:-_String_comparison,_interning_and_object_type_casting">Scenario 3:- String comparison, interning and object type casting</a></h2>
<p>Now strings are immutable objects or reference types so they should be checked using the rules of reference types. In other words in the below scenario when we assign value to “str” it creates a string object and in heap has “test” stored. When you now assign “str1” this a different object so it should be a different instance.</p>
<p>But look at the value, it the same. So C# string follows interning rule. In other words if the content is same “str” and “str1” they point to the same memory location and data. So both “==” and “Equals” will be true.</p>
<pre>objectstr = "test";
object str1 = "test";
Console.WriteLine(str==str1);
Console.WriteLine(str.Equals(str1));
</pre>
<p>But now look at the below code where we are explicitly creating new separate objects of string with same value. We are forcing and overriding interning behavior of string.In the below code “==” will return false even though the content is same while “Equals” will return true. This is one place where the equality behavior differs.</p>
<pre>objectstr = newstring(newchar[] { 't', 'e', 's', 't' });
object str1 = newstring(newchar[] { 't', 'e', 's', 't' });
Console.WriteLine(str==str1); // false
Console.WriteLine(str.Equals(str1)); // true
</pre>
<h1><a name="Point_2_:-_Compile_time_VS_RunTime">Point 2 :- Compile time VS RunTime</a></h1>
<p>The next point which makes them different is when do type checks happen. “==” does type checking during compile time while “Equals” is more during runtime. You can see in the below code how “==” is showing a warning message with green sign saying that you are comparing different types and you can have issues. “Equals” does not show any such warnings.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjuz9aBQCY9OhUcr7eBLdbhWi-cBz-TuQkBqiTIHDw0eIPDm9G7-9-BEGJ7ITAoLU2WDf1K8tJTg5jlSL7klxU5DCx7QkhyphenhyphenpFQy45eBDUZ7BpFkWw6zzfUGZzx2RQCZw3njyRalXoGIFA/s1600/1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjuz9aBQCY9OhUcr7eBLdbhWi-cBz-TuQkBqiTIHDw0eIPDm9G7-9-BEGJ7ITAoLU2WDf1K8tJTg5jlSL7klxU5DCx7QkhyphenhyphenpFQy45eBDUZ7BpFkWw6zzfUGZzx2RQCZw3njyRalXoGIFA/s400/1.jpg" width="400" height="101" /></a></div>
<h1><a name="Point_3_:-_The_NULL_Situation">Point 3 :- The NULL Situation</a></h1>
<p>“==” works with nulls but “Equals” crashes when you compare NULL values , see the below print screen.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgGnISkKG1GJxk6ss38SmiHZy5awjEw4p9Nx1MzFgMm7kmfnAOSqV8Yu9G0m34ioyeSSucIEagt7Y_GS6cD-9LL30KMOEUxEp6mgZC39nverkzzzhj8GYFv-SRgUlMihgNNVw_5zbiEGQ/s1600/2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgGnISkKG1GJxk6ss38SmiHZy5awjEw4p9Nx1MzFgMm7kmfnAOSqV8Yu9G0m34ioyeSSucIEagt7Y_GS6cD-9LL30KMOEUxEp6mgZC39nverkzzzhj8GYFv-SRgUlMihgNNVw_5zbiEGQ/s400/2.jpg" width="400" height="127" /></a></div>
<h1><a name="When_to_use_what_:-_Technical_comparison_VS_Semantical_comparison">When to use what :- Technical comparison VS Semantical comparison</a></h1>
<p>“==” is a C# operator while “Equals” is a polymorphic method. So in other words “==” is a language feature while “Equals” is an object oriented programming feature which follows polymorphism.</p>
<p>Now comparison is of two types one is purely based on content and reference, means computer based comparison and other is based on semantics. Semantics means the actual meaning of a thing. For example 1 <> 70 numerically ( technically) but 1 $ = 70 Rs in real world semantically.</p>
<p>Some more examples:-</p>
<ul><li>Technically: - 1 is equal to 1.</li>
<li>Semantically: - 1 Dollar is not equal to 1 Rs.</li>
<li>Technically: - “Destination “ word is not equal to “Last Stop”.</li>
<li>Semantically: - “Destination” means same as “Last Stop”.</li>
</ul>
<p>So technical comparison is computer based while semantic comparison is business based or we can say there is some kind of domain rule for comparison purpose.</p>
<p>So now when to use “==” and when to use “Equals”:-</p>
<ul><li>If you are looking for technical comparison then use “==” and most of the time “==” suffices as developers mostly do technical comparison.</li>
<li>If you are comparing semantically then you need over the “equals” with the semantic comparison logic and you need to use “equals” method while comparing.</li>
</ul>
<h1><a name="The_Full_Picture">The Full Picture</a></h1>
<p>So if we list down all the point the final conclusion is the below table.</p>
<table border="1" style="width: 526px;">
<tbody>
<tr>
<td width="154"><span style="font-family: "times new roman"; font-weight: 700; line-height: 115%;">
</span></td>
<td width="168" align="center"><span style="font-family: "times new roman"; font-weight: 700; line-height: 115%;"> == </span></td>
<td width="182" align="center"><span style="font-family: "times new roman"; font-weight: 700; line-height: 115%;">
Equals</span></td>
</tr>
<tr>
<td width="154" height="22">
<span style="font-family: "times new roman"; line-height: 115%; font-weight:700">Usage</span></td>
<td width="168" height="22"><span style="font-family: "times new roman"; line-height: 115%;">Technical based.</span></td>
<td height="22"><span style="font-family: "times new roman"; line-height: 115%;">
Semantic based.</span></td>
</tr>
<tr>
<td width="154">
<span style="font-family: "times new roman"; line-height: 115%; font-weight:700">Value types</span></td>
<td width="168"><span style="font-family: "times new roman"; line-height: 115%;">Content based Comparison</span></td>
<td><span style="font-family: "times new roman"; line-height: 115%;">
Content based Comparison</span></td>
</tr>
<tr>
<td width="154">
<span style="font-family: "times new roman"; line-height: 115%; font-weight:700">Objects</span></td>
<td width="168"><span style="font-family: "times new roman"; line-height: 115%;">Reference based Comparison</span></td>
<td><span style="font-family: "times new roman"; line-height: 115%;">
Reference based Comparison</span></td>
</tr>
<tr>
<td width="154">
<span style="font-family: "times new roman"; line-height: 115%; font-weight:700">String </span></td>
<td width="168"><span style="font-family: "times new roman"; line-height: 115%;">Content based Comparison</span></td>
<td><span style="font-family: "times new roman"; line-height: 115%;">
Content based Comparison</span></td>
</tr>
<tr>
<td width="154">
<span style="font-family: "times new roman"; line-height: 115%; font-weight:700">String with no interning</span></td>
<td width="168"><span style="font-family: "times new roman"; line-height: 115%;">Reference based Comparison</span></td>
<td><span style="font-family: "times new roman"; line-height: 115%;">
Content based Comparison</span></td>
</tr>
<tr>
<td width="154">
<span style="font-family: "times new roman"; line-height: 115%; font-weight:700">Type checking</span></td>
<td width="168"><span style="font-family: "times new roman"; line-height: 115%;">Compile time</span></td>
<td><span style="font-family: "times new roman"; line-height: 115%;">
Run time</span></td>
</tr>
<tr>
<td width="154">
<span style="font-family: "times new roman"; line-height: 115%; font-weight:700">Nulls</span></td>
<td width="168"><span style="font-family: "times new roman"; line-height: 115%;">Works </span></td>
<td><span style="font-family: "times new roman"; line-height: 115%;">
Can crash</span></td>
</tbody></table>
<br />
<p>See the following practical video on understanding the difference between == and .Equals :-</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://www.youtube.com/embed/hVKnNxhXk0w" target="_blank" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhofIBZWsPbJgytFZWU36KqxVQ2Yw7Bo7mNNHBV-HgiEDEvuEc7mqbGASDE3XaKCUvWGDRsCCNYhLFs2KRr_oGpaAjETzDad009kfajSCxz1aSFRo7akfRTmeuhikzEpoE5DJr25DQP_A/s400/EQUALS.jpg" width="500" height="350" /></a></div>
<div><a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a></div>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-25984217286856154262016-03-11T02:45:00.000-08:002016-03-11T03:15:10.387-08:00Learn ASP.NET MVC step by step: - Part 2<h2>Contents</h2>
<p><a href="#Introduction">Learn ASP.NET MVC step by step: - Part 2</a></p>
<p><a href="#Introduction">Introduction</a></p>
<p><a href="#Step_11:_Understanding_Model_binder">Step 11: Understanding Model binder</a></p>
<p><a href="#Step_12:_Create_model_Binder_Class.">Step 12: Create model Binder Class.</a></p>
<p><a href="#Step_13:_Attach_the_binder_with_the_object_and_execute">Step 13: Attach the binder with the object and execute</a></p>
<p><a href="#Step_14:_Implementing_validation">Step 14: Implementing validation</a></p>
<p><a href="#Step_15:_Check_If_the_validations_are_proper">Step 15: Check If the validations are proper</a></p>
<p><a href="#Step_16:_Displaying_error_message">Step 16: Displaying error message</a></p>
<p><a href="#Step_17:_Client_side_validation_with_Jquery">Step 17: Client side validation with Jquery</a></p>
<h2><a name="Introduction">Introduction</a></h2>
<p>This complete article is a guest post written by Mr. Prathamesh mestry <a target="_blank" href="https://www.facebook.com/prathamesh.mestry?pnref=story">https://www.facebook.com/prathamesh.mestry?pnref=story</a> . If you think he is doing a good job send him a silent thanks to his FB.</p>
<p>In part 1 we saw <a target="_blank" href="http://www.codeproject.com/Articles/1081437/Learn-ASP-NET-MVC-Step-by-Step-Part">http://www.codeproject.com/Articles/1081437/Learn-ASP-NET-MVC-Step-by-Step-Part</a> basics of how to start MVC. In this session we will see model binder and validations. In validation we will do server side validations using data annotations and client side using Jquery.</p>
<p>In case you are completely new to MVC we would suggest you to watch this video series Learn MVC in 16 hours given in the below youtube video.</p>
<iframe width="500" height="315" src="https://www.youtube.com/embed/Lp7nSImO5vk" frameborder="0" allowfullscreen></iframe>
<h2><a name="Step_11:_Understanding_Model_binder">Step 11: Understanding Model binder</a></h2>
<p>Model binder helps to connect the UI controls to the model objects of MVC. In the previous article our UI text box names where same as customer class names so we did not have issues. But what if you text box names are different from class names.</p>
<p>For example below is a customer UI which has text box names start with “txt” and class property names are without word “txt”.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJMC-LLlTRJ9-1ZBYspbwkDkSFXkE61XAqMKVmOXCTLAC5-5uq1Z6kHUm88ghP6EOnNsZ4dcsQSH1vtmvUWg-S3mraexFc2QFUzJYOCMP0Y21K4zJlpKVCcZ1Fh5vWCJc6kq0zQu0s-g/s1600/Validation1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJMC-LLlTRJ9-1ZBYspbwkDkSFXkE61XAqMKVmOXCTLAC5-5uq1Z6kHUm88ghP6EOnNsZ4dcsQSH1vtmvUWg-S3mraexFc2QFUzJYOCMP0Y21K4zJlpKVCcZ1Fh5vWCJc6kq0zQu0s-g/s400/Validation1.jpg" /></a></div>
<p>You can see the below class is not in synch with UI text box names.</p>
<pre>publicclassStudent
{
publicstringStudentRollNo{ get; set; } //Student Roll No.
publicstringStudentName{ get; set; } //Student Name.
publicstringStudentStd{ get; set; } //Student Standard.
publicstringStudentDIV { get; set; }//Student Division.
}
</pre>
<p>This is where model binder class comes to picture. Model binder class binds the UI textboxes with model.</p>
<h2><a name="Step_12:_Create_model_Binder_Class.">Step 12: Create model Binder Class.</a></h2>
<p>To create a model binder class the first thing we need to do is implement interface “IModelBinder”.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEtYJkZlQnDssTm4MB1CU3CeuwVpEFm6ikzd5aFsaUqX7RdGVEUTbNkRjYr0kkKeCYDhIkGjYO3rB1QKBR75VUQAHtfLTaMESCnPXl1aEBJz3l658njYz_3CjX6Mh-Mwhdyeo5JBjyOQ/s1600/Validation2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEtYJkZlQnDssTm4MB1CU3CeuwVpEFm6ikzd5aFsaUqX7RdGVEUTbNkRjYr0kkKeCYDhIkGjYO3rB1QKBR75VUQAHtfLTaMESCnPXl1aEBJz3l658njYz_3CjX6Mh-Mwhdyeo5JBjyOQ/s400/Validation2.jpg" /></a></div>
<p>Right Click on ModelBinder Class Implement Interface Implement Interface.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzH5eQdblyTpMZj2wGFWgFNH0kEMsNMDJRkk-41Nnq5w0TUiIGU9432G8FzJywKFxge-nSsnJXmNL8NqSg82eY1LOMiRd6m_N6UO_RpsExFTe4AFXoV2bJmWidTyVyc-NPAm1BLyjruw/s1600/Validation3.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzH5eQdblyTpMZj2wGFWgFNH0kEMsNMDJRkk-41Nnq5w0TUiIGU9432G8FzJywKFxge-nSsnJXmNL8NqSg82eY1LOMiRd6m_N6UO_RpsExFTe4AFXoV2bJmWidTyVyc-NPAm1BLyjruw/s400/Validation3.jpg" /></a></div>
<p>In the class we need to put the binding code in “BindModel” method as shown below.</p>
<pre>public class StudentBinder : IModelBinder
{
public object BindModel(ControllerContextcontrollerContext,
ModelBindingContextbindingContext)
{
HttpContextBaseobjContext = controllerContext.HttpContext;
stringstuRoll = objContext.Request.Form["txtStudentRollno"];
stringstuName = objContext.Request.Form["txtStudentName"];
stringstuStd = objContext.Request.Form["txtStudentStd"];
stringstuDiv = objContext.Request.Form["txtStudentDiv"];
Student obj = new Student()
{
StudentRollNo = stuRoll,
StudentName = stuName,
StudentStd = stuDiv,
StudentDIV = stuDiv,
};
returnobj;
}
}
</pre>
<h2><a name="Step_13:_Attach_the_binder_with_the_object_and_execute">Step 13: Attach the binder with the object and execute</a></h2>
<p>Once the binding code is completed attach the binder with the object and execute to see the results.</p>
<pre>public ActionResult Submit([ModelBinder(typeof(StudentBinder))] Student obj)
{
return View("Student",obj);
}
</pre>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPLc_n0E1CIeN_rpUX0wdf-BAgLuJTJzHguxE_3W1wZrzYGZMJiS5r2v0hrXzeVBEvyMWIiDprUmJvQu6Qv2hHsGsM_2DAdbP58jQy47DTsiWDwrc5f-wD7dnIBfWTPmgcLUVTMhFSjw/s1600/Validation4.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPLc_n0E1CIeN_rpUX0wdf-BAgLuJTJzHguxE_3W1wZrzYGZMJiS5r2v0hrXzeVBEvyMWIiDprUmJvQu6Qv2hHsGsM_2DAdbP58jQy47DTsiWDwrc5f-wD7dnIBfWTPmgcLUVTMhFSjw/s400/Validation4.jpg" /></a></div>
<h2><a name="Step_14:_Implementing_validation">Step 14: Implementing validation</a></h2>
<p>Now that we have the student screen and the output is displayed it’s time to put validations. So we will be applying the following validation for our student class:-</p>
<ul><li>Student name and roll number is required.</li>
<li>Student Rollno should be alphanumeric with 7 characters with first three letter characters and last four letter numeric for example :-ABC1234, XYZ5678.
</li></ul>
<p>In order to implement validations we need to import “data annotation” namespace and decorate the attributes on the student properties.</p>
<pre>using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel.DataAnnotations;
usingSystem.Linq;
usingSystem.Web;
namespaceHelloWorld.Models
{
public class Student
{
[Required]
[RegularExpression("^[A-Z]{3,3}[0-9]{4,4}$")]
public string StudentRollNo{ get; set; } //Student Roll No.
[Required]
[StringLength(10)]
public string StudentName{ get; set; } //Student Name.
public string StudentStd{ get; set; } //Student Standard.
public string StudentDIV { get; set; }//Student Divsion.
}
}
</pre>
<h2><a name="Step_15:_Check_If_the_validations_are_proper">Step 15: Check If the validations are proper</a></h2>
<p>When the object is filled the final output whether the validation is passed or failed is updated to the “ModelState” object. You can see in the below code we are checking if the “ModelState” object is valid by using the “IsValid” property.</p>
<p>Depending on the property value its redirecting to the views.</p>
<pre>public ActionResult Submit(Student obj)
{
if (ModelState.IsValid)
{
return View("Student", obj);
}
else
{
return View("EnterStudent");
}
}
</pre>
<h2><a name="Step_16:_Displaying_error_message">Step 16: Displaying error message</a></h2>
<p>To display error message we need to use Helper class as shown in the below code.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh7YszRsEirJBV1Pk4Pac9oOTsjwwSLN1Jd6xjeml5XTwbhddZa6A4d0lDjrs7qsF8pb5u0W7GRsWIRM2HtRHmtZQakpoQy1MioMzjpUfvwKG6GSyAM1f0FmVii5sLiXmbyXuzYiMMnnw/s1600/Validation5.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh7YszRsEirJBV1Pk4Pac9oOTsjwwSLN1Jd6xjeml5XTwbhddZa6A4d0lDjrs7qsF8pb5u0W7GRsWIRM2HtRHmtZQakpoQy1MioMzjpUfvwKG6GSyAM1f0FmVii5sLiXmbyXuzYiMMnnw/s400/Validation5.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiO2clRl-rqFg0HrjujCz5UbPAEZNg3kutBOe-zPde4esTVktP6V22NcTOVpZZC1txrbUKxQH7NFJ26w4f21_Kqb8wp7fMexe8X_hpZ3wWttqCAnhcgpeIYxWRZJKedslZol8bXjlRuqA/s1600/Validation6.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiO2clRl-rqFg0HrjujCz5UbPAEZNg3kutBOe-zPde4esTVktP6V22NcTOVpZZC1txrbUKxQH7NFJ26w4f21_Kqb8wp7fMexe8X_hpZ3wWttqCAnhcgpeIYxWRZJKedslZol8bXjlRuqA/s400/Validation6.jpg" /></a></div>
<h2><a name="Step_17:_Client_side_validation_with_Jquery">Step 17: Client side validation with Jquery</a></h2>
<p>Install Jqurey validation from Nuget.</p>
<p>33.1 In Solution Explorer Right Click on MyApplication (HelloWorld). Click on Manage NuGet Packages</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhrqb9pR1RU5a0la0CkFcnSrAYrexcQUxD-EB6uvSqFLlqZBhcyaWdbkD42RkHrhNDLme_9ZUjAgHIikb1C3RuxYKxZ_q6Ti_kdigfjc0t4sBeiQW4YpEmVk5n0ymuQFTu-4KP8BwrZxA/s1600/Validation7.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhrqb9pR1RU5a0la0CkFcnSrAYrexcQUxD-EB6uvSqFLlqZBhcyaWdbkD42RkHrhNDLme_9ZUjAgHIikb1C3RuxYKxZ_q6Ti_kdigfjc0t4sBeiQW4YpEmVk5n0ymuQFTu-4KP8BwrZxA/s400/Validation7.jpg" /></a></div>
<p>Search jQuery Validation. Select Microsoft jQuery Unobtrusive Validation install</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhCGoCU8RBgI2wEMFDtakjeJPcHIVm932ryIpW35pklJY3CwxUTaVO5vAykCTP6KS_m1OtL-2KqYzSvJLHkloxfAMrmz9FLoRghn5Hjze-usw6H2eM9gVkCyxqJJvI87Xlei-cuf73KRA/s1600/Validation8.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhCGoCU8RBgI2wEMFDtakjeJPcHIVm932ryIpW35pklJY3CwxUTaVO5vAykCTP6KS_m1OtL-2KqYzSvJLHkloxfAMrmz9FLoRghn5Hjze-usw6H2eM9gVkCyxqJJvI87Xlei-cuf73KRA/s400/Validation8.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhp-9wVMVpFIU94yYZF5LOAqpECExlN_kPYLKUw42d_qnL9HCSNeuAPvGxauFM6-tpOXugE08GW5A-UluYJR66DdZPV8ZkVmp3luY_VcVQM1vZ4uaIZNVyBvHQfWJeuRvq7915EVrBocA/s1600/Validation9.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhp-9wVMVpFIU94yYZF5LOAqpECExlN_kPYLKUw42d_qnL9HCSNeuAPvGxauFM6-tpOXugE08GW5A-UluYJR66DdZPV8ZkVmp3luY_VcVQM1vZ4uaIZNVyBvHQfWJeuRvq7915EVrBocA/s400/Validation9.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgd94ti7agzz3B4y_jqY5QStzAgMqlPSDhjvEHDEEjFK9hYBdVsmzbIMHgjmS9aRbuU07LewqQgTlyoNUL_OGOarjGKztwh7UGclSRKoEYP3Ao1DSt4fazUe1W9ONTBcpswTplbrAr3Tg/s1600/Validation10.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgd94ti7agzz3B4y_jqY5QStzAgMqlPSDhjvEHDEEjFK9hYBdVsmzbIMHgjmS9aRbuU07LewqQgTlyoNUL_OGOarjGKztwh7UGclSRKoEYP3Ao1DSt4fazUe1W9ONTBcpswTplbrAr3Tg/s400/Validation10.jpg" /></a></div>
<p>Using Helper class Create UI elements like Textboxes.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixLRNKsV1H1Pg98RYGF800x6bfJsLeVGLdKfmn6ZRPHoJEX2ve6UmQCdBrdmi10MHao7m9pEK89QUoRpPqQd2-MyR3pOVb3kMjy_CZDJoqtn6m0ccX38mANbJRweHj8q2NHS89ocqoGQ/s1600/Validation11.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixLRNKsV1H1Pg98RYGF800x6bfJsLeVGLdKfmn6ZRPHoJEX2ve6UmQCdBrdmi10MHao7m9pEK89QUoRpPqQd2-MyR3pOVb3kMjy_CZDJoqtn6m0ccX38mANbJRweHj8q2NHS89ocqoGQ/s400/Validation11.jpg" /></a></div>
<p>Output Screen of EnterStudent View using Html helper Class...</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhj7NKcY4-oIdU4abgL51wI0fGVKBXYQhhhw32x-Nbc1feWPgRchabN3b9bnpOJ84dDIo0in-I2Q3UkRhwJi5F0_ffOD0Vp7FfhxFsVf-tTYlaS4tU3vmZBoA_bVfktUgmDw1frAMBX6A/s1600/Validation12.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhj7NKcY4-oIdU4abgL51wI0fGVKBXYQhhhw32x-Nbc1feWPgRchabN3b9bnpOJ84dDIo0in-I2Q3UkRhwJi5F0_ffOD0Vp7FfhxFsVf-tTYlaS4tU3vmZBoA_bVfktUgmDw1frAMBX6A/s400/Validation12.jpg" /></a></div>
<p>Validation Output 2(incorrect RollNo)</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9Li_dDHxsha81FYVPpNJ-Uv4ANCx5_Si7yInrRiMETva4wh3BpbekGSBjMzHWiDGlpTBolgtqOLYxfbZztTjC1QZy-qeWTLHBIde_fLxBo8HCNVizUT5Oge8MtfPo0eTkItR1inMzKw/s1600/Validation13.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9Li_dDHxsha81FYVPpNJ-Uv4ANCx5_Si7yInrRiMETva4wh3BpbekGSBjMzHWiDGlpTBolgtqOLYxfbZztTjC1QZy-qeWTLHBIde_fLxBo8HCNVizUT5Oge8MtfPo0eTkItR1inMzKw/s400/Validation13.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbE2z40y_iTrJQOuBa3tQGAGw2RLagc3t7iFySXRzhX5nWIl1vs1L6OyoG_n91Wjv7GqFcMFxNMPgcP9nTM8UN-xOGFb7at_pluSuk7vimLqc5WOkoyEgQiAWP-4DbfxeeOpZUu-AJFQ/s1600/Validation14.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbE2z40y_iTrJQOuBa3tQGAGw2RLagc3t7iFySXRzhX5nWIl1vs1L6OyoG_n91Wjv7GqFcMFxNMPgcP9nTM8UN-xOGFb7at_pluSuk7vimLqc5WOkoyEgQiAWP-4DbfxeeOpZUu-AJFQ/s400/Validation14.jpg" /></a></div>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-61265659363568351192016-02-27T00:59:00.000-08:002016-02-27T01:08:12.630-08:00Learn ASP.NET MVC step by step: - Part 1<h2>Contents</h2>
<p>
<span style="line-height: 115%; font-family: Times New Roman">
<p><a href="#Introduction">Learn ASP.NET MVC step by step: - Part 1</a></p>
<p><a href="#Introduction">Introduction</a></p>
<p><a href="#Step_1:_Download_&_Install_Microsoft_Visual_Studio_2013_Ultimate">Step 1: Download & Install Microsoft Visual Studio 2013 Ultimate</a></p>
<p><a href="#Step_2:_Creating_project">Step 2: Creating project</a></p>
<p><a href="#Step_3:_Add_a_New_Controller">Step 3: Add a New Controller</a></p>
<p><a href="#Step_4:_Add_a_view">Step 4: Add a view</a></p>
<p><a href="#Step_5:_Putting_code_in_the_controller_and_view">Step 5: Putting code in the controller and view</a></p>
<p><a href="#Step_6:_Run_the_project">Step 6: Run the project</a></p>
<p><a href="#Step_7:_Creating_the_student_model">Step 7: Creating the student model</a></p>
<p><a href="#Step_8:_Adding_the_students_controller">Step 8: Adding the students controller</a></p>
<p><a href="#Step_9:_Creating_the_students_screen">Step 9: Creating the students screen</a></p>
<p><a href="#Step_10:_Writing_logic_for_Submit_click">Step 10: Writing logic for Submit click</a></p>
<p><a href="#Step_11:_Run_the_application">Step 11: Run the application</a></p>
<h2><a name="Introduction">Introduction</a></h2>
<p>This article series is targeted for freshers who want to learn ASP.NET MVC. So if you are senior then I would suggest to start from this <a target="_blank" href="http://www.codeproject.com/Articles/866143/Learn-MVC-step-by-step-in-days-Day">MVC article</a>.</p>
<p>So in this two partarticle I will be creating a simple student data entry screen using ASP.NET MVC , ADO.NET and Jquery. I have used the below youtube video for reference purpose. And would encourage any new ASP.NET MVC learner to first see this videoto get a good kick start.</p>
<iframe width="500" height="315" src="https://www.youtube.com/embed/Lp7nSImO5vk" frameborder="0" allowfullscreen></iframe>
<p>I have broken this tutorial in to two parts. In part 1 we will see what we need to start MVC , we will learn the basics of creating controller , models and view and then we would create a simple student data entry screen and see how it works with the HTTP Post and submit.</p>
<p>In the next article we will learn validations both client side and server side and also we will looking to how to interact with SQL Server using ADO.NET.</p>
<h2>
<a name="Step_1:_Download_&_Install_Microsoft_Visual_Studio_2013_Ultimate">Step 1: Download & Install Microsoft Visual Studio 2013 Ultimate</a></h2>
<p>For doing ASP.NET MVC the first thing we need is visual studio. So go ahead and install visual studio from the below link.</p>
<p><a target="_blank" href="http://www.microsoft.com/en-US/download/details.aspx?id=44915">http://www.microsoft.com/en-US/download/details.aspx?id=44915</a></p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTImDW9qMf5KrNIRiO0MAw3DtDAx4zUol9hN1PgANNt1tsKbhPcqdEHx2n85RIyyrlpBzonOMTu88afGTweLFiIRgOXnX6gEpQIf6I0pNihpBj41EF_iFtQDaD6l4YDpe9zwq2GqWAIg/s1600/SBS1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTImDW9qMf5KrNIRiO0MAw3DtDAx4zUol9hN1PgANNt1tsKbhPcqdEHx2n85RIyyrlpBzonOMTu88afGTweLFiIRgOXnX6gEpQIf6I0pNihpBj41EF_iFtQDaD6l4YDpe9zwq2GqWAIg/s400/SBS1.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYPvrL38zoJf8mFbY2_zsQ-CoJYjUTbAo_nSpRjcmMX4QTMdqee-ZPE64hamog3VcdHIDswxP77nQxJRrjQkczRUFKDzrbvp20UXQsChcBaI3Q9IiKeBsab4wsgz5-ENay1g9brAGTLw/s1600/SBS2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYPvrL38zoJf8mFbY2_zsQ-CoJYjUTbAo_nSpRjcmMX4QTMdqee-ZPE64hamog3VcdHIDswxP77nQxJRrjQkczRUFKDzrbvp20UXQsChcBaI3Q9IiKeBsab4wsgz5-ENay1g9brAGTLw/s400/SBS2.jpg" /></a></div>
<p><h2><a name="Step_2:_Creating_project">Step 2: Creating project</a></h2></p>
<p>Visual studio is an official IDE for doing any kind of Microsoft development work. And to do any Microsoft development we need to create a project. So click on file – menu and project as shown in the below figure.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSpmpG9iCuHrxz9faao8_sOQgumHeIhhWUYQTEEXHD-SoVit5sA8N7Qm6_1reJ0joRjHDjYEWJtbQtZUXjD9TSiyZkLctgt8kwsZOW4R2CYJbtGUOiDhGT1YoKwRIvWX9JJuJvDXJL0Q/s1600/SBS3.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSpmpG9iCuHrxz9faao8_sOQgumHeIhhWUYQTEEXHD-SoVit5sA8N7Qm6_1reJ0joRjHDjYEWJtbQtZUXjD9TSiyZkLctgt8kwsZOW4R2CYJbtGUOiDhGT1YoKwRIvWX9JJuJvDXJL0Q/s400/SBS3.jpg" /></a></div>
<p>As said previously visual studio is used to do any kind of development like Windows, mobile , web and so on. So when we say ASP.NET MVC it is for web application. So select Visual C# à Web à ASP.Net Web Application àEnter File NameàPress ok as shown in the below figure.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPBkP8zBgYrAXsveQSyCwpMarx9WEOfQdegj3wRr4KY8tQ9Igx2wrfQYgSxc6Tq__KcKVdcsKDCpTnuLms_nNfgr0c9EAw9sZieYg7BnlN-Uv5Rr0YrdNrmHROY8cJ5NzEGg_NebxNYA/s1600/SBS4.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPBkP8zBgYrAXsveQSyCwpMarx9WEOfQdegj3wRr4KY8tQ9Igx2wrfQYgSxc6Tq__KcKVdcsKDCpTnuLms_nNfgr0c9EAw9sZieYg7BnlN-Uv5Rr0YrdNrmHROY8cJ5NzEGg_NebxNYA/s400/SBS4.jpg" /></a></div>
<p>Now remember ASP.NET is the main framework on which MVC, WebAPI , Webforms and other web programming technologies work. So once you create the project you will get lot of options, select MVC from the same as shown below.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSc4PwhhId7Ki8RBdnPqrYQNoCTENUC-svA-wSUuFCEXbvEdsYG_1tH3xrdCXuIgS_I6sOnVUiCio0H3elWpxvXuNoyY1-AsvwDGwVV3-C3uT_aYKwGIXynizdH0M3MkJH3G4lAt7_6w/s1600/SBS5.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSc4PwhhId7Ki8RBdnPqrYQNoCTENUC-svA-wSUuFCEXbvEdsYG_1tH3xrdCXuIgS_I6sOnVUiCio0H3elWpxvXuNoyY1-AsvwDGwVV3-C3uT_aYKwGIXynizdH0M3MkJH3G4lAt7_6w/s400/SBS5.jpg" /></a></div>
<p>Also change Authentication to “No Authentication” for now. We will learn more about authentication and authorization later. Lets first get our simple hello world project running and keep complicated things later.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0tqf1D4_0jmkCHT0NJITBeyxTi8m7eRAosgjKaGp81C_krLfaedxGY0RURe5W-rhow2lOV4epcx2TRPCu6XOSi0qJHyDGGqbJo1MsnL1jnpxnkecXOuwXS__kfLvJwjCSJYWqAWVbaQ/s1600/SBS6.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0tqf1D4_0jmkCHT0NJITBeyxTi8m7eRAosgjKaGp81C_krLfaedxGY0RURe5W-rhow2lOV4epcx2TRPCu6XOSi0qJHyDGGqbJo1MsnL1jnpxnkecXOuwXS__kfLvJwjCSJYWqAWVbaQ/s400/SBS6.jpg" /></a></div>
<p>Once you click ok you should see the MVC project created with all necessary files as shown below. Do not get too much confused about the folder and file structure for now. For now concentrate on only three folders “Controller”, “View” and “Model”.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjt1LfOQ3JtApxDX0TJvWGAhi5ksL11owtfUuxYgm0IhK04dJiaN_XAwHdzesY_Tlg21U8AVqGF88MNzUIK3mnxOGjo-S1XNcqzjW9nIPyQh486kCgGr1w9xH-ia9zWRW0ympSvblTs9Q/s1600/SBS7.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjt1LfOQ3JtApxDX0TJvWGAhi5ksL11owtfUuxYgm0IhK04dJiaN_XAwHdzesY_Tlg21U8AVqGF88MNzUIK3mnxOGjo-S1XNcqzjW9nIPyQh486kCgGr1w9xH-ia9zWRW0ympSvblTs9Q/s400/SBS7.jpg" /></a></div>
<h2><a name="Step_3:_Add_a_New_Controller">Step 3: Add a New Controller</a></h2>
<p>In MVC architecture the first hits comes to controller, which in turn loads the model data and this model data is then sent to the view. So the first step is to create the controller.
If you see the solution there is a controller folder. So let us add a new controller by click on the Controllers folderà Add àController.
</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJP4_Piy-N_W_K50wZBDkChJ5SFDg49u7ANVnYf80HRCn3Y_EJ3FsXl-UHV5ALSG3GMVzH7b7D9MXwQAxEldYrDMMLRwo1U1Xyo4muDldVg16_RPqHlD_AOc35Q99Sf_YmJX-hECUIRA/s1600/SBS8.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJP4_Piy-N_W_K50wZBDkChJ5SFDg49u7ANVnYf80HRCn3Y_EJ3FsXl-UHV5ALSG3GMVzH7b7D9MXwQAxEldYrDMMLRwo1U1Xyo4muDldVg16_RPqHlD_AOc35Q99Sf_YmJX-hECUIRA/s400/SBS8.jpg" /></a></div>
<p>The next thing you will see is lot of readymade controller templates. But because we are learning let’s not use any readymade templates let’s start from scratch and select MVC 5 controller empty.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzw5PlUYOuROlQUUMNfLPjaay8RvxpcDMbRXC6O_HEiVL9t9OsdwoSIceQBtdkVU_ZLmdlhpo8i7E9bBFOVtNlOyA3KxEcRF48F-lmEWsSnJ4Pc0TDNH8lzTe1bl5C_JM1_MCatOLRqg/s1600/SBS9.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzw5PlUYOuROlQUUMNfLPjaay8RvxpcDMbRXC6O_HEiVL9t9OsdwoSIceQBtdkVU_ZLmdlhpo8i7E9bBFOVtNlOyA3KxEcRF48F-lmEWsSnJ4Pc0TDNH8lzTe1bl5C_JM1_MCatOLRqg/s400/SBS9.jpg" /></a></div>
<p>Now when we add a controller, do not delete the word controller from the file name. For example if you want to create a “Home” controller then the full name of the file is “HomeController”. The word “Controller” should be present.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjfwOI79eXV6BHbt0ekUNrmsQstGnepQvXpSGVXK8qGfmNTugf8kBb53IKW88PYYojmhBZ1UIzX3LJam9pvSZi1aUsrKH_-wB5LC_smaRcnPYLu4Lbek8-y_MZ1dMvfAfcKFTJJ9SNUxg/s1600/SBS10.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjfwOI79eXV6BHbt0ekUNrmsQstGnepQvXpSGVXK8qGfmNTugf8kBb53IKW88PYYojmhBZ1UIzX3LJam9pvSZi1aUsrKH_-wB5LC_smaRcnPYLu4Lbek8-y_MZ1dMvfAfcKFTJJ9SNUxg/s400/SBS10.jpg" /></a></div>
<p>4.3: Enter the Name Of Controller as Home.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtPQ7GQthJmKjCod4d3iIC7cZs_ldEUo65bQ0_D-VmS7Sgs8g-sQ-xl73kAHIISTccAzNq9wSRYiUhnsiW7QrWjh625-gbBJFGtcHxarCkRCNdqc4AX7kwOgux9BzzreJ5icv2o5Evjw/s1600/SBS11.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtPQ7GQthJmKjCod4d3iIC7cZs_ldEUo65bQ0_D-VmS7Sgs8g-sQ-xl73kAHIISTccAzNq9wSRYiUhnsiW7QrWjh625-gbBJFGtcHxarCkRCNdqc4AX7kwOgux9BzzreJ5icv2o5Evjw/s400/SBS11.jpg" /></a></div>
<h2><a name="Step_4:_Add_a_view">Step 4: Add a view</a></h2>
<p>So now that we have added controller, lets add view. To add view go to views folder and add view as shown below.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhULlFK8Y-JBE2Zxd6MPzHEM7s5qDgp4YHkM3Ju_9AptS-0GfdzhoJUSDotcKxsi7hCFdVr8fUO0jcFsf0gp4u2zeq0bo_KHcbBqzkZ8-AphmHF0NDdVf8hv4zlhyphenhyphenjfsYxL3xxuukyXLg/s1600/SBS12.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhULlFK8Y-JBE2Zxd6MPzHEM7s5qDgp4YHkM3Ju_9AptS-0GfdzhoJUSDotcKxsi7hCFdVr8fUO0jcFsf0gp4u2zeq0bo_KHcbBqzkZ8-AphmHF0NDdVf8hv4zlhyphenhyphenjfsYxL3xxuukyXLg/s400/SBS12.jpg" /></a></div>
<p>Give a proper view name and uncheck the “user layout page” box.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGbBxjbNM_ko-uxEEQ5TWRGHpvRK0I64feGSim06APHzG7i0JNEjs3rnzHES205vpE4AVV_vWnsFY0FDJdULStjLzM9GZifebGfpkFZ3lRbOkKmkQZUfuwSQyFdN8_uMMEXcRCJAUc-w/s1600/SBS13.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGbBxjbNM_ko-uxEEQ5TWRGHpvRK0I64feGSim06APHzG7i0JNEjs3rnzHES205vpE4AVV_vWnsFY0FDJdULStjLzM9GZifebGfpkFZ3lRbOkKmkQZUfuwSQyFdN8_uMMEXcRCJAUc-w/s400/SBS13.jpg" /></a></div>
<p>Finally you should see controller and views added in the respective folder as shown below.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgFt4_0dthNGLu7_NLqWXcBVhLfdTqpVg3M5cRvTh8bkyawrLwJIIPwxfWzNmX507jzHYLrMJB8IgZYDFb-D0bt6hf83oM3zOXcOEDrYoFVFugv_mgDNvN3Pr7uNwP_oDMkgHMKvUi4HQ/s1600/SBS14.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgFt4_0dthNGLu7_NLqWXcBVhLfdTqpVg3M5cRvTh8bkyawrLwJIIPwxfWzNmX507jzHYLrMJB8IgZYDFb-D0bt6hf83oM3zOXcOEDrYoFVFugv_mgDNvN3Pr7uNwP_oDMkgHMKvUi4HQ/s400/SBS14.jpg" /></a></div>
<h2><a name="Step_5:_Putting_code_in_the_controller_and_view">Step 5: Putting code in the controller and view</a></h2>
<p>So let’s start putting some code in Hompage.cshtml (HomePage View). In the HomePage.cshtml we have put a simple hello world text.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikBF9dMPcH2Y4_gQCusr4-9ppbq03j2JVQbET6ECoQpOBphRMDr34KGLAao-PTSyuVnNobYV-Ograf6qBQ_rgJ7KM5LtpHsE-h4g-zLbLjCOpEq4ick6WJF2Vgv6iIzhADzofa7FZLYQ/s1600/SBS15.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikBF9dMPcH2Y4_gQCusr4-9ppbq03j2JVQbET6ECoQpOBphRMDr34KGLAao-PTSyuVnNobYV-Ograf6qBQ_rgJ7KM5LtpHsE-h4g-zLbLjCOpEq4ick6WJF2Vgv6iIzhADzofa7FZLYQ/s400/SBS15.jpg" /></a></div>
<p>In the controller let’s add a simple “ActionResult” method called as “GotoHome” and in that we are returning the view.</p><pre>namespaceHelloWorld.Controllers
{
publicclassHomeController : Controller
{
//
// GET: /Home/
publicActionResult Index()
{
return View();
}
publicActionResultGotoHome()
{
return View("HomePage");
}sp; }
}
}
</pre><h2><a name="Step_6:_Run_the_project">Step 6: Run the project</a></h2><p>So once you are done with the previous steps just press control + f5 and run the project. It’s possible you get a below error as shown below. Do not get discouraged. This error comes because you have not specified the controller and action name.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjwD0H5D1UrcqlkQnsJ39KkDE4QDvY-g1XcVbCI4d8Lxq6Cm60azcNu0XGv9RqB5vi8nMhDtumU7IJrd01TT9HQR8Whgu6DTRyc9E6QZd42M_UJRH0yWsv7IR7POJ9W_2kdF1ffnLuuNQ/s1600/SBS16.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjwD0H5D1UrcqlkQnsJ39KkDE4QDvY-g1XcVbCI4d8Lxq6Cm60azcNu0XGv9RqB5vi8nMhDtumU7IJrd01TT9HQR8Whgu6DTRyc9E6QZd42M_UJRH0yWsv7IR7POJ9W_2kdF1ffnLuuNQ/s400/SBS16.jpg" /></a></div>
<p>On the browser URL type your controller name (without the word controller) followed by action name as shown below. In our case we have “Home” controller and action name is “GotoHome” and you should be able to see the output.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgE71cIRs3VNSFhJ0l6uebTZXzrhp_lEvdKhV2Xuz4S9B18Df2Z9rW56KaRXcLavohJdXVhU6kKRbo6mPUEQGfKDsEZ-mOap85ADCqwWITNCBQyu14IDLq_cM288os66n7yS9MIQv3CFg/s1600/SBS17.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgE71cIRs3VNSFhJ0l6uebTZXzrhp_lEvdKhV2Xuz4S9B18Df2Z9rW56KaRXcLavohJdXVhU6kKRbo6mPUEQGfKDsEZ-mOap85ADCqwWITNCBQyu14IDLq_cM288os66n7yS9MIQv3CFg/s400/SBS17.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQF1Mw_tm8m50fAZs70NTr9GUabQCmvDeu5HjLP3RCIBV7WPEXGOgZ051yBgN15MbddP7EW785EaeNTFumlDQy-8fQ_MxrC1BJNvHl-wZT6kac-eJVt8ClpQh7oYTOPYDu8xXaOoE8BQ/s1600/SBS18.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQF1Mw_tm8m50fAZs70NTr9GUabQCmvDeu5HjLP3RCIBV7WPEXGOgZ051yBgN15MbddP7EW785EaeNTFumlDQy-8fQ_MxrC1BJNvHl-wZT6kac-eJVt8ClpQh7oYTOPYDu8xXaOoE8BQ/s400/SBS18.jpg" /></a></div>
<h2><a name="Step_7:_Creating_the_student_model">Step 7: Creating the student model</a></h2>
<p>Till now we have not added any model. So let us go ahead and create a simple model by the name students. A model is nothing but a class. So right on models folder and add a class as shown in the below figure.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEik1Nmhws_sOHn4uMgLpbgO1q1p7sQyzv8lvxHTj70xBDROq4F76Ab4lTMzAesSj8HD88ioXi5ckycGiLWCJDpv77odEa3W09wYN6mN98vFQOZuRL-M2_ehhSDd8ohLlHvnzEgrK0oBNQ/s1600/SBS19.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEik1Nmhws_sOHn4uMgLpbgO1q1p7sQyzv8lvxHTj70xBDROq4F76Ab4lTMzAesSj8HD88ioXi5ckycGiLWCJDpv77odEa3W09wYN6mN98vFQOZuRL-M2_ehhSDd8ohLlHvnzEgrK0oBNQ/s400/SBS19.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXDJVaP0OCmEoOH32ZsoWzwnRu7Zj3KmgNVtSK8VzmEdyx_tW9gkjB4j5Vw73b1Ddlh9xlBz5CKKxpQ1lLB3QZWdS0oNMJRyH2ftg8_HZgwlS6HZBna08szPdPmtMTGqkTLRus-wVQfg/s1600/SBS20.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXDJVaP0OCmEoOH32ZsoWzwnRu7Zj3KmgNVtSK8VzmEdyx_tW9gkjB4j5Vw73b1Ddlh9xlBz5CKKxpQ1lLB3QZWdS0oNMJRyH2ftg8_HZgwlS6HZBna08szPdPmtMTGqkTLRus-wVQfg/s400/SBS20.jpg" /></a></div>
<p>In the model we have created four properties for the class as shown below.</p><pre>using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
namespaceHelloWorld.Models
{
publicclassStudent
{
publicstringStudentRollNo{ get; set; } //Student Roll No.
publicstringStudentName{ get; set; } //Student Name.
publicstringStudentStd{ get; set; } //Student Standard.
publicstringStudentDIV { get; set; }//Student Divsion.
}
}
</pre><p>Once you write the coderebuild the solution. I again repeat do not miss this step REBUILT THE SOLUTION.</p><h2><a name="Step_8:_Adding_the_students_controller">Step 8: Adding the students controller</a></h2><p>Let’s add a students controller from where we invoke the data entry screen for the students.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbastuxlNrflxDYznJwA-xEetddUZ2_KnEI9c2JQ4-fDc53cDYRMJfcXezT4UBN1s134giGcPLdnQG5EE3K_mIIGau8xHYY0dhvvUciH5oRo1IA6-YYd0t1jdLwCFaRuB13Iw8ZJYctQ/s1600/SBS21.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbastuxlNrflxDYznJwA-xEetddUZ2_KnEI9c2JQ4-fDc53cDYRMJfcXezT4UBN1s134giGcPLdnQG5EE3K_mIIGau8xHYY0dhvvUciH5oRo1IA6-YYd0t1jdLwCFaRuB13Iw8ZJYctQ/s400/SBS21.jpg" /></a></div>
<p>In the controller do not forget to import model namespace.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhyL5SuAIWrqx37jsuSaDfFtSJs0OI0_D3S5pWN3Dcwh1NVBq5bYYgwybpcZZAwh5PJcQ9275kDqFWiVGkubOYIcRyGD5imJDyHeETy3lfEJY23kxtUZcfrMzQZinTScYHvNfzHNH8pZQ/s1600/SBS22.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhyL5SuAIWrqx37jsuSaDfFtSJs0OI0_D3S5pWN3Dcwh1NVBq5bYYgwybpcZZAwh5PJcQ9275kDqFWiVGkubOYIcRyGD5imJDyHeETy3lfEJY23kxtUZcfrMzQZinTScYHvNfzHNH8pZQ/s400/SBS22.jpg" /></a></div>
<p>Lets add an action “Enter” which will invoke the data entry screen.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjeEMvEdWet8L9R-VPp3psrvFTYjlDsqxld2mK47GOwXVfuMivBGGmCtXTi5Vt5Vo4jMVRK4L5GAAOrR5niXR0Ns0wSq3v6nVxCMfHUDPSFO7YXg4fNM_HPPIcqlVkI0Ih2yfh2NARXbg/s1600/SBS23.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjeEMvEdWet8L9R-VPp3psrvFTYjlDsqxld2mK47GOwXVfuMivBGGmCtXTi5Vt5Vo4jMVRK4L5GAAOrR5niXR0Ns0wSq3v6nVxCMfHUDPSFO7YXg4fNM_HPPIcqlVkI0Ih2yfh2NARXbg/s400/SBS23.jpg" /></a></div>
<h2><a name="Step_9:_Creating_the_students_screen">Step 9: Creating the students screen</a></h2><p>So we have completed the model and the controller let us add a view for the same.
So right click on the “Enter” Action and click add view as shown in the below figure.
</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKE01aG2KwjHmKmj4uBGG3ZFH4sFo7VfSibpcT2sZzecSMqSS9hHdrHQFIIcU47M7h0iTu0q7Y00ZH_kSj2iJU1PxqhjXcLpIWdHOR4ZdRyx2uePG7mkRuDSZNmtUolWgFnMlozznSoQ/s1600/SBS24.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKE01aG2KwjHmKmj4uBGG3ZFH4sFo7VfSibpcT2sZzecSMqSS9hHdrHQFIIcU47M7h0iTu0q7Y00ZH_kSj2iJU1PxqhjXcLpIWdHOR4ZdRyx2uePG7mkRuDSZNmtUolWgFnMlozznSoQ/s400/SBS24.jpg" /></a></div>
<p>Lets give the view name as “EnterStudent” and uncheck the layout page box. Layout pages are like master pages in ASP.NET webforms.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEJ2E0UwMmjcBYFtevY4SjOZBn3Zrh_6cdaXnatpL9dxMPj-9k0Yx9LFhFLXDo7DfxIriagP0-qoWwXoHlamB0yV4zwaH1vZ9RrPoJ3XMNSQdIbkbRJAk-sUHZsYIHL2WzxMdeCzgo9Q/s1600/SBS25.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEJ2E0UwMmjcBYFtevY4SjOZBn3Zrh_6cdaXnatpL9dxMPj-9k0Yx9LFhFLXDo7DfxIriagP0-qoWwXoHlamB0yV4zwaH1vZ9RrPoJ3XMNSQdIbkbRJAk-sUHZsYIHL2WzxMdeCzgo9Q/s400/SBS25.jpg" /></a></div>
<p>In view let’s put the below code which has four textboxes for the student data and one submit button.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh7WVAqjv9QnssMx1sYKM9S_w0vR_Lw8_9Xt3hl9xqAzrucRJGnfiQB2xdfUm9Wl8EQN1zQ4dNsJVFYLync4mSqWHd61eP5lwbXbV8LGC6ZE7mfIIGwBDGkfANqzSl6DwsDizRr2UkDqg/s1600/SBS26.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh7WVAqjv9QnssMx1sYKM9S_w0vR_Lw8_9Xt3hl9xqAzrucRJGnfiQB2xdfUm9Wl8EQN1zQ4dNsJVFYLync4mSqWHd61eP5lwbXbV8LGC6ZE7mfIIGwBDGkfANqzSl6DwsDizRr2UkDqg/s400/SBS26.jpg" /></a></div>
<p>So now the user will enter data and click on Submit button , we need some kind of logic in the controller for handling the submit click.</p><h2><a name="Step_10:_Writing_logic_for_Submit_click">Step 10: Writing logic for Submit click</a></h2><p>To handle the submit click we need to create submit action in the student controller.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiy-ah6PJZ5ZUcUUxYdwT1A0Y5WAI4H1PaC6vxwTbezTBcDaMOdLMVWuAQIkAK0oNwkYGvYEIO_OqoIaWv7vU7NQgOhboJQHL0zHC_azAO3ip8FLopwHsKVbIQWPHKc9Po39-V0rOB2Ow/s1600/SBS27.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiy-ah6PJZ5ZUcUUxYdwT1A0Y5WAI4H1PaC6vxwTbezTBcDaMOdLMVWuAQIkAK0oNwkYGvYEIO_OqoIaWv7vU7NQgOhboJQHL0zHC_azAO3ip8FLopwHsKVbIQWPHKc9Po39-V0rOB2Ow/s400/SBS27.jpg" /></a></div>
<p>When this submit action is called the data sent from the form will be collected and displayed in a view. Let us add a new view with name “Student” to this submit action.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjwbiZGOXdfDs9K65z6owhjBvrABHHj-UDoPF-8wfTWa4U6NTZvb9e6BhQ18hAGlWqTw0hXTzJfNkbVfqoryyFKHfxmGBLfKPzhJ4Oa5TPfilf4X_mamL7j8GynC0uGDS_pG_UyA9JHoA/s1600/SBS28.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjwbiZGOXdfDs9K65z6owhjBvrABHHj-UDoPF-8wfTWa4U6NTZvb9e6BhQ18hAGlWqTw0hXTzJfNkbVfqoryyFKHfxmGBLfKPzhJ4Oa5TPfilf4X_mamL7j8GynC0uGDS_pG_UyA9JHoA/s400/SBS28.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_DyITyM81sxPCBHCkdnKxKCl2zrsPF72VZJjs88CNQBq67a_ex98E2ue1emzasHqGbPv_HeHlV79huKtPE86AVjqETQse6FkhGScOhS8KNHlpeh0kfuJ9qA6O80ZTuoQ7EWNZF_hp3Q/s1600/SBS29.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_DyITyM81sxPCBHCkdnKxKCl2zrsPF72VZJjs88CNQBq67a_ex98E2ue1emzasHqGbPv_HeHlV79huKtPE86AVjqETQse6FkhGScOhS8KNHlpeh0kfuJ9qA6O80ZTuoQ7EWNZF_hp3Q/s400/SBS29.jpg" /></a></div>
<p>This view we will connect with the model namespace where we have the customer controller.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhWm8iT7HX-R4dTV5KMMzvcw0hNwKKKpcRSrFe04PdirtZrXhnn87xSyo_5XzHX1RbNRxqVqnt4t99GsGZI5skVR015l4YoboPEykyzCiM9ba_E2uu2Hl0F7fsumlMhw_zMnbnlNr-YfA/s1600/SBS30.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhWm8iT7HX-R4dTV5KMMzvcw0hNwKKKpcRSrFe04PdirtZrXhnn87xSyo_5XzHX1RbNRxqVqnt4t99GsGZI5skVR015l4YoboPEykyzCiM9ba_E2uu2Hl0F7fsumlMhw_zMnbnlNr-YfA/s400/SBS30.jpg" /></a></div>
<p>Below is the view of the student.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGkNnLVyNTaQ0biKz71hHQpFgCgbN2G4wMcthAOH6YUq1VJY7-evZ3V-KcbZOF-AR0S_4Qoa_BT9_GD924nbxGMd28i7KA4GTThi4RgCJ10v9X_rGIKsN51OxYqgE8njWtOL5BGYtchA/s1600/SBS31.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGkNnLVyNTaQ0biKz71hHQpFgCgbN2G4wMcthAOH6YUq1VJY7-evZ3V-KcbZOF-AR0S_4Qoa_BT9_GD924nbxGMd28i7KA4GTThi4RgCJ10v9X_rGIKsN51OxYqgE8njWtOL5BGYtchA/s400/SBS31.jpg" /></a></div>
<p>When the user click on submit we need to send data to the submit action. So on the form given the action name as “Submit” and method as “Post”. And also ensure that all textboxes are provided with a name as shown in the below code.
For now keep name of the textbox and the class property names same.
</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAzTWXYF4I6z84Au_5PdC3k5CM5e9TWGTSb95Tt7x9yFXIJPldBSIi6V7xAvyU-QxYiasdXQprxAOg1V9Mw7pRXaAPTAGXHkh5IISQw1eQp5U6IA-aUyD96H0x8c7HDsl3tOKbOmhqsg/s1600/SBS32.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAzTWXYF4I6z84Au_5PdC3k5CM5e9TWGTSb95Tt7x9yFXIJPldBSIi6V7xAvyU-QxYiasdXQprxAOg1V9Mw7pRXaAPTAGXHkh5IISQw1eQp5U6IA-aUyD96H0x8c7HDsl3tOKbOmhqsg/s400/SBS32.jpg" /></a></div>
<p>In the submit action we will use the request object to fetch data and load the student object and this student object is sent to “Student” view which we have created.</p><pre>publicActionResult Submit()
{
Studentobj = newStudent();
obj.StudentRollNo=Request.Form["StudentRollno"];
obj.StudentName = Request.Form["StudentName"];
obj.StudentStd = Request.Form["StudentStd"];
obj.StudentDIV = Request.Form["StudentDiv"];
return View("Student",obj);
}
</pre>
<p>In this the student view we are displaying the values by using the “Model” object as shown below.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimHM1knmvmnl__II6jP9GUPGiWEW7n1ReVn5mzUfAC-vdhtI-QpFoapuQwX1LAWVkwLmNxoQWTCGILnuw8b0x7-v3VpZ8J8QsWXsc6FX7j5X0ij6niO9HRtH_a6ZTI2jah5ogCqKeXRw/s1600/SBS33.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimHM1knmvmnl__II6jP9GUPGiWEW7n1ReVn5mzUfAC-vdhtI-QpFoapuQwX1LAWVkwLmNxoQWTCGILnuw8b0x7-v3VpZ8J8QsWXsc6FX7j5X0ij6niO9HRtH_a6ZTI2jah5ogCqKeXRw/s400/SBS33.jpg" /></a></div>
<h2><a name="Step_11:_Run_the_application">Step 11: Run the application</a></h2><p>So now that all the hard work is done, take a deep breath and press control + f5 and enter the URL in format of controller name/action name :- <a href="http://localhost:22144/student/Enter">http://localhost:22144/student/Enter</a></p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEQyuUiM9rigLy3vGEgUcIfiw9d_cnumv-84iDCwTFdwrzHIp5TnSW8liJkBjhlCfWFp2w3NH683Z6K0R2EEgdXxP4L4GrxmNLAp49yMXf4tcZdltTJaH9Q4-TDRuGR60y1030jNavNQ/s1600/SBS34.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEQyuUiM9rigLy3vGEgUcIfiw9d_cnumv-84iDCwTFdwrzHIp5TnSW8liJkBjhlCfWFp2w3NH683Z6K0R2EEgdXxP4L4GrxmNLAp49yMXf4tcZdltTJaH9Q4-TDRuGR60y1030jNavNQ/s400/SBS34.jpg" /></a></div>
<p>Enter data in to the text boxes and press submit.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEirhwCEEUQvbH57f2zkeEbPqR7PfMOzz9PetpGx90gHJgyAd16g97jxei773o31zIXuurv4tuq21JZgPeLPQJQf2vkwVBB-cM-kHtaaswSVuiRegznqtiy1vDps9Zs6-YP5ErVMHMcykQ/s1600/SBS35.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEirhwCEEUQvbH57f2zkeEbPqR7PfMOzz9PetpGx90gHJgyAd16g97jxei773o31zIXuurv4tuq21JZgPeLPQJQf2vkwVBB-cM-kHtaaswSVuiRegznqtiy1vDps9Zs6-YP5ErVMHMcykQ/s400/SBS35.jpg" /></a></div>
<p>And you should see this screen.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhg6r55bEb80YLnrJUMrV50o55Mjxqchyd9nZHNZfef_yHweuMQ38sgsyyETb_FfySkfHkV0RrZ-Uj-JVglcHWr0NnHzhTzrqTXCX2Cz2WMF-_5zZ1QJIjjfP30hRKnXMFFQCA95SmR4g/s1600/SBS36.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhg6r55bEb80YLnrJUMrV50o55Mjxqchyd9nZHNZfef_yHweuMQ38sgsyyETb_FfySkfHkV0RrZ-Uj-JVglcHWr0NnHzhTzrqTXCX2Cz2WMF-_5zZ1QJIjjfP30hRKnXMFFQCA95SmR4g/s400/SBS36.jpg" /></a></div>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-10508858703360718282016-02-12T21:31:00.000-08:002016-02-12T21:59:43.248-08:00Learn AngularJS Step by Step– Lab 2(Events and Validations)<h2>Contents</h2>
<p><a href="#Introduction">Learn Angularjs Step by Step – Lab 2 (Events and
Validations)</a></p>
<p><a href="#Introduction">Introduction</a></p>
<p><a href="#Step_6:-_Creating_functions_and_adding_events">Step 6:- Creating functions and adding events</a></p>
<p><a href="#Step_7:-_Adding_HTML_validators">Step 7:- Adding HTML validators</a></p>
<p><a href="#Step_8:-_Using_$valid_property_of_angular">Step 8:- Using $valid property of angular</a></p>
<p><a href="#Step_9:-_Run_the_program">Step 9:- Run the program</a></p>
<p><a href="#Step_10:-_Understanding_the_full_code_till_Lab_2">Step 10:- Understanding the full code till Lab 2</a></p>
<p><a href="#So_what’s_next_in_Lab_3">So what’s next in Lab 3</a></p>
<h2><a name="Introduction">Introduction</a></h2>
<p>In the previous
<a href="http://computerauthor.blogspot.com/2016/02/learn-angularjs-step-by-step-lab-1.html">Learn AngularJS Step by Step(Lab 1)</a> series we saw a simple hello world example and while doing so we learnt the basics of Angular. Let us continue with Lab 2 of Learn AngularJs step by step series and in this Lab we will see how to create events and do validations in AngularJS.</p>
<p>In Lab 1 we executed 5 steps so let us continue in this Lab with step 6.</p>
<p>I would recommend you to go through the below 1 hour Learn Angular youtube video for better and speedy understanding.</p>
<iframe width="500" height="360" src="https://www.youtube.com/embed/0kmdjqgO9IY" frameborder="0" allowfullscreen></iframe>
<h2><a name="Step_6:-_Creating_functions_and_adding_events">Step 6:- Creating functions and adding events</a></h2>
<p>So let us add a simple function “Fun1” to the same “Hello” class we created in Lab 1. “Fun1” function will display whatever data is entered into “txthello” variableusing alert.</p>
<pre>function Hello($scope) {
$scope.txthello = "";
$scope.Fun1 = function(){
alert($scope.txthello);
}
}
}
</pre>
<p>Now if you are thinking that the above method “Fun1()” can be called by simple JavaScript then you are on a very wrong track. Instances created by Angular can only be accessed by angular events. So the below code will not work.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigZPS8yMBdHOxBffTZyENJ1rX54SxI4Go5SAcsyQMIld7aPFjIRKiQLf04gql7fQV8Ks7XDd1AIgKVfmKmeuF7tSB2QIMgmLGcz8ocQXeSif1EpDXTcXeq9kLOW4sd9AysmT2RmguF8Q/s1600/1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigZPS8yMBdHOxBffTZyENJ1rX54SxI4Go5SAcsyQMIld7aPFjIRKiQLf04gql7fQV8Ks7XDd1AIgKVfmKmeuF7tSB2QIMgmLGcz8ocQXeSif1EpDXTcXeq9kLOW4sd9AysmT2RmguF8Q/s400/1.jpg" /></a></div>
<p>We need to use angular events to make call to the function. So if we want to call “Fun1” of we need to use “ng-click” of Angular.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8lgA3h8WGlmBjEggS89gUZijX3SOyn1rNkY2dk12Sy5Cdh0baxGY3M6p-6ipbkblONMO7liaM7N5jzWPU_ws-1QCz_XoesWpLpafKgNyvtlS2A08VZO9RaRpfGmGG_tYMYddVFCp7Dg/s1600/2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8lgA3h8WGlmBjEggS89gUZijX3SOyn1rNkY2dk12Sy5Cdh0baxGY3M6p-6ipbkblONMO7liaM7N5jzWPU_ws-1QCz_XoesWpLpafKgNyvtlS2A08VZO9RaRpfGmGG_tYMYddVFCp7Dg/s400/2.jpg" /></a></div>
<p>Once done you should be able to see the click event in action as shown in the below figures.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0Gc6KQczj9tftz1FRSL_OhsPRPKiXIt3XNrOEvQdjxcYSStLYT7pKnNnbF6IsoUZ6-W3nmPjPrbAap5KiokqHiPbZF57hM5v0IgU8tksnzimJThOndQVYRvueNRyXHwjZp-pIsqXgPQ/s1600/3.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0Gc6KQczj9tftz1FRSL_OhsPRPKiXIt3XNrOEvQdjxcYSStLYT7pKnNnbF6IsoUZ6-W3nmPjPrbAap5KiokqHiPbZF57hM5v0IgU8tksnzimJThOndQVYRvueNRyXHwjZp-pIsqXgPQ/s400/3.jpg" /></a></div>
Below is the complete source code of angular event as described in the above steps.<p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCyZSNv1h8m24CJs7a-H9qa4svYioIqeS0hb-10SB5ybUmOIIf_UhUSubRDHcyUAYriHHIL-9ivo9VBx7zxNRcsKznruQWj_TF420HKGFGB_HXOSrzZYmh-yOTniwb40xfELJX5_mCHg/s1600/4.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCyZSNv1h8m24CJs7a-H9qa4svYioIqeS0hb-10SB5ybUmOIIf_UhUSubRDHcyUAYriHHIL-9ivo9VBx7zxNRcsKznruQWj_TF420HKGFGB_HXOSrzZYmh-yOTniwb40xfELJX5_mCHg/s400/4.jpg" /></a></div>
<h2><a name="Step_7:-_Adding_HTML_validators">Step 7:- Adding HTML validators</a></h2>
<p>Angular validations use HTML 5 validators internally. So let’s say we want to make sure that “txthello” cannot be null. So we need to apply three steps :-</p>
<ul><li>Decorate the input type text with HTML validators. For example in the below code we have applied “required” attribute. There are lots of other validators in HTML 5 as well , I would suggest you go through the complete list from this article. In this article we will just use “required” for now.</li>
<li>The input text which has validators has to be enclosed in a form tag which has to named and also the textbox has to be named. For example we have named the form as “frm1” and textbox as “texthello”. Please note ID does not matter for Angular validation it should have names.</li>
<li>Now HTML validators are processed by the browsers automatically.When the end users hit submit button they would get errors in the following way in chrome. Now we do not want to use the chrome or IE validation display messages but we want angular to take control.</li>
</ul>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhoWdGmCo6Mj3OlzADdi2qvicE4jaSwrQQu_X7ZcgsdmHUFk7bFUWHPgna4YMAt5rLjuR2FlPSNLVf62PQ18-f_rbDk9G8supi7-ZUPJQHNBY0R10OcznIAhfwLUZk4HWKm7uo7y8IUow/s1600/5.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhoWdGmCo6Mj3OlzADdi2qvicE4jaSwrQQu_X7ZcgsdmHUFk7bFUWHPgna4YMAt5rLjuR2FlPSNLVf62PQ18-f_rbDk9G8supi7-ZUPJQHNBY0R10OcznIAhfwLUZk4HWKm7uo7y8IUow/s400/5.jpg" /></a></div>
<p>Below is the code which has the above three steps applied.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEin0AmNaScva56cUuKika4OdkOG0BU4I2UwYTakLIbk_IId_Zlxx2HZhfuLb5k0boFvxaZEKGDOWRqDA_LfOZMXNaKUdaiuMBapwTGo-0hqesb5f68ze8ruB62WHYEhdqzXy3GG-Y9igQ/s1600/6.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEin0AmNaScva56cUuKika4OdkOG0BU4I2UwYTakLIbk_IId_Zlxx2HZhfuLb5k0boFvxaZEKGDOWRqDA_LfOZMXNaKUdaiuMBapwTGo-0hqesb5f68ze8ruB62WHYEhdqzXy3GG-Y9igQ/s400/6.jpg" /></a></div>
<a name="Step_8:-_Using_$valid_property_of_angular">Step 8:- Using $valid property of angular</a></h2>
<p>So now we are all set. We have the HTML validators in place. We would like to achieve two things when the end user types data in the input fields:-</p>
<ul><li>Disable and enable button if there are validation issues.</li>
<li>Show/Hide error message of the “DIV” tag.</li>
</ul>
<p>For that we need to use “ng-disabled” and “ng-show” directives of Angular. When any validation fire “$valid” property of angular is evaluated and set to true and false depending on data.Using this property we can enable/disable and show/hide HTML elements. </p>
<p>See the below code where we have set “$valid” to the button for enabling and disabling and to hide/show the “DIV” tag we have used “ng-show”.</p>
<p>Also very closely observe we have negated (“!”) the results.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2D-L_pZXMbYgqMN4DNte1xLG7QXEISFYSN2hiNksnL2OyWh8yLea-Oze6ryhu5reIalBFpBLECsNkgIYLlIg4mOJeAeGAMrqYVsj2H1yKGaTaGFKXuuWPI6n3JD4gbnqAQBdT-JszJg/s1600/7.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2D-L_pZXMbYgqMN4DNte1xLG7QXEISFYSN2hiNksnL2OyWh8yLea-Oze6ryhu5reIalBFpBLECsNkgIYLlIg4mOJeAeGAMrqYVsj2H1yKGaTaGFKXuuWPI6n3JD4gbnqAQBdT-JszJg/s400/7.jpg" /></a></div>
<h2><a name="Step_9:-_Run_the_program">Step 9:- Run the program</a></h2>
<p>Once all things are done, press control + f5 and enjoy your hardwork. Below is an animated GIF which shows how the program looks like when it’s running.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEeGHYb1Bvkk7Ny6YbgTF6eUO8lXSX4vyR8tpOggkw12rhmsq38d5OM3AsRnqjRGvmAxN13ngWTcIGYG8TwVo7-AZi44Cyxg6c6g-fR3QC4rFAVatZG7-KZQSMFVzxAruwBg_C_Iak3A/s1600/8.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEeGHYb1Bvkk7Ny6YbgTF6eUO8lXSX4vyR8tpOggkw12rhmsq38d5OM3AsRnqjRGvmAxN13ngWTcIGYG8TwVo7-AZi44Cyxg6c6g-fR3QC4rFAVatZG7-KZQSMFVzxAruwBg_C_Iak3A/s400/8.gif" /></a></div>
<h2><a name="Step_10:-_Understanding_the_full_code_till_Lab_2">Step 10:- Understanding the full code till Lab 2</a></h2>
<p>Below is the full code till Lab 2 with basics , events and validation.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXRbZGy6dKVlfYF26iQ8QfB-ZlG-qtJ8iMG78tj9pM4WGTYJM97PEWKOlR7OT7DHQMp7PhtDQPH3Nmx581shYs2MRg216DWro4wsBpYfiBh4n70aTSIszIoneu-bBtcSnxpVbV9yo2sg/s1600/9.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXRbZGy6dKVlfYF26iQ8QfB-ZlG-qtJ8iMG78tj9pM4WGTYJM97PEWKOlR7OT7DHQMp7PhtDQPH3Nmx581shYs2MRg216DWro4wsBpYfiBh4n70aTSIszIoneu-bBtcSnxpVbV9yo2sg/s400/9.jpg" /></a></div>
<h2><a name="So_what’s_next_in_Lab_3">So what’s next in Lab 3</a></h2>
<p>In the next lab 3 of Learn AngularJS step by step we will see how to post Angular data to WebAPI.</p>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-27704934118158370042016-02-07T01:21:00.002-08:002016-02-07T01:41:01.609-08:00Learn Angularjs Step by Step– Lab 1<h2>Contents</h2>
<p><a href="#Introduction">Learn AngularJS Step by Step – Lab 1</a></p>
<p><a href="#Introduction">Introduction</a></p>
<p><a href="#Step_1:-_Creating_a_simple_HTML_hello_world_project">Step 1:- Creating a simple HTML hello world project</a></p>
<p><a href="#Step_2:-_Get_AngularJS_framework">Step 2:- Get AngularJS framework</a></p>
<p><a href="#Step_3:-_Applying_ng-controller_,ng-model_and_expressions">Step 3:- Applying ng-controller ,ng-model and expressions</a></p>
<p><a href="#Step_4:-_ng-app_and_understanding_scoping">Step 4:- ng-app and understanding scoping</a></p>
<p><a href="#Step_5:Bootstrapping_the_project_and_seeing_the_results">Step 5:Bootstrapping the project and seeing the results</a></p>
<p><a href="#Final_Complete_code">Final Complete code</a></p>
<p><a href="#What_in_Next_Lab_">What in Next Lab ?</a></p>
<h2><a name="Introduction">Introduction</a></h2>
<p>AngularJS is one the most talked JavaScript framework. Rich bindings of Angular make HTML and Javascript object interaction like a breeze. The core reason why Angular was born was
binding, binding and binding. It’s a binding framework it binds the HTML UI with Javascript objects.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEix9LPN8TgrOTOd5VT_L4pFDVyZcdMStvgk6PFFvTgDFXo09bE-21s9nefzfuz0hgOgntcRAlIgKopCB-IkyyMalhB7uSnbMNZK8tvgwpZqpX1Kv-qlML1uG-eRigEjmHilgo_9ekvxeQ/s1600/1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEix9LPN8TgrOTOd5VT_L4pFDVyZcdMStvgk6PFFvTgDFXo09bE-21s9nefzfuz0hgOgntcRAlIgKopCB-IkyyMalhB7uSnbMNZK8tvgwpZqpX1Kv-qlML1uG-eRigEjmHilgo_9ekvxeQ/s400/1.jpg" /></a></div>
<p>By doing so it reduces lot of interaction code we need to write between HTML and Javascript objects. </p>
<p>For the same reason Angular team also named it as a MVW framework. Where “M” stands for javascript objects , “V” stands for HTML UI and “W” stands Whatever code that binds the
model and UI. Lot of people call this whatever code as gel code , behind code , view model and so on.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEioK7aXzlDuqjidIgWN5pS_fxBxAE71MTZxflAQUzu2J4oPn0oZYNjq1iWRwLAJwJTD5FtlbfKejUzOEtGwmFvuyTfVuj2YE7AuYHEta7PQxSKWb1d0QVQhl_VoKami-uadHR6d1u0PDQ/s1600/2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEioK7aXzlDuqjidIgWN5pS_fxBxAE71MTZxflAQUzu2J4oPn0oZYNjq1iWRwLAJwJTD5FtlbfKejUzOEtGwmFvuyTfVuj2YE7AuYHEta7PQxSKWb1d0QVQhl_VoKami-uadHR6d1u0PDQ/s400/2.jpg" /></a></div>
<p>To understand Angular MVW framework concept I would suggest you to see the below 1 hour youtube video which explains the concept in more detail.</p>
<iframe width="480" height="315" src="https://www.youtube.com/embed/0kmdjqgO9IY" frameborder="0" allowfullscreen></iframe>
<p>So in this demo we will create simple UI </p>
<h2><a name="Step_1:-_Creating_a_simple_HTML_hello_world_project">Step 1:- Creating a simple HTML hello world project</a></h2>
<p>So let us go ahead and create a simple project and get angular in it. Now when we create any project in visual studio it always has that Microsoft stamp attached to it.</p>
<p>I mean for example when you create an empty ASP.NET Web application you would get“Web.config” files , ASPX files etc. These files are very much Microsoft specific.</p>
<p>Now to maintain the purity of angular we would like create a simple project which does not have Microsoft stamp on it. But at the same time we would like to get the benefits of visual
studio intellisense.</p>
<p>This would be a simple project with just HTML , CSS , JS files and Angular files. So create a simple folder in your hard drive and open visual studio and click fileàopenàWebsite as show in
the below figure. When you open a folder as website , visual studio does not add unnecessary files like web.config and global.asax files etc.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdMCVjKy8LPG_ddgq8A3HQ2DzaDxPNHanzwYA4jARzJasIuXF75NcVqPJtCHAkzk4D9u1aLz2EeXaBSetU69QxnfBgfLUzZhJLEStiqmFHtKIe0HKEok84OVGk-83VafoEbLB30MEAEg/s1600/3.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdMCVjKy8LPG_ddgq8A3HQ2DzaDxPNHanzwYA4jARzJasIuXF75NcVqPJtCHAkzk4D9u1aLz2EeXaBSetU69QxnfBgfLUzZhJLEStiqmFHtKIe0HKEok84OVGk-83VafoEbLB30MEAEg/s400/3.jpg" /></a></div>
<p>And give the path of the folder as shown in the below figure.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPhn9zLc1n-TTfaNg8pKgZQYMAM2MaGOLFQXatnc3ujbp2qgK-STvbFYd6a6OYMDcTWZrnWPnzJVRNH4taW5U2sLRJGXqTXg14GhqVmjRGyb4dj5JPCHR2b4l601pVqbXLYflLs0LPCQ/s1600/4.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPhn9zLc1n-TTfaNg8pKgZQYMAM2MaGOLFQXatnc3ujbp2qgK-STvbFYd6a6OYMDcTWZrnWPnzJVRNH4taW5U2sLRJGXqTXg14GhqVmjRGyb4dj5JPCHR2b4l601pVqbXLYflLs0LPCQ/s400/4.jpg" /></a></div>
<p>Once you have done you would see a very simple project which does not have anything. It just has a simple project with no Microsoft specific files.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjY5_bnjudu6Fe0G5SKk3FfisqAhcZz4hzjA0orLEma-3Js7lp3S2JvgwOQZ2FQJfEsy5dwNGdoiHNj3-jZ94uSG4vM39Tr0uBtbuauCwsQM7Hw0jAu2_VPv5vwJSTMcyQL_UaoAE98MQ/s1600/5.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjY5_bnjudu6Fe0G5SKk3FfisqAhcZz4hzjA0orLEma-3Js7lp3S2JvgwOQZ2FQJfEsy5dwNGdoiHNj3-jZ94uSG4vM39Tr0uBtbuauCwsQM7Hw0jAu2_VPv5vwJSTMcyQL_UaoAE98MQ/s400/5.jpg" /></a></div>
<p>In this project let us add a simple HTML page and name it as “HelloWorld.html”.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikvKuit0izHUw7GwwDBykCDuG1LTC9Q822CZ3CGS7vj2D0x9ngtH_HNfwhtm0czXE4MfwmXZH5_DArzwWtYKejclwr_OmoeN7nwrAOHAQX9CrvDaNIAJoM-q9SodgFzGtRa9bGlTqWog/s1600/6.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikvKuit0izHUw7GwwDBykCDuG1LTC9Q822CZ3CGS7vj2D0x9ngtH_HNfwhtm0czXE4MfwmXZH5_DArzwWtYKejclwr_OmoeN7nwrAOHAQX9CrvDaNIAJoM-q9SodgFzGtRa9bGlTqWog/s400/6.jpg" /></a></div>
<p> </p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEib8pPkKxiZGrqfSWMwFJ_nFkKC6EL0ATpkOdn4UChsARbNSpPQ-SvDraGVUYAN0S1Jrrly6gkQD87h73e1_kG3Y9HQ0Q2ONzO-k5WfBqO2K43AR3GVRMXtuS-Q8D_8Piq7pqybjgst-w/s1600/7.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEib8pPkKxiZGrqfSWMwFJ_nFkKC6EL0ATpkOdn4UChsARbNSpPQ-SvDraGVUYAN0S1Jrrly6gkQD87h73e1_kG3Y9HQ0Q2ONzO-k5WfBqO2K43AR3GVRMXtuS-Q8D_8Piq7pqybjgst-w/s400/7.jpg" /></a></div>
<p>In thisHTML page we will create a simple input text box called as “txtHello” and this text box will bind with “Hello” javascript function / class.</p>
<p>You can see the below code where we have the hello world text box and the javascript function “Hello” and our goal is to bind the text box with the javascript function.</p>
<p>And now we would be using Angular to bind these two entities.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgcrzZcDIdBmAbeEQUYkrOxFdI0AVS13iqjGNsC_7udFefzGDVwj8bT4L0jP9sY0NhZPFOW3O6WYtujbmlPmByOcT_-Y4yqrKQJrg3ocD1CGlbdL8-EawNupR4AVf258jmWMTeTtqmRzw/s1600/8.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgcrzZcDIdBmAbeEQUYkrOxFdI0AVS13iqjGNsC_7udFefzGDVwj8bT4L0jP9sY0NhZPFOW3O6WYtujbmlPmByOcT_-Y4yqrKQJrg3ocD1CGlbdL8-EawNupR4AVf258jmWMTeTtqmRzw/s400/8.jpg" /></a></div>
<h2><a name="Step_2:-_Get_AngularJS_framework">Step 2:- Get AngularJS framework</a></h2>
<p>Now that we have the HTML UI and Javascript class in place let us first get AngularJS framework. Right click on project and click Manage NuGet Packages as shown in the below figure.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHWOZjryG71PhjMaUoWauOlLg-K_VgUaqHOhpdSteOd2du8GVw5RAmGl29DKdsCl7XeIMOTuhRKgYIfQ13-3pPuLBxbmOOo9dQAMhgaBqyu2Clro24gfb9TLqvp1xwpMOoySthmADhwA/s1600/9.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHWOZjryG71PhjMaUoWauOlLg-K_VgUaqHOhpdSteOd2du8GVw5RAmGl29DKdsCl7XeIMOTuhRKgYIfQ13-3pPuLBxbmOOo9dQAMhgaBqyu2Clro24gfb9TLqvp1xwpMOoySthmADhwA/s400/9.jpg" /></a></div>
<p>Search Angular in the search text box and install “AngularJS” core from the list. You can see lot of other Angular packages those are extensions of Angular. We will see the other packages
later on gradually.<br>
The most important is Angular core so click on install and get it.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiPLvfnBNHofSCvwKuu13RmvON2DBPpXE7cdQSFsw03y4SM0ceC62SEXrjQR741uieYERJVpTMS2n5m6pcgDBsPzCsRG8vGdiOi8ZIzSNL4wihaRe4Y1_X-3PHAxGACmI2CsY7l4jObhg/s1600/10.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiPLvfnBNHofSCvwKuu13RmvON2DBPpXE7cdQSFsw03y4SM0ceC62SEXrjQR741uieYERJVpTMS2n5m6pcgDBsPzCsRG8vGdiOi8ZIzSNL4wihaRe4Y1_X-3PHAxGACmI2CsY7l4jObhg/s400/10.jpg" /></a></div>
<p>At the Time of installation the below dialog box will be appear (select project) click ok.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhWVmcO6iIYYQsTeTRJ4_ohTaCFam31CVC5K8RWgqxPLIzbqle5zDX34sEjRlSN7w1chN3SFWFk0AgVCSAiBMAUTweImJ7xdlbKjWUq2zapf1mdLc5vYwI5dFyNhyO_eUIr1f6Inv9Shw/s1600/11.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhWVmcO6iIYYQsTeTRJ4_ohTaCFam31CVC5K8RWgqxPLIzbqle5zDX34sEjRlSN7w1chN3SFWFk0AgVCSAiBMAUTweImJ7xdlbKjWUq2zapf1mdLc5vYwI5dFyNhyO_eUIr1f6Inv9Shw/s400/11.jpg" /></a></div>
<p>Once installed you can see the Angular files in the scripts folder.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgADUY5-e0GYF8dic4HKSv8rs0cLEaOJPZ3PMFGg-k73Guxj1nH7gyKp2dLDm-__WJTbVgBKiN5vtxYyMVKqSGAqk-SY7OmX-hCZV5xbvT55p6Wn6bPiy8D8BUZ_kjpKcPtUtI4fpBH9Q/s1600/12.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgADUY5-e0GYF8dic4HKSv8rs0cLEaOJPZ3PMFGg-k73Guxj1nH7gyKp2dLDm-__WJTbVgBKiN5vtxYyMVKqSGAqk-SY7OmX-hCZV5xbvT55p6Wn6bPiy8D8BUZ_kjpKcPtUtI4fpBH9Q/s400/12.jpg" /></a></div>
<p>Now reference the “Angular” file using the script tag as show in the below code( see the bold lines).</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4h4uCzvFl2ZQVGK-mHXHYFenGCWR7eGymXnnfkGKj_-lc5izGi8Xpfa3ukXGuBoYmTxSdZSPlqZUHA6wSeoY8nFwWfiCOk8c2llhEnGssj9s9TY7DpgxEazyLaaCx726CdGQwmBe3Jg/s1600/13.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4h4uCzvFl2ZQVGK-mHXHYFenGCWR7eGymXnnfkGKj_-lc5izGi8Xpfa3ukXGuBoYmTxSdZSPlqZUHA6wSeoY8nFwWfiCOk8c2llhEnGssj9s9TY7DpgxEazyLaaCx726CdGQwmBe3Jg/s400/13.jpg" /></a></div>
<h2><a name="Step_3:-_Applying_ng-controller_,ng-model_and_expressions">Step 3:- Applying ng-controller ,ng-model and expressions</a></h2>
<p>Now in order to bind the “HelloWorld” class with hello HTML text box we need to do two things :-</p>
<ul><li>Create an instance of “HelloWorld” class.</li>
<li>Second set the property of the “HelloWorld” object to the textbox.</li>
</ul>
<p>For this we need to use “ng-controller” and “ng-model”. “ng-controller” and “ng-model” are termed as directives. Remember angular is a declarative programming language.</p>
<p>Declarative means you just apply the directive and things will work. In case you are new to this declarative work I would suggest you to quickly see the below video link where its explained
with a example
<a href="https://youtu.be/0kmdjqgO9IY?t=15m33s">https://youtu.be/0kmdjqgO9IY?t=15m33s</a></p>
<p>“ng-controller” directive creates an object of “Helloworld” controller and binds it with the UI DIV tag and “ng-model” binds the property with textbox with “txtHello” property. </p>
<p>To display the property on the screen we need to expression “{{}}” as shown in the below code. So when we type in the text “txthello” it will get displayed inside the “div1” tag.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh37_7t-jdWXTduXkOYqyVvubLUJPtTxhhcWXG63yMQ_kxIIsgniWGSYjKXCXr_EpDIEAarMMiFbYGeD0_C1eB-Xp4E7Ohpt1fs2xqCHsMo7PfyqDfSYFJ91urtoqsjIN2VKZ6-AZEoqQ/s1600/14.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh37_7t-jdWXTduXkOYqyVvubLUJPtTxhhcWXG63yMQ_kxIIsgniWGSYjKXCXr_EpDIEAarMMiFbYGeD0_C1eB-Xp4E7Ohpt1fs2xqCHsMo7PfyqDfSYFJ91urtoqsjIN2VKZ6-AZEoqQ/s400/14.jpg" /></a></div>
<h2><a name="Step_4:-_ng-app_and_understanding_scoping">Step 4:- ng-app and understanding scoping</a></h2>
<p>So if “ng-controller” directive creates instances , what will happen if you have multiple “ng-controller” directives in your HTML page as shown in the below code. Will it create two
instances or one instance ?.</p>
<p>Think about it….</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyVtrNKP5O4bbao_PcjMe5L82rBZqSETexrP1DOHYxUpE9sKQzhem-aMymefYsNKyceQcHRK2tG2kDhTDUqOX-XrjB1knwuu1CU8BEh2mCy7pg6CANX-tyhF9OVbJyr3Ip0m9j5fgNVQ/s1600/15.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyVtrNKP5O4bbao_PcjMe5L82rBZqSETexrP1DOHYxUpE9sKQzhem-aMymefYsNKyceQcHRK2tG2kDhTDUqOX-XrjB1knwuu1CU8BEh2mCy7pg6CANX-tyhF9OVbJyr3Ip0m9j5fgNVQ/s400/15.jpg" /></a></div>
<p>Obviously as a developer you would like different instances of “HelloWorld” to bind with both the DIV HTML UI. That’s what exactly AngularJS does he creates two different instances.</p>
<p>But now if there are two instances in the same HTML page what is the scope of these two instances , is it full HTML page or something else ?.</p>
<p>The scope of these two instances is the start of the <di-v> tag "<div> and end of '</d-iv>'
</div> tag. These instances are created by angular automatically when angular encounters “ng-controller” tag.<p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6HLYkLHscT5gj_KclgNY-xRXHFg4tO43EtFqHRTeywwHJjP1VY-l8R4ePBB6-PBY3IFn_kz3WcXVIauygfjyVZBv7lgqCYZ4rnXEgqCv1fPe46GtYP9hFXAafvDy5ZRPRN-z9Abcxhg/s1600/16.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6HLYkLHscT5gj_KclgNY-xRXHFg4tO43EtFqHRTeywwHJjP1VY-l8R4ePBB6-PBY3IFn_kz3WcXVIauygfjyVZBv7lgqCYZ4rnXEgqCv1fPe46GtYP9hFXAafvDy5ZRPRN-z9Abcxhg/s400/16.jpg" /></a></div>
</p>
<p>Now there can be a situation where want these controller instances to communicate with each other , share some common data. That’s where we have something called as “ng-app”.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwqymyrB89-JThtOjZ1nC42JM3yz8Ca1gavKvg_C13pMq5q5f8Uu3g8aMdSQYAFCip8-kBjYv5UoOl8BQCCxRF4EKnDOJyGInP4q_EzWov0Xg3LKET7MynklLlG8E_AAixzcUxKRQkWA/s1600/17.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwqymyrB89-JThtOjZ1nC42JM3yz8Ca1gavKvg_C13pMq5q5f8Uu3g8aMdSQYAFCip8-kBjYv5UoOl8BQCCxRF4EKnDOJyGInP4q_EzWov0Xg3LKET7MynklLlG8E_AAixzcUxKRQkWA/s400/17.jpg" /></a></div>
<p>“ng-app” creates a top object which has control of all controller objects and they also help to communicate shared data between the controller instances.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizCrKrwV3mpepBuwmkIvEbH6elyz12zIy68LaR3Zu-XBzDC8uuLJtfosiqY7tE0EfUpr3sYM4iMvrB68Vxh5DXKwjxebJA3K6oTE25mM-n1J7_V3Oo3wZnvPUEdkOGDZ2tmon4VYc_ng/s1600/18.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizCrKrwV3mpepBuwmkIvEbH6elyz12zIy68LaR3Zu-XBzDC8uuLJtfosiqY7tE0EfUpr3sYM4iMvrB68Vxh5DXKwjxebJA3K6oTE25mM-n1J7_V3Oo3wZnvPUEdkOGDZ2tmon4VYc_ng/s400/18.jpg" /></a></div>
<h2><a name="Step_5:Bootstrapping_the_project_and_seeing_the_results">Step 5:Bootstrapping the project and seeing the results</a></h2>
<p>So now that we are all setup we need some code which help to kick off angular. We would like angular to start creating the controller objects ,ng-app objects and do the binding. </p>
<p>So we need two lines of code as shown below. The first line creates the app instance and the second line adds the controller object to the app.</p>
<pre>var myApp = angular.module("myApp", []);
myApp.controller("HelloWorld", Hello);
</pre>
<p>So that’s it , press control + f5 and see the fun of automatic binding in action. The time you type on the textbox expression are updated.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiO1C78PkeDy0xVYWUBbvx3eQlQtlphN66ftiTBLPgIT45TXS7z83TjAQrvsLCLWSQlHLhuf_3I8RhNQCezz4DB5ZlVkdkOlKIjf_JPBYXgbWW-kkINiptI8lnUxUZMEI0vJ7E9QbNAg/s1600/19.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiO1C78PkeDy0xVYWUBbvx3eQlQtlphN66ftiTBLPgIT45TXS7z83TjAQrvsLCLWSQlHLhuf_3I8RhNQCezz4DB5ZlVkdkOlKIjf_JPBYXgbWW-kkINiptI8lnUxUZMEI0vJ7E9QbNAg/s400/19.jpg" /></a></div>
<h2><a name="Final_Complete_code">Final Complete code</a></h2>
<p>Below is the complete source code for the same.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEilrdGOeElOvtfvE4vaS9M__8z2AuX65u-W6VTL5ss7Nlby6vR1ZtLp4Lrw4J9fIv33FUaCCTmuFJI_fqLKV5lbQkME5jeEwazGMsQcx4haLG40KMar_OrHDSuAfe4P0OaV46SV29vFJA/s1600/20.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEilrdGOeElOvtfvE4vaS9M__8z2AuX65u-W6VTL5ss7Nlby6vR1ZtLp4Lrw4J9fIv33FUaCCTmuFJI_fqLKV5lbQkME5jeEwazGMsQcx4haLG40KMar_OrHDSuAfe4P0OaV46SV29vFJA/s400/20.jpg" /></a></div>
<h2><a name="What_in_Next_Lab_">What in Next Lab ?</a></h2>
<p>In the next Lab we will see how use events and validations in Angular.</p>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-46420872145601884102015-11-17T05:02:00.000-08:002015-11-17T05:02:48.398-08:00Anemic data models (ADM) VS Rich Data Models (RDM) in C#<a href="#Whatareanemicdatamodels">What are anemic data models? </a><br>
<a href="#WhatareRichDatamodels">What are Rich Data models ?</a><br>
<a href="#AnemicdatamodelVSTechnicalconcerns">Anemic data model VS Technical concerns
</a><br>
<a href="#3bigComplaintsaboutAnemicmodel">3 big Complaints about Anemic model</a><br>
<a href="#AnemicmodelindisguiseofIOCandDI">Anemic model in disguise of IOC and DI</a><br>
<a href="#Conclusion">Conclusion </a><br>
<a href="#Furtherreferencesandreading">Further references and reading</a><br>
</br>
<a name="Whatareanemicdatamodels"><h2>What are anemic data models?</h2></a>
<p><i>Anemic in English means plain so Anemic Models means plain Models.</p></i>
<p>Plain models are classes without business logic / behaviors. For example below is a simple “Customer” model which just has the data (properties) but it does not have business logic (behavior).</p>
<pre>class Customer
{
private string _CustomerName;
public string CustomerName
{
get { return _CustomerName; }
set { _CustomerName = value; }
}
private string _CustomerCode;
public string CustomerCode
{
get { return _CustomerCode; }
set { _CustomerCode = value; }
}
}
</pre>
<p>Now in real world plain models are of no use without business logic unless you are
<a target="_blank" href="http://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp">creating DTO ( data transfer objects)</a> which are meant for different purpose. Some developers feel comfortable in pushing
these actions and methods in a separate classes which are named with different vocabularies like service, façade , manager , utility etc. These plain models are then passed to these classes who run the behavior over them.</p>
<p>For example below is a simple service class which validates the “Customer” object and decides if the object valid or not. Putting in simple words Anemic model has behavior in separate service / utility / manager classes.</p>
<pre>class CustomerValidationService
{
public bool Validate(Customer obj)
{
if (obj.CustomerCode.Length == 0)
{
return false;
}
if (obj.CustomerName.Length == 0)
{
return false;
}
return true;
}
}
</pre>
<h2><a name="WhatareRichDatamodels">What are Rich Data models ?</a></h2>
<p>Rich data models have both data and behavior in the same class. Below is the RDM for the previously defined ADM. You can see the data ( CustomerCode and CustomerName) and behavior (Validate) both are part of the same model.</p>
<pre>class Customer
{
private string _CustomerName;
public string CustomerName
{
get { return _CustomerName; }
set { _CustomerName = value; }
}
private string _CustomerCode;
public string CustomerCode
{
get { return _CustomerCode; }
set { _CustomerCode = value; }
}
public bool Validate()
{
if (CustomerCode.Length == 0)
{
return false;
}
if (CustomerName.Length == 0)
{
return false;
}
return true;
}
}
</pre>
<a name="AnemicdatamodelVSTechnicalconcerns">
<h2>Anemic data model VS Technical concerns</h2>
</a>
<p>Lot of developers confuse Technical cross cutting concerns with Anemic model. In Anemic model the behaviors in the service class is the behavior of the real world model.</p>
<p>Lot of developers create utility or service classes which decouple technical behavior from the model which is not anemic model. For example someone can create a “Dal” class as shown below and pass the “Customer” object to be inserted in to the database. Lot of people term this kind of approach as “Repository” pattern.</p>
<pre>class Dal
{
public void InsertDb(Customer obj)
{
// Code of ADO.NET goes here
}
}
</pre>
<p>Now this kind of model is not anemic model. This is separating the technical behavior from the business behavior which perfectly makes sense. In the previous example we had “validate” method which actually belongs to the “Customer” model. So Anemic model are those models which have business behavior separated in a different class and not technical behavior. So the above “Dal” class is not an Anemic model.</p>
<pre>Customer cust = new Customer();
cust.CustomerName = "Shiv";
Dal dal = new Dal();
dal.InsertDb(cust);
</pre>
<h2><a name="3bigComplaintsaboutAnemicmodel">3 big Complaints about Anemic model</a></h2>
<p>Lot of developers unknowingly follow Anemic model because of simplicity, but OOP community has the below concerns for ADM:-</p>
<ul><li>Anemic model disrespects OOP concepts. Objects in OOP have data and behavior. Object should model real time entity. By separating the behavior we are not following OOP. With behaviors residing in a separate class it would be difficult to inherit , apply polymorphism , abstraction and so on.<br>
</li><li>Anemic models can have inconsistent states at any time. For example see the below code we have first created a valid customer object and the validation service logic ran over it and set the “IsValid” to true. So till step 1 everything is fine “IsValid” is true and in synch with the customer object data. Now somewhere down the line you can say in step 2 customer name property is set to nothing. In this step the customer object is not valid in reality but if you try to display in Step 3 it shows valid. In order words the data and the IsValid flag is not in synch</li></ul>
<pre>Customer obj = new Customer();
obj.CustomerName = "Shiv";
obj.CustomerCode = "1001";
CustomerValidationService validationService = new CustomerValidationService();
validationService.Validate(obj);
Console.WriteLine(obj.IsValid); // Step 1 :- till here Valid
obj.CustomerName = ""; // Step 2 :- we made the model invalid
Console.WriteLine(obj.IsValid); // Step 3 :- but it says Still Valid
</pre>
<ul><li>Lot of people complain that this is<a target="_blank" href="http://www.martinfowler.com/bliki/AnemicDomainModel.html"> procedural programming and so is a Anti pattern</a>. If you see procedural programming approach we create methods and function , we pass structure to it and get the output. </li></ul>
<h2><a name="AnemicmodelindisguiseofIOCandDI">Anemic model in disguise of IOC and DI</a></h2>
<p>With all respect to the views of OOP developers Anemic models exists very beautifully and amicably in the disguise of DI IOC architecture today. I personally find it very cruel to say it’s an Anti-pattern.</p>
<p>Consider the below scenario where we have a customer class who has different kind of discount calculations. So rather than putting the discount calculation logic inside the customer class you can inject the object from the constructor as shown in the below. In case you are new to dependency injection please read this
<a target="New Window" href="http://www.codeproject.com/Articles/592372/Dependency-Injection-DI-vs-Inversion-of-Control-IO">DI IOC in C#.</a></p>
<pre>class Customer
{
private IDiscount _Discount = null;
public Customer(IDiscount _Dis)
{
_Discount = _Dis;
}
private string _CustomerName;
public string CustomerName
{
get { return _CustomerName; }
set { _CustomerName = value; }
}
public string Region { get; set; }
public double Amount { get; set; }
public double CalculateDiscount()
{
return _Discount.Calculate(this);
}
}
</pre>
<p>And your discount calculation logic is in a different class all together which takes the customer object for calculating discount.</p>
<pre>public interface IDiscount
{
double Calculate(Customer Cust);
}
</pre>
<p>Below are two kinds of discount calculations one is a week end discount and the other is a special discount. The week end discount does calculation as per region and week day while the special discount is a 30% flat.</p>
<p>Now the below classes also follow anemic model because the actions are in a different class but still its perfectly decoupled, valid and OO.</p>
<pre>public class WeekEndDiscount : IDiscount
{
public double Calculate(Customer Cust)
{
if (Cust.Region == "Asia")
{
if (DateTime.Today.DayOfWeek == DayOfWeek.Sunday)
{
return (Cust.Amount * 0.20);
}
}
return (Cust.Amount * 0.10);
}
}
public class SpecialDiscount : IDiscount
{
public double Calculate(Customer Cust)
{
return (Cust.Amount * 0.30);
}
}
</pre>
<h2><a name="Conclusion">Conclusion</a></h2>
<ul><li>Anemic data model is a simple plain model class with only data and behavior resides in a separate class.</li><li>Rich data model have both data and behavior.</li><li>Anemic model is criticized for not been OO , extensible , inconsistent and follows procedural programming approach.</li><li>Anemic model should be confused with cross cutting concern technical classes like Logging , Repository etc.</li><li>DI IOC indirectly forces anemic model. So Anemic model in today world is very much present in the disguise of DI IOC.</li></ul>
<h2><a name="Furtherreferencesandreading">Further references and reading</a> </h2>
<p>I have been writing a lot on design patterns, architecture, domain driven development and so on. So below are the link feel free to read and do give feedback.</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=YDobmucohqk">Learn design patterns in 8 hours with a project</a></li>
<li>
<a target="_blank" href="http://www.codeproject.com/Articles/28309/Design-pattern-FAQ-Part-Training">23 GOF design pattern covered using C#</a></li>
<li>
<a target="_blank" href="http://www.codeproject.com/Articles/1043301/Immutable-objects-in-Csharp">Immutable objects in C#</a></li>
<li>
<a target="_blank" href="http://www.codeproject.com/Articles/1046193/Value-Object-Design-Pattern-in-Csharp">Value object design pattern in C#</a></li>
<li>
<a target="_blank" href="http://www.codeproject.com/Articles/1042674/NULL-Object-Design-Pattern#MakingitSingletonandImmutable">NULL object design pattern in C#</a></li>
<li>
<a target="_blank" href="http://www.codeproject.com/Articles/1055514/Aggregate-Root-Pattern-in-Csharp">Aggregate root pattern in C#</a></li>
<li>
<a target="_blank" href="http://www.codeproject.com/Articles/592372/Dependency-Injection-DI-vs-Inversion-of-Control-IO">DI VS IOC</a></li>
<li>
<a target="_blank" href="http://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp">DTO ( Data transfer) objects in C#</a></li>
<li>
<a target="_blank" href="http://www.codeproject.com/Articles/819294/WPF-MVVM-step-by-step-Basics-to-Advance-Level">MVVM architecture step by step</a></li>
</ul>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a>
Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0Mumbai, Maharashtra, India19.0759837 72.87765590000003618.5957917 72.232208900000032 19.556175699999997 73.52310290000004tag:blogger.com,1999:blog-5571184103023259871.post-91345179725993486772015-11-12T22:27:00.000-08:002015-11-12T22:37:43.126-08:00Aggregate root pattern in C#<p>Aggregate root are cluster / group of objects that is treated as single unit of data.</p>
<p>I am sure lots of developers are already using this pattern unknowingly, via this short note I would like to inform you formally what you are doing.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiB4j5ClmaJx6uFLM9fxvEpPnwzzhrw3JnyXMdoHXjrWvqHqPBCKpPU7p2LiMZiNMNzo_Q7D3mOHMSyuxzlT9vyDl0pJ6oeiusBo1MY1mYv8D92mOjQ29SnjSVHY-Xq94asmxFyNL12zg/s1600/Aggregate+pattern.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiB4j5ClmaJx6uFLM9fxvEpPnwzzhrw3JnyXMdoHXjrWvqHqPBCKpPU7p2LiMZiNMNzo_Q7D3mOHMSyuxzlT9vyDl0pJ6oeiusBo1MY1mYv8D92mOjQ29SnjSVHY-Xq94asmxFyNL12zg/s400/Aggregate+pattern.png" /></a></div>
<p>Let us try to understand the above definition with an example. Consider the below “Customer” class which has the capability to add multiple “Address” objects to it. In order to achieve the same we have exposed an address collection from the customer class to represent the 1 to many relationships.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjh-4Z5IUR2kCNeGV6FqGvMhuUGekx1S2YCQMDPvBhJDGhbsUROOFNL85vSxJZvcN4DezxjIEQXMRnS073JHfaOARf1OthsX4Yiil-nz_HmkpiNvGDqz4gnMprbZbbhcU1xQ67VIaa6tg/s1600/Aggregate+pattern2.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjh-4Z5IUR2kCNeGV6FqGvMhuUGekx1S2YCQMDPvBhJDGhbsUROOFNL85vSxJZvcN4DezxjIEQXMRnS073JHfaOARf1OthsX4Yiil-nz_HmkpiNvGDqz4gnMprbZbbhcU1xQ67VIaa6tg/s1600/Aggregate+pattern2.png" /></a></div>
<p>The above class structure works perfectly well. You can create object of customer and add multiple addresses object to it.</p>
<pre>Customer cust = new Customer();
cust.CustomerName = "Shiv koirala";
cust.DateofBirth = Convert.ToDateTime("12/03/1977");
Address Address1 = new Address();
Address1.Address1 = "India";
Address1.Type = "Home";
cust.Addresses.Add(Address1);
Address Address2 = new Address();
Address2.Address1 = "Nepal";
Address2.Type = "Home";
cust.Addresses.Add(Address2);
</pre>
<p>Now let's say we want to implement the following validations:-</p>
<p>“Customer can only have one address of Home type”.</p>
<p>At this moment the address collection is a NAKED LIST COLLECTION which is exposed directly to the client. In other words there are no validations and restrictions on the “Add” method of the list. So you can add whatever and how much ever address objects as you wish.</p>
<pre>cust.Addresses.Add(Address2);</pre>
<p>So how to address this problem in a clean and logical way. If you think logically “Customer” is composed of Addressescollection, so Customer is like a main root.So rather than allowing DIRECT NAKED ACCESS to Addresses list how about accessing the address list from the customer class.In other words centralizing access to address objects from the customer class.</p>
<p>So below are three steps which I have implemented to put a centralize address validation.</p>
<p>Step 1 :- I have made the address list private. So no direct access to the collection is possible.</p>
<p>Step 2 :- Created a “Add” method in the “Customer” class for adding the “Address” object. In this add method we have put the validation that only one “Home” type address can be added.</p>
<p>Step 3 :- Clients who want to enumerate through the address collection for them we have exposed “IEnumerable” interface.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5y6CAHAmfRNpMuwDXO_vgeWtzAO_yK-jdfGEYCP5DWThlXMLWEE_H8GohfdIUMEdfQAv3uiq5o0oeS00gHCPGvH4KGjudhQX3sDRTbXglASYPexaM19b1Re3_p6q1eheQeQ1c6hTvlg/s1600/Aggregate+pattern3.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5y6CAHAmfRNpMuwDXO_vgeWtzAO_yK-jdfGEYCP5DWThlXMLWEE_H8GohfdIUMEdfQAv3uiq5o0oeS00gHCPGvH4KGjudhQX3sDRTbXglASYPexaM19b1Re3_p6q1eheQeQ1c6hTvlg/s1600/Aggregate+pattern3.png" /></a></div>
<p>If you analyze the above solution closely the customer is now the root and the address object is manipulated and retrieved via the customer class.</p>
<p>Why did we do this? , because “Customer” and “Address” object is one logical data unit. To maintain integrity of address validation we need to go via the “Customer” class. In the same way loading of data ,updation , deletion etc should all happen via the “Customer” class so that we have proper data integrity maintained.</p>
<p>So when we say load customer from database all the respective address objects should also get loaded.</p>
<p>So when a group of objects which form one logical unit should have centralized root via which the manipulation of the contained object should happen. This kind of arrangement is terms as “Aggregate Root”.</p>
<p>The best way to Learn Design pattern is by doing a project. So if interested you can start from the below youtube video which demonstrates Design pattern by doing a project.</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/YDobmucohqk" frameborder="0" allowfullscreen></iframe>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-79009600249268047182015-11-06T06:03:00.000-08:002015-11-06T06:03:26.194-08:00Data Transfer object design pattern in C#<p><a href="#Introduction and Definition">Introduction and Definition</a></p>
<p><a href="#Scenario 1 :- Improve performance">Scenario 1 :- Improve performance</a></p>
<p><a href="#Scenario 2:- Flatten object hierarchy">Scenario 2:- Flatten object hierarchy</a></p>
<p><a href="#Scenario 3 :- Exclude properties">Scenario 3:- Exclude properties</a></p>
<p><a href="#Difference between DTO and Business objects">Difference between DTO
and Business objects</a></p>
<h2><a name="Introduction and Definition">Introduction and Definition</a></h2>
<p>DTO(Data Transfer objects) is a data container for moving data between layers. They are also termed as transfer objects. DTO is only used to pass data and does not contain any business logic. They only have simple setters and getters.
</p>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNBm5bjQF6_O6_hsRP16DtGNQG9pGhI0EgDW1sSGW_Ro5Dji7p-GoqskO85qiSvkz-IqdMy-S5gO4M6vRxT1um9VuIshD1Jn-S8Q53sbOAF9qif9Y6yrmGcAxOtUe_RdPZNsthz0mf_w/s1600/Design+pattern1.png">
<p>For example below is an Entity class or a business class. You can see that it has business logic in the setters.</p>
<pre>class CustomerBO
{
private string _CustomerName;
public string CustomerName
{
get { return _CustomerName; }
set
{
if (value.Length == 0)
{
throw new Exception("Customer name is required");
}
_CustomerName = value;
}
}
}
</pre>
<p>A data transfer object of the above Customer entity class would look something as shown below. It will only have setters and getters that means only data and no business logic.</p>
<pre>class CustomerDTO
{
public string CustomerName { get; set; }
}
</pre>
<p>So in this article let us try to understand in what kind of scenarios DTO’s are used.</p>
<h2><a name="Scenario 1 :- Improve performance">Scenario 1 :- Improve performance</a></h2>
<p>Consider the below scenario we have a customer business class and a product business class. </p>
<pre>class CustomerBO
{
private string _CustomerName;
public string CustomerName
{
get { return _CustomerName; }
set
{
if (value.Length == 0)
{
throw new Exception("Customer name is required");
}
_CustomerName = value;
}
}
}
</pre>
<pre>public class ProductsBO
{
private string _ProductName;
public string ProductName
{
get { return _ProductName; }
set
{
if (value.Length == 0)
{
throw new Exception("Product Name is required");
}
_ProductName = value;
}
}
public double ProductCost { get; set; }
}
</pre>
<p>Assume there is a remote client which is making calls to get Customer data and the Products they bought. Now the client has to make two calls one to get Customer data and the other to get Products data. Now that quiet inefficient. It would be great if we can get data in one call.</p>
<pre>DataAccessLayer dal = new DataAccessLayer();
//Call 1:- get Customer data
CustomerBO cust = dal.getCustomer(1001);
//Call 2:- get Products for the customer
ProductsBO prod = dal.getProduct(100);
</pre>
<p>So to achieve the same we can create a unified simple class which has properties from both the classes.</p>
<pre>class CustomerProductDTO
{
// Customer properties
public string CustomerName { get; set; }
// Product properties
public string ProductName { get; set; }
public double ProductCost { get; set; }
}
</pre>
<p>You can now get both Customer and Product data in one go.</p>
<pre>//Only one call
CustomerProductDTO cust = dal.getCustomer(1001);
</pre>
<p>Proxy objects in WCF and Web services are good candidates for data transfer objects to improve performance.</p>
<h2><a name="Scenario 2:- Flatten object hierarchy">Scenario 2:- Flatten object hierarchy</a></h2>
<p>The second scenario where I end up using DTO objects isfor flattening the object hierarchy for easy data transfer.</p>
<p>For example you have a customer business class which has one to many relationships with an address class. But now let us say we want to write this whole data to a CSV file or transfer it across layers. In those scenarios a flattened denormalized structure makes things easier.</p>
<p><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjV3XeHT-O2Mc6UG89QpVUhoKkMuAfN4T5ncbqMIGsTNu8Dqp6eqSGtdggOLaC9R4ZH3uvlqWIoWDP49dy_FfgR67CiNTOhmxc6mDIWlAyvD_KcwFdFvwuKrh9uncY0Ts-4HiRUQcsEeA/s1600/Design+pattern2.png"></p>
<p>So you have a customer class which has one to many relationship with address objects. It also has business rules in it.</p>
<pre>class CustomerBO
{
// Customer properties removed for reading clarity
public List<AddressBO> Addresses { get; set; }
}
</pre>
<pre>class AddressBO
{
private string _Address1;
public string Address1
{
get { return _Address1; }
set
{
if (value.Length == 0)
{
throw new Exception("Address is required");
}
_Address1 = value;
}
}
}
</pre>
<p>To create a DTO of the above customer and address class we can just merge both the properties of the classes in to one class and exclude the business logic.</p>
<pre>class CustomerDTO
{
public string CustomerName { get; set; }
public string ProductName { get; set; }
public double ProductCost { get; set; }
}
</pre>
<h2><a name="Scenario 3 :- Exclude properties">Scenario 3:- Exclude properties</a></h2>
<p>Because DTO is completely detached from the main business object you have the liberty to remove certain fields which you do not want to transfer to the other layers. For example below is a simple customer business object class which has two properties called as “IsAdmin” and “CustomerName”. </p>
<p>When you pass this business object to the UI layer you do not wish to transfer the “IsAdmin” value to the UI.</p>
<pre>class CustomerBO
{
private bool _IsAdmin;
public string IsAdmin
{
get { return _IsAdmin; }
}
private string _CustomerName;
public string CustomerName
{
get { return _CustomerName; }
set
{
if (value.Length == 0)
{
throw new Exception("Customer name is required");
}
_CustomerName = value;
}
}
}
</pre>
<p>So you can create a DTO which just has the “CustomerName” property.</p>
<pre>class CustomerDTO
{
public string CustomerName { get; set; }
}
</pre>
<h2><a name="Difference between DTO and Business objects">Difference between DTO and Business objects</a></h2>
<table border="1" width="50%">
<tr>
<td> </td>
<td width="161"><b>
<span style="font-size: 12.0pt; line-height: 115%; font-family: Calibri,sans-serif">
Business objects</span></b></td>
<td width="209"><b>
<span style="font-size: 12.0pt; line-height: 115%; font-family: Calibri,sans-serif">
DTO</span></b></td>
</tr>
<tr>
<td><b>
<span style="font-size: 12.0pt; line-height: 115%; font-family: Calibri,sans-serif">
Data</span></b></td>
<td width="161">
<span style="font-size: 12.0pt; line-height: 115%; font-family: Calibri,sans-serif">
Yes</span></td>
<td width="209">
<span style="font-size: 12.0pt; line-height: 115%; font-family: Calibri,sans-serif">
Yes</span></td>
</tr>
<tr>
<td><b>
<span style="font-size: 12.0pt; line-height: 115%; font-family: Calibri,sans-serif">
Business logic</span></b></td>
<td width="161">
<span style="font-size: 12.0pt; line-height: 115%; font-family: Calibri,sans-serif">
Yes</span></td>
<td width="209">
<span style="font-size: 12.0pt; line-height: 115%; font-family: Calibri,sans-serif">
No</span></td>
</tr>
<tr>
<td><b>
<span style="font-size: 12.0pt; line-height: 115%; font-family: Calibri,sans-serif">
Structure</span></b></td>
<td width="161">
<span style="font-size: 12.0pt; line-height: 115%; font-family: Calibri,sans-serif">
Normalized </span></td>
<td width="209">
<span style="font-size: 12.0pt; line-height: 115%; font-family: Calibri,sans-serif">
Normalized or Denormalized</span></td>
</tr>
</table>
<p>If we can mathematically summarize:- </p>
<pre>Business object = Data + Logic
DTO = Data
</pre>
<p>In case you want to learn design pattern I would suggest to learn design pattern with a project. Do not learn each design pattern individually. Because when design patterns are used in project they overlap with each other and such kind of experience can only be felt by doing an actual project and implementing design patterns on demand and naturally. </p>
<p>Below is a youtube video which demonstrates 15 important design pattern in a C# project.</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/YDobmucohqk" frameborder="0" allowfullscreen></iframe>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-67411946479345736202015-11-01T23:03:00.000-08:002015-11-01T23:12:00.608-08:00Value Object design pattern in C#<div dir="ltr" style="text-align: left;" trbidi="on">
<b>
Introduction of Value object design pattern</b>
<br />
<div>
<br /></div>
Definition<i>: - “Value object is an object whose equality is based on the
value rather than identity. “ </i><br />
<br />
Let us understand the above statement with more clarity. When you create two objects and even if their values are same they represent different entities. For example in the below code we have created two person objects with the same name “Shiv”.<br />
<br />
<pre>Person PersonfromIndia = new Person();
PersonfromIndia.Name = "Shiv";
PersonfromIndia.Age = 20;
Person PersonfromNepal = new Person();
PersonfromNepal.Name = "Shiv";
PersonfromNepal.Age = 20;
</pre>
But the first person stays in “India” and the other stays in “Nepal”. So in other words “PersonFromIndia” object is different from “PersonFromNepal” object even if the person’s name and age is same. In other words they have DIFFERENT IDENTITIES.<br />
<br />
If you try to compare the above C# object it will return false and this is completely in line with our expectations. You can use the “Equal” method or you can use “==”. <br />
<pre></pre>
<pre></pre>
<pre></pre>
<pre>if (PersonfromIndia.Equals(PersonfromNepal))
{
}
</pre>
But now consider the below scenario of a money example. We are creating two money objects of 1 rupee value but one is using a paper material and the other is made of steel material.<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzQ1CTTm8wYoszixPWZxFaUuyzIECFK85gz3pep0jvFVdBro6mOiaPX60-Dv9z73cm16bb1OLbT0C-nYDq4Ez2LToN_MBU6AvaYZWcK5sfKgrNGPpHxqeljqqj3MkbGeNKsaPes_a8fg/s1600/1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="198" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzQ1CTTm8wYoszixPWZxFaUuyzIECFK85gz3pep0jvFVdBro6mOiaPX60-Dv9z73cm16bb1OLbT0C-nYDq4Ez2LToN_MBU6AvaYZWcK5sfKgrNGPpHxqeljqqj3MkbGeNKsaPes_a8fg/s400/1.jpg" width="400" /></a></div>
<br />
But in this case “OneRupeeCoin” value is equal to “OneRupeeNote” value. So even if the objects are of different instances they are equal by money value. So if the money and currency type matches both the objects are equal.<br />
<br />
<pre>Money OneRupeeCoin = new Money();
OneRupeeCoin.Value = 1;
OneRupeeCoin.CurrencyType = "INR";
OneRupeeCoin.CurrencyType = "INR";
OneRupeeCoin.SerialNo = "A3123JJK332";
Money OneRupeeNote = new Money();
OneRupeeNote.Value = 1;
OneRupeeCoin.CurrencyType = "INR";
OneRupeeCoin.CurrencyType = "INR";
OneRupeeNote.Material = "Paper";
OneRupeeCoin.SerialNo = "Z2232V4455";
</pre>
In other words value objects when compared are same when the values of the properties are same. <br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2jGtbxSIZ0OFY4NCAHLonIGM5DW50JpVyT52WRGRsW7Q3LmPuNoyhtzNYpx1oOsN-4EkfpBICnHfmhXj6ly9ZHAHJD86ma-fr8Iv_Lg2nYeGuIRnNKPnZjxRatPzpNNuLcVyWAdG4-g/s1600/2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="181" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2jGtbxSIZ0OFY4NCAHLonIGM5DW50JpVyT52WRGRsW7Q3LmPuNoyhtzNYpx1oOsN-4EkfpBICnHfmhXj6ly9ZHAHJD86ma-fr8Iv_Lg2nYeGuIRnNKPnZjxRatPzpNNuLcVyWAdG4-g/s400/2.jpg" width="400" /></a></div>
<br />
Implementing Value object pattern in C# is a two step process , so in the further article let us run through those steps.<br />
<br />
<b>
Step 1 :- Making Value object pattern work logically in C#</b>
<br />
<div>
<br /></div>
Now for the above “Money” value object to function properly the below comparison should work both for “Equals” and “==”. But technically C# does object reference comparison and not value.<br />
<pre></pre>
<pre></pre>
<pre></pre>
<pre>if (OneRupeeCoin==OneRupeeNote)
{
Console.WriteLine("They are equal");
}
if (OneRupeeCoin.Equals(OneRupeeNote))
{
Console.WriteLine("They are equal");
}
</pre>
So to achieve the same we need to override the “equals” methods and overload “==” operator as shown in the code below. You can see now the equality is compared on the base of “Value” and “CurrencyType”. If the “CurrencyType” and “Value” is same that means the objects are same.<br />
<pre></pre>
<pre></pre>
<pre>class Money
{
public override bool Equals(object obj)
{
var item = obj as Money;
if (item.Value == Value)
{
return true;
}
return false;
}
public static bool operator !=(Money money1, Money money2)
{
if ((money1.Value == money2.Value) &&
(money1.CurrencyType == money1.CurrencyType))
{
return true;
}
return false;
}
public static bool operator ==(Money money1, Money money2)
{
if ((money1.Value == money2.Value)&&
(money1.CurrencyType == money1.CurrencyType))
{
return true;
}
return false;
}
}</pre>
<br />
Once the above methods are incorporated the equality will work on the values and not the reference. This is in synch with the Value object pattern behavior we discussed in the introduction.<br />
<br />
<h1>
</h1>
<b>
Step 2 :- Value objects should be immutable</b>
<br />
<b><br /></b>
Now let us say we are using the above money object inside a product class. So you can see we have created two product objects one for shoes and one for chocolates.<br />
<br />
But BY MISTAKE we have assigned the same “Money” object to both the products. In other words the money object is now shared between both the products.<br />
<pre></pre>
<pre></pre>
<pre></pre>
<pre>Product shoes = new Product();
shoes.ProductName = "WoodLand";
// Step 1:- Money object set to 100 INR
Money Cost = new Money();
Cost.CurrencyType = "INR";
Cost.Value = 100;
shoes.Cost = Cost;
// Step 2 :- the same money object is modified to 1 value
// this affected the shoes cost as well
Product Chocolates = new Product();
Chocolates.ProductName = "Cadbury";
Chocolates.Cost = Cost;
Chocolates.Cost.Value = 1;
Chocolates.Cost.CurrencyType = "USD";
</pre>
So in Step 1 the money object was set to 100 INR and in step 2 it was modified to 1 USD. Step 2 affected the cost of Shoes product as well. This can cause lot of defects and unusual behavior.<br />
<br />
A Value “100” cannot be replaced by anything, “100” is “100”. In other words value objects should be made IMMUTABLE to avoid confusion. In case you are new to the concept of immutability I would suggest reading this article on
<b>
<a href="http://www.codeproject.com/Articles/1043301/Immutable-objects-in-Csharp" target="_blank">C# Immutable objects</a></b>.<br />
<br />
<i>Immutable means once the object is filled with data, that data cannot be changed.</i><br />
<i><br /></i>
To make the money class immutable is a 2 step process:-<br />
<ul>
<li>Make the property set as private.
</li>
<li>Make provisions to set data via constructor.
</li>
</ul>
Below is the code with comments of both the steps.<br />
<pre></pre>
<pre></pre>
<pre>class Money
{
// Step 1 :- Make the sets private
public readonly double Value { get; private set; }
public readonly string CurrencyType { get; private set; }
public readonly string Material { get; private set; }
// Step 2 :- Pass data via constructor
public Money(double _Value,
string _CurrencyType,
string _Material)
{
Value = _Value;
CurrencyType = _CurrencyType;
Material = _Material;
}
// Code of Equals and == operator removed for simplification
}
</pre>
Below is the code which shows how the product object will be assigned with money immutable object. This would further avoid changes to the money object and any confusion around the same. Now the money value object of shoes is different from chocolates.<br />
<pre></pre>
<pre></pre>
<pre>Product shoes = new Product();
shoes.ProductName = "WoodLand";
shoes.Cost = new Money(100, "INR", "Paper");
Product Chocolates = new Product();
Chocolates.ProductName = "Cadbury";
Chocolates.Cost = new Money(1, "USD", "Coin");
</pre>
<pre></pre>
<b>
Conclusion about Value object pattern</b>
<br />
<div>
<br /></div>
<ul>
<li>Value objects equality is based on value rather than identity.
</li>
<li>Value objects should me IMMUTABLE to avoid confusion.
</li>
<li>In C# to ensure proper behavior of value object we need to override “Equals” method and “==” operator.
</li>
</ul>
The best way to learn design pattern is by doing a project. Below is a simple customer project in which I have implemented 8 design patterns (Factory Pattern,Lazy Loading,RIP Pattern,Stratergy Pattern,Decorator pattern,Repository,Unit of Work and Template pattern).<br />
<br />
Below is the first video of Learn Design pattern in 8 hours.<br />
<br />
<iframe allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/YDobmucohqk" width="560"></iframe>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a>
</div>
Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-12365174529681574262015-10-25T00:30:00.000-07:002015-10-25T02:21:43.478-07:00Immutable objects in C#<div dir="ltr" style="text-align: left;" trbidi="on">
<h2>
<span style="font-family: Verdana; font-size: x-small;">Introduction</span></h2>
<span style="font-family: Verdana; font-size: x-small;">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIv5aYmhodK4LRJT0IK8B0X03nkAN_wUWpoSTmWZFP0gHB9PGmHbIT27_Se9uDXw9F4T0OGcpBbFn-9NL-WyC_f5trROLuFAYS4sKjZD84xbRn5h1Duh98cAgjz18kjCxBwq05M_Gkzw/s320/Top.JPG" />
</span><br />
<span style="font-family: Verdana; font-size: x-small;"><span style="font-family: Verdana; font-size: x-small;">There is saying which goes “MAKE THE POT WHILE THE MUD IS WET”. Once Mud
becomes dry it cannot be changed. Immutable objects walks on the similar lines.
Once the object is created it cannot be modified by anyway.</span></span><br />
<span style="font-family: Verdana; font-size: x-small;">
<h2>
<span style="font-family: Verdana; font-size: x-small;"><a href="https://www.blogger.com/null" name="Whatareimmutableobjects">What are immutable objects?</a></span></h2>
<span style="font-family: Verdana; font-size: x-small;">Immutable objectsare objects which once loaded cannot be changed / modified
by anyway external or internal.</span><br />
<h2>
<span style="font-family: Verdana; font-size: x-small;"><a href="https://www.blogger.com/null" name="Whereareimmutableobjectsused">Where are immutable objects used?</a></span></h2>
<span style="font-family: Verdana; font-size: x-small;">If I put in one line Immutable objects are used for data WHICH IS STATIC.
Below are some of the instances of the same.</span><br />
<span style="font-family: Verdana; font-size: x-small;">• <b>Master data: -</b> One of the biggest uses of immutable objects is to load
master data. Master data like country,currency , region etc rarely change. So we
would like to load master data once in the memory and then we do not want it to
be modified.</span><br />
<br />
<span style="font-family: Verdana; font-size: x-small;">• <b>Configuration data: -</b> All application needs configuration data. In
Microsoft world we normally store these configuration data in to Web.config or
App.config file. Such kind of data is represented by objects and these data once
loaded in the application memory will not change.Its again a good practice to
make these kind of configuration data objects as immutable.</span><br />
<span style="font-family: Verdana; font-size: x-small;"><br />
• <b>Singleton objects: </b>-In applications we normally create singleton objects for
shared static data. So if the shared data is not changing it’s aawesome
candidate for immutable objects. In case you are new to Singleton pattern please
refer this article
<a href="http://www.codeproject.com/Articles/28309/Design-pattern-FAQ-Part-Training#Canyouexplainsingletonpattern" target="_blank">Singleton Pattern in C#</a><br />
</span><br />
<h2>
<span style="font-family: Verdana; font-size: x-small;"><a href="https://www.blogger.com/null" name="HowcanwecreateimmutableobjectsinC">How can we create immutable objects in C#?</a></span></h2>
<span style="font-family: Verdana; font-size: x-small;">Immutable objects can be created only from immutable classes. To create an
immutable class is a three step process :-</span><br />
<span style="font-family: Verdana; font-size: x-small;"><br />
• Step 1:- Remove the setters of the class only have getters.<br />
The first step towards creating an immutable class is to remove the setters. As
we said values of a immutable class cannot be modified EXTERNALLY or INTERNALLY.
So by removing the getters any client who creates the object of this class
cannot modify the data once loaded.<br />
</span><br />
<span style="font-family: Verdana; font-size: x-small;"><img height="195" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHLRNQtGrrUp5yYv-uloWFLgFueHWkkETYZz16jhND0wH5AiboZBt_qVcgs_wnuVQ3gb1YYYIh7SOyIZEqM8hY0XF0lgMKW6nOgm5A5DMzkkVhE0S9Xv5RyX7200TwNdEvagDtJKCf8Q/s400/1.JPG" width="400" /></span><br />
<span style="font-family: Verdana; font-size: x-small;">• Step 2:- Provide parameters via constructor.<br />
We have removed the getters so there is no way to load data in to the class. So
to provide data we need to create constructors with parameters via which we can
pass data to the object. Below is the modified code for the same.<br />
</span><br />
<span style="font-family: Verdana; font-size: x-small;"><img height="15" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0valgxuF0kwE31NB7-W2blqQ_2EEJ70SB1kk1B5i-jf3jEYFHJaDumb2sJObbc1dO-8xy3dmw7A2qADzOwCcfDbVcAfltTtZAVicTWTkTiuU_SyY1p38gzIrcZ8obds7jNvUDJboxBg/s400/2.JPG" width="400" /></span><br />
<span style="font-family: Verdana; font-size: x-small;"><img height="152" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgB2t3Ps2DRPMzQpemnZg6dhBCbW4brdhKJdS1fIaFopDt1RK7-VCCdhVq3ccq-SdNc79DlTjVnXXlFP7fhEyt_EqquDWZnyx_eVAQVDfclc0Dj56iEcL2l7qcCCqWQc4KP5RNaYx1i1Q/s400/3.JPG" width="400" /></span><br />
<span style="font-family: Verdana; font-size: x-small;">• Step 3 :- Make the variables of the property READONLY</span><br />
<span style="font-family: Verdana; font-size: x-small;"><br />
As we said in the previous definition immutableobjects cannot be modified by
ANYWAY once the data is loaded. I will go one step further and say it cannot be
modified EXTERNALLY by client or INTERNALLY by the class code himself. <br />
</span><br />
<span style="font-family: Verdana; font-size: x-small;">But if you see our currency class the variables can be modified after the
object creation. In other words see the below class code. We have created a
method in the class called as “SomeLogic”. This method is able to successfully
modify the variables after the object has been created.</span><br />
<span style="font-family: Verdana; font-size: x-small;"><img height="227" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlT71WnQ4HzvsVVaScsfzlV7nk7EyI20u8ak7DMK9H7VlGpXIzX6vXMtdNC5aiO462iq_Lg2e8YpxtRsu8zE0Eo5lBkiWNwqwpA_C98WrlE8BJDWghfL5pz-Zo5_b29G3OQMqe-rUryQ/s400/4.JPG" width="400" /></span><br />
<span style="font-family: Verdana; font-size: x-small;">So the solution for the above to make the variables “READONLY”. Below is the
currency class modified where the property variables are made readonly.Readonly
variables can be only initialized in the constructor and later they cannot be
modified.</span><br />
<span style="font-family: Verdana; font-size: x-small;"><img height="331" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgMbk-QTxMzVyet5aizg4S715mmEYKbIcPTYq6eQ4jKIjd-O6NjYZ5wqMCAArSuDEb0wDibQxM9cX659hYOlOO7WcY_qNRbuGFGSuZVflmY-pJSBXlvoZxaoJAUU5HvQG_Fhszu3KlXuA/s400/5.JPG" width="400" /></span><br />
<span style="font-family: Verdana; font-size: x-small;">Hope you enjoyed this short note on Immutable objects. Immutable objects is a
design pattern which was first officially discussed in Java concurrency in
practice book. In case you are interested to learn design pattern I would
suggest creating a full blown project and starting implementing design pattern
in the same. <br />
</span><br />
<span style="font-family: Verdana; font-size: x-small;">You can start from the below youtube video in which I have demonstrated
design pattern with a full blown project.</span><br />
<iframe width="560" height="315" src="https://www.youtube.com/embed/YDobmucohqk" frameborder="0" allowfullscreen></iframe>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a></div>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-6536619785586318062015-09-28T06:15:00.000-07:002015-09-28T06:24:47.339-07:00Out and REF in C#<div dir="ltr" style="text-align: left;" trbidi="on">
Out and REF are one of those most confused topics in C#. In this small article we will try to simplify the same.<br />
<br />
There are three important points to remember about OUT and REFand once you understand these three points you would never have problem with OUT and REF.<br />
<br />
<i>Point number 1:- By default variables are passed BYVAL to methods and functions. Out and Ref helps to pass variable BY REF (By reference) .</i><br />
Let us try to understand the above point. Consider the below code snapshot where we have the “Main” method and its calling “SomeFunction” method and its passing “OutSideVar” variable to “SomeFunction”.<br />
<br />
Now by default only value of “OutSideVar” will be copied to the method so any changes in “InsideVar” variable change will have no affect outside. You can see after the function call “OutSideVar” still has value “20”. In other words by default the values are passed BY VAL.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgi0ty-YBcrKtjMFn7ODCVYhAroKCMeIlOMQ7vAqpd7xcAn784d0N_FgeBT6qvOQa9ooByJvv6iQlqdn3RSH8A1lYT5nZbBEbSJhIUMnHjxvEVveSQNwbcXZOZsR9fDeqNWT4_l48guHg/s1600/c1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="225" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgi0ty-YBcrKtjMFn7ODCVYhAroKCMeIlOMQ7vAqpd7xcAn784d0N_FgeBT6qvOQa9ooByJvv6iQlqdn3RSH8A1lYT5nZbBEbSJhIUMnHjxvEVveSQNwbcXZOZsR9fDeqNWT4_l48guHg/s400/c1.jpg" width="400" /></a></div>
<br />
So if we summarize in a normal situation data is passed BY VAL , from the caller to callee. Any modifications done in the callee will not be reflected to the caller.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0m2imGiB8ZGSdle9UYpyUf_0m0-3fWcor_22pupk6-3zSEVhZt303Z6xdRwMSuRcrxc-9YoZrOiWF3qEfWq2UCW-WAmbRKmLQrPoYAmH093_Fe5beEVEv6zscjwqdEWST4JqDM62tzQ/s1600/c2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0m2imGiB8ZGSdle9UYpyUf_0m0-3fWcor_22pupk6-3zSEVhZt303Z6xdRwMSuRcrxc-9YoZrOiWF3qEfWq2UCW-WAmbRKmLQrPoYAmH093_Fe5beEVEv6zscjwqdEWST4JqDM62tzQ/s1600/c2.jpg" /></a></div>
<br />
<i>Point number 2:- When we mark parameters with REF, reference of the variable is passed to the function / method and any modification in that method and function will affect to the outside variable.</i><br />
In the below code you can see we have marked variablesusing the REF keyword and you can see how the changes within the function modifies the outside variable also. This is happening because now variable is passed by reference.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_4qY1R0WOH0j5mv1Q7UPW0eclhxVkLGDThw66uJo583UxWP5cKifBKNvafsR2jg7BYYff9CPQUZWjyRUa02GT5UJBAmyW_TxHSX4DvPwyBZWZ6lXqAHwDiASPoZluQwkXjcDh6rl3Ng/s1600/c3.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="233" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_4qY1R0WOH0j5mv1Q7UPW0eclhxVkLGDThw66uJo583UxWP5cKifBKNvafsR2jg7BYYff9CPQUZWjyRUa02GT5UJBAmyW_TxHSX4DvPwyBZWZ6lXqAHwDiASPoZluQwkXjcDh6rl3Ng/s400/c3.jpg" width="400" /></a></div>
<br />
Summarizing in this scenario DATA + REFERENCE is passed to the function and any modification inside the function affects the outside variable.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhoytdUlKGhYVY-mVkGL_guTFS41irc3uuTDNF7lRtuw_s0vn2J5qV6fzeVE3vrDp3qrpnccTEw_bgEbGEFTv4NIlP_Bx20rvmrhMMPddqSaM3ONNIDNPllPadI_B9zCHg1ZPvLotYOsQ/s1600/c4.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhoytdUlKGhYVY-mVkGL_guTFS41irc3uuTDNF7lRtuw_s0vn2J5qV6fzeVE3vrDp3qrpnccTEw_bgEbGEFTv4NIlP_Bx20rvmrhMMPddqSaM3ONNIDNPllPadI_B9zCHg1ZPvLotYOsQ/s1600/c4.jpg" /></a></div>
<i><br />Point number 3:- When we mark parameters with OUT, ONLY reference of the variable is passed to the function or method and NOT DATA.Any modification in that method and function will affect outside variable as well. Also its compulsory to initialize the variable.</i><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
When we mark the variable as OUT only reference is passed no data is passed to the function. For instance in the below code the value “20” from “OutSideVar” is not sent to the function. But any modification in variable from the inside function is reflected to the outside variable.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjmH6s2-3HKgyAD3FvpNwhDMbfynJJ33bxv3nptBPVYR8zVNkiWN0_BPmQErvbRvVxf-enz_eNTXwwgFFIzX__8K3K4GfnfX8ctkwD_ssVEXsvqYu36XOUM-Gxygb_Rjhz02VaL600PHA/s1600/c5.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="222" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjmH6s2-3HKgyAD3FvpNwhDMbfynJJ33bxv3nptBPVYR8zVNkiWN0_BPmQErvbRvVxf-enz_eNTXwwgFFIzX__8K3K4GfnfX8ctkwD_ssVEXsvqYu36XOUM-Gxygb_Rjhz02VaL600PHA/s400/c5.jpg" width="400" /></a></div>
<br />
Summarizing, you can term this also has one way but it’s one way from the callee to the caller and any data sent from the caller is discarded.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnIw5nPwfYp_pTA_nEczEX1nfRV6PZbkQCf3tAl51Tyrip-HMepZoAJZ2SK_4E-T9DeoZht-CaPZjYVyPdWSfmVHR7vMFxNfylgbbzwsUr9iRZeusc6OafU4it_qEjqFkUfnR2SCWIag/s1600/c6.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnIw5nPwfYp_pTA_nEczEX1nfRV6PZbkQCf3tAl51Tyrip-HMepZoAJZ2SK_4E-T9DeoZht-CaPZjYVyPdWSfmVHR7vMFxNfylgbbzwsUr9iRZeusc6OafU4it_qEjqFkUfnR2SCWIag/s1600/c6.jpg" /></a></div>
<br />
So summarizing what we have learnt:-<br />
<ul>
<li>Out and Ref help to pass variables by reference.</li>
<li>In REF with reference data is also passed from caller to the callee and vice versa. It’s two way i.e. from caller to the callee and vice-versa.</li>
<li>In OUT only reference is passed and modified data from the callee is passed to the caller variable. This is one way from the callee to the caller.</li>
<li>In OUT if data is passed from the caller function it is discarded and the variable has to be initialized inside the function. </li>
</ul>
Below image summarizes what we talked in the above article.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgM9GS_hZRaod9itu7cj_2ffLJr5G-MQnOE63yr6NyWEt5tTsaiKlwBqjNbtLpk2yV8zh8gtrf2ohxxk6RONGO3Q_hbqs1yTiSxFNLxTK97MI7Gg1RSwSMWELo87Ixdk1j4fR3sj7AwuA/s1600/c7.bmp" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgM9GS_hZRaod9itu7cj_2ffLJr5G-MQnOE63yr6NyWEt5tTsaiKlwBqjNbtLpk2yV8zh8gtrf2ohxxk6RONGO3Q_hbqs1yTiSxFNLxTK97MI7Gg1RSwSMWELo87Ixdk1j4fR3sj7AwuA/s1600/c7.bmp" /></a></div>
<br />
Below is a nice C# video which explain Out Vs Ref.<br />
<br />
<iframe allowfullscreen="" frameborder="0" height="295" src="https://www.youtube.com/embed/lYdcY5zulXA" width="515"></iframe>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a></div>
Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0Mumbai, Maharashtra, India19.0759837 72.87765590000003618.5957917 72.232208900000032 19.556175699999997 73.52310290000004tag:blogger.com,1999:blog-5571184103023259871.post-35529559258872992012015-09-03T23:59:00.000-07:002015-09-03T23:59:19.288-07:00C# Out VS Ref<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
Lot of times we come across C# fundamentals which are bit confusing and one such concept which is discussed a lot is Out VS Ref. So this small blogpost would make a full attempt to simplify the OUT vs REF concept.<br />
<br />
Out and Ref are keywords which you need to worry when you want to get MULTIPLE values from a function. It helps you to define how data would be passed from caller to the callee and vice versa.<br />
<br />
For example take the case of a simple “Add” function below. It has only one output so with just a single return call things work perfectly well.<br />
<br />
<pre>static int Add(int num1,int num2)
{
return num1 + num2;
}
</pre>
<br />
But now lets do something more complicated. In the below function we need to get 4 outputs or putting in other words we have four OUT parameter values. This is where OUT keyword comes to help.<br />
<br />
<pre>static int Maths(int num1,int num2)
{
int Add = num1 + num2;
int Sub = num1 - num2;
int Divide = num1 / num2;
int Multi = num1 * num2;
}
</pre>
<br />
When you use OUT keyword you are indicating that you are expecting output from the function but you do not intend to pass data to the function. It is just ONE WAY :- so the Caller get data from the Callee.<br />
<br />
So to indicate this one-way data transfer you need to use the OUT keyword on the Callee as shown below.<br />
<br />
<pre>static void Maths(int num1,
int num2,
out int Add,
out int Sub,
out int Multi,
out int Div)
{
Add = num1 + num2;
Sub = num1 - num2;
Div = num1 / num2;
Multi = num1 * num2;
}
</pre>
<br />
The caller also needs to provide the variables in which the data will be received and the caller needs to mark the variables with OUT keyword while making the call. In short both the caller and callee will have the OUT keyword indicating that data will come out of these variables.<br />
<br />
<pre>int Add,Sub,Multi,Div=0;
Maths(10, 10,out Add,
out Sub,
out Multi,
out Div);
</pre>
<b><br />Note :-</b> If you are specifying a variable as OUT and also trying to set data while calling, the passed DATA WILL BE DISCARDED inside the method / function.<br />
<br />
Now let us take a scenario of a swapping number function code as shown below. In this scenario we want that the function should take “num1” and “num2” values and update the swapped values in the same two variables.<br />
<br />
<pre>static void Swap(int num1, int num2)
{
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
}
</pre>
<br />
For that we need use the REF keyword as shown below.<br />
<br />
<pre>static void Swap(ref int num1,ref int num2)
{
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
}
</pre>
<br />
From the caller side we need to again use the REF keyword as shown below.<br />
<br />
<pre>int num1 = 10;
int num2 = 20;
Swap(ref num1,ref num2);
</pre>
<br />
In REF the data will be passed to the function / method and when the callee method updates the variables it will update the caller variables as well.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiA2nIpcI_pkAG94LZuwEa-LxHxX50io27kIyw_dr67fm8OcD2n8wSzcUDk8WNfsi-XKNE3Ficxt3eEEQRWqn2r-UHSJIWr7X2xwnRCWp0qbtmKAbWoL0pMOig_Ymzw7uFFmGBLTzk20Q/s1600/ref.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiA2nIpcI_pkAG94LZuwEa-LxHxX50io27kIyw_dr67fm8OcD2n8wSzcUDk8WNfsi-XKNE3Ficxt3eEEQRWqn2r-UHSJIWr7X2xwnRCWp0qbtmKAbWoL0pMOig_Ymzw7uFFmGBLTzk20Q/s1600/ref.jpg" /></a></div>
<br />
Below is a visual diagram which explains the difference between REF and OUT. In REF Parameter + Data is passed while in OUT only parameter is passed and data is set from the callee.<br />
<br />
<br />
So the conclusion is as follows of the above post is as follows:-<br />
<ul>
<li>It should be used only when we are expecting multiple outputs from a function or a method.</li>
<li>REF and OUT are keywordswhich dictate how data is passed from caller to callee and vice versa.</li>
</ul>
<table border="1" style="height: 59px; width: 538px;">
<tbody>
<tr>
<td height="24" width="226"><div align="center">
<span style="font-family: Calibri,sans-serif; font-size: 11.0pt; line-height: 115%;">
REF</span></div>
</td>
<td height="24" width="296"><div align="center">
<span style="font-family: Calibri,sans-serif; font-size: 11.0pt; line-height: 115%;">
OUT</span></div>
</td>
</tr>
<tr>
<td height="25" width="226"><span style="font-family: Calibri,sans-serif; font-size: 11.0pt; line-height: 115%;">
Data passes two way. From caller to callee and vice-versa.</span></td>
<td height="25" width="296"><span style="font-family: Calibri,sans-serif; font-size: 11.0pt; line-height: 115%;">
Data passes only one way from callee to caller. Caller data if passed is
rejected.</span></td>
</tr>
</tbody></table>
<br />
Below is one such concept which is not known to many developers, the C# yield keyword. Below is a simple video of the same which explains the same in a practical manner.<br />
<br />
<iframe allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/4fju3xcm21M" width="560"></iframe></div>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a></div>
Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0Mumbai, Maharashtra, India19.0759837 72.87765590000003618.5957917 72.232208900000032 19.556175699999997 73.52310290000004tag:blogger.com,1999:blog-5571184103023259871.post-7555396582111447172015-05-28T05:43:00.000-07:002015-09-04T00:05:33.760-07:00Preventing XSS Attacks in ASP.NET MVC using ValidateInput and AllowHTML<div dir="ltr" style="text-align: left;" trbidi="on">
<a href="https://www.blogger.com/blogger.g?blogID=5571184103023259871#intro">Introduction</a><br />
<a href="https://www.blogger.com/blogger.g?blogID=5571184103023259871#isxss">What is XSS?</a><br />
<a href="https://www.blogger.com/blogger.g?blogID=5571184103023259871#intro1">How can we prevent the same in MVC?</a><br />
<a href="https://www.blogger.com/blogger.g?blogID=5571184103023259871#isxss2">What is the difference between “ValidateInput” and “AllowHTML” in MVC ?</a><br />
<h3>
<a href="https://www.blogger.com/null" name="intro">Introduction</a></h3>
In this blog we will try to understand how we can prevent and fine tune XSS(Cross Site Security) security attacks in ASP.NET MVC.<br />
<h3>
<a href="https://www.blogger.com/null" name="isxss">What is XSS?</a></h3>
XSS(Cross Site Security) is a security attack where the attacker injects malicious code while doing data entry. This code can be a javascript, vbscript or any other scripting code. Once the code is injected in end user’s browser. This code can run and gain access to cookies,sessions, local files and so on.<br />
For instance below is a simple product data entry form. You can see in the product description how the attacker has injected a javascript code.<br />
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiyD4__GNu8eXfl4p-bNiuT3l5RcUXjTX7__tG6ey-kqu9qQCsVxXnGKPwNR-C4kJ_vN3AuooDtypyGedOs1f5XNS6GxrvpCy3UpYE0KeTmSG049ZDnsERLNwnQ9qX_rE1Rjs9SpWhovA/s1600/1.jpg" /><br />
Once we click submit you can see the JavaScript code actually running.<br />
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhucrGR0jKGZMlNZhLXWdzAZbZOkZP4LwhZ8GO-LZyYU6JgaZvy6xZCxqhxm5ct4csOhoNxf9rLAKLYUwNqFMPGKMYG-SUYAHn57K4hcSK5IKQzGLy9C3TwgTatlBoU854CplNOW7_Hew/s1600/2.jpg" /><br />
<h3>
<a href="https://www.blogger.com/null" name="intro1">How can we prevent the same in MVC?</a></h3>
In MVC by default XSS attack is validated. So if any one tries to post javascript or HTML code he lands with the below error.<br />
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSh3bXLc4EAUSumtawg7onVdsw5awARxZOOiHXM7go2JWEeAN5MW6S5asZaOj2uCum_wC7z9WDeHDonbgRM6ydi8d4WHQlsHiDFXF00Wx2w7weiQPBT3ifQus_Q64QnRFelxOtOD00lw/s450/3.jpg" /><br />
<h3>
<a href="https://www.blogger.com/null" name="isxss2">What is the difference between “ValidateInput” and “AllowHTML” in MVC?</a></h3>
As said in the previous question in ASP.NET MVC we are not allowed to post scripts and HTML code by default. But consider the below situation where we want HTML to be written and submitted. <br />
The other scenario where we need HTML to be posted is HTML editors. So there is always a need now and then to post HTML to the server.<br />
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNynsYeTk7Md7vWc5uTdo5Cjljn1ChrawJ5JOlTZvYh5wJCgUaOdy_aZlG5L0nE0tX-Y95jNehz37h5Vwh7HWn0xk6_8eTXZYZAblk4VUaYuZbU9WYjKwId1gSrbEbgnIHniCLjTXoZQ/s1600/4.jpg" /><br />
So for those kinds of scenarios where we want HTML to be posted we can decorate the action with “ValidateInput” set to false.This by passes the HTML and Script tag checks for that action.<br />
You can see in the below code we have requested the MVC framework to NOT VALIDATE the input to the action.<br />
<pre lang="lang">[ValidateInput(false)]
public ActionResult PostProduct(Product obj)
{
return View(obj);
}
</pre>
But the above solution is not proper and neat. It opens a complete Pandora box of security issues. In this product screen scenario we just HTML in product description and not in product name. <br />
But because we have now decorated validate false at the action level , you can also write HTML in product name field as well. We would love to have more finer control on the field level rather than making the complete action naked.<br />
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNCaARg78Siz4blGzOgGGQjuqfmGhp2jD2iFXtCVlmjnSZi8WcVAYsZ1amUW1agQet0GGS0laahYvimqE1oCxhagG92EHsSSNjJxXr3i71kTbF-XtNMFJFo01DzuXy9PuqRzBkMKJKVw/s1600/5.jpg" /><br />
That’s where “AllowHTML” comes to help. You can see in the below code we have just decorated the “ProductDescription” property .<br />
<pre lang="html">public class Product
{
public string ProductName { get; set; }
[AllowHtml]
public string ProductDescription { get; set; }
}
</pre>
And from the action we have removed “ValidateInput” attribute.<br />
<pre lang="html">public ActionResult PostProduct(Product obj)
{
return View(obj);
}
</pre>
If you now try to post HTML in product name field you will get the below error saying you cannot post HTML tags in product name field.<br />
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibvoKEWvdME-L2Z2l5AEwf06m-hc1UTaIswBKc7oWgh_Q74WJbqMfrJfMISkvsAUYJr0LJIj6mpFNAGkLZTRsf2sg6feOhz9dCnEtp0OzQUdHlXTU2aRiXD3j243k1Fhw3g_mF7Fxibg/s450/6.jpg" /><br />
So the difference between ValidateInput and AllowHTML is the granularity of preventing XSS attacks.<br />
Hope you have enjoyed this blog.<br />
Also the other dead attack which happens on a MVC website is CSRF, see the below facebook video which demonstrates how CSRF attack can be prevented.<br />
<a href="https://www.facebook.com/shivprasad.koirala/videos/vb.100002224977742/811974695553355" target="_blank">
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-11hBUnwAPYfDS4Br38yZSE62TXYbrlnbU-xP3hqGRTVudRZmgVQyLvk_6sTzGycsLeQ7SRop19UzawFEw7exg0pVW5w_WYcEdLnoW_kabL2V7Ft2xvo01Op25AX11eVAdVXHuGhmLQ/s450/7Vid.jpg" /></a><br />
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a></div>
Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-50386108910479811462015-05-25T01:35:00.001-07:002015-09-28T05:51:54.816-07:00What is CSRF attack and how can we prevent the same in MVC?<div dir="ltr" style="text-align: left;" trbidi="on">
<p>CSRF (Cross site request forgery) is a method of attacking a website where the attacker imitates a.k.a forges as a trusted source and sends data to the site. Genuine site processes the information innocently thinking that data is coming from a trusted source.</p>
<p>For example conside the below screen of a online bank. End user’s uses this screen to transfer money.</p>
<p>
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCEOVhRnsq-ryevLzqSXcN4DZxYCpR2tmlmiJK1p_nIY74mAY9WnKgvwGszPkx5F9-VzfquEJd5QjR9AAegcZx2L416UVUicphOubAd2JFQzHtijQmFXp8-bpkrYpQkUC67ZS1ccjA1g/s1600/1.jpg" ></p>
<p>Below is a forged site created by an attacker which looks a game site from outside, but internally it hits the bank site for money transfer.</p>
<p>
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhK_ju7CGUECxjme_ypogT2Ff0nRQVVsobvXCOjUCWqwyOVFdDVLqgnXvJ41M57pWCXNaUR8Uc2bEmSDsbzj9PM7WNZp1PoasqcoMZXg34GqGnlbMq2LbQP_AMCFCyGouDpLqurVq-VAg/s1600/2.jpg" ></p>
<p>The internal HTML of the forged site has those hidden fields which have the account number and amount to do money transfer. </p>
<p><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiAxbVnmbXB7pZDT4UMEnTJj3dPys3TjoYkkeZvVKyObdbrhoxprCLRIIEym1oFaxHXg2zEuNU6f8t1FXA7HTjVJmcoSBTMCY4yiVdRwNpgzMCc4pUL8sqnOi0ebos5SX3q0P1WTaf9hA/s450/6.jpg" /></p>
<p>Now let’s say the user has logged in to the genuine bank site and the attacker sent this forged game link to his email. The end user thinking that it’s a game site clicks on the “Play the Ultimate Game” button and internally the malicious code does the money transfer process.</p><p><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQKPPfFbI4DqTgi4YqMSoUaT9huWf_-ufUFJ_TvZofGqV-VJok30uCBBQq5oBBxUjtnH88IokVYV-rrP4tVjjaJtHVrkfuptHv6Y4t9E0ldsUcOj475splLfqBY7aOowS-YajMKoGYFQ/s1600/3.jpg"></p><p>So a proper solution to this issue can be solved by using tokens: -</p><ul><li>End user browses to the screen of the money transfer. Before the screen is served server injects a secret token inside the HTML screen in form a hidden field.</li><li>Now hence forth when the end user sends request back he has to always send the secret token. This token is validated on the server.</li></ul><p></p>
<p><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiQ5lebl5prpCULoZtTDqPNm6vXAVZQYJFvYnN782kkeIRfEO4jmM2Vl0SslPdU3HpB6oXBCscFlhY9ff8XXib_T2gVD14YvTP43CsOGl3syhOU7j_CoX01ZDBCL76vod06ivligVJmaA/s450/4.jpg"></p><p>Implementing token is a two-step process in MVC: -</p><p>First apply “ValidateAntiForgeryToken” attribute on the action.</p>
<pre lang="html">[ValidateAntiForgeryToken]
public ActionResult Transfer()
{
// password sending logic will be here
return Content(Request.Form["amount"] +
" has been transferred to account "
+ Request.Form["account"]);
}</pre>
<p>Second in the HTML UI screen call “@Html.AntiForgeryToken()” to generate the token.</p>
<p><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3WobH2gZ1R8jyWM6sOzUVqWl-L6sszvt81whfTVSO8Lf9xFOCHEXOejOpx5pZSrLbr2yejzjs7BSDD7OqIGnyZIVd9Zx3_3cn7yZ3XGEwZhPf1mvqZ1N4RpbJD0pJSz-ZmVleg7JSig/s450/7.jpg" /></p>
<p>So now henceforth when any untrusted source send a request to the server it would give the below forgery error.</p>
<p><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiG_0CTdTM4VkUb8xcOO4_7ck7btdA-Sqtu2IEezw1E7tb6g7THWFm5a0c1QMA7hG4Y9IdZvWOKa4oYTX4iJGdqQU3cjx8XpTg25iF9N98R54SLkCBIXyZEMpGNakHRxkXiAxHsbsfhfA/s450/5.jpg" ></p>
<p>If you do a view source of the HTML you would find the below verification token hidden field with the secret key.</p>
<p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjv3_nwFZERNhz_VvTPTu9D6gWCZsSp1_m41FxWN7qtcYPBqRJCYyb4DWz0Q47lU74ZZdiBm3UAmPVzk-f_TpEJohqo9ONsF7cyPDXd7N8XNJA5OyhbZQhNUI2GrnrAzdBiV_FHjM5xUQ/s1600/8.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjv3_nwFZERNhz_VvTPTu9D6gWCZsSp1_m41FxWN7qtcYPBqRJCYyb4DWz0Q47lU74ZZdiBm3UAmPVzk-f_TpEJohqo9ONsF7cyPDXd7N8XNJA5OyhbZQhNUI2GrnrAzdBiV_FHjM5xUQ/s500/8.jpg" /></a></div></p>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a></div>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-61416548638760094132015-05-19T03:16:00.000-07:002015-05-19T03:16:22.313-07:00How to handle multiple Submit button issues in ASP.NET MVC? (MVC Interview Questions)<div dir="ltr" style="text-align: left;" trbidi="on">
<h3>How to handle multiple Submit button issues in ASP.NET MVC? (MVC Interview Questions)</h3>
<p>Let us understand the above problem in more detail.</p>
<p>Take a scenario where you have a view with two submit buttons as shown in the below code.</p>
<p><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhk1PsFY8Oqqnkeu1if0qABuQihVQkRXbyTMy7hjCHJ-7bT0ct-H8lp4JxAKQbCIz2lAnQQP8FVxYgzdCc3kanIQhZQBporTawtABC8msubWQ8y91bS6e90jedLYIlXXnVXpcE2rXvipA/s1600/1.jpg" /></p>
<p>In the above code when the end user clicks on any of the submit buttons it will make a HTTP POST to “Action1”.</p><p>The question from the interviewer is: -</p><p>“What if we have want that on “Submit1” button click it should invoke “Action1” and on the “Submit2” button click it should invoke “Action2”.”</p><p>There are three basic approaches to solve the above problem scenario.</p><h4>HTML way: -</h4><p>In the HTML way we need to create two forms and place the “Submit” button inside each of the forms. And every form’s action will point to different / respective actions. You can see the below code the first form is posting to “Action1” and the second form will post to “Action2” depending on which “Submit” button is clicked.</p>
<p><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGDUjndYAuiLzthL1brMFm03thCzQrxSKl3momSKiorh4ICiYLxyDxB0_BjrZ-PfrX-GAclOBHuDO2c2pYlJCOzWx61p6QRUDB2kFdDi6j0tisdrVbnVGFOzz3_SrwyvmKZf8Jij5a7w/s1600/2.jpg" /></p>
<h4>AJAX way: -</h4><p>In case you are an AJAX lover this second option would excite you more. In the Ajax way we can create two different functions “Fun1” and “Fun1”, see the below code. These functions will make Ajax calls by using JQUERY or any other framework. Each of these functions is binded with the “Submit” button’s “OnClick” events. Each of these function make call to respective action names.</p>
<p><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgndQKRLv7oX1BSwovDxFUwm00hjKhtFd7lmYgr90jhmc9m5SoWQ8y6rxBwvk4mnAjEyO0HoPUru9fngUTVycpCRUU7z2-URQuRPkkA0HHoCyucqEeylmpBzdxaw4w-jQ78JHnPKGPONA/s1600/3.jpg" />
</p>
<h4>Using “ActionNameSelectorAttribute”: - </h4>
<p>This is a great and a clean option. The “ActionNameSelectorAttribute” is a simple attribute class where we can write decision making logic which will decide which action can be executed.</p><p>So the first thing is in HTML we need to put proper name’s to the submit buttons for identifying them on the server. </p>
<p>You can see we have put “Save” and “Delete” to the button names. Also you can notice in the action we have just put controller name “Customer” and not a particular action name. We expect the action name will be decide by “ActionNameSelectorAttribute”.</p>
<p>
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyMQfhGZk_5nryxgZo1oMj7OqSukLKedaOZh-6YLOzmSSnBkm4adssQBVBwOqnJzqYz2pL-ScHRLBSYNpTpuTvABtbg0MdWQ3FsTGkyv9jvQJZCnJNsYu93RUtf8oJwghuTXzHkeKkcQ/s1600/4.jpg" />
</p>
<p>So when the submit button is clicked, it first hits the “ActionNameSelector” attribute and then depending on which submit is fired it invokes the appropriate action.</p><p><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibBauzlJE7LYN_1Z6tmgvCw67SqpPt0E3uNOK5Tea0yZmCvlt4Nro7I7pmRHod759aKr8EunmTkyJPBRgGjFPs6euTUvpOftgE6gliJQjplEGJVKQ9wKmT03QDvcb2B-QbgK4HEGULiA/s1600/submit.jpg" /></p><p>So the first step is to create a class which inherits from “ActionNameSelectorAttribute” class. In this class we have created a simple property “Name”.</p><p>We also need to override the “IsValidName” function which returns true or flase. This function is where we write the logic whether an action has to be executed or not. So if this function returns true then the action is executed or else it is not.</p>
<pre lang="html">
public class SubmitButtonSelector : ActionNameSelectorAttribute
{
public string Name { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, System.Reflection.MethodInfo methodInfo)
{
// Try to find out if the name exists in the data sent from form
var value = controllerContext.Controller.ValueProvider.GetValue(Name);
if (value != null)
{
return true;
}
return false;
}
}
</pre><p>The main heart of the above function is in the below code. The “ValueProvider” collection has all the data that has been posted from the form. So it first looks up the “Name” value and if its found in the HTTP request it returns true or else it returns false.</p>
<pre lang="html">var value = controllerContext.Controller.ValueProvider.GetValue(Name);
if (value != null)
{
return true;
}
return false;
</pre><p>This attribute class can then decorated on the respective action and the respective “Name” value can be provided. So if the submit is hitting this action and if the name matches of the HTML submit button name it then executes the action further or else it does not.</p>
<pre lang="html">public class CustomerController : Controller
{
[SubmitButtonSelector(Name="Save")]
public ActionResult Save()
{
return Content("Save Called");
}
[SubmitButtonSelector(Name = "Delete")]
public ActionResult Delete()
{
return Content("Delete Called");
}
}
</pre>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a>
</div>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-79783109661649542732015-05-11T03:52:00.000-07:002015-05-11T03:56:11.420-07:00Validation’s using C# “DataAnnotation”<div dir="ltr" style="text-align: left;" trbidi="on">
<dt><a href="#Introduction">Introduction</a></dt>
<dt><a href="#Howtouse">How to use “DataAnnotations” ?</a></dt>
<dd><a href="#Step1">Step 1:- Refer System.ComponentModel.DataAnnotations</a></dd>
<dd><a href="#Step2">Step 2:- Decorate the class with attributes</a></dd>
<dd><a href="#Step3">Step 3:- Call the “Validator” for validation.</a></dd>
<br />
<h3><a name="Introduction">Introduction</a></h3>
<p>Validations are one of the most important aspects of any software application. Normally as a best practice we put these validation’s in the business class , model etc.
So if you normally see the trend, developers end up writing these validations in the “set” method of the class property.
</p>
<pre>
public class Customer
{
private string _CustomerName;
public string CustomerName
{
get { return _CustomerName; }
set
{
if (value.Length == 0)
{
throw new Exception("Customer Name is required");
}
_CustomerName = value;
}
}
}
</pre>
<p>“DataAnnotation” gives you ready made attributes which you can decorate on the class properties and the validation will be applied accordingly.</p>
<pre>[Required]
public string CustomerName
{
get { return _CustomerName; }
set {_CustomerName = value; }
}
</pre>
<h3><a name="Howtouse">How to use “DataAnnotations” ?</a></h3><br>
<h4><a name="Step1">Step 1:- Refer System.ComponentModel.DataAnnotations</a></h4>
<p>The first step is to add reference to “System.ComponentModel.DataAnnotations” assembly to your class library project.</p>
<h4><a name="Step2">Step 2:- Decorate the class with attributes</a></h4>
<p>The next step is to decorate the class with validation attributes. For instance on the “CustomerName” property we have decorated the “Required” attribute.</p>
<pre>
public class Customer
{
private string _CustomerName;
[Required]
public string CustomerName
{
get { return _CustomerName; }
set {_CustomerName = value; }
}
}
</pre>
<h4><a name="Step3">Step 3:- Call the “Validator” for validation.</a></h4>
<p>Once the validation attributes are decorated we need to call the “Validator” class to do the validations.
Create the customer object and set the “CustomerName” property to nothing , so validation errors fire up.
</p>
<pre>
Customer obj = new Customer();
obj.CustomerName = "";
Use the above created object to create the “ValidationContext” object.
var context = new ValidationContext(obj,null,null);
Use “Validator” to call “TryValidateObject” method to run the validations. The validation errors get collected in the “ValidationResult” collection.
var result = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(obj, context, result,true);
</pre>
<p>If you wish to loop through the error results you can run a “foreach” on the “result” collection.</p>
<pre>
foreach (var str in result)
{
Console.WriteLine(str.ErrorMessage.ToString());
}
</pre>
<p>Below is a pictorial representation of the above code. In simple words the object to be validated is passed to the “validator” class with the context and the error results come out in “ValidationResult” collection.</p>
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZHc7q54O0812HrrKXkSSnIMWXjRuqKIdk5_GkB2Z2bDl0eSvJKCh6ji2Cdud-2BEF6kRmB2LbZbPxDUqNaEia4kZ86k80xHrp55vfIOt17G2puoEC1-4XXRTWo0HJ0CUcqAPv9ra1VQ/s1600/1.jpg"></img>
<p>FYI :- If you have multiple validation do not forget to make the last property true.</p>
<pre>var isValid = Validator.TryValidateObject(obj, context, result,true);</pre>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a></div>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0tag:blogger.com,1999:blog-5571184103023259871.post-26814218850493348352015-04-27T23:48:00.000-07:002015-04-28T22:53:16.879-07:00What is Automapper?<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<h3>
Contents</h3>
<p><a href="#WhatisAutomapper">What is Automapper ?</a></p>
<p><a href="#Ihavenotspecifiedmappinghowdoesitwork">I have not specified mapping how does it work ?</a></p>
<p><a href="#HowcanwemapdifferentpropertynamesinAutomapper">How can we map different property names in Automapper ?</a></p>
<p><a href="#CanyougivesomerealtimescenariosoftheuseofAutomapper">Can you give some real time scenarios of the use of Automapper ?</a></p>
<p><a href="#FromwheretogetAutoMapper">From where to get AutoMapper ?</a></p>
<h3>
<br /></h3>
<h3>
<a href="https://www.blogger.com/null" name="WhatisAutomapper">What is Automapper ?</a></h3>
<br />
Automapper is a simple reusable component which helps you to copy data from object type to other. If you wish to get automapper read this.<br />
<br />
For example below is a simple employee class loaded with some dummy data.<br />
<pre lang="”html”">class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Salary { get; set; }
}
// Loaded with some data
Employee emp = new Employee();
emp.FirstName = "Shiv";
emp.LastName = "Koirala";
emp.Salary = 100;
</pre>
Now let’s say we want to load the above employee data in to a “Person” class object.<br />
<pre lang="”html”">class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
</pre>
So normally developers end up writing mapping code as shown in the below snippet.<br />
<pre lang="”html”">Person per = new Person();
per.FirstName = emp.FirstName;
per.LastName = emp.LastName;
</pre>
<br />
At the first glance this does not look much of a problem but wait…think, what if you want to use this mapping code again and again.<br />
<br />
So as a best practice you would like to centralize this mapping code and reuse this mapping code again and again. This is where our super hero “AutoMapper” comes for rescue.“Automapper” sits in between both the objects like a bridge and maps the property data of both objects.<br />
<br />
<div align="center">
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEipXVV_OhDcjk7t6aDy8BiFE3SvXcctR2GarANdU0Pb1xk1C8lGDZ0p5dWfazernbuDwcFBWq9iWiuKqesyK4IwmCpNOdv1sUwdPvJlfrmB8m0TyTgygX7Gh57a-fxi4yQfFxnSODS64A/s1400/1.jpg" height="95" width="520" /></div>
<br />
Using Automapper is a two-stepprocess:-<br />
<ul>
<li>Create the Map.</li>
<li>Use the Map so that objects can communicate.</li>
</ul>
<pre lang="”html”">Mapper.CreateMap<employee person="">(); // Create Map
Person per = Mapper.Map<employee person="">(emp); // Use the map
</employee></employee></pre>
<h3>
<a href="https://www.blogger.com/null" name="Ihavenotspecifiedmappinghowdoesitwork">I have not specified mapping how does it work ?</a></h3>
<div>
<br /></div>
In the above example property names of both classes are same so the mapping happens automatically.<br />
<br />
<h3>
<a href="https://www.blogger.com/null" name="HowcanwemapdifferentpropertynamesinAutomapper">How can we map different property names in Automapper ?</a></h3>
<br />
If the classes have different property names then we need to use “ForMember” function to specify the mapping.<br />
<pre lang="”html”">Mapper.CreateMap<employee person="">()
.ForMember(dest => dest.FName , opt => opt.MapFrom(src => src.FirstName))
.ForMember(dest => dest.LName , opt => opt.MapFrom(src => src.LastName));
</employee></pre>
<h3>
<a href="https://www.blogger.com/null" name="CanyougivesomerealtimescenariosoftheuseofAutomapper">Can you give some real time scenarios of the use of Automapper ?</a></h3>
<ul>
<li>When you are moving data from ViewModel to Model in projects like MVC.</li>
<li>When you are moving data from DTO to Model or entity objects and vice versa.</li>
</ul>
<div>
<br /></div>
<h3>
<a href="https://www.blogger.com/null" name="FromwheretogetAutoMapper">From where to get AutoMapper ?</a></h3>
<br />
The easiest way is to use nugget. In case you are new to nuget see this YouTube video <br />
<br />
<a href="https://youtu.be/AXfZsTj-7P0" target="_blank"><iframe allowfullscreen="" frameborder="0" height="355" src="https://www.youtube.com/embed/AXfZsTj-7P0" width="530"></iframe><br />
<br />
</a><br />
<div style="text-align: center;">
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhD7apXOfjMENPLKWXAYDWeYAdLPMdm9b_8MuTn1s7Xv5ioCfvoKutC53ol-uiaFbwHmtkFfp7U723RK1gYo8CmrOcQ6Jm4OYLYmV3ZMrhZcB3ah_RNDMnxDvJuZzsmwFrCUA2qZVtxSg/s1400/2.jpg" height="247" width="520" /></div>
</div>
</div>
<br />
Or you can download the component form their main site
<a href="http://automapper.org/" target="_blank">http://automapper.org/</a>
<a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1335831" rel="tag" style="display: none;">CodeProject</a></div>Shivprasad Koiralahttp://www.blogger.com/profile/12249592539960384111noreply@blogger.com0