lundi 10 décembre 2012

Push notifications with Parse.com

Parse.com provides a set of handy tools to rapidly build mobile applications that needs back-end. One of the main provided features is the push notifications that enables asynchronous and real-time communiation. This post illustrates how to set up the push mechnism in an Android application.
  • First, we need to create an Account at Parse.com and register an application to have an application key and client key
  • Second, in the application settings wen have to enable push notifications
  • Then, download the latestes Parse SDK, i.e. the parse.jar
  • Finally, code time
In the manifest, we need to add the following lines to ask permessions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 
<uses-permission android:name="android.permission.VIBRATE" />
Then, before the </application> register a broadcast receiver
<receiver android:name=".PushReceiver">
   <intent-filter>  
 <action android:name="com.telethonix.NOTIFICATION"> </action>
   </intent-filter>
</receiver>
Then create the PushReceiver class as follow:
public class PushReceiver extends BroadcastReceiver {
   public final static String TAG = PushReceiver.class.getSimpleName(); 
   @Override
   public void onReceive(Context context, Intent intent) {     
      try {
 Bundle extras = intent.getExtras();        
 String message = extras != null ? extras.getString("com.parse.Data") : "";    
 Log.i(TAG, "Received message: "+message);
       // do something with the received data
      } catch (JSONException e) {
 e.printStackTrace();
      }  
   }
}
Finnaly in the main activity, we should initiate parse with the application keys, and send a notification
String app_id     = "your application key";
String client_key = "your client key";
Parse.initialize(this, app_id, client_key);
// subscribe to be notified
PushService.subscribe(MainActivity.this, "channel", MainActivity.class);
// push a message
ParsePush push = new ParsePush(); push.setChannel("channel");
push.setData(data);
push.sendInBackground(new SendCallback(){   
   @Override
   public void done(ParseException arg0){
      Log.i(TAG, "push sent done!");
   }
});
More details at Push Developer Guide.

mercredi 5 décembre 2012

J2EE Solution Logs

Changing the context root of a dynamic web app URL (StackOverflow)
  1. Right click on the project in the project explorer tab, the choose properties.
  2. Set the new context root in the Web Project Settings.
Exception when launching jetty (StackOverflow)
java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor
It seems that jetty cannot find the asm.jar file in its classpath, check this as follow:
  1. On eclipse, go to the Servers view (or open it via window -> view -> Servers)
  2. Right click on jetty, then choose Open or just type F3
  3. On the Overview tab, click on Open Lauchn Configuration
  4. Go to Classpath tab and check for asm.jar
If you cannot find it, then you should manually download it from the project website.

