Monday, January 26, 2015

jQuery - Pro Tip #4

Difference between find() and filter()


If I have a list of items such as:

<ul id="tasks">
    <li class="task">Do some work</li>
    <li class="task">Do more work</li>
    <li class="relax">Relax!</li>
</ul>

and I'd like to select all list elements inside with class="task" assigned.

I might want to do something like this:

// cache the result.
var $tasks = $('#tasks li');

var $task = $tasks.find('.task');

and that of course won't work. The reason is this: http://api.jquery.com/find/

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

in other words it says: 'search through all the child elements only' and since we are already at the <li> level there's nothing below it!

The solution to this is to use .filter() method that works on the currently matched elements.

var $task2 = $tasks.filter('.task');

jsFiddle example: http://jsfiddle.net/seba368/gn8L204a/

Saturday, January 24, 2015

jQuery - Pro Tip #3

Extend jQuery pseudo class

It's a little bit contrived example, but let's say I have an input group:

     <div class="form-group">
        <input class="form-control" type="text" name="name">
     </div>

and I'd like to do something to that input group, such as:

      $('.form-group').removeClass('has-error').addClass('has-success');

If I do it over and over again, I might consider wrapping it in a method:
 
       RemoveAddClass('.form-group');

function RemoveAddClass(selector){
    $( selector ).each(function() {
       $(this).removeClass('has-error').addClass('has-success');
    });    
};

and this is pretty good, however there's a better way, and that is extending jQuery pseudo class:

turning the above into:

$.extend($.expr[":"], {
    removeAddClass: function(element){     
        $(element).removeClass('has-success').addClass('has-error');
    }
});

you can check out my fiddle here: http://jsfiddle.net/seba368/osub4xw2/1/




Friday, January 23, 2015

jQuery - Pro Tip #2

jQuery - Pro Tip #2 - selector caching!


instead of repeating the selector and hence (re)traveling the DOM:

function doWork(){
    $('#divTag').addClass("has-error");
    $('#divTag').slideUp();
}

cache the selector - caching it outside the method allows for reuse in multiple methods.
var someDivTag = $('#divTag'); 
function doWork(){
   someDivTag.addClass("has-error");
    someDivTag.slideUp();
}
and finally chain it:

function doWork(){
   someDivTag.addClass("has-error").slideUp();
}

Thursday, January 22, 2015

jQuery - Pro Tip #1.

jQuery - Pro Tip #1


1. Use CDN (content delivery network)
Go to: https://developers.google.com/speed/libraries/devguide
and pick a version of jQuery you're interested in:
e.g.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

