Off the Ridge Code Newsletter

Search

Starting with jQuery – Part 2

Published April 24, 2014 in jQuery - 0Comments

What is selector in jQuery?

Selectors allow you to select elements on the page or in other words identify an HTML element on the page so that you can manipulate it with jQuery.
The basic syntax is:

jQuery(selector) or $(selector)

Selecting:
1. By Tag Name:

                  $(‘p’) – selects all <p> elements
                  $(‘a’) – selects all <a> elements
– reference multiple tags use comma, to separate the elements:
                $(‘a,p,div’) – selects all anchors, paragraphs and div elements.
– selecting descendants: 
      $(‘ancestor descendant’) – selects all descendants of the ancestor:
      $(‘table tr’) – selects all tr elements that are descendants of the table element
2. By ID:
   $(‘#myID’) – # hash tag indicates to jQuery that we’re looking for the ID.
3. By Class Name:
    
    $(‘.myClass’) – selects <p class=’myClass”>
Combining Tag Name with Class Name:
    $(‘a.myClass’) – selects only <a> tags with class “myClass”
Example:
Let’s apply some CSS to my html via jQuery.

HTML:

<body>
<div class=”FirstDiv”>
        <span>Stitched</span>
    </div>
 
    <br />
    <span class=”FirstDiv”>This is my First Span</span>
    <br />
    <div class=”SecondDiv”>
        <span>Second Div</span>
    </div>
</body>

jQuery:

<script type=”text/javascript”>
     
          $(document).ready(function()
          {
             $(‘.FirstDiv’).css({‘padding’:’20px’,
            ‘margin’:’10px’,
                                 ‘background’:’#ff0030′,
                                 ‘color’:’#fff’,
                                 ‘font-size’:’21px’,
                                  ‘font-weight’:’bold’,
                                  ‘line-height’:’1.3em’,
                                  ‘border’:’2px dashed #fff’,
                                  ‘border-radius’:’10px’,
                                  ‘box-shadow’:’0 0 0 4px #ff0030, 2px 1px 6px 4px rgba(10, 10, 0, 0.5)’,
                                  ‘text-shadow’:’-1px -1px #aa3030′,
                                  ‘font-weight’:’normal’});
                             
 
          });
       
      </script>

Result:

I’ve applied CSS only to my FirstDiv (or so I thought) but we can see that there’s a problem.
The issue here is my span and my div have the same class name. One solution would be to rename the span but we jQuery selectors we can be very specific and fix it by qualifying the selector to with div, i.e. div.FirstDiv

  $(‘div.FirstDiv’).css({‘padding’:’20px’,
                 ‘margin’:’10px’,
                                    ‘background’:’#ff0030′,
                                    ‘color’:’#fff’,
                                    ‘font-size’:’21px’,
                                    ‘font-weight’:’bold’,
                                    ‘line-height’:’1.3em’,
                                     ‘border’:’2px dashed #fff’,
                                     ‘border-radius’:’10px’,
                                     ‘box-shadow’:’0 0 0 4px #ff0030, 2px 1px 6px 4px rgba(10, 10, 0, 0.5)’,
                                     ‘text-shadow’:’-1px -1px #aa3030′,
                                     ‘font-weight’:’normal’});
Result:

Much better!

4. By Attributes:

To select by Attribute value we use brackets:
  1. $[‘a[author]] -> select all the anchor tags that have an author attribute.
  2. $[‘a[author=”charles dickens”]’) – select all anchor elements that have ‘charles dickens’ author attribute value.

Example:
HTML:
 <div author=’charles dickens’>
    charles dickens
    </div>

jQuery:
   $(document).ready(function()
              {
             var divs = $(‘div[author=”charles dickens”]’);
             divs.css({‘background’:’red’});
              });

Result:

 5. By Input Nodes

$(‘:input’) – selects all form control. (e.g.input, textarea, button, image, etc)
$(‘:input[type=”button”]’) – selects all buttons on the page.

6. Additional selectors:

 1. :contains()
     $(‘div:contains(“dickens”)’) – selects div’s that contain the text (case-sensitive) “dickens”.
     as in:
    <div>charles dickens</div>

2. odd or even rows in a table
    e.g. $(‘tr:odd’) and $(‘tr:even’)

3. $(‘element:first-child’) – selects the first child of every element group:
       e.g. $(‘span:first-child’)
as in:
<div>
   <span>first child, first group</span>
   <span>second child, first group</span>
</div>
<div>
   <span>first child, second group</span>
   <span>second child, second group</span>
</div>
<div>
   <span>first child, third group</span>
   <span>second child, third group</span>
</div>
etc..

4. [attribute^=”value“] – selects the elements that begin with value.
  e.g.
    $(‘input[value^=”Process“/>
 as in:
<input type=”button” value=”Process this stuff”/>
<input type=”button” value=”Process that stuff”/>

5. [attribute$=”value“] – selects the elements that end with value.
  e.g.
    $(‘input[value$=”stuff“/>
 as in:
<input type=”button” value=”Process this stuff“/>
<input type=”button” value=”Process that stuff“/>

5. [attribute*=”value“] – selects the elements that contains the value.
  e.g.
    $(‘input[value*=”stuff“/>
 as in:
<input type=”button” value=”Process this stuff“/>
<input type=”button” value=”Process that stuff“/>

You can download an example file to get you started.

Starting with jQuery – Part 1

Published April 24, 2014 in jQuery - 0Comments

How to start with jQuery?

1. Go to http://jQuery.com and download either jQuery 1.x if you’re planning on supporting older browsers (e.g. IE 6-8) or jQuery 2.x if you’d like more slimmer version that doesn’t have the overhead of supporting older versions and it’s much leaner. In other words jQuery 2.x is meant for IE 9 and higher.

You’ll find two different versions for each of the versions one with *.min and the other without the *.min. The *.min is a very condensed version of jQuery with all the whitespace removed and shortened variables and is generally meant for production. If you’re developing code and would like to be able to step through it, I recommend downloading one without the suffix .min.

2. Reference it in your page:

<head>
  <script type=”text/javascript” src=”jquery.js”></script>
</head>

Alternatively, you can use Content Delivery Network or CDN – either from Microsoft or Google 


<head>
 <script type=”text/javascript”
   src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.0.js“>
</script>
</head>

OR from Google:

<head><script src=”http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js”></script></head>


– We’re almost Ready()

When jQuery is loaded the window document or object gets a property called jQuery and that property is initialized IFF jQuery is loaded. i.e. window.jQuery.
You can either use window.jQuery or you can use the alias of it which is a $.
If you were going to peek at the jQuery source code at the end of the file you would find this line:

window.jQuery = window.$ = jQuery;

So to detect when the page is ‘ready’ (the DOM hierarchy is loaded) we can simply use:

$(document).ready(function(){

              // do something useful here..
            });
          </script>

This is it for the first post.

How to create Navigation Bar with CSS3

Published April 22, 2014 in CSS3 - 0Comments

Navigation bar is really just a set of links or put it differently it’s a list of links that can be implemented using html list <ul> without any numbers or bullets. i.e. list-style-type:none, no padding or margins and in order to prevent any new lines set the display to inline-block.

If you’d like to follow along, you can click here to download the ‘Before’ sample.
First thing I’m going to do is create three different pages, Page1.html, Page2.html and Page3.html so that I have something to navigate to.

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>Page 1</title>
</head>
<body>
<p>Page 1 </p>
</body>
</html>

Let’s create our <ul> (or unordered list):

<ul class=”navigation”>
  <li> <a href=”index.html”>Home</a></li>
  <li> <a href=”Page1.html”>Page 1</a></li>
  <li> <a href=”Page2.html”>Page 2</a></li>
  <li> <a href=”Page3.html”>Page 3</a></li>
</ul> 

and add some CSS:

ul.navigation{   list-style-type:none;   padding-left:0;   margin-left:0;   border-bottom: 1px dashed #000000;}

What the above CSS will do is eliminate the bullet points from our list and will get rid of any spaces and margins, as a bonus it will add a nice border to the bottom.
However, if you were to take a peek right now, you’d notice that it doesn’t look like it’s a navigation bar. What will form it into horizontal looking navigation bar is: display:inline; i.e. it won’t have a starting new line. 
Let’s add the following CSS:

.navigation li
{    display: inline;
}

Now, we’re almost there, but let’s remove the ugly looking links:

.navigation a
{
background-color:#bcbaba;
color: #085068;
display: inline-block; border-bottom: none;
padding: 5px 15px 5px 15px;
       text-decoration: none;

}

That’s pretty much it. If you’d like to download finished ‘After’ sample then click here.

Testing waters with HTML5!

Published April 20, 2014 in HTML5 - 1Comments

Testing waters with HTML5! – Part:1 (Possibly, most likely..)

Recently I’ve became interested in HTML5, here are some of my findings:

<!DOCTYPE html> – believe or not, the new DOCTYPE is much simpler to memorize. Originally in HTML 4.X, DOCTYPED referred to Document Type Definition (DTD), that’s because it was based on XML.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

        “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
It’s was a pain to memorize it, not anymore, HTML5 is not based on SGML and therefore does not need a reference to DTD, but there’s more! (or less), only one variant of the DOCTYPE and it is:
<!DOCTYPE html>
Some basics:
1. Now with simple calendar! 
There are several new input types and one of them is called ‘date’:
Let’s try a simple example:
<!DOCTYPE html>
<html lang=”en”>
    <head>
        <meta charset=”utf-8″>
        <link rel=”stylesheet” href=”style.css”/>
        <title>Hello HTML5</title>
    </head>
    <body>
        <p>Hello HTML5!</p>
        
        <form id=”helloHTML5Form”>
        <label for=”date-input”> Please select a date:</label>
        <input type=”date” id=”date-input”/>                
    </body>
<html>
running it quickly in Chrome, renders a calendar picker:
2. Now with (extra) time!
Let’s add type ‘time’:
<input type=”time” id=”time”/>


3.  Range:
<label for=”range”> Please select a week:</label>
<input type=”range” id=”range” min=”0″ max=”99″/>
4. Search
<label for=”search”> Search</label>
<input type=”search” id=”search” placeholder=”Search here..”/>
5. Phone (with required attribute)
<label for=”phone”> Phone:</label>
<input type=”tel” id=”phone” required/>
6. Data List

<input type=”text” list=”datasource”>
<datalist id=”datasource”>
<option label=”OSX” Value=”OSX”></option>
<option label=”Windows 8″ Value=”Windows 8″></option>
<option label=”Ubuntu” Value=”Linux”></option>
</datalist>  
double clicking inside the box opens up the ‘dropdown’

Keep in mind that the feel and look is up to the browser implementation so they will render differently in different browsers, unless of course you style them with CSS.

How to create column with CSS3

Published April 20, 2014 in Uncategorized - 0Comments

How to create column using CSS3

In order to create (float) a colum using CSS3 you need to perform to simple steps:
1. Set its width
2. Set keyword ‘float’

Click here to download the ‘Before’ HTML if you’d like to follow along with the article.

The first I’m going to do is take the section that starts with ‘Lorem ipsum’


<section>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent posuere, urna ut pulvinar sagittis, leo leo aliquam dui, eu iaculis nisl risus at lectus. Nunc tincidunt, odio vulputate dignissim sagittis, lectus sapien fermentum neque, ut accumsan est nibh id sapien. Etiam in nulla eget mi condimentum hendrerit vel a turpis. Cras eget nibh euismod, auctor purus eget, iaculis urna. Vestibulum odio nulla, dictum quis turpis ut, laoreet viverra erat. Cras ut leo eget magna imperdiet vulputate a vitae justo. In dui ante, tincidunt nec porta eu, ullamcorper a odio. Phasellus in purus elit. Mauris ac faucibus magna. Quisque auctor nec dolor eget egestas. Quisque eget ante ut velit interdum eleifend. Vivamus sodales dapibus felis scelerisque auctor.
</p>
</section>



and add a new ‘class’ to it:


<aside class=”sidecolumn”>

<section>………..</section></aside>


<aside> is an HTML5 keyword that “consists of content that is tangentially related to the content around”, but it also allows me to link CSS to it.

Let’s create the CSS class for it that will go between the <style>…</style> tags:

.sidecolumn
{
float:right;
width: 200px;
  margin-top: -50px;
}

The sidebar will float to the right, with width of 200 pixels and decreased top margin by 50 pixels so that it fits our page nicely.
This will actually create a sidebar. We can improve by marking-off the main section and creating a small gutter between the main section and the sidebar itself – so that it doesn’t look like it’s running into one another.

In order to do that, I’m going to add a <div> for the entire main section – it will go right after the closing of </aside> and right before the beginning of the <footer> section.

<div class=”mainSection”>


It’s looking much better, but I’d like that image to be also positioned to the right so I’m going to add a class to the image itself.

img class=”image”


<a href=”http://photobucket.com/images/programmer” target=”_blank”><img class=”image” src=”http://i111.photobucket.com/albums/n135/orion43B/funny/programmer.jpg” border=”0″ alt=”programmer photo: programmer programmer.jpg”/></a>

Let’s add the necessary CSS for it:

.image{  width: 150px;   height: 150px;  margin: 10px;  float:right; }

This is pretty much it. You can download both and before html files here:

WPF – Part: 2

Published December 4, 2013 in WPF - 0Comments

WPF overview tutorial Part: 2 – Part 1 is here.

Let’s take a look at WPF from 10,000 foot view:

Direct X – used to render the actual pixels onto the screen.

Composition Engine – (Media Integration Layer) – It’s a native component written in unmanaged code that resides in milcore.dll and is responsible for providing support 2D and 3D imaging. It interfaces directly with Direct X. It’s written in unmanaged code for a simple reason: Direct X uses COM Interfaces to communicate with the outside world and these calls do not come very cheap in the managed world of interop calls.

Presentation Core – exposes rendering services of the Composition Engine – essentially managed wrapper for the Composition Engine.

Presentation Framework – provides concepts such as: Control, Layout, command handling, data binding, etc.

XAML or Extensible application markup language.

I’ve said it again, and I’ll say it again: WPF doesn’t need XML and XML doesn’t need WPF. It’s simply a language for building .NET objects and XAML user interfaces are built as trees of objects.

Let’s take a look at a simple button:

[[code style="color: black; word-wrap: normal;"]]czo1NTk6XCIxOiAgJmx0O1BhZ2UgIDxiciAvPjI6ICAgeG1sbnM9XCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dpbmZ4LzIwe1smKiZdfTA2L3hhbWwvcHJlc2VudGF0aW9uXCIgIDxiciAvPjM6ICAgeG1sbnM6eD1cImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd2luZntbJiomXX14LzIwMDYveGFtbFwiJmd0OyAgPGJyIC8+NDogICAmbHQ7R3JpZCBIb3Jpem9udGFsQWxpZ25tZW50PVwiQ2VudGVyXCIgVmVydGljYWxBe1smKiZdfWxpZ25tZW50PVwiQ2VudGVyXCImZ3Q7ICAgPGJyIC8+NTogICAgICZsdDtCdXR0b24geDpOYW1lPVwiWEFNTEJ1dHRvblRlc3RcIiAgIDxie1smKiZdfXIgLz42OiAgICAgICAgICAgICAgICAgICAgIEZvbnRGYW1pbHk9XCJWZXJhbmRhXCIgIDxiciAvPjc6ICAgICAgICAgICAgICAgICAgIHtbJiomXX0gIEZvbnRTaXplPVwiNDJcIiAgPGJyIC8+ODogICAgICAgICAgICAgICAgICAgICBGb3JlZ3JvdW5kPVwiRGFya1JlZFwiJmd0OyAgPGJyIHtbJiomXX0vPjk6ICAgICAgIF9TdWJtaXQhICA8YnIgLz4xMDogICAmbHQ7L0J1dHRvbiZndDsgICA8YnIgLz4xMTogICAmbHQ7L0dyaWQmZ3Q7e1smKiZdfSAgPGJyIC8+MTI6ICAmbHQ7L1BhZ2UmZ3Q7ICA8YnIgLz5cIjt7WyYqJl19[[/code]]
Note: On Line 4 HorizontalAlignment=”Center” VerticalAlignment=”Center” properties describe how a child elements should be position within its parent. i.e. this is what actually makes a button, otherwise it would fill out all available space.
Also, note that I have prefixed the ‘_Submit’ – this is how you define Mnemonic in WPF. (you need to hold an ALT key in order for it to show up)

XAML is a language for building .NET objects and here is how we would accomplish the same thing in C# using object initializer:

[[code style="color: black; word-wrap: normal;"]]czoyNDM6XCIgIHZhciB4bWxCdXR0b25UZXN0ID0gbmV3IEJ1dHRvbiAgPGJyIC8+ICAgICAgIHsgIDxiciAvPiAgICAgICAgIEZvbnR7WyYqJl19RmFtaWx5ID0gbmV3IEZvbnRGYW1pbHkoXCJWZXJhbmFkYVwiKSwgIDxiciAvPiAgICAgICAgIEZvbnRTaXplID0gNDIsICA8YnIgLz4ge1smKiZdfSAgICAgICAgRm9yZWdyb3VuZCA9IEJydXNoZXMuRGFya1JlZCwgIDxiciAvPiAgICAgICAgIENvbnRlbnQgPSBcIl9TdWJtaXRcIiAgPHtbJiomXX1iciAvPiAgICAgICB9OyAgPGJyIC8+XCI7e1smKiZdfQ==[[/code]]

There are two concepts how the input is handled in WPF, these are routed events and routed commands.
Events routing allows events to be handled by ancestor of the element who originated the event – there are two patterns for doing that:
1. Bubbling  (most common)
    The event propagates up the visual tree from the source element.

2. Tunneling
    These, as you may suspect, go the other way, down from the source element.

Events come in pairs: There’s usually a preview event that tunnels, followed by an event that bubbles – the reason being is so that the main element gets the first opportunity to respond or react to that event.

Controls 
WPF controls have no intrinsic look, they are ‘lookless’ – this is because templates can replace default look with your own design, unlike in WIN32 where we do have a default look.

Let’s take a look at how to define a template for a button, i.e. custom look, using property element syntax:

Line 2: The part before the dot is interpreted as the ‘class name’ and the part after the dot as the ‘property name’.
Line 3: TargetType=”Button” – defines what control is the template for.

[[code style="color: black; word-wrap: normal;"]]czoyNzA6XCIxOiAgJmx0O0J1dHRvbiBXaWR0aD1cIjY0XCIgSGVpZ2h0PVwiMzBcIiZndDsgIDxiciAvPjI6ICAgICAgICAmbHQ7QnV0dG9ue1smKiZdfS5UZW1wbGF0ZSZndDsgIDxiciAvPjM6ICAgICAgICAgICZsdDtDb250cm9sVGVtcGxhdGUgVGFyZ2V0VHlwZT1cIkJ1dHRvblwiJmd0O3tbJiomXX0gIDxiciAvPjQ6ICAgICAgICAgICZsdDsvQ29udHJvbFRlbXBsYXRlJmd0OyAgPGJyIC8+NTogICAgICAgICZsdDsvQnV0dG9uLlRle1smKiZdfW1wbGF0ZSZndDsgIDxiciAvPjY6ICAgICAgJmx0Oy9CdXR0b24mZ3Q7ICA8YnIgLz5cIjt7WyYqJl19[[/code]]
The code above represents the natural look for the button which essentially is ‘no look’.
Let’s fill in the appearance: (fully working XAML)
[[code style="color: black; word-wrap: normal;"]]czoxMzEzOlwiMTogICZsdDtXaW5kb3cgeDpDbGFzcz1cIldwZkFwcGxpY2F0aW9uMi5NYWluV2luZG93XCIgIDxiciAvPjI6ICAgICAgeHtbJiomXX1tbG5zPVwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93aW5meC8yMDA2L3hhbWwvcHJlc2VudGF0aW9uXCIgIDxiciAvPjM6ICB7WyYqJl19ICAgIHhtbG5zOng9XCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dpbmZ4LzIwMDYveGFtbFwiICA8YnIgLz40OiAgICAgIFRpe1smKiZdfXRsZT1cIk1haW5XaW5kb3dcIiBIZWlnaHQ9XCIzNTBcIiBXaWR0aD1cIjUyNVwiJmd0OyAgPGJyIC8+NTogICAgJmx0O0dyaWQgSG9yaXpvbnR7WyYqJl19YWxBbGlnbm1lbnQ9XCJDZW50ZXJcIiBWZXJ0aWNhbEFsaWdubWVudD1cIkNlbnRlclwiJmd0OyAgPGJyIC8+NjogICAgICAmbHQ7QnV0dG97WyYqJl19biBXaWR0aD1cIjg1XCIgSGVpZ2h0PVwiNDVcIiBCYWNrZ3JvdW5kPVwiU3RlZWxCbHVlXCIgVmVydGljYWxBbGlnbm1lbnQ9XCJDZW50ZXJcIiBIe1smKiZdfW9yaXpvbnRhbEFsaWdubWVudD1cIkNlbnRlclwiJmd0OyAgPGJyIC8+NzogICAgICAgICZsdDtCdXR0b24uVGVtcGxhdGUmZ3Q7ICA8YntbJiomXX1yIC8+ODogICAgICAgICAgJmx0O0NvbnRyb2xUZW1wbGF0ZSBUYXJnZXRUeXBlPVwiQnV0dG9uXCImZ3Q7ICA8YnIgLz45OiAgICAgICB7WyYqJl19ICAgICAmbHQ7R3JpZCZndDsgIDxiciAvPjEwOiAgICAgICAgICAgICZsdDtSZWN0YW5nbGUgRmlsbD1cIntUZW1wbGF0ZUJpbmRpbmd7WyYqJl19IEJhY2tncm91bmR9XCIgUmFkaXVzWD1cIjhcIiBSYWRpdXNZPVwiOFwiJmd0OyZsdDsvUmVjdGFuZ2xlJmd0OyAgPGJyIC8+MTE6ICAgICAge1smKiZdfSAgICAgICAgJmx0O0NvbnRlbnRQcmVzZW50ZXIgUmVjb2duaXplc0FjY2Vzc0tleT1cIlRydWVcIiAgIDxiciAvPjEyOiAgICAgICAgIHtbJiomXX0gICAgICAgICAgICAgIENvbnRlbnQ9XCJ7VGVtcGxhdGVCaW5kaW5nIENvbnRlbnR9XCIgICA8YnIgLz4xMzogICAgICAgICAgICAgICB7WyYqJl19ICAgICAgICBWZXJ0aWNhbEFsaWdubWVudD1cIntUZW1wbGF0ZUJpbmRpbmcgVmVydGljYWxBbGlnbm1lbnR9XCIgICA8YnIgLz4xNDoge1smKiZdfSAgICAgICAgICAgICAgICAgICAgICBIb3Jpem9udGFsQWxpZ25tZW50PVwie1RlbXBsYXRlQmluZGluZyBIb3Jpem9udGFsQWxpZ25te1smKiZdfWVudH1cIiAvJmd0OyAgPGJyIC8+MTU6ICAgICAgICAgICAgJmx0Oy9HcmlkJmd0OyAgPGJyIC8+MTY6ICAgICAgICAgICZsdDsvQ29ue1smKiZdfXRyb2xUZW1wbGF0ZSZndDsgIDxiciAvPjE3OiAgICAgICAgJmx0Oy9CdXR0b24uVGVtcGxhdGUmZ3Q7ICA8YnIgLz4xODogICAgICB7WyYqJl19ICBfU3VibWl0ICA8YnIgLz4xOTogICAgICAmbHQ7L0J1dHRvbiZndDsgIDxiciAvPjIwOiAgICAmbHQ7L0dyaWQmZ3Q7ICA8YnIgL3tbJiomXX0+MjE6ICAmbHQ7L1dpbmRvdyZndDsgIDxiciAvPlwiO3tbJiomXX0=[[/code]]
Line: 10 “TemplateBinding Background” – allows us to bind the property ‘Background’ on line: 6 to the Content Presenter which essentially is a placeholder for any XAML content to be used during runtime.

The curly brackets tell XAML that we are using something called: the markup extension. (more about it in future posts). For now, let’s just say that markup extensions decide during runtime how the properties are set. What line 10 says is that we are creating an object of type: TemplateBinding and we are passing a string (yes, string) called ‘Background’ to a constructor.

Primitive elements:

The elements that define or rather have template are the controls in WPF, and as you may suspect not everything is a control in WPF. In other words you don’t have to worry as to how anything ever appears on your screen when programming in WPF. It’s only the elements that derive from the Control class, such as button that look for their appearance in template.
For example Rectangle, TextBlock and Image derive from the framework element – these are primitives and do not have a template of their own.

Layout primitives:

Grid Panel – flexible grid-based area with columns and rows.
Canvas Panel – fixed area to position elements by the use of coordinates.
Stack Panel – simple vertical or horizontal arrangement in a single line.
Dock Panel – allows to arrange child elements vertically or horizontally relative to each other; similar to windows forms docking.
Wrap Panel – allows to arrange child elements in a flow-like formatting.



WPF – Part: 1

Published October 26, 2013 in WPF - 0Comments

This is Part: 1 of the overview WPF Tutorial. 
I will tackle specific WPF concepts separately in future posts.

    WPF is a powerful framework for building windows applications, however there is a steep curve in learning. The whole WPF framework only makes sense when all the individual pieces of the framework fall in together. In other words, one must understand the entire WPF framework in order to understand any of it.

1. How Windows Forms differ from WPF?


    Windows forms are simply wrappers around USER 32 and GDI 32 APIs – which provide the traditional Windows look and feel and drawing support for rendering shapes, text, images, etc. respectively.

WPF doesn’t use GDI 32 rendering API at all, it’s part of .NET and a mixture of managed and unmanaged code and it’s only available from .NET – i.e. no public, unmanaged API calls allowed.


2. What’s in it for me?

    Today’s hardware and graphics cards in particular offer a lot of computing power, it’s not unheard of having gigabytes of memory purely on the graphics cards. If fact today’s graphics cards have more processing power than windows machines did 25 years ago, back when user.exe (16bit dll – and yes it had .exe extension) and later 32-bit backwards compatible USER 32 were designed. Also, remember that GDI and USER subsystems were introduced with Windows 1.0 in 1985. 
The USER 32 and GDI 32 subsystems weren’t designed for the new powerful graphics cards, so most of the power sits unused.

How do we take advantage of new graphics cards that offer 3D accelaration? 

One way is to write open GL or Direct X code, but that of course does not easily intergrate with user interface application, drop down boxes, data binding, etc. Using (or so I’ve heard) Direct X API to create windows business applications isn’t for the faint of heart. That’s where WPF comes in. WPF uses Direct X API,  so all WPF drawing is performed through Direct X, which allows it to take advantage of the latest in modern video cards.
   

    There’s also an issue with resolution, classic style of constructing user interfaces has issues on modern PCs because windows applications are bound by certain assumptions about screen resolution and that makes traditional applications unscalable. Windows applications render small on very high resolution monitors because they cram pixels more densely. 
WPF does not have this problem, because it uses system DPI setting and renders all elements on the screen by itself, so a button that’s 1 inch long on low resolution monitor will remain 1 inch long on a high resolution monitor. In other words, all elements on the screen are measured using device-independent units.

   Of course it is possible to write an application (without using WPF) that scales up or down itself and adapts to different screen resolutions (pixel size of the display), however most displays or monitors in the past had roughly the same pixel size, so of course nobody bothered to do that. Luckily for us WPF applications are DPI aware and hence scalable by default, nothing special needs to be done on your part. 

3. Let’s get our hands dirty and do some XAML WPF test (without actually writing any real code)

Note: It may surprise you but WPF doesn’t need XAML and XAML doesn’t need WPF.
Althought most of WPF is written using XAML.


Back in the day Microsoft used to bundle XamlPad with Visual Studio 2008, but it has been discontinued. You can still get it if you have MSDN Subscription but since not everyone reading this has one I found an alternative solution: Kaxaml.
It essentially lets you enter XAML and see what it will look like.

Enter the code below, if fact all you need to enter is the text in bold:

[[code style="color: black; word-wrap: normal;"]]czoyOTY6XCIgJmx0O1BhZ2UgIDxiciAvPiAgeG1sbnM9XCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dpbmZ4LzIwMDYveGFte1smKiZdfWwvcHJlc2VudGF0aW9uXCIgIDxiciAvPiAgeG1sbnM6eD1cImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd2luZngvMjAwNi94YXtbJiomXX1tbFwiJmd0OyAgPGJyIC8+ICAmbHQ7R3JpZCZndDsgIDxiciAvPiAgPGI+ICZsdDtCdXR0b24gQ29udGVudD1cIk9LXCIgV2lkdGg9XCI4NXtbJiomXX1cIiBIZWlnaHQ9XCIyNVwiLyZndDsgPC9iPiA8YnIgLz4gICZsdDsvR3JpZCZndDsgIDxiciAvPiAmbHQ7L1BhZ2UmZ3Q7ICA8YnIgLz5cIntbJiomXX07e1smKiZdfQ==[[/code]]



Now, if you zoom in, you can see that the button does not get pixelated.



Composibility – it’s the power of WPF. We can compose all the different styles of content that WPF supports inside the button, so let’s take this basic button control and…

a. Add layout:


[[code style="color: black; word-wrap: normal;"]]czo4MTpcIiAmbHQ7UGFnZSB4bWxucz1cImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd2luZngvMjAwNi94YW1sL3ByZXNlbnRhe1smKiZdfXRpb25cIiZuYnNwO1wiO3tbJiomXX0=[[/code]]
[[code style="color: black; word-wrap: normal;"]]czozNDE6XCIgICAgICAgeG1sbnM6eD1cImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd2luZngvMjAwNi94YW1sXCImZ3Q7ICAgPHtbJiomXX1iciAvPiAgJmx0O0dyaWQmZ3Q7ICA8YnIgLz4gICAgJmx0O0J1dHRvbiBXaWR0aD1cIjg1XCIgSGVpZ2h0PVwiMjVcIiAmZ3Q7ICAgIDxicntbJiomXX0gLz4gICAgIDxiPiAmbHQ7U3RhY2tQYW5lbCZndDsgICAgPGJyIC8+ICAgICAgICZsdDtUZXh0QmxvY2sgVGV4dD1cIk9LXCIvJmd0OyB7WyYqJl19ICAgPGJyIC8+ICAgICAgJmx0Oy9TdGFja1BhbmVsJmd0OyA8L2I+ICA8YnIgLz4gICAgJmx0Oy9CdXR0b24mZ3Q7ICAgPGJyIC8+IHtbJiomXX0gJmx0Oy9HcmlkJmd0OyAgPGJyIC8+ICZsdDsvUGFnZSZndDsgIDxiciAvPlwiO3tbJiomXX0=[[/code]]
WPF supports something called: a content model

Button in WPF lets you add only one child, just so it doesn’t have to be in charge of how all the other children are laid out, here I’ve used <StackPanel> so I can add more children later.

2. Format text:
[[code style="color: black; word-wrap: normal;"]]czo3NTpcIiAmbHQ7UGFnZSB4bWxucz1cImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd2luZngvMjAwNi94YW1sL3ByZXNlbnRhe1smKiZdfXRpb25cIlwiO3tbJiomXX0=[[/code]]
[[code style="color: black; word-wrap: normal;"]]czo0Mzc6XCIgICAgICAgeG1sbnM6eD1cImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd2luZngvMjAwNi94YW1sXCImZ3Q7ICA8YntbJiomXX1yIC8+ICAmbHQ7R3JpZCZndDsgIDxiciAvPiAgICAmbHQ7QnV0dG9uIEhvcml6b250YWxBbGlnbm1lbnQ9XCJDZW50ZXJcIiBWZXJ0aWN7WyYqJl19YWxBbGlnbm1lbnQ9XCJDZW50ZXJcIiZndDsgICAgPGJyIC8+ICAgICAgJmx0O1N0YWNrUGFuZWwmZ3Q7ICAgPGJyIC8+ICAgICAgIDxie1smKiZdfT4mbHQ7VGV4dEJsb2NrIEZvbnRTaXplPVwiMzBcIiZndDsgV1BGICZsdDtJdGFsaWMmZ3Q7UnVsZXombHQ7L0l0YWxpYyZndDsgJmx0O3tbJiomXX0vVGV4dEJsb2NrJmd0OzwvYj4gICAgIDxiciAvPiAgICAgICZsdDsvU3RhY2tQYW5lbCZndDsgICAgIDxiciAvPiAgICAgJmx0Oy9Ce1smKiZdfXV0dG9uJmd0OyAgICA8YnIgLz4gICZsdDsvR3JpZCZndDsgIDxiciAvPiAmbHQ7L1BhZ2UmZ3Q7ICA8YnIgLz5cIjt7WyYqJl19[[/code]]

Notice that I’ve added HorizontalAlignment and VerticalAlignment so that the button will size itself according to the content.

3. and some graphics:

[[code style="color: black; word-wrap: normal;"]]czo2NjM6XCIgJmx0O1BhZ2UgeG1sbnM9XCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dpbmZ4LzIwMDYveGFtbC9wcmVzZW50e1smKiZdfWF0aW9uXCIgIDxiciAvPiAgICAgICB4bWxuczp4PVwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93aW5meC8yMDA2L3hhbWxcIiZ7WyYqJl19Z3Q7ICA8YnIgLz4gICZsdDtHcmlkJmd0OyAgPGJyIC8+ICAgICZsdDtCdXR0b24gSG9yaXpvbnRhbEFsaWdubWVudD1cIkNlbnRlclwie1smKiZdfSBWZXJ0aWNhbEFsaWdubWVudD1cIkNlbnRlclwiJmd0OyAgIDxiciAvPiAgICAgJmx0O1N0YWNrUGFuZWwmZ3Q7ICAgICA8YnIgLz4gIHtbJiomXX0gICAgICZsdDtUZXh0QmxvY2sgRm9udFNpemU9XCIzMFwiJmd0OyBXUEYgJmx0O0l0YWxpYyZndDtSdWxleiZsdDsvSXRhbGljJmd0OyZ7WyYqJl19bHQ7L1RleHRCbG9jayZndDsgICAgPGJyIC8+ICAgICAgICA8Yj4mbHQ7RWxsaXBzZSBGaWxsPVwiUmVkXCIgV2lkdGg9XCIzMy4xNDNcIiB7WyYqJl19SGVpZ2h0PVwiMzMuMTQzXCIvJmd0OyAgIDxiciAvPiAgICAgICAgJmx0O0VsbGlwc2UgRmlsbD1cIkJsdWVcIiBXaWR0aD1cIjMzLjE0M1wiIHtbJiomXX1IZWlnaHQ9XCIzMy4xNDNcIi8mZ3Q7IDwvYj4gIDxiciAvPiAgICAgJmx0Oy9TdGFja1BhbmVsJmd0OyAgPGJyIC8+ICAgICZsdDsvQnV7WyYqJl19dHRvbiZndDsgICA8YnIgLz4gICZsdDsvR3JpZCZndDsgIDxiciAvPiAmbHQ7L1BhZ2UmZ3Q7ICA8YnIgLz5cIjt7WyYqJl19[[/code]]
Not very exciting graphics but the point to illustrate was composability of WPF.

As I’ve mentioned at the beginning, WPF does not necessarily need XAML, so how would
something like this?
<Button x:name=”submitButton” FontSize=”30″ FontFamily=”Arial’>_Submit</Button>

be written without XAML? Here’s how:

Button button = new Button();button.FontSize=30;button.FontFamily=new FontFamily(“Arial”);button.Content = “_Submit”;

That’s it for the first.





ASP.NET MVC

Published October 6, 2013 in ASP.NET MVC - 0Comments

As a recent convert from fat client applications (MFC (C++), Windows Forms, WPF) to ASP.NET and ASP.NET MVC, I’ve created a simple project and implemented it twice using both of these two technologies. First in ASP.NET and second in ASP.NET MVC.

Here you can download the sample solution file that includes both the ASP.NET and ASP.NET MVC projects. It was written using Visual Studio 2012 and .NET Framework 4.5
Latest code for this solution from codeplex:

Let’s start with ASP.NET and create a Web Forms application to post and record blog posts.

1. First we’ll start with creating an ASP.NET WebForms application
   a. Create an empty application.
 
   Go to File -> New -> Project and select ASP.NET Empty Web Application:

 2. Add new Web Form:
    a. Right click on the project
       Add New Item -> Web Form
       Type “Default.aspx” and click the OK button:

    b. Right-click on the Default.aspx entry in the Solution Explorer and select Set as Start Page from the pop-up menu.

       
3. Add Data Model:
     a. Right click on the project
        Add New Item -> Class
        Type: Comment.cs

Copy/Paste the following lines into the Comment model object:

[[code style="color: black; word-wrap: normal;"]]czozNTM6XCIgdXNpbmcgU3lzdGVtLkNvbXBvbmVudE1vZGVsLkRhdGFBbm5vdGF0aW9uczsgIDxiciAvPiBuYW1lc3BhY2UgQ29tbWV7WyYqJl19bnRQb3N0ICA8YnIgLz4geyAgPGJyIC8+ICAgcHVibGljIGNsYXNzIENvbW1lbnQgIHsgIDxiciAvPiAgICAgW1JlcXVpcmVkXSAgPHtbJiomXX1iciAvPiAgICAgcHVibGljIHN0cmluZyBQb3N0ZXJOYW1lIHsgZ2V0OyBzZXQ7IH0gIDxiciAvPiAgICAgW1JlcXVpcmVkXSAgPGJye1smKiZdfSAvPiAgICAgcHVibGljIHN0cmluZyBQb3N0ZXJFbWFpbCB7IGdldDsgc2V0OyB9ICA8YnIgLz4gICAgIFtSZXF1aXJlZChFcnJvck17WyYqJl19ZXNzYWdlID0gXCJEaWQgeW91IGxpa2Ugb3IgZGlkblwndCBsaWtlIG15IHBvc3Q/XCIpXSAmbmJzcDtcIjt7WyYqJl19[[/code]]
[[code style="color: black; word-wrap: normal;"]]czo3MTpcIiAgICAgcHVibGljIGJvb2w/IExpa2VkUG9zdCB7IGdldDsgc2V0OyB9ICA8YnIgLz4gICB9ICA8YnIgLz4gfSAgPGJyIC97WyYqJl19PlwiO3tbJiomXX0=[[/code]]
I’m jumping ahead and adding Model Validation here. The [Required] Attribute simply specifies that a data field value is required.
       

4. Add a Collection object – we need to have some sort of storage, since we don’t have any database backing:

     a. Right click on the Project:

        Right click and select Add New Item -> Class

     
 Copy/Paste the following lines into the CommentsCollection object:

[[code style="color: black; word-wrap: normal;"]]czo3MDU6XCIgdXNpbmcgU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWM7ICA8YnIgLz4gbmFtZXNwYWNlIENvbW1lbnRQb3N0ICA8YnJ7WyYqJl19IC8+IHsgIDxiciAvPiAgIHB1YmxpYyBjbGFzcyBDb21tZW50c0NvbGxlY3Rpb24gIDxiciAvPiAgIHsgIDxiciAvPiAgICAgcHJpdntbJiomXX1hdGUgc3RhdGljIHJlYWRvbmx5IENvbW1lbnRzQ29sbGVjdGlvbiBDb2xsZWN0aW9uID0gbmV3IENvbW1lbnRzQ29sbGVjdGlvbigpe1smKiZdfTsgICAgcHJpdmF0ZSByZWFkb25seSBMaXN0Jmx0O0NvbW1lbnQmZ3Q7IF9jb21tZW50cyA9IG5ldyBMaXN0Jmx0O0NvbW1lbnQmZ3R7WyYqJl19OygpOyAgPGJyIC8+ICAgICBwdWJsaWMgdm9pZCBBZGRSZXNwb25zZShDb21tZW50IHJlc3BvbnNlKSAgPGJyIC8+ICAgICB7ICA8YntbJiomXX1yIC8+ICAgICAgIF9jb21tZW50cy5BZGQocmVzcG9uc2UpOyAgPGJyIC8+ICAgICB9ICA8YnIgLz4gICAgIHB1YmxpYyBzdGF0aWMge1smKiZdfUNvbW1lbnRzQ29sbGVjdGlvbiBHZXRDb21tZW50c0NvbGxlY3Rpb24oKSAgPGJyIC8+ICAgICB7ICA8YnIgLz4gICAgICAgcmV0dXJ7WyYqJl19biBDb2xsZWN0aW9uOyAgPGJyIC8+ICAgICB9ICA8YnIgLz4gICAgIHB1YmxpYyBJRW51bWVyYWJsZSZsdDtDb21tZW50Jmd0OyBHZXtbJiomXX10QWxsQ29tbWVudHMoKSAgPGJyIC8+ICAgICB7ICA8YnIgLz4gICAgICAgcmV0dXJuIF9jb21tZW50czsgIDxiciAvPiAgICAgfSAge1smKiZdfTxiciAvPiAgIH0gIDxiciAvPiB9ICA8YnIgLz5cIjt7WyYqJl19[[/code]]
5. Now we are going to create a simple form in Default.aspx page
 
Copy/Paste the following lines into your Default.aspx page:
[[code style="color: black; word-wrap: normal;"]]czoxNTU1OlwiICZsdDslQCBQYWdlIExhbmd1YWdlPVwiQyNcIiBBdXRvRXZlbnRXaXJldXA9XCJ0cnVlXCIgQ29kZUJlaGluZD1cIkRlZmF1bHtbJiomXX10LmFzcHguY3NcIiBJbmhlcml0cz1cIkNvbW1lbnRQb3N0LkRlZmF1bHRcIiAlJmd0OyAgPGJyIC8+ICZsdDshRE9DVFlQRSBodG1sJmd0e1smKiZdfTsgIDxiciAvPiAmbHQ7aHRtbCB4bWxucz1cImh0dHA6Ly93d3cudzMub3JnLzE5OTkveGh0bWxcIiZndDsmbHQ7aGVhZCBydW5hdD1cInN7WyYqJl19ZXJ2ZXJcIiZndDsgICZsdDt0aXRsZSZndDtNeSBCbG9nJmx0Oy90aXRsZSZndDsgIDxiciAvPiAgICZsdDtsaW5rIHJlbD1cInN0eWxle1smKiZdfXNoZWV0XCIgaHJlZj1cIlN0eWxlU2hlZXQxLmNzc1wiIC8mZ3Q7Jmx0Oy9oZWFkJmd0OyZsdDtib2R5Jmd0OyAgJmx0O2Zvcm0gaWQ9XCJme1smKiZdfW9ybTFcIiBydW5hdD1cInNlcnZlclwiJmd0OyAgICAmbHQ7ZGl2Jmd0OyAgPGJyIC8+ICAgICAgICZsdDtoMSZndDtXZWxjb21lIHRvIG17WyYqJl19eSBibG9nISAgPGJyIC8+ICAgICAgICZsdDsvaDEmZ3Q7ICA8YnIgLz4gICAgICAgJmx0O3AmZ3Q7ICA8YnIgLz4gICAgICAgICBQbHtbJiomXX1lYXNlIGxlYXZlIGEgdmVyeSBwb3NpdGl2ZSBjb21tZW50LiAgPGJyIC8+ICAgICAgICZsdDsvcCZndDsgIDxiciAvPiAgICAgJmx0e1smKiZdfTsvZGl2Jmd0OyAgPGJyIC8+ICAgICAmbHQ7ZGl2Jmd0OyAgPGJyIC8+ICAgICAgICZsdDthc3A6VmFsaWRhdGlvblN1bW1hcnkgSUR7WyYqJl19PVwidmFsaWRhdGlvblN1bW1hcnlcIiBydW5hdD1cInNlcnZlclwiIFNob3dNb2RlbFN0YXRlRXJyb3JzPVwiVHJ1ZVwiLyZndDsgICAgICAmbHtbJiomXX10O2xhYmVsJmd0O05hbWU6ICZsdDsvbGFiZWwmZ3Q7ICA8YnIgLz4gICAgICAgJmx0O2lucHV0IHR5cGU9XCJ0ZXh0XCIgaWQ9XCJQb3N0e1smKiZdfWVyTmFtZVwiIHJ1bmF0PVwic2VydmVyXCIgLyZndDsgICAgJmx0Oy9kaXYmZ3Q7ICA8YnIgLz4gICAgICZsdDtkaXYmZ3Q7ICA8YnIgLz57WyYqJl19ICAgICAgICZsdDtsYWJlbCZndDtFbWFpbDogJmx0Oy9sYWJlbCZndDsgIDxiciAvPiAgICAgICAmbHQ7aW5wdXQgdHlwZT1cInRleHR7WyYqJl19XCIgaWQ9XCJQb3N0ZXJFbWFpbFwiIHJ1bmF0PVwic2VydmVyXCIgLyZndDsmbHQ7L2RpdiZndDsgICAgJmx0O2RpdiZndDsgIDxiciAvPiAge1smKiZdfSAgICAgJmx0O2xhYmVsJmd0O0xpa2VkIHRoZSBwb3N0PzogJmx0Oy9sYWJlbCZndDsgIDxiciAvPiAgICAgICAmbHQ7c2VsZWN0IGl7WyYqJl19ZD1cIkxpa2VkUG9zdFwiIHJ1bmF0PVwic2VydmVyXCImZ3Q7Jmx0O29wdGlvbiB2YWx1ZT1cIlwiJmd0O0xpa2VkIGl0PyZsdDsvb3B0aW9uJntbJiomXX1ndDsgIDxiciAvPiAgICAgICAgICZsdDtvcHRpb24gdmFsdWU9XCJ0cnVlXCImZ3Q7TWUgTGlrZXkhJmx0Oy9vcHRpb24mZ3Q7ICA8YnJ7WyYqJl19IC8+ICAgICAgICAgJmx0O29wdGlvbiB2YWx1ZT1cImZhbHNlXCImZ3Q7TWUgTk8gTGlrZXkhJmx0Oy9vcHRpb24mZ3Q7ICA8YnIgLz4ge1smKiZdfSAgICAgICZsdDsvc2VsZWN0Jmd0OyAgPGJyIC8+ICAgICAmbHQ7L2RpdiZndDsgIDxiciAvPiAgICAgJmx0O2RpdiZndDsmbHQ7YnV7WyYqJl19dHRvbiB0eXBlPVwic3VibWl0XCImZ3Q7T0smbHQ7L2J1dHRvbiZndDsmbHQ7L2RpdiZndDsgIDxiciAvPiAgICZsdDsvZm9ybSZndDsge1smKiZdfSA8YnIgLz4gJmx0Oy9ib2R5Jmd0OyZsdDsvaHRtbCZndDsgICA8YnIgLz5cIjt7WyYqJl19[[/code]]

Notice that I’ve already included support to display validation errors:
  <asp:ValidationSummary ID=”validationSummary” runat=”server” ShowModelStateErrors=”True”/>  

6. Handle the Form Post when the ‘OK’ button is pressed:
ASP.NET 4.5 has a built in Web Forms binding. It is a Ad-Hoc Model Biding where you can bind to controls without using data bound controls such as formview.
We need to grab values from the browser request and populate properties in our data model through process called: model binding, for this purpose we’ll use Page.TryUpdateModel method.

a. Double click on Default.aspx.cs file

Copy/Paste the following lines into your Default.aspx.cs page:

[[code style="color: black; word-wrap: normal;"]]czo4MTU6XCIgdXNpbmcgU3lzdGVtOyAgPGJyIC8+IHVzaW5nIFN5c3RlbS5XZWIuTW9kZWxCaW5kaW5nOyAgPGJyIC8+IG5hbWVzcGF7WyYqJl19Y2UgQ29tbWVudFBvc3QgIDxiciAvPiB7ICA8YnIgLz4gICBwdWJsaWMgcGFydGlhbCBjbGFzcyBEZWZhdWx0IDogU3lzdGVtLldlYntbJiomXX0uVUkuUGFnZSAgeyAgPGJyIC8+ICAgICBwcm90ZWN0ZWQgdm9pZCBQYWdlX0xvYWQob2JqZWN0IHNlbmRlciwgRXZlbnRBcmdzIGUpe1smKiZdfSAgPGJyIC8+ICAgICB7ICA8YnIgLz4gICAgICAgaWYgKCFJc1Bvc3RCYWNrKSByZXR1cm47ICA8YnIgLz4gICAgICAgQ29tbWVudCB7WyYqJl19Y29tbWVudCA9IG5ldyBDb21tZW50KCk7ICA8YnIgLz4gICAgICAgaWYgKCFUcnlVcGRhdGVNb2RlbChjb21tZW50LCBuZXcgRm9ybXtbJiomXX1WYWx1ZVByb3ZpZGVyKE1vZGVsQmluZGluZ0V4ZWN1dGlvbkNvbnRleHQpKSkgcmV0dXJuOyAgPGJyIC8+ICAgICAgIENvbW1lbnRze1smKiZdfUNvbGxlY3Rpb24uR2V0Q29tbWVudHNDb2xsZWN0aW9uKCkuQWRkUmVzcG9uc2UoY29tbWVudCk7ICA8YnIgLz4gICAgICAgaWYgKGN7WyYqJl19b21tZW50Lkxpa2VkUG9zdC5IYXNWYWx1ZSAmYW1wOyZhbXA7IGNvbW1lbnQuTGlrZWRQb3N0LlZhbHVlKSAgPGJyIC8+ICAgICAgIHtbJiomXX17ICA8YnIgLz4gICAgICAgICBSZXNwb25zZS5SZWRpcmVjdChcInRoYW5rc2Zvcmxpa2luZ2l0Lmh0bWxcIik7ICA8YnIgLz4gICAgICB7WyYqJl19IH0gIDxiciAvPiAgICAgICBlbHNlICAgICAgeyAgPGJyIC8+ICAgICAgICAgUmVzcG9uc2UuUmVkaXJlY3QoXCJvaHdlbGwuaHRtbFwie1smKiZdfSk7ICA8YnIgLz4gICAgICAgfSAgPGJyIC8+ICAgICB9ICA8YnIgLz4gICB9ICA8YnIgLz4gfSAgPGJyIC8+XCI7e1smKiZdfQ==[[/code]]

Notice that I’ve added runat=”server” to the HTML elements. If I didn’t the biding process would not work.

7. Create two response pages:
   a. thanksforlikingit.html
 
   Right click on the project and select new item -> HTML page
   Type: thanksforlikingit.html and Click ‘Add’ button

   b. ohwell.html
    Perform the same steps as above but type ohwell.html instead.
 
   c. Double click on  thanksforlikingit.html file and type

[[code style="color: black; word-wrap: normal;"]]czo4MTU6XCIgdXNpbmcgU3lzdGVtOyAgPGJyIC8+IHVzaW5nIFN5c3RlbS5XZWIuTW9kZWxCaW5kaW5nOyAgPGJyIC8+IG5hbWVzcGF7WyYqJl19Y2UgQ29tbWVudFBvc3QgIDxiciAvPiB7ICA8YnIgLz4gICBwdWJsaWMgcGFydGlhbCBjbGFzcyBEZWZhdWx0IDogU3lzdGVtLldlYntbJiomXX0uVUkuUGFnZSAgeyAgPGJyIC8+ICAgICBwcm90ZWN0ZWQgdm9pZCBQYWdlX0xvYWQob2JqZWN0IHNlbmRlciwgRXZlbnRBcmdzIGUpe1smKiZdfSAgPGJyIC8+ICAgICB7ICA8YnIgLz4gICAgICAgaWYgKCFJc1Bvc3RCYWNrKSByZXR1cm47ICA8YnIgLz4gICAgICAgQ29tbWVudCB7WyYqJl19Y29tbWVudCA9IG5ldyBDb21tZW50KCk7ICA8YnIgLz4gICAgICAgaWYgKCFUcnlVcGRhdGVNb2RlbChjb21tZW50LCBuZXcgRm9ybXtbJiomXX1WYWx1ZVByb3ZpZGVyKE1vZGVsQmluZGluZ0V4ZWN1dGlvbkNvbnRleHQpKSkgcmV0dXJuOyAgPGJyIC8+ICAgICAgIENvbW1lbnRze1smKiZdfUNvbGxlY3Rpb24uR2V0Q29tbWVudHNDb2xsZWN0aW9uKCkuQWRkUmVzcG9uc2UoY29tbWVudCk7ICA8YnIgLz4gICAgICAgaWYgKGN7WyYqJl19b21tZW50Lkxpa2VkUG9zdC5IYXNWYWx1ZSAmYW1wOyZhbXA7IGNvbW1lbnQuTGlrZWRQb3N0LlZhbHVlKSAgPGJyIC8+ICAgICAgIHtbJiomXX17ICA8YnIgLz4gICAgICAgICBSZXNwb25zZS5SZWRpcmVjdChcInRoYW5rc2Zvcmxpa2luZ2l0Lmh0bWxcIik7ICA8YnIgLz4gICAgICB7WyYqJl19IH0gIDxiciAvPiAgICAgICBlbHNlICAgICAgeyAgPGJyIC8+ICAgICAgICAgUmVzcG9uc2UuUmVkaXJlY3QoXCJvaHdlbGwuaHRtbFwie1smKiZdfSk7ICA8YnIgLz4gICAgICAgfSAgPGJyIC8+ICAgICB9ICA8YnIgLz4gICB9ICA8YnIgLz4gfSAgPGJyIC8+XCI7e1smKiZdfQ==[[/code]]
}
   d. Double click on ohwell.html file and type:
[[code style="color: black; word-wrap: normal;"]]czo0MTg6XCIgICZsdDshRE9DVFlQRSBodG1sJmd0OyAgPGJyIC8+ICAmbHQ7aHRtbCB4bWxucz1cImh0dHA6Ly93d3cudzMub3JnLzE5e1smKiZdfTk5L3hodG1sXCImZ3Q7ICA8YnIgLz4gICZsdDtoZWFkJmd0OyAgPGJyIC8+ICAgICZsdDt0aXRsZSZndDtNeSBCbG9nIC0gc29ycnkge1smKiZdfXlvdSBkaWQgbm90IGxpa2UgaXQhJmx0Oy90aXRsZSZndDsgIDxiciAvPiAgJmx0Oy9oZWFkJmd0OyAgPGJyIC8+ICAmbHQ7Ym9keSZ7WyYqJl19Z3Q7ICA8YnIgLz4gICAgJmx0O2gxJmd0O1RoYW5rcyEmbHQ7L2gxJmd0OyAgPGJyIC8+ICAgICZsdDtwJmd0O1BsZWFzZSB3cml0ZXtbJiomXX0gbWUgd2l0aCB5b3VyIGNvbW1lbnRzIGFuZCBzdWdnZXN0aW9ucyBvbiBob3cgdG8gaW1wcm92ZS4mbHQ7L3AmZ3Q7ICA8YnIgLz4ge1smKiZdfSAmbHQ7L2JvZHkmZ3Q7ICA8YnIgLz4gICZsdDsvaHRtbCZndDsgIDxiciAvPlwiO3tbJiomXX0=[[/code]]
8. Optionally apply some basic CSS:
a. Add style sheets:
 Right Click the project in the solution and select “StyleSheet”



 Copy paste CSS:

[[code style="color: black; word-wrap: normal;"]]czo0MDY6XCIgI2Zvcm0xIGxhYmVsIHsgYm9yZGVyLXJhZGl1czo2cHg7IHdpZHRoOiAxMjBweDsgZGlzcGxheTogaW5saW5lLWJsb2N7WyYqJl19azt9ICA8YnIgLz4gICAjZm9ybTEgaW5wdXQgeyBib3JkZXItcmFkaXVzOjZweDsgbWFyZ2luOiA0cHg7IG1hcmdpbi1sZWZ0OiA2cHtbJiomXX14OyB3aWR0aDogMTUwcHg7fSAgPGJyIC8+ICAgI2Zvcm0xIHNlbGVjdCB7IGJvcmRlci1yYWRpdXM6NnB4OyBtYXJnaW46IDRweDsge1smKiZdfXdpZHRoOiAxNTBweDt9ICA8YnIgLz4gICBidXR0b25bdHlwZT1zdWJtaXRdIHtib3JkZXItcmFkaXVzOjZweDsgZm9udDoyLjRlbSB7WyYqJl19RnV0dXJhLCBcJ0NlbnR1cnkgR290aGljXCcsIEFwcGxlR290aGljLCBzYW5zLXNlcmlmOyBmb250LXNpemU6MTAwJTsgY3Vyc29yOnBve1smKiZdfWludGVyOyBtYXJnaW4tdG9wOiAyMHB4O30gIDxiciAvPlwiO3tbJiomXX0=[[/code]]
*****************************************************
ASP.NET MVC

MVC stands for Model-View-Controller where
M – is a Model(s) – > that represent the data of the application and logic.
V – is View(s) – > these managed display of the information
C – controller (usually) interprets the mouse and keyboard inputs from the user, except in ASP.NET MVC it acts as a handler for incoming browser requests and retrieves model data.

We are going to add ASP.NET MVC to the same solution 
1. Right click on the solution file and choose new project then Web->ASP.NET MVC 4 Web application



Hit OK

(Don’t forget to set CommentPostMVC project as the startup project)


Choose Empty for project template and Razor View Engine.

2. Adding controller
We need to add controller to our MVC application:
Right click on the controllers and choose Add -> Controller
Name the controller: CommentController

MVC parses path in the following manner:

 url: “{controller}/{action}/{id}”




 Now since we’ve named our controller CommentController we have to modify our default routing. Head over to to App_Start folder and open RouteConfig.cs file. Change controller to controller = ‘Comment”

  routes.MapRoute(
                name: “Default”,
                url: “{controller}/{action}/{id}”,
                defaults: new { controller = “Comment”, action = “Index”, id = UrlParameter.Optional }
            );

         
         


   3. Adding View
   Right click on the Views folder in the project area – type ‘Index’ for the view name and uncheck ‘Use a layout or master page:’ and click Add button.

Controllers pass data to the view, which is responsible for rendering it to HTML.
 
   4. Adding Model
   Right click on the Models, add -> class and name is Comments – just like we did for web forms ASP.NET – non mvc

 
   Copy/paste the following lines into Models: (hint: it’s same as ASP.NET NON MVC)
 
using System.ComponentModel.DataAnnotations;

namespace CommentPostMVC.Models
{
    public class Comment
    {
        [Required]        public string PosterName { get; set; }
        [Required]        public string PosterEmail { get; set; }
        [Required(ErrorMessage = “Did you like or didn’t like my post?”)]        public bool? LikedPost { get; set; }
    }
}

5. Add call to our leave comment on our page:

a. Add Html.ActionLink from index.cshtml page to BlogPostComments page:

Copy/paste the following lines into index.cshtml

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name=”viewport” content=”width=device-width” />
    <title>Index</title>
</head>
<body>
    <div>
     
        @Html.ActionLink(“Leave blog post comment”, “BlogPostComments”)
     
    </div>
</body>
</html>

6. The second parameter in ActionLink is essentially an action that we need to implement back in our CommentController, so let’s head back to CommentController.cs and add 
two new methods:

       [HttpGet]
        public ViewResult BlogPostComments()
        {
            return View();
        }
        [HttpPost]
        public ViewResult BlogPostComments(Comment comment)
        {
            return View(“Comment”, comment);
        }

     
        Now, Right click either on the method itself (BlogPostComments or inside the method and add View.
        Check ‘Create a strongly-typed view’ and choose our previously created model Comment (CommentPostMVC.Models) from the drop down list.
 

  The method tagged with attribute [HttpGet] will handle our initial page load and the method tagged with [HttpPost] will handle our post back(s). It also tells MVC to render a view called Comment and pass in a comment model (object.)

     
7. Modify BlogPostComments.cshtml

Copy/Paste the following lines into BlogPostComments.cshtml
     

@model CommentPostMVC.Models.Comment
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name=”viewport” content=”width=device-width” />
    <title>BlogPostComments</title>
</head>
<body>
   @using (Html.BeginForm())
   {
        <p>Name: @Html.TextBoxFor(x => x.PosterName) </p>
        <p>Email: @Html.TextBoxFor(x => x.PosterEmail)</p>
     
       <p>Liked the post?:
           @Html.DropDownListFor(x => x.LikedPost, new[]            {
                new SelectListItem {Text = “Me Likey!”, Value = bool.TrueString},
                new SelectListItem {Text = “Me NO Likey”, Value = bool.FalseString}
            }, “Liked it?”)
        </p>
        <input type=”submit” value=”OK” />
    }
</body>
</html>

     
Notice: the Html.BeginForm() generates PostBack which will be handled by the method tagged with attribute [HttpPost] in our CommentController. 

 
  8. Add a second view (Comment View) for the action method:  ViewResult BlogPostComments(Comment comment)
  Right click inside that method add choose add view:
  Type: ‘Comment’ as a view name.
  Check ‘create a strongly-typed view’ and choose Comment (CommendPostMVC.Models) as a model from the drop down list.

copy/paste the following lines into the Comment.cshtml

@model CommentPostMVC.Models.Comment
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name=”viewport” content=”width=device-width” />
    <title>Comment</title>
</head>
<body>
    <div>
        <h1>Thank you, @Model.PosterName! with email: @Model.PosterEmail</h1>
        @if (Model.LikedPost.HasValue && Model.LikedPost.Value)
        {
            @:Thanks! and Please come again..
        }
        else
        {
           @:Please write me with your comments and suggestions on how to improve.
        }
    </div>
</body>
</html>

9. Validation
Now, that we’ve already have copy/pasted our old Comment model (from our asp.net comment.cs to MVC project comment.cs) mean that we are already including some have some very basic validation inside.

Go back to CommentController.cs and add check to validate the model:

        [HttpPost]        public ViewResult BlogPostComments(Comment comment)
        {
            return ModelState.IsValid ? View(“Comment”, comment) : View();
        }

We, also need to display the errors back to the user, to do this we’ll use:  @Html.ValidationSummary() which returns an unordered list (ul element) of validation messages that are in the System.Web.Mvc.ModelStateDictionary object.

That’s all folks. You can download and/or browse the code here: codeplex