Register a listener to do things before the VM exits (even if you "Ctrl-C" the running example before it's completed)
private void registerShutdownHook() {
   Runtime.getRuntime().addShutdownHook( new Thread() {
      @Override
      public void run() {
         // do some thing
      }
   });
}

Increase Maven memory, in mvn.bat add:
set MAVEN_OPTS=-Xmx2048m -XX:MaxPermSize=512m

To be continued

samedi 17 novembre 2012

Notes on Operations Management

The dimensions used to measure performance of an operation and to differenciate it from other operations are:
  • Cost and efficiency,
  • Variety for supporting heterogensous customer
  • Quality of the operation can be divided into product quality and process quality (does the promise hold?)
  • Time and responsiveness
for example in case of a restaurant operations, the cost can be measured with indicators like number of served customer per employee or number of customer per restaurant (in case someone want to rent a restaurant), the heterogenity can be measured by the number of items in the menu, the quality can be measured by heigienity, the responsivness can be measured by the waiting time before serving.

It is impossible to out perform in all these dimensions, that's why as a manager/consultant you need to find a compromise; priorities dimensions.
Step1. Help making operational trade-offs (picture).
Example call center of a large retail bank, at the service level, the objective is 80% of incoming calls wait less than 20s, and the starting point is 30% of incoming calls wait less than 20s.
Here, the problem is the staffing levels of call centers with respect on efficiency. In fact, very short waiting time leads to frequent operator idle time. While long waiting times means the operators are fully utilized.
Step2. Overcome inefficiencies ny providing tools to identify and eliminate inefficiency
Example: Benchmarking of the market shows the pattern in the picture where the inefficiency of a given operation is the difference to the competitor with better productivity (less cost) and better responsiveness (less waiting time).
The curve that hold the competitor operations is the ineffecieny frontier that the operation should go beyond (to the right side).
Step 3. Evaluate proposed redesign/new technologies before they occur by answering questions like what will happen if we develop / purchase technology X? Are better technologies always nice to have? but will they pay?

Example in the picture the innovation related to the process redesign lead to a new frontier.

Module 1; business process analysis
To measure the performance of a business process three dimensions flow rate (throughput), inventiry and flow time.

Subway example: sitting in front of the store and counts number of arrival (flow rate) and departure and draw the corresponding cumulative customers number based on time. The difference at any time between both graphs represent the number of customers currently in the system.

Definitions:
Flow Unit: customer or Sandwich
Flow rate/throughput: number of flow units going through the process per unit of time
Flow Time: time it takes a flow unit to go from the beginning to the end of the process
Inventory: the number of flow units in the process at a given moment in time

Process Analysis: examples.
            Immigration department        MBA program                Auto company
Flow unit  Applications                   Student                      Car
Flow rate  Approved or rejected cases     Graduating class             Sales per year
Flow Time  Processing time                2 years                      60 days
Inventory  Pending cases                  Total campus population      inventory

Finding the bottleneck
Figure 1 processing/activity times (time needed for serving a customer in a given station) in subway example.

Drawing a Process Flow Diagram:
Triangles captures waiting time in a queue or some delay while boxes capture an activity. Arrows capture the flow of the process.
Process managemebnt is about doing things repeatdly, where project management deals.

Basic Process Vocabulary:
Processing times: how long does the worker spend on the task?
Capacity=1/processing time: how many units can the worker make per unit of time. If there are m workers at the activity: Capacity=m/processing time.
Bottleneck: process step with the lowest capacity
Process capacity: capacity of the bottleneck
Flow rate: Minimum{Demand rate, Process Capacity}
Uitilization: Flow rate / Capacity
Flow Time: The amount of time it takes a flow unit to go through the process
Inventory: The number of flow units in the system

Session 3: Labor cost and labor utilization
Labor Productivity Measures
Some definitions:
*Cycle time CT = 1/Flow Rate
Direct Labor Content = p1 + p2 + p3 + p4 (p stands for process)
If one worker per resource then we define
Direct Idle Time= (CT-p1) + (CT-p2) + (CT-p3)

*Average labor utilization = labor content / (labor content + direct idle time)
*Cost of direct labor = Total wages per unit of time / Flow Rate per unit of time
In an example of using these definition, calculate based on the Proccessing time: Capacity of each resource, its process capacity, flow rate, cycle time (which is the porcessing time of the bottleneck), idle time for (which is cycle time minus processing time) each resource, total idle time, labor content, labor utilization, utilization.

The Role of Labor Costs in Manufacturing (The Auto Industry):
While labor costs appear small at first, they are important:
 - look relative to value added
 - role up costs throughout the value chain

Implications
 - also hunt for pennies (e.g. line balancing)
 - spread operational excellence through the value chain

mercredi 14 novembre 2012

Android Solution Logs

Get a bitmap from an ImageView (StackOverflow)
imageView.setDrawingCacheEnabled(true);
imageView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
                   MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
imageView.layout(0, 0, imageView.getMeasuredWidth(), imageView.getMeasuredHeight()); 
imageView.buildDrawingCache(true);
Bitmap bmap = Bitmap.createBitmap(imageView.getDrawingCache());
imageView.setDrawingCacheEnabled(false);

Display the soft keyboard (StackOverflow)
// show keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
// hide keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0); 

Check whether the software keyboard is displayed (StackOverflow)
final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
    Rect r = new Rect();
    //r will be populated with the coordinates of your view that area still visible.
    activityRootView.getWindowVisibleDisplayFrame(r);

    int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
    if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
        ... do something here
    }
 }
});

Get the root view of current activity (StackOverflow)
View rootView = getWindow().getDecorView().findViewById(android.R.id.content)

Canvas drawing example on Android, link.
Draw text on canvas with a custom font (StackOverflow)
Paint paint = new Paint(); 
paint.setStyle(Paint.Style.FILL);     
paint.setColor(Color.WHITE); 
paint.setTextSize(30);
Typeface tf = Typeface.create("Helvetica", Typeface.BOLD);
paint.setTypeface(tf);     
Canvas canvas = new Canvas(bitmap);     
canvas.drawText(text, x, y, paint);

Gesture event detection (snippets)
  • Implements android.view.GestureDetector.OnGestureListener interface
  • Create a new GestureDetector instance: detector = new  GestureDetector(this, this)
  • Call detector.onTouchEvent(event) on the activity onTouchEvent(event)
Detecting touch event (Android Coding).

Display action bar (StackOverflow)

Capture a frame from a video (change since API 14
protected Bitmap videoFrame(String uriString, long msec) {  
  MediaMetadataRetriever retriever = new MediaMetadataRetriever();
  try {                         
     if (Build.VERSION.SDK_INT >= 14) {       
        Map<String, String> headers = new HashMap<String, String>();
        retriever.setDataSource(uriString, headers);
     }else {
        Uri uri = Uri.parse(uriString);
        retriever.setDataSource(context, uri);
     }                     
     return retriever.getFrameAtTime(msec);
  } catch (Exception ex) {
         ex.printStackTrace();
  } finally {
     try {
        retriever.release();
     } catch (RuntimeException ex) {
     }
  }
  return null;
}

Share content via intents (tutorial), sharing image (StackOverflow), set title (StackOverflow)
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));

Customized looking TabActivity (link).

Use Intent share to invoke a Twitter application to post text+image (StackOverflow)
private void share(String nameApp, String imagePath) {
    List<Intent> targetedShareIntents = new ArrayList<Intent>();
    Intent share = new Intent(android.content.Intent.ACTION_SEND);
    share.setType("image/jpeg");
    List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
    if (!resInfo.isEmpty()){
        for (ResolveInfo info : resInfo) {
            Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
            targetedShare.setType("image/jpeg"); // put here your mime type

            if (info.activityInfo.packageName.toLowerCase().contains(nameApp) || 
                    info.activityInfo.name.toLowerCase().contains(nameApp)) {
                targetedShare.putExtra(Intent.EXTRA_TEXT,     "My body of post/email");
                targetedShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(imagePath)) );
                targetedShare.setPackage(info.activityInfo.packageName);
                targetedShareIntents.add(targetedShare);
            }
        }

        Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Select app to share");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
        startActivity(chooserIntent);
    }
}

Display pictures of a specific folder in the Gallery app (StackOverflow)
To be continued.

mardi 13 novembre 2012

IP Routing

1. Routing Basics:

- static routing: the administrator must hand-type all network locations into the routing table;
- dynamic routing: a protocol on one router communicates with the same protocol running on neighbor routers. The routers then update each other about all the network they know about.
The command 'show ip route' display the routing table content.
In the command's output, the 'C' means that the networks listed are 'directly connected', and until adding a routing protocol (RIP, EIGRP, ...), we'll have only directed connected networks.

1.1. The IP Routing Process:

The command 'show ip arp' display the ARP cache, in the output, the dash (-) means that this is the physical interface on the router. Cisco routers will keep an entry in the ARP table for 4 hours.
"When a ping fail, most administrator think the packet never reached the destination host. Taht's not always the case, all it takes is for just one of the remote routers to be lacking a route back to the originating host's network and the packet is dropped on the return trip, not on its way to teh host".
If a packet is lost on the way back to the originating host, you'll get a "request time out" message because it is an unknown error. If the error occurs because of a known issue, such as if a route is not in the routing table on the way to the destination device, you will see a destination unreachable message.
Hardware addresses are always local, and they never pass a router's interface.

1.2. Testing Your IP routing Undestanding

In figure 6.7 (p 380), the Lab_A router has received the packet and will send it out Fa0/0 onto LAN toward the server. The source MAC address will be the Lab_A router's  Fa0/0 interface, and the destination will be the Sales server's MAC address. (All MAC addresses must be local on the LAN).
Host 4 is displaying two web documents from the Sales server in two different browser windows at the same time. TCP port numbers are used to direct the data to the correct application window.

1.3. Configuring IP Routing: (p 382)
steps to configure a router: erase startup-config, then reload, hostname, secret password, motd banner, interfaces (ip address, description, no shutdown, [rate clock, exec-timeout]), console, aux and telnet passwords, save a backup of the running config.
special configuration of a wireless interface, SSID is the Service Set IDentifier that creates a wireless network that hosts can connect to. The interface is a routed one, which is the reason why the IP address is placed under the physical interface--typically the IP address would be placed under he management VLAN or Bridge-Group Virtual Interface (BVI).
- The 'guest-mode' line means that the interface will broadcast the SSID so wireless hosts can connect to this interface.
- The 'Authentification open' means no authentification.
- The 'infrastructure-ssid' indicates that this interface can be used to communicate to other access points or other devices on the infrastructure.
Then, we need to configure the DHCP pool for the wireless clients:
- create the pool name 'ip dhcp pool Admin'.
- annd the network/subnet and gateway 'network 10.1.8.0 255.255.255.0', 'default-router 10.1.8.1'.
- exclude addresses you don't want handed out (like default gateway) 'ip dhcp excluded-address @'.

2. Configuring IP Routing in Our Network (p 403)

2.1. Static Routing:

It occurs when you manually add routes in each router's routing table.
ip route [destination_network] [mask] [next-hop_address or exitinterface] [administrative_distance] [perment].
- permanet: If the interface is shut down or the router can't communicate to the next-hop router, the route will automatically be discarded from the routing table. With this option you keep the entry in the routing table no matter what happens.

2.1.1. Corp

Each routing table automatically includes directly connected networks. To be able to route to all networks within the internetwork, the routing table must include information that describes where these networks are locaed and how to get them.

If you have two link between two routers, give to one a higher administrative-distance value, to make it a backup route if the other link fails. Static routing can't handle multiple links to the same destination. On the routing table, the route with the lower AD will be displayed only if the currently used link fails.
If you use exit interface instead of next-hop, you'll see the static routes as directly connected. And you don't need the "permanent" option.
To use default routing: ip route 0.0.0.0 0.0.0.0 10.1.11.1
                                ip classless
2.2. Default Routing: (p 415)
To create a default route, type:
      ip route 0.0.0.0 0.0.0.0 [next_hop or exit_interface]
      ip classless
If you show up the routing table, you'll see an S* which indicates that it's a candidate default route.
the command "ip default-network [next_hop]" can be used to define a default gateway.

3. Dynamic Routing (p 418)
Dynamic routing is when protocols are used to find networks and update routing tables. A routing protocol defines the set of rules used by a router when it commmunicates routing information between neighbor routers.

3.1. Routing Protocol Basics

3.1.1. Administrative Distances

The AD is used to rate the trustworthiness of routing information received on a router from a neighbor router. It is an integer from 0 (most trusted) to 255(means no traffioic will be passed via this route). If a router receives two updates listing the same remote network, the router checks the AD and choose the one with the lowest value to put in the routing table.
The following table show the default administrative distances used by a Cisco router.
Route Source            Default AD
Connected interface        0
Static route                     1
EIGRP                            90
IGRP                              100
OSPF                             110
RIP                                 120
External EIGRP             170
Unknown                       255 (this route will never be used)

3.1.2. Routing Protocols

- Distance vector: The route with the least number of hops to the network is determined to be the best route. Both RIP and IGRP are distance-vector routing protocols. They send the entire routing table to directly connected neighbors.
- Link state: alos called shortest-path-first protocols, each router create three tables, one keeps track to directly attached neighbors, one determine the topology of the entire internetwork, and one as the routing table. OPSF is completely link state.
- Hybrid: Those ones use aspects of bith type, like EIGRP.

4. Distance-Vector Routing Protocols (p 420)
The distance-vector routing algorithm passes complete routing table contents to neighboring routers. In case of having multiple links to the same network, the Administrative Distance is checked first. If the AD is same, the protocol will have to use other metrics to determine the best path.
RIP uses only hop count to determine the best path to a network. If more than one link exist for a remote network, RIP would consider them equal in term of cost. This little snag is called "pinhole congestion".

4.1. Routing Loops (p 421)
If a network ourtage happens, plus the slow convergence of distance-vector routing protocols can result in inconsistent routing tables and routing loops. Routings loops can occur because every router isn't updated simultaneously, or even close to it.

4.2. Maximum Hop Count:

The previous problem is called "counting to infinity", by defining a "maximum hop count" will allow solving that problem. RIP permits a hop count of up 15, anything that requires 16 hops is deemed unreachable and make the routing entries invalid.

4.3. Split Horizon:

The routing protocols differentiate which interface a network route was learned on, and once this is determined, it won't advertise the route back out that same interface.

4.4. Route Poisoning

When a network goes down, the directly attached router (router A) initiates route poisoning by advertising or unreachable (sometimes referred to as infinite). This poisoning of the route keeps the router B from being susceptible to incorrect updates about the route to network. When router B receives a route poisoning from RouterA, it sends an update, called a "poison revers" back to RouterA. This ensures that all routes on the segment have received the poisoned route information.

4.5. Holddowns

It prevents regular update messages from reinstating a route that is going up and down (called flapping). It prevents routes from changing too rapidly by allowing time for either the downed route to come back up or the network to stabilize somewhat before changing to the next best route. This also tell routers to restrict, for a specific time period, changes that might affect recently removed routes.