2. but don't forget to fallback onto the local server in case the CDN isn't available with:
<script> window.jQuery || document.write("<script src='js/jquery.js'></script>

3. putting it all together:

 <html>  
 <head>   
   <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"</script>  
   <script>  
     window.jQuery || document.write("<script src='js/jquery.js'></script>");  
   </script>  
 </head>  
 </html>  

Thursday, October 9, 2014

What happens when you select 'Create Git repository on..' in Xcode.

When you create a new project in Xcode, you have an option of selecting 'Create Git repository on..'.

 

    I'm still fairly new to Xcode (compared to my 15+ yrs with Visual Studio), and wondered what exactly happens. What I mean by that is by default you can't see where the Git repository was created and that's because it's hidden. Every time you select 'Create Git repository on 'My Mac'' Xcode creates hidden Git folder in the same folder as your project. To be able to see it (in Mavericks) open terminal window and type:
defaults write com.apple.finder AppleShowAllFiles TRUE
Hit Enter and type:
killall Finder
You should now be able to see the hidden Git folder inside your project:



To revert that behavior and re-hide the files type:
defaults write com.apple.finder AppleShowAllFiles FALSE
Hit Enter and type:
killall Finder
That's all.


Wednesday, August 27, 2014

Fun with Knockout - observables.

This is continuation of the previous post on knockout, so let's continue and modify the previous example to include obervable feature, i.e. when the data changes in the input box (go ahead and play with it) then the field (in this case <span>) gets updated automatically without any need for extra JavaScript code or jQuery. 


Previously I defined simple JavaScript object:
 var stock = {
            cusip: 12345,
            symbol: "MSFT",
            name: "Microsoft",
            bid: 45.92,
            ask: 46.99
        };

Let's add observable to it:
 var data = {
                stock: {
                    cusip: ko.observable(12345),
                    symbol: ko.observable("MSFT"),
                    name: ko.observable("Microsoft"),
                    bid: ko.observable(45.92),
                    ask: ko.observable(46.99)
                }
            };

Screenshots:


I highlighted the difference between creating non-observable object and observable in knockout.
Once again, fully working example posted on the JSFiddle. (note that I'm using bootstrap for nice formatting.)



Fun with Knockout - binding.

Fun with Knockout - binding. 

I started learning Knockout JS - a standalone JavaScript library that implements MVVM design pattern.
I have tons of notes and examples that I've constructed, some of them may or may not resemble to some extent those of the original authors, however they are all mine.

Ever since I discovered JSFiddle I've been trying to port, when possible, all of my examples from Visual Studio to JSFiddle for easy sharing. The first that I'd like to present is how to bind data and text fields using knockout and constrast that with binding through jQuery.

Let's create a JavaScript object to represent a stock:

 var stock = {
            cusip: 12345,
            symbol: "MSFT",
            name: "Microsoft",
            bid: 45.92,
            ask: 46.99
        };

To simply bind and display the text for cusip all we need to do is:
<span data-bind="text: cusip">
For values it's just slightly different:
<input data-bind="value: bid" />

and instruct the knockout to perform the bindings for us:
ko.applyBindings(stock);
and that is pretty much the gist of it.

 I have a fully working example posted on the JSFiddle. (note that I'm using bootstrap for nice formatting.)

Screenshots:



Monday, June 9, 2014

Calling object's property via string.

How to call object's property via its string name.


Recently, I needed a way to invoke object's property via string, instead of its real name, yes I sacrificed the compile time checking :)

What do I mean by that?

Instead of writing code like this:


class SampleObject 
{
  public Property1{get;set;}
}

SampleObject o = new SampleObject()
o.Property1 = "some value";

I needed a way to do this:

o."Property1" = "some value";

One simple (enough) way to accomplish this is by implementing an object indexer inside the class combined with reflection:

public object this[string name]
 {
   get
      {
         var properties =
            typeof(SampleObject).GetProperties(
            BindingFlags.Public | BindingFlags.Instance);

          foreach (var property in properties)
          {
             if (property.Name == name && property.CanRead)
             {
                return property.GetValue(this, null);
              }
           }           
       }

set{......}

}


and Voilà

Now I can call the object via string like this:

to get value:
var myValue = o["Property1"];

to set value:
o["Property1"] = "SomeValue" // see my sample project for details.

You can download my sample project here.

Happy coding!









Tuesday, April 29, 2014

Starting with jQuery - Part 4

How to load html data from the server (Ajax style)

$(selector).load(url,data,callback) - loads data from the server and inserts the returned HTML into the DOM. 
The first parameter is mandatory, while the other two are optional.

1. Using just the first parameter: url.
    $(#FirstDiv).load('MyPage.html);

2. Using the first two parameters: url and passing in JSON data.
     $(#FirstDiv).load('MyPage.html, {author:Homer});

3. Using the url and callback function:
     $(#FirstDiv).load('MyPage.html,
        function(response, status, xhr){
          if(status == "error"){
              alert(xhr.statusText);
          }
         if(status == "success"){
             alert("External content loaded successfully!");
        }

       });

I'm including the sample files here. You can extract them and if you have IIS Express (usually comes with Visual Studio installation) you can run it without starting Visual Studio.

C:\Program Files\IIS Express\

and drop the files into the path pointed by the default website.






Good Luck!


Saturday, April 26, 2014

Starting with jQuery - Part 3


Click here to download example file

- How to iterate over html nodes:

jQuery provides us with an each function - that can be used to iterate over any collection, whether it's an object or a simple array. It iterates over DOM elements and passes current loop iteration starting with 0.

.each(function(index, Element))

There are two ways to iterate over the elements:

1.
 $('div').each(function(index){
         alert(index + '=' +$(this).text());
}


OR

2.
 $('div').each(function(index, elem){
     alert(index + '=' +$(elem).text());}

They both accomplish the same thing, the first one uses $(this), basically passing DOM element to jQuery so this refers to the current element.


-  How to modify DOM:

this.property, so to iterate through each div in the DOM tree and update the author node:

$('div').each(function(i){   this.author = "index= " + i;});

Note: There's a difference between $(this) and this:
1. $(this) - represents the jQuery object.
2. this - represents the raw javascript (DOM) object.

- How to modify attributes:

We can grab the author attribute using:

var result = $('#SomeDiv').attr('author');

If we want to modify the value of object's attributes:

$("button").click(function(){
  $("img").attr("height","50");});

$('div.FirstDiv,div.SecondDiv').each(function(index){
   this.title = 'New Title';});

OR:

 $('div.FirstDiv,div.SecondDiv').each(function(index){
     $(this).attr("title", 'New Title'); });

The first example uses raw DOM javascript object (this.title), the second example, while accomplishing the same thing, uses jQuery object and accesses title via jQuery API.

Mousing over reveals the title:


Now, if we want to update multiple values (title, style, etc.) or attributes then we can harness the power of JSON (JavaScript Object Notation) 

$('img').attr({
  alt: 'Richard Feynman',
  width: '400',
 style: 'border: 1px solid red;'
});

jQuery supports what's called a map - which is basically a JSON object with properties.
Note: the attributes above need to match the <img> attributes. 
JSON object is essentially an unordered collection of name/value pairs, self describing, easy to understand AND much faster to parse than XML - and yes, it is language independent.

The first object is delimited by the outside brackets {FirstName, LastName} - then inside we have another object that is part of the outside object - nested object with the Address:
{
 FirstName:'Jeane',
 LastName:'Waterman',
  Address:
  {
     Street: '123 Nice St.',
     City: 'Chicago',
     State: 'IL',
     Zip: 60606
  }
}

You can do arrays: (the square bracket represents an array)
{
 "employees": 
   [
    { "FirstName":"Jeane" , "LastName":"Waterman" }, 
    { "FirstName":"Dania" , "LastName":"Dates" }, 
    { "FirstName":"Tamie" , "LastName":"Rost" }
  ]
}




  $('div.SecondDiv').attr(
  {
    title: "Yet Another Title",
    style: 'font-size: 20pt; background-color:green;' 
   });

OR

 $('div.SecondDiv')
    .attr(
            {
              title: 'Yet Another Title'
            }
           )
     .css('background-color','green')
     .css('title','Yet Another Title')
     .css('font-size', '20pt');


The second example uses chaining of the jQuery properties.



- How Insert and Remove Nodes:

1. append() - insert content to the end of element.
2. appendTo() - insert element to the end of the target.
3. prepend() - insert content to the beginning of element.
4. prependTo() - insert element to the beginning of the target.
5. remove() - remove elements from the DOM.

$('#FirstTableDiv')
.append('<span style="background-color:steelblue">appended Child 1 Blue</span>');  

$('#FirstTableDiv')
.prepend('<span style="background-color:steelblue">prepended Child 2 Blue</span>'); 




To remove some rows from the table:

$('tbody.RowsToRemove').remove();  

results in:

    

Click here to download example file.


Friday, April 25, 2014

How to build WCF server with Windows Forms client.

A while ago I wrote a sample project: a server application that accepts incoming trade information from several different brokers. It consists of central position server, client and broker simulator.
The server was implemented using WCF while both the client and broker simulator using Windows Forms.

It's a good learning project for those interested in WCF.
The project was written and built using Visual Studio 2012
It uses WCF and as such the server (PositionServerHost) must be run with administrative privileges, i.e. run your Visual Studio as administrator.

1. Database
   a. I've used SQL Express 2012.
   b. In the Database folder under PositionServer\Database.
      I've provided both the database itself that can be attached as well scripted database objects: tables, types and store procedures.
      i.e. the database can be either attached (Right-click on Databases in the Object Explorer and attach PositionServer.mdf)
      or execute the following from \PositionServer\Database\
         1. [dbo].[OpenPositions].sql
2. [dbo].[InsertOpenPositions].sql
         3. [dbo].[UpdateOpenPositions].sql

2. To Run in Visual Studio 2012
   a. Open Solution PositionServer.sln
   b. Build
   c. Click Debug/Run

   The following projects should start automatically:
   1. PositionServerHost
   2. DemoClient
   3. BrokerSimulator

3. To Run Outside Visual Studio
   1. Nagivate to \PositionServer\PositionServerHost\bin\Debug\ , Right Click on BrokerSimulator.exe and run as Administrator
   2. Nagivate to  \PositionServer\DemoClient\bin\Debug\ ,     double click on DemoClient.exe
   3. Nagivate to  \PositionServer\BrokerSimulator\bin\Debug\ ,dobule click on BrokerSimulator.exe

4. In the Demo Client click "Connect" button to connect to the server.
   The Broker Simulator connects automatically upon hitting "Start Simulator" button.

Here's the project, enjoy!

Wednesday, April 23, 2014

Starting with jQuery - Part 2

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

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.



Monday, April 21, 2014

How to create Navigation Bar with CSS3

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.

Saturday, April 19, 2014

Testing waters with HTML5!

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



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:







Tuesday, December 3, 2013

WPF - Part: 2

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:

1:  <Page  
2:   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
3:   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">  
4:   <Grid HorizontalAlignment="Center" VerticalAlignment="Center">   
5:     <Button x:Name="XAMLButtonTest"   
6:                     FontFamily="Veranda"  
7:                     FontSize="42"  
8:                     Foreground="DarkRed">  
9:       _Submit!  
10:   </Button>   
11:   </Grid>  
12:  </Page>  

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:

  var xmlButtonTest = new Button  
       {  
         FontFamily = new FontFamily("Veranada"),  
         FontSize = 42,  
         Foreground = Brushes.DarkRed,  
         Content = "_Submit"  
       };  


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.

1:  <Button Width="64" Height="30">  
2:        <Button.Template>  
3:          <ControlTemplate TargetType="Button">  
4:          </ControlTemplate>  
5:        </Button.Template>  
6:      </Button>  

The code above represents the natural look for the button which essentially is 'no look'.
Let's fill in the appearance: (fully working XAML)
1:  <Window x:Class="WpfApplication2.MainWindow"  
2:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
3:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
4:      Title="MainWindow" Height="350" Width="525">  
5:    <Grid HorizontalAlignment="Center" VerticalAlignment="Center">  
6:      <Button Width="85" Height="45" Background="SteelBlue" VerticalAlignment="Center" HorizontalAlignment="Center">  
7:        <Button.Template>  
8:          <ControlTemplate TargetType="Button">  
9:            <Grid>  
10:            <Rectangle Fill="{TemplateBinding Background}" RadiusX="8" RadiusY="8"></Rectangle>  
11:              <ContentPresenter RecognizesAccessKey="True"   
12:                       Content="{TemplateBinding Content}"   
13:                       VerticalAlignment="{TemplateBinding VerticalAlignment}"   
14:                       HorizontalAlignment="{TemplateBinding HorizontalAlignment}" />  
15:            </Grid>  
16:          </ControlTemplate>  
17:        </Button.Template>  
18:        _Submit  
19:      </Button>  
20:    </Grid>  
21:  </Window>  

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.