Sunday, August 5, 2012

ASP.Net - Web Form using Server Control

Hello

This post covers in different levels the following :

  • Server controls categories
  • Label
  • TextBox
  • Button
  • Image control
  • Image
  • CheckBox
  • RadioButton
  • ListControls
  • Panel
  • AdRotator
  • Calender
  • HyperLink
  • Table
  • PlaceHolder
  • Literal
  • ImageMap
  • SmallHome Project




Server controls are tags that are understood by the server.

Server controls categories :
  • Standard : Button, Label,...
  • Data :  GridView , ListView
  • Validation : RangeValidator
  • Navigation : Menu, SiteMapPath, TreeView
  • Login : Login  , LoginName
  • HTML - same as in HTML e.g. Input, Table....
  • advanced :
  • Web part 
  • AJAX (  Asynchronous JavaScript and XML Extension - allow to update part of web page not all of it thus improve performance
  • Dynamic Data
  • Reporting - reports



Source sample 1 - label
Lets create a web site  - ASP.Net Empty Web Site . make sure Web Location is HTTP and you run Visual Studio "as administrator"

Lets add a web form - default.aspx and put a label in it.




Now lets add text



Run the page using view in browser (or using localhost/<web site name>

What happened :

  • an HTTP GET request with the page URL was sent from the browser to the server
  • the server got the request , send it for the ASP.Net engine for processing
  • the response - HTML file is sent back to the browser


You can view the returned html source via the browser e.g. for chrom it is Tools->View Source.



<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
    <form method="post" action="Label.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
 value="/wEPDwUJOTczNTMyNjI5D2QWAgIDD2QWAgIBDw8WAh4EVGV4
 dAUUNy8yMi8yMDEyIDE6NDE6MjMgUE1kZGRzZ+wB1xyZnb0BtmErYtqt
HQKmhiNCSXSL1nk9lByRpw==" />
</div>
    <div>
        <span id="Label1">7/22/2012 1:41:23 PM</span>
    </div>
    </form>
</body>
</html>


remarks :

  • The strange hidden input type is created by ASP.Net. It contains control state (background color, font, ...). This may be used for POSTBACK.
  • The asp engine has return HTML - the browser does not know ASP it know HTML so the ASP engine make the translation !!


Maintaining the ViewState

When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.
When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control. The source could look something like this:

Maintaining the ViewState is the default setting for ASP.NET Web Forms. 

Exercise  1 - Button + Text Box
Write an asp page with button and two text boxes. The button handler switch the text between the text boxes

Source sample 2 - Image control
source_sample_2.zip
Create a web site name WebSite4 with an image and label - This is my phone. Add a tool tip - MyPhone.

Add the image via Add Existing Item.

Set the ImageUrl to the image file name

Note that you can set this via code or the control properties (via GUI).
I have chosen to change the properties so we can see it in the aspx file :



Run via the browser localhost/WebSite4 e.g. in this case


Note that you can control the image size with properties width , height

Source sample 3 - CheckBox and AUTOPOSTBACK

Add a page to the web site and add check box
Click on the check box to create it's handle and put a break point inside;


Run the application via F5 - the break point is not hit !!!

Change the check box property AutoPostBack True and run via F5 , now you can see that the change has reached the server - an HTTP POSTBACK  was done and the handler is served.

remark - one might ask himself why do i need this ? i guess there are scenario when a check box click should be notified but only when you does POSTBACK and not automatically.

Exercise  2  - illustrate further AUTO POST BACK
create a web site with button and check box. click on the check box and put a break point.
run the web site and click the  check box, the breakpoint is not hit (AUTO POSTBACK is false). Now click the button , this generate POSTBACK so now the break point is hit !!

Source sample 4 - Radio button (illustrate the AUTOPOSTBACK issue)
sample4_radioButton
Important Properties :

  • Checked
  • Text
  • Group
  • AutoPostBabk


Important Events :

  • CheckedChanged


create a web site with label choose a drink and 3 radio button : coffee,tea,water
and Text box choosing one trigger the text into the text box. Only one radio button can be chosen

hint : make sure AutoPostBack is true for all radio buttons

Run to createWebSite4

List controls


  • ListBox
  • list of item 
  • very common - e.g. list of locations 
  • allow to choose one or more items from the list 

  • DropDownList :
  • like listbox but allow to choose ONLY on items from list
  • CheckBoxList 
  • list of check box
  • compact way of handling  check box e.g. one method to trap change in some item
  • RadioButtonList
  • list of radio buttons
  • compact way of handling radio button e.g. one method to trap change in some item
  • BulletedList
  • display list of bullets
  • you can not choose an item



Source sample 5 - ListBox + Binding
Sample 5 ListBox + Binding

important properties :

  • SelectedIndex
  • SelectedItem
  • DataSource
  • SelectionMode(Single\Multiple)
  • AutoPostBabk
  • Items


important methods :

  • DataBind
important events
  • SelectedIndexChanged


It is possible to use binding with list control .
Need to use IsPostBack.


Remark - note that adding to the list automatically update the GUI (like in WPF)

View this page in browser result in :


Click on the control to create


Put a break point inside ListBox1_SelectedIndexChanged , click F5 and choose USA - breakpoint hit ?
yes ONLY if AUTOPOSTBACK is true.

Add a search button and show population for the selected country :

 ["Israel"] = 7848800;
 ["Jordan"] = 6508271;
 ["USA"] = 311800000;
 ["Germany"] = 81859000;
 ["Syria"] = 22530746;




Run to create :



remark - the result text box TextMode should be MultiLine so it will fit inside the text box control.


Source sample 6 - Panel
sample 6 - Panel
Panel is a container for other controls. It is best use with Visible true\false

Service screen

Production screen

Source sample 7- AdRotator

Sample 7 AdRotator.zip
Display advertisements on your web page.
The Data Source that pop up when you add AdRotator is the source of adds. you can choose None and add later the source





important properties :

  • AdvertismentFile - put here the XML file
  • XML Ad tags   
  • <ImageUrl>  - url of the image , what you see
  • <NavigateUrl> -  url of the link, click on the image and this link opens
  • <Impressions> - relative importance of this ad 

The XML file :


  
    ICON-STEPS2 (1).png
    http://www.msn.com
    25
  
  
    green-footsteps-ii1-300x295.jpg
    http://www.startvbdotnet.com
    5


remark :

  • for some reason strange reason you some time get error "" during debug. run as "view in browser" 
  • the ratio of appearance is about 5:1 for msn.com ad (it is not accurate)

enter http://localhost/WebSiteAdRotator/into the browser and click enter. few time you will get one ad and then the other

Remark :

  • This work OK for HTTP web location (use view in Browser)
  • On FileSystem web location you get an exception "The AdRotator AdRotator1 could not find the AdvertisementFile or the file is invalid."


Source sample 8- Calender
Sample 8 Calender.zip


Calender 

important properties :
  •  SelectedDate  
important events
  • SelectionChanged 
  • DayRender - issued when day cell is created (including postback)

DayRenderEventArgs

important properties :

  • Cell
  • Day









Write a Web Site with Calander and ListBox.
Every date picked is sent to the list box
Allow the user to add appointment (use DayRender which is forced by postback - use some button for this)


Source sample 9 - HyperLink
This control is actually a link.

Sample 9 HyperLink.zip
important properties :

  • ImageUrl - image url
  • NavigateUrl - target URL


Unlike LinkButton , HyperLink does not issue POSTBACK when HyperLink is clicked. It will simply request for the URL.

Create a simple web site with HyperLink control , fill ImageUrl  and NavigateUrl

Source sample 10 - Table
Table sample 10.zip

Table important properties

  • Rows - collection of TableRow


TableRow important properties

  • Cells - collection of TableCells

TableCell  important properties
  • Controls - collection of Controls

You can look at this also in this way (table has rows, rows has , .....)

  • Table
  • Rows
  • Cells
  • Controls 

code snippet for creating table with button as cell




Create web site as follows :
  • The user can enter the number of rows\coulmns
  • Create Table button create a table of buttons with the text that identify the button in the table
  • handle the case of non valid input (exception)




Remark 
It is possible to use table for layout using 




Then drag and drop controls into the table.

Go back to the sample and use table in this way for layout of insert number of row and col (2x2 table)


Source sample 11 - PlaceHolder

This is only a container for other controls.



Click on the button

Generate POSTBACK e.g. by clicking on the browser address line and the placeholder disappears !. 


Source sample 12 - Literal
This control is similar to label but it can be used inside the HTML title because it is tranlated by the ASP.engine to simple text as sen in view source :


Literal is put inside the HTML title




Run to create




Source sample 13 - ImageMap
ImageMap sample 13.zip

This control has an image , you can divide it logically and perform action when different part are clicked.

important properties :
  • ImageURL - url of image
  • HotSpots - collection of HotSpot type
  • RectangularHotSpot - define rect by (top,left) , (bottom,right)
  • CircleHotSpot
  • PolygonHotSpot 
  • NavigateUrl - property of each hotspot, allows to navigate to e.g. asp page



You can add hot spot via the IDE : click on HotSpot and then click Add and choose mode


Sample control :



Create a Web Site with an image. In case you click on it's upper part you are navigated to one aspx file , in case you click on it's lower part you are naviagted to another apsx. Both aspx allow you to get back to the original aspx.



Run the project :
click on the image upper part
You are navigated to upper.aspx


Click Back to navigate to the main page. Now click on the lower part, you are navigated to lower.aspx



Advanced
Properties :
  • HotSpotMode




Small Project Home
Following is a GUI for a small home project
Control used :

  • Label
  • TextBox
  • Image
  • Button or ImageButton
  • RadioButtonList
  • ListBox
  • HyperLink
  • Table (not must)

HTML Table is used for layout
Player moves and winners are written into the Messages list including date\time



  Nathan

Saturday, July 14, 2012

JSON

Hello



1. Introduction

JSON: Java Script Object Notation.
JSON is smaller and faster then XML , it is also parsed easier
JSON syntax used to store and exchange information


JSON example  :
{
"students": [
{ "firstName":"Jim" , "lastName":"Deer" },
{ "firstName":"Kim" , "lastName":"Wild" },
{ "firstName":"Jana" , "lastName":"Jampolski" }
]

student is an array of three objects


XML similarities

  • JSON is simple text
  • JSON is "self-describing" (human readable)
  • JSON can be parsed by JavaScript
  • JSON data can be transported using AJAX
  • JSON is hierarchical (values within values)

XML dissimilarities

  • No end tag
  • Shorter
  • Uses arrays 
  • Quicker to write and read 
  • Can be parsed using built-in JavaScript eval()
  • No reserved words




Why JSON?
For AJAX applications, JSON is faster and easier than XML:


Using XML
  • Load an XML document
  • Use the XML DOM to read the document
  • Extract values and store in variables
Using JSON
  • Get a JSON string
  • eval() the JSON string


2. JSON Syntax


JSON syntax is a subset of JavaScript syntax

JSON Syntax Rules :

  • Data is in name/value pairs
  • Data is separated by comma
  • Square brackets holds arrays
  • Curly brackets holds objects



JSON Name/Value Pairs
JSON data is written as name/value pairs.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
"firstName" : "Anna"


This is equals to the JavaScript statement:
firstName = " Anna "





JSON Values
JSON values can be 


  • A number (integer or floating point)
  • A string (in double quotes) 
  • A Boolean (true \ false)
  • An array (in square brackets)
  • An object (in curly brackets)
  • null




JSON Objects
JSON objects are written inside curly brackets,
Objects can contain multiple name/values pairs:
{ "firstName":"Anna" , "lastName":"Long" }


This is equals to the JavaScript statements:
firstName = " Anna "
lastName = "
Long "



JSON Arrays
JSON arrays are written inside square brackets.
An array can contain multiple objects:


{
"students": [
{ "firstName":"Pete" , "lastName":"Cool" },
{ "firstName":"Nathan" , "lastName":"Krasney" },
{ "firstName":"James" , "lastName":"Kid" }
]
}

In the example above, the object "students " is an array containing three objects. Each object is a record of a student (with a first name and a last name).



JSON Uses JavaScript Syntax

Because JSON uses JavaScript syntax, no extra software is needed to work with JSON within JavaScript.
With JavaScript you can create an array of objects and assign data to it like this:
Example
var  students = [
{ "firstName":"Pete" , "lastName":"Cool" },
{ "firstName":"Nathan" , "lastName":"Krasney" },
{ "firstName":"James" , "lastName":"Kid" }
];


The first entry in the JavaScript object array can be accessed like this:
students[0].lastName;
The returned content will be:
Cool

Nathan

Thursday, June 21, 2012

HTML based Web Site (chap 2 web beginners)

Hello

This chapter include the following :

  • Tools
  • HTML
  • Sample of web site with HTML page
  • Sample of web site with HTML pages , pictures , sound and video.


Tools

We will need the following tools for development of HTML based web site :

  • Browser
  • IIS
  • Visual Web Developer 2010
  • HTML
  • LoopBack (127.0.0.1)

Browser - allow HTTP GET to the web site


IIS :

  • Web server for hosting the web site and serving requests


Visual Web Developer 2010 :

  • development environment
  • free download


HTML :

  • markup language
  • used for static web site. I.e the info stored on the web site is delivered to the client as is. Dynamic web site may build the page on demand
  • http://www.w3schools.com/html/



LoopBack 

  • use for internal web site testing
  • use IP 127.0.0.1 or localhost



HTML (Hyper Text Markup Language)


Basic structure of HTML page


<HTML>
<HEAD>
                  <TITLE>
                            ................ title of the page
                  </TITLE>
 </HEAD>
  <BODY>
                            ................ body of the page
  </ BODY >

</HTML>


Tag list


remark - tag are not case sensitive


<br> - new line




div - it defines a section so we can e.g. apply the font to all of them
example :


<div align="center">
  This is some text center align!

<br>
text centered
</div>

<div align="left">
  This is some text  left align!
</div>
<div align="right">
  This is some text  right align!
</div>

This will create :


<p>
The <p> tag defines a paragraph.


<h1> ..... <h7> - heading
example :


<h1>big   heading </h1>
<br>
<h7>small heading </h7>


This will create :






Tag nesting
example :

<HEAD>
                  <TITLE>
                            ................ title of the page
                  </TITLE>
 </HEAD>



<hr> - line


example :


<hr color="blue"/>


<font>
example :


<font face="arial"  size="7"/>some text</font>
size is 1-7

This will create :



<big> - big text
<small> - small text
example :


<big>big text</big>
<small>small text</small>

This will create :




Sample of web site with HTML page


Run visual studio as administrator (Windows 7)


Create a new web site





Choose ASP.Net Empty Site, HTTP, and the location of the site




Open the IIS via "Control Panel"->"Administrative Tools"  and notice the name "WebSite" which we just created


Now we will add a new HTML pahe into the web site.




By adding HTML page


Now you can edit the page



It is possible check that the page is loading correctly (using HTTP GET) in few ways :

via the browser - http://localhost/WebSite/HTMLPage.htm

via the IDE -

in any way you will get the same result on the browser

Tag list continued


style

  • attribute
  • style determine the visual appearance
example :

<div style="background:green">
<h1>text</h1>
another text
</div>
<div style="background:red">
<h1>text</h1>
another text
</div>

This will create :

You can also use : background-color, text-align,color,font-family


test it yourself

<img> - using image
the basic structure is <img src="url"  width="pixel width" height=" pixel height"/>


example :

<img src="http://budgetstockphoto.com/freeimages/environment/pics/clean_beach6085.jpg"
    width="100" height="100"/>

will create:
<ol> - ordered list
<li> - list item


example :



<h4>An Ordered List:</h4>
<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>


will create :



<ul> - un ordered list

example :



<h4>An Un Ordered List:</h4>
<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>


will create :
<dl> - definition list
<dt> - subject item in definition list
<dd> - sub subject item in definition list


example :


<dl>
  <dt>Coffee</dt>
    <dd>- black hot drink</dd>

      <dd>- latte</dd> 
  <dt>Milk</dt>
    <dd>- white cold drink</dd>
</dl>



will create :
<table> - table
<tr> - define a row in a table
<th> - define a header cell in table
<td> - define standard cell in table


example :


<table border="1"> <tr> <th>Month</th> <th>Savings</th> </tr> <tr> <td>January</td> <td>$100</td> </tr> <tr> <td>February</td> <td>$80</td> </tr> </table>


will create :


common table attributes :
border = n , table width
cellspacing = n , space beteen cells
cellpadding = n , space inside cells
width = n , table width
bgcolor = color , table background color
colspan = n , number of columns cell should span
rowspan= n , number of rows cell should span


test it yourself !!



write hebrew
This require :

  • setting the encoding :
  • meta http-equiv="content-type" content="text/html;charset=UTF-8"
  • should be inside the head 
  • setting direction - dir=rtl

example :


<html > <HEAD> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> </HEAD> <BODY dir=rtl> שלום חבר </ BODY > </html>


will create :
<fieldset> - Group related elements in a form


exanmple :
<form>
  <fieldset>
    Name: <input type="text" /><br />
    Email: <input type="text" /><br />
    Date of birth: <input type="text" />
  </fieldset>
</form>



Will create :




The <legend> tag defines a caption for the <fieldset> element.


<form>
  <fieldset>
    <legend>Personalia:</legend>
    Name: <input type="text" size="30" /><br />
    Email: <input type="text" size="30" /><br />
    Date of birth: <input type="text" size="10" />
  </fieldset>
</form>



Will create :




links
<a> - link


attributes :

  • href - URL
  • target - specify where to open the windows e.g. _blank is new windows



link may refer to :

  • html file
  • web site
  • picture
  • audio\video file
  • mail



example
<a href="http://www.w3schools.com">Visit W3Schools.com!</a>
<br>
<a href="http://budgetstockphoto.com/freeimages/environment/pics/clean_beach6085.jpg">Nice Picture</a>
<br>
<a href="mailto:nathan@nynkmobile.com">Nathan's e-mail</a>



will create :
you can click on the links


reamrk - link can be relative e.g. point to html inside the web site.
e.g. <a href="HTMLPage.htm">Load Local Page</a>






Sample of web site with HTML pages , pictures , sound and video.


we will create a project as before


and add directories :

  • pictures
  • cars
  • airplanes
  • sound
  • video

and main html file






download files.rar into your desktop and then add to the project








loading all the file result in :




Actually we will have 6 pages which are organized like a tree as follows

  • Main page
  • Picture page
  • Cars page
  • Airplanes page 
  • Video page
  • Sound page 



project (you need to create web site and add files from above zip)


Main Page :
Picture page :
Sound Page :
Video Page :




Cars Page :




Airplane Page :






Nathan

Thursday, April 5, 2012

REST api

Hello

What is REST ?

  • REST stand for Representional State Transfer.
  • It relies on stateless,client\server,cacheable communication protocol
  • Uses HTTP
  • Restfull applications use HTTP to post data (create/update) , read data (make queries) , and delete data


REST as Lightweight Web Service
Much like Web Services a REST service is :

  • Platform independent i.e. does not care if Windows,Mac,Linux ... is used
  • Language  independent i.e. Java,C#,...
  • Standard based (runs over HTTP)
  • Can easyly be used with firewalls

How simple is REST


To get a user details the follolwing query may be used :
http://www.acme.com/phonebook/UserDetailes/1234

1234 is the requested user id
UserDetailes is the desired info

This is a URL which is sent via HTTP GET request.

More complex REST request


http://www.acme.com/phonebook/UserDetailes?firstName=John&LastName=Doe

Nathan