5. Routing Information Protocol (RIP) (page 424)
RIP sends hte complete routing table out to all active interfaces every 30s. RIP works well with small network. RIPv1 is classful (doesn't send subnet mask related information) instead of RIPv2 which is classless, it provides something called prefix routing and send subnet mask related information.

5.1. RIP Timers

- Route update timer: sets the interval between periodic routing updates.
- Route invalid timer: Determines the time that must elapse (180s) without receiving route updates to deemed that a route has become invalid.
- Holddown timer: Sets the amount of time during which routing information is suppressed. Routes will enter into holddown state when an update packet is received that indicated the route is unreachable. this continues either until an update packet is received with a better metric or until the holddown timer expires.
- Route flush timer: Sets the time between a route becoming invalid and its removal from the routing table.

5.2. Configuring RIP Routing

To configure RIP routing, use "router rip" and tell the RIP routing protocol which networks to advertise "netword remote_network".

5.3. Verifying the RIP Routing Tables (p 428)
5.4. Configuring RIP Routing Example 2

5.5. Holding Down RIP Propagations

The "passive-interface" command prevents RIP updates from being sent out a specified interface, yet that same interface can still receive RIP updates.

5.6. RIP Version 2 (RIPv2)

RIPv2, unlike RIPv1, is a classless routing protocol, it can support Variable Length Subnet Masks (VLSMs) as well as the summarization of network boundaries. It can support discontiguous networking.
example:
router rip
network 192.168.40.0
network 192.168.50.0
version 2
6. Interior Gateway Routing Protocol (IGRP) p 433
The main difference between RIP and IGRP is that when configuring IGRP, you supply the autonomous system number. All routers must use the same number in order to share routing table information.
IGRP is no longer supported in CISCO routers, use instead EIGRP.
7. Verifying Your Configurations (p 434)
The following commands can be used to verify the routed and routing protocols configured on CISCO routers:
- show ip route
- show ip protocols
- debug ip rip

7.1. The show ip protocols Command

This command shows you the routing protocols that are configured on the router.
- Troubleshooting with the show ip protocols Command
use command "show ip protocol" and "show ip interface brief" to see which interfaces are in a specific network.

7.2. The debug ip rip Command:

This command display, at the session console, the routing updates as they are sent and received. If you're telnetted to a router you've to use the terminal monitor command to view the debug output.

Managing a Cisco Internetwork

1. The Internal Components of a Cisco Router:

The following are the router's components:
- Bootstarp: It will boot the router and then load the IOS.
- POST: Power-On-Self-Test used to check the router's hardware functionality.
- ROM monitor: used for testing and troubleshooting.
- Mini-IOS: called RXBOOT, it's used to load the router IOS into a flash memory.
- RAM: used to hold data (packet, ..).
...

2. Managing Configuration Register:

You can see the current value of the configuration register by using the "show version" command.

2.1. Changing the Configuration Register:

You can change the configuration register value to modify how the router boots and runs. The change can be done using: config-register 0x2101.
The command 'show flash' will show the flash content.


2.2. Recovering Passwords: p 299
The default configuration register value is 0x2102, when loading the router look for configuration stored in NVRAM. To recover a password and ignore the NVRAM content, turn on bit 6. The configuration will become 0x2142.
Here are the main steps to password recovery:
- Iterrupting the Router Boot Sequence: press Ctrl+Break to interrupt the router boot.
- Changing the configuration register: use the 'config-register' command. On Cisco ISR/2600 Series Commands 'confreg 0x2142', Cisco 2500 series, enter 'o/r' followed by the new register value.
- Reloading the Router and Entering Privileged Mode: From the ISR/2600 series type 'I' or 'reset', from a 2500 series type 'I'. When reloading, answer no to enter setup mode.
- Viewing and changing the configuration: copy the startup to the running config file. While you can't view the password since it is encrypted, change the password using the 'enable secret' command.
- Resetting the configuration register and reloading the router: after changing the password, return back the register value to 0x2102.
Finally, save the new configuration to the startup an reload the router.

2.3. Boot System Commands: p 302.
-The 'boot system' command allow you to tell the router which file to boot from flash memory. By default, the router boots the first file found in flash.
-The 'boot system tftp file_name host_addr' command makes your routers boot from TFTP host.
-The 'boot system rom' command loads the mini-IOS from ROM.

3. Backing Up and Restoring the Cisco IOS:

3.1. Verifying Flash Memory:

You can verify the amount of flash memory and the files being stored in flash by using the 'show flash' command.
The 'show version' command shows the actual name of the file that the router is using to run the router.

3.2. Backing Up the Cisco IOS:

To back up the Cisco IOS to a TFTP server, use the 'copy flash tftp' command which will ask you then the server address or name. You have to check the connectivity to the tftp server beforte backing up the IOS.

3.3. Restoring or Upgrading the Cisco Router IOS:

You can download a file from a tftp server to flash by using the 'copy tftp flash' command. Make sure that the file is in the default directory of the tftp server.

3.4. Using the cisco IOS File System (Cisco IFS):

Cisco IFS is a file system that allows you to work with files and directories. The commands you use are dir, copy, more, delete, erase or format, cd and pwd, mkdir and rmdir.
The 'delete' command doesn't free up the space used by the deleted file. To free it up use the command 'squeeze'.
Remember that the IOS is expanded into RAM when the router boots, so the new IOS will not run until you reload the router.

4. Backing Up and Restoring the Cisco Configuration:

4.1. Backing Up the Cisco Router Configuration:

You can use 'copy running-config tftp' or 'copy startup-config tftp' to back up the router configuration that's currently in DRAM or in NVRAM.

4.2. Copying the Current Configuration to NVRAM:

You can use startup-config as a back up, and the current config will be reloaded as the router reboot.

4.3. Copying the Configuration to a TFTP Server: p 317
You can make a back up of the running-config to a tftp server using 'copy running-config tftp'. To restore the configuration use 'copy tftp running-config' or 'copy tftp startup-config'.

4.4. Erasing the Configuration:

To delete the stratup-config file use the command 'erase startup-config'. If you relaod without saving changes, you'll be directed to setup mode.

5. Using Cisco Discovery Protocol (CDP):

It's a proprietary protocol designed to collect information about locally attched and remote devices.

5.1. Getting CDP Timers and Holdtime Information:

The 'sh cdp' command gives you information about two global parameters:
- CDP timer is how often CDP packets are transmitted out all active interfaces;
- CDP holdtime is the amount of time that the device will hold packets received from neighbor devices.
The commands 'cdp holdtime' and 'cdp timer' allows to configure the CDP's.
Use 'no cdp run' to turn off cdp, 'no cdp enable' and 'cdp enable' to turn off or on for an interface.

5.2. Gathering Neighbor Information:

The 'show cdp neighbor' command delivers information about directely connected devices. CDP packet aren't passed through a Cisco switch.
The 'show cdp neighbors detail' can be run on a router or a switch, it displays detailed information about each directly connected device.
The 'show cdp entry *' command displays the same information as the previous command, but has two options. 'show cdp entry * protocols' display only the ip address of the directly connected devices, 'show cdp entry * version' show only the IOS version.

5.3. Gathering Interface Traffic Information:

The 'show cdp traffic' command displays information about interface traffic, including the number of CDP packets sent and received and errors with CDP.

5.4. Gathering Port and Interface Information:

The 'show cdp interface' gives you the CDP status on router interfaces or switch ports. You can turn off the cdp on a per-interface basis with 'no cdp enable' from the interface configuration mode. You enable a port with 'cdp enable'.

5.5. Documenting a Network Topology Using CDP:

You have a router with a four interfaces, two FastEthernet and two Serial. First, determine the IP addresses of each interface by using the 'show running-config'.
Next, you need to determine the type of device on the others end of each of these interfaces by using 'show cdp neighbors'. Now you know about all the IP addresses of the router plus the types of routers connected to each of its interfaces.
And so you can reveal the network topology. We could've also used the 'show cdp neighbors detail' to view the neighbor's IP addresses.

6. Using Telnet: p 336
On a cisco router, when typing an IP address it assume that you want to telnet to the device. The VTY password is the user-mode password, not enable-mode's one.
To allow console messages to be sent to your Telnet session, use the 'terminal monitor' command.

6.1. Telnetting into Multiple Devices Simultaneously:

You can end a telnet session by typing 'exit', to return to the original router console without closing the telnet session press 'Ctrl+Shift+6', then X.

6.2. Checking Telnet Connections:

To see the connections made from your router to a remote device use 'show sessions'. Youis last session will be prefixed by an asterisk. You can return to a session by typing the number of the connection.

6.3. Checking Telnet Users:

You can list all active consoles and VTY ports in use on your router with 'show users'. In the output, 'con' represent local console. 'vty' has an IP address connected to the local device.

6.4. Closing Telnet Sessions:

To end a telnet session enter 'exit' or 'disconnect' (from a local device and specifying the sessin number). To end a session of a device attached to the local device through Telnet, first check if any devices are telnetted into your router by 'show users', then to clear the connection, use 'clear line #' (# is port number).

7. Resolving Hostnames:

7.1. Building a Host Table:

A host table provides name resolution only on the router that it was built upon. It can be built by 'ip host  host_name tcp_port_number ip_address'. You can assign up to eight IP addresses to a hostname. 'show hosts' to view the table.
If you want to remove a hostname from the table use 'no ip host' command.

7.2. Using DNS to Resolve Names:

When typing anything that can't be understood by the device, it try to resolve it using DNS, you can prevent a time-consuming DNS lookup by using 'no ip domain-lookup'. If you have a DNS server, the following steps make DNS  
name resolution work:
- 'ip domain lookup' is turned on by default;
- 'ip name-server' sets the up to six IP addresses of the DNS server.
- 'ip domain-name' (optional). It appends the domain name to the hostname you type in, you must have a full DNS name like domain.com .

8. Checking Network Connectivity and Troubleshooting:

8.1. Using the ping Command:

Type 'ping ?' to see the different protocols that you can use with the ping program. The ping can be used in user and privileged mode, but not in configuration mode.

8.2. Using the traceroute (trace) Command

It shows the path a packet takes to get to a remote device. It show you which router in the path to an unreachable network host should be examined more closely for the cause of the network's failure.

8.3. Debugging (p 349)
Debug command is used to display information about various router operations and the related traffic generated or received by the router. Type 'debug ?' to see all options. To disable debugging 'no debug all' or 'undebug all'.

8.4. Using the show processes Command:

The 'show processes' (or 'show processes cpu') to determine a given rouuter's CPU utilization. It will give a list of active processes along with their corresponding process ID, priority, scheduler test (status), CPU time used, number of times invoked.

Introduction to TCP/IP

1. The Process/Applicationn Layer Protocols:

1.1. Simple Mail Transfert Protocol (SMTP):

SMTP is used to send mail, POP3 to receive mail.

1.2. Line Printer Daemon (LPD)

It is designed for printer sharing. The LPD, along with the Line Printer (LPR) program, allows print job to be spooled and sent to the network's printer using TCP/IP.

1.3. X Window:

It defines a protocol for writing client/server application based on a graphical user interface (GUI). Allow a program (client) to run on one computer and have it display through a window server on another computer.

1.4. Simple Network Management Protocol (SNMP)

It collects and manipulates valuables network information. It gathers data by polling the devices on the network from a management station each intervals. When all is well, SNMP receives something called a baseline -- a report delimiting the operational traits of a healthy network. Agent (SNMP stand as a watchdog over the network) send trap to management station.

1.5. Domain Name Service (DNS):

DNS is used to resolve a Fully Qualified Domain Name (FQDN); this one is a hierarchy that can logically locate a system based on its domain identifier.
If you want to resolve the device toad, you must enter the FQDN, or let your router adding the suffix by configuring it such: ip domain-name lammle.com to append this suffix to all resolvation requests.

1.6. Dynamic Host Configuration Protocol (DHCP)/Bootstrap Protocol (BootP):

BootP assigns an IP address to a host but the host's hardware address must be entered manually in a BootP table. DHCP is a dynamic BootP. BootP is also used send an operation system that a host can boot from. DHCP can't do that.
When a host is requesting an IP address by sending a DHCP Discover message, the DHCP server (which can be any device) send the following information:
IP address, Subnet mask, domain name, default gateway (routers), DNS, WINS information.


2. The Host-to-Host Layer Protocols:


2.1. Transmission Control Protocol (TCP) (p 116)
TCP is full-duplex, connection-oriented, reliable, and accurate protocol, establish error checking.

2.1.1. TCP Segment Format:

The TCP header is 20 bytes long (up to 24 bytes with options):
 - Source port: 2 bytes for port number of the sender application.
 - Destination port: port number of the destinated application.
 - Sequence number: A number used by TCP that puts data back in the correct order.
 - Acknowledgment number: The next TCP octet expected.
 - Header length: indicates where the data begins.
 - Reserved: always set to zero.
 - Code bits: (6-bits), control functions used to set up and terminate a session.
 - Window: The window size the sender is willing to accept, in octets.
 - Checksum: The CRC checks the header and data fields.
 - Urgent: A valid field only if the Urgent pointer is put in the code bits. The value indicates the offset from the current sequence number, in octets, where the first segment of non-urgent data begins.
 - Options: May be 0 or a multiple of 32 bits.
 - Data:

2.2. User Datagram Protocol (UDP)

2.2.1. TCP vs UDP:

The cost in overhead to establish, maintain, an dclose a TCP connection would reduce efficient network. Use UDP instead of TCP when reliability is already handled at the Process/Application layer.
UDP is a connectionless protocol, it doesn't create a virtual circuit, nor does it contact the destination before delivering information.
2.2.2 UDP Segment Format:
- Source port;
- Destination port;
- Length of UDP header and data;
- Checksum of both UDP header and data;
- Data.

2.3. Key Concepts of Host-to-Host Protocols (TCP vs UDP, p 120)
2.4 Port Numbers (p 121)
The different port numbers that can be used are explained next:
- Numbers below 1024 are considered well-know port numbers and are defined in RFC 3232.
- Numbers 1024 and above are used by the upper layers to set up sessions with other hosts and by TCP.
2.4.1. TCP Session: Source port
The source make up a port number ro differentiate between sessions with different hosts. How would a server know where information is coming from if it didn't have a different number from a sending host. It's easy to imagine the receiving host getting throughly confused if all the hosts used the same source port number to get to FTP.

2.4.2. TCP Session: Destination Port

Sometimes when looking to an analyzer, we can see that only the source port is above 1024 and the destination port is a well-known port.

2.4.3. TCP Session: Syn Packet Acknowledgment

TCP protocols                      UDP Protocols
TELNET (23)                             SNMP  (161)
SMTP    (25)                             DNS     (53)
HTTP    (80)
FTP       (21)
DNS      (53)
HTTPS  (443)

3. The Internet Layer' Protocols:

IP provide routing fnctionalities, and a single network interface to upper layers (no need to build different application's version for evry network Ethernet, Token Finder,..).

3.1. Internet Protocol (IP): (p 125)

Internet Protocol (IP)  essentially is the Internet layer. The other protocols found here merely exist to support it. The following fileds make up the IP header:
- Version: IP version number;
- Header length: HLEN in 32-bits word;
- Priority and Type of Service: Type of service tells how the datagram should be handled. The first 3-bits are for priority;
- Total length: packet length including header and data;
- Identification: Unique IP-packet value;
- Flags: specifies whether fragmentation should occur;
- Fragment offset: provides fragmentation and reassembly if the packet is too large to put in a frame;
- Time to Live: This stopes IP packets from continuously circling the network looking for a home;
- Protocol: Port of upper-layer protocol (TCP is port 6, UDP is port 17 [hex]). Also supports Network layer protocols, like ARP and ICMP.
- Header checksum: CRC of the header;
- Source IP address: 32-bits IP address of sending station;
- Destination IP address: 32-bits of the destinated station;
- Options: Used for network testing, debugging, security, and more;
- Data: upper-layer data.

3.2. Internet Control Message protocol (ICMP): (p 128)
ICMP packets have the following characteristics:
- They can provide hosts with information about network problems;
- They are encapsulated within IP datagrams.
The following are some commen events and messages that ICMP relates to:
3.2.1. Destination Unreachable:
If a router can't send an packet, it uses ICMP to send back a message to the sender, advising it of the situation.
3.2.2. Buffer Full:
If a router's memory is full, it use it to send out this message.
3.2.3. Hops:
Uesed to inform the sender that its packet have been dropped by the last router after the hop packet get its limit.
3.2.4. Ping (Packet Internet Groper):
Ping uses ICMP echo request and reply messages to check the logical and physical connectivity of machines.
3.2.5. Traceroute:
Using ICMP time-outs to discover the path a packet takes as it traverses an internetwork.

3.3. Address Resolution Protocol (ARP):

It finds the hardware address of a host from a known IP address. ARP interogates the local network by sending out a broadcast asking the machine with the specified IP address to reply with its hardware address.

3.4. Reverse Address Resolution Protocol (RARP):

If a host is looking to its IP address, it send a RARP request to a RARP server with its MAC address, the server will respond with the answer and the identity crisis is over.

3.5. Proxy Address Resolution Protocol (Proxy ARP):

When a router turns down, the host won't immediately start sending ro another one -- it must be configurate. Proxy ARP can help machines on a subnet reach remote subnets without configuring routing. Proxy ARP is added as a service to the router, and is enabled by default. Using it imply host to have a larger ARP table in order to handle all the IP-to-MAC address mappings. Disable it if you don't have to use it.

4. IP Addressing (p 133)

4.1. The Hierarchical IP Addressing Scheme:

4.1.1. Network Addressing: (p 135)
Class A: Network .    Host    .    Host    . Host
Class B: Network . Network .    Host    . Host
Class B: Network . Network . Network . Host
Class D: Multicast
Class E: Research

4.1.1.1. Network Address Range: Class A
The first byte in a Class A must always be 0. It is between 0 and 127.
4.1.1.2. Network Address Range: Class B
In a Class B, the first bit of the first byte is 1, the second bit must always been 0.
Class B addresses are between 128 and 191.
4.1.1.3. Network Address Range: Class C
The first 2 bits of the first byte are set to 1, the third is always 0.
The range of addresses is from 192 to 223.
4.1.1.4. Network Address Range: Class D and E
you don't need them, Class D (224-239) is for multicast addresses.
Class E (240-255) is form scientific purposes.
4.1.1.5. Network Addresses: Special Purpose
- Network address of all 0s: Interpreted to mean "this network or segment".
- Network address of all 1s: Interpreted to mean "all networks".
- Network 127.0.0.1: reserved to loop back tests.
- Node address of all 0s: Interpreted to mean "network address" or any host on specified network.
- Node address of all 1s: Interpreted to mean "all nodes" on the specified network, ex: 128.2.255.255.
- Entire IP address set to all 0s: Used by Cisco routers to designate the default route.
- Entire IP address set to all 1s: Broadcast to all nodes on the current network.

Class A Addresses (p 137)
The network address 0000 0000 is reserved to designate the default route.
The address 127 is reserved for diagnostics.

4.1.2. Private IP Addresses:

Private IP addresses can be used on a private network, but they're not routable through the Internet. By using private IP addresses, users need a tiny group of bona fide IP addresses to connect their network to Internet. To accomplish that, they need Network Address Translation (NAT). Which convert a private IP address for use on the Internet.
Class A private address range is 10.0.0.0 through 10.255.255.255 .
Class B private address range is 172.16.0.0 through 172.31.255.255 .
Class C private address range is 192.168.0.0 through 192.168.255.255 .

5. Broadcast Addresses (141)
There is 4 type:
- Layer 2 broadcasts  : These are sent to all nodes on a LAN. hardware broadcast has the address FF.FF.FF.FF.FF.FF.
- Broadcasts (layer 3): These are sent to all nodes on the network. Broadcast message are meant to reach all hosts on a broadcast domain. (Network Broadcast).
- Unicast                    : These are sent to a single destination hosts.
- Multicast                 : These are packets sent from a single source and transmitted to many devices on different networks.

Unicast it's a broadcast that goes from 255.255.255.255 to an actual destination IP address, it's directed to a specific host, like a DHCP client request.

Multicast does allow point-to-multipoint communication. It works by sending messages to IP multicast group addresses, routers then forward copies out every interface that has hosts 'subscribed' to that group address. Like EIGRP packets.
The range of multicast addresses starts with 224.0.0.0 and goes through 239.255.255.255 . This range falls within IP Class D.