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: