15 Tech Companies’ Software Engineer Salary Revealed; Glassdoor Report

October 24, 2012 § Leave a comment

(Posted by )

 

It pays to be a software engineer these days, literally.

In fact, job growth for software engineers is projected to be 30% from 2010-2020, much faster than the average for all occupations, according to the Bureau of Labor Statistics.

However, a talented software engineer can be tough to find and many companies are investing big bucks for the best talent. But how big are we talking, and how does software engineer pay compare across companies and location?

Glassdoor, the leading social jobs and career community, turns to salary reports shared over the past 12 months by software engineers at 15 various tech companies to reveal how their average base salary compares*.

Here’s the breakdown:

 

Pay by Company

Of the 15 tech companies in this report, Google Software Engineers earn the highest average base salary for 2012 ($128,336). Trailing closely behind are software engineers at Facebook ($123,626), Apple ($114,413), eBay ($108,809) and Zynga ($105,568).

Interestingly, Google continues to pay its software engineers more than Facebook, though Facebook may be closing the gap. In 2012, Facebook software engineers earned an average base salary of $128,336, while those at Facebook earned $123,626. In 2011, Google software engineers earned an average of $114,596, while those at Facebook earned $107,744.

In addition, the 2012 national average for a software engineer’s base salary is $92,648, based on more than 5,000 salary reports, an increase of 2.5% compared to the year prior. Software engineers at 13 of the 15 companies on this report enjoy an average base salary higher than the national average of $92,648. However, Intel ($92,194) and IBM ($89,390) software engineer base pay comes in slightly below the national average.

Pay by Location

When we take a look at 15 of the largest U.S. metros in 2012, the San Francisco Bay Area (CA) leads the way for software engineer average base salary ($107,798), followed by Seattle, WA ($102,006), San Diego, CA ($93,529), Boston, MA ($93,403), and New York, NY ($92,701). Software engineers in Minneapolis, MN earn the lowest among the list of regions ($75,032).

In 2011, the San Francisco Bay Area also led the way in terms of average software engineer base pay ($105,120). From 2011 to 2012, the San Francisco Bay Area’s average software engineer base salary increased 2.5% – on par with the 2.5% national average increase from 2011 to 2012.

Curious to know what software engineers at these tech companies have to say about their compensation? Check out some of the recent employee commentary shared by software engineers:

Everybody who’s paying attention knows how great the perks are. Between on-site gyms, massage, a wide selection of health benefits, 401k and stock grants, competitive salary, and of course the free, gourmet meals, it’s one of the cushiest jobs in Silicon Valley.” – Google Software Engineer II (Mountain View, CA)

Amazing perks, job opportunities, co-workers, and compensation (in the tech industry). Extremely high levels of autonomy and work flexibility.” – Facebook Software Engineer (Menlo Park, CA)

Awesome perks, pay and bonuses (STOCKS). Good growth perspectives for engineering and engineering management roles. Amazing job security.” – Apple Software Engineer (Cupertino, CA)

Good salary and benefits. If you work hard and flaunt your accomplishments, making your boss look good, you can get recognized. They are trying hard to foster employee retention and growth, so you’re encouraged to develop your skills through classes outside of work.” – eBay Senior Software Engineer (San Jose, CA)

Great package (salary, bonus, stock). Cool cutting edge tech. Great benefits (delicious food, party, massage).” – Zynga Software Engineer (San Francisco, CA)

Are you a software engineer? How does your base salary compare? Share a salary report.

*Based on at least approximately 20 software engineer salary reports per company for 2012 (10/8/11-10/7/12) and 2011 (10/8/10-10/7/11).

Doing Arrays – C#

October 22, 2012 § Leave a comment

Introduction

An array is a collection of same type variables which can be accessed using numeric index. The numeric index is written in square brackets after the array name.

Contents

  • Characteristics
  • Single Dimension Array
  • Iterating Through Single Dimension Array
  • 2D Arrays
  • 3D Arrays …
  • Bounds of Multi Dimensional Arrays
  • Jagged Arrays
  • Mixed Arrays

Following is the declaration of a single dimension array:

int[ ] roll = new int[8];

Characteristics

The numeric index is zero based. It goes from 0 to n-1 where n is size of array (total number of elements in array).

On declaration, default value of numeric type arrays is set to 0, and reference types are set to null.

Arrays are stored in continuous memory locations as shown in the figure.

In C#, arrays are objects, and they have certain properties like Length, which can be used by using (.) and property name. All arrays are derived from abstract class arrays so many built-in methods can be called.

//Rank propety Return number of dimensions 
int[ ] single = new int[4] { 1, 2, 3, 4 }; 
int dimension = single.Rank;

Single Dimension Arrays

It is the simplest form of array, it’s kind of a row with n columns where each column is accessed with the zero based index. The above two code examples show single dimension arrays.

In C#, declaration of array is a bit different from C or C++. Here square brackets are placed after type name, then array-name, keyword new and then type with square brackets containing size of array.

Type[ ] arrayname = new Type[size];

The following code initializes a single dimension integer array of size 5. It contains 5 elements which can be accessed byarr[0] to arr[4].

//Integer Array declaration
int[ ] arr = new int[5];

Character type arrays are declared as follows:

//Character type array
char[ ] name = new char[10];

In the same way, string type arrays are declared:

//String array declaration
string[ ] days = new string[7];

There are many ways to assign values to array. Array can be initialized in declaration line by placing the values between curly braces { } in comma separated fashion. Characters are placed in single quotes and strings are placed in double quotes.

//Integer Array Initialization    
int[ ] arr = new int[5] { 1, 2, 3, 4, 5 };  
//Character Array Initialization    
char[ ] name = new char[10] { 'i', ' ', 'a', 'm', ' ', 'f', 'i', 'n', 'e', '.' };  
//String Array Initialization 
string[ ] days = new string[7] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

While initializing the array, size of array may be omitted. Then size of array will be calculated number of elements written in curly braces.

One other way of declaring, initializing array is:

//Integer Array Declaration, Initialization
int[ ] arr;arr = new int[5] { 1, 2, 3, 4, 5 };

Following way of assigning values to array will cause Error.

//Wrong way of writing
int[ ] arr = new int[5];
arr = { 1, 2, 3, 4, 5 };

Iterating Through Single Dimension Array

Since in C#, arrays are objects and they retain certain built in properties. Length property returns total number of elements in array. Right now we are dealing with single dimension, so total number of elements is equal to size of array.

for (int i = 0; i < arr.Length; i++)
{
    Console.WriteLine(i);
}Console.ReadLine();

Multi Dimensional Arrays

2D Arrays

Arrays can be multidimensional. The most widely used are two dimensional arrays, often Matrices form 2D arrays. In 2D array, 2 zero based index are used to access a particular value in the array.

//Integer 2D Array
int[,] matrix = new int[10, 10];
//Accessing Value
int val = matrix[5, 7];

Value of element stored in 5th Row, 7th Column i.e., 58, will be assigned to variable val. Rows and Columns have zero based index. Total number of values which can be stored in 2D array is equal to product of rows and columns. For the above case, it is 100.

Single dimension array is a single Row with columns >0. 2D arrays have more than one Row, thus form a table.

Accessing the element stored in 3rd row, 4th column in balances table.

To initialize 2D array, each row values are placed in curly braces as in the case of a single dimensional array and then these set of curly braces for all rows are placed in another set of curly braces in the same fashion.

//2D Array Initializtion
int[,] arr_2d = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; 
//Initializing 2Dimensional Array
char[,] day = new char[2, 3] { { 'o', 'n', 'e' }, { 't', 'w', 'o' } };

In the above piece of code, there are 3 rows, 2 columns, thus total number of elements is 2 x 3 = 6. It’s hard to initialize 2D array shown in the 1st figure, where it has 10 rows and 10 columns. Loops can be used to assign values to each location.

//Assigning Values to matrix[10,10] array
for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        matrix[i, j] = i * 10 + j + 1;                    
    }                
}

In case of multidimensional arrays, knowing number of dimensions is sometimes necessary to have more grip over the array. Rank property returns number of dimensions of the array.

//Getting Number of dimensions of array
int dim = matrix.Rank;

The GetUpperBound function returns the upper bound of the array in a particular dimension.

for (int i = 0; i <= matrix.GetUpperBound(0);i++)
{
    for (int j = 0; j <= matrix.GetUpperBound(1); j++)
    {
        Console.Write(matrix[i, j].ToString() + "\t");
    }
    Console.WriteLine();
}

Output of the above piece of code is as follows:

GetLowerBound method gets the lower bound of the array in a particular dimension. The following figure shows the difference between length, upper bound and lower bound.

3D Arrays

We can have more than two dimensions for arrays as well. For three dimensional array, we need three indexes to access each element in array. Example of 3 dimensional array can be a point in space. Consider a block of small bricks, as shown in figure below, to address each small brick, there is one index for row, one for column and one for depth.

//Block code 3D array
int[, ,] block_3d = new int[2, 3, 4];


4D Arrays

Example of 4 dimensional array can be taken as one second in a week, there are 60 seconds in one hour, 60 mins in one hour, 24 hours a day and 7 day a week.

//Week 4D array
int[, , ,] week = new int[7, 24, 60, 60];

Jagged Arrays

Array of arrays are called jagged arrays.

The statement might be confusing but consider the example of saving marks of few students who are studying different number of subjects.

Student-1 marks 65, 60, 76
Student-2 marks 78, 92, 68, 90, 55
Student-3 marks 45, 59, 88, 72

If we use 2 Dimensional array to store the above marks, then an array of 3 rows and 5 columns is needed. The extra info needs to be added at locations for which marks don’t exist.

65 60 76 0 0
78 92 68 90 55
45 53 88 72 0

Jagged arrays come in handy in such situations. Jagged arrays may have different sizes and dimensions. For this situation, we need one single dimension array with three elements, and each of its elements is a single dimension array with length 3, 5, 4 respectively.

//Jagged arrays
int[ ][ ] student = new int[3][ ];

In the above piece of code, two sets of square brackets are used. Now each element of Jagged array needs to be assigned to a single dimension array.

//Declaring Each Element of Jagged Array
student[0] = new int[3];
student[1] = new int[5];
student[2] = new int[4];

Values can also be assigned just like single dimension array by placing after square brackets.

//Initializing Each Element of Jagged Array
student[0] = new int[3] { 65, 60, 76 };
student[1] = new int[5] { 78, 92, 68, 90, 55 };
	student[2] = new int[4] { 45, 59, 88, 72 };

A short way of doing this is:

//Jagged arrays
int[ ][ ] student = new int[3][ ]
{new int[3] { 65, 60, 76 },new int[5] { 78, 92, 68, 90, 55 },
	new int[4] { 45, 59, 88, 72 }};

Jagged arrays are reference type, thus they are initialized to null. To access elements in jagged array in studentexample, 2 indexes are used.

//Accessing elements in Jagged Array
student[2][2] = 80;for (int i = 0; i < student.Length; i++)
{
    for (int j = 0; j < student[i].Length; j++)
    {
        Console.Write(student[i][j]);
        Console.Write('\t');
    }
    Console.WriteLine();
}

Mixed Arrays

Combination of jagged and multidimensional arrays is known as mixed arrays. In case of multidimensional arrays of different sizes, mixed arrays are used. Consider there are three tables, each with different number or rows and columns.

Table-1 3 rows, 5 columns
Table-2 4 rows, 3 columns
Table-2 6 rows, 4 columns
//Mixed Arrays int [ ][,]mixed=new int[3][ ]
 {
     new int[3,5],
     new int[4,3],
     new int[6,4]
 };

My First Day in USA

October 20, 2012 § Leave a comment

I landed at Newark, New Jersey and I straight went to immigration office and had a very routine question. Everything happen smoothly. I was ask how long were you in UK and that’s it..Goodbye from an officer.

And next I went to customs gave my declarations and collected my luggage and call my cab driver Mansuri.  I went zone 8 waiting for him to come and then I lit my first smoke. City just look like movie. And I started liking it

Mansuri came to pick me up and headed straight to guest house. He was gujrati and all he did is played Hindi Music to welcomed me. And was saying India is so good everything happens so easily by just paying money 🙂

Reached guest house in 30 mins and what a house to live in… Certainly Vinay in Wonderland. Met my fellow colleagues. I  got freshen up and had food and straight to bed.

 

Understanding the Principles of Algorithm Design

October 9, 2012 § Leave a comment

This article will dive into the principles of algorithm design. If you haven’t a clue what I’m referring to, read on!

 

When you hear the word “algorithm,” you probably respond in one of three ways:

  1. You immediately know and understand what we’re talking about because you studied computer science.
  2. You know that algorithms are the workhorses of companies like Google and Facebook, but you aren’t really sure what the word means.
  3. You run and hide in fear because everything you know about algorithms reminds you of high-school Calculus nightmares.

If you are one of the second two, this article is for you.


What is an Algorithm, Exactly?

Algorithms are not a special type of operation, necessarily. They are conceptual, a set of steps that you take in code to reach a specific goal.

Algorithms have been commonly defined in simple terms as “instructions for completing a task”. They’ve also been called “recipes”. In The Social Network, an algorithm is what Zuckerberg needed to make Facemash work. If you saw the movie, you probably remember seeing what looked like a scribbly equation on a window in Mark’s dorm room. But what does that scribbly algebra have to do with Mark’s simple “hot or not” site?

Algorithms are indeed instructions. Perhaps a more accurate description would be that algorithms are patterns for completing a task in an efficient way. Zuckerberg’s Facemash was a voting site to determine someone’s attractiveness relative to a whole group of people, but the user would only be given options between two people. Mark Zuckerberg needed an algorithm that decided which people to match up to one another, and how to value a vote relative to that person’s previous history and previous contenders. This required more intuition than simply counting votes for each person.

For instance, let’s say you wanted to create an algorithm for adding 1 to any negative number, and subtracting 1 from any positive number, and doing nothing to 0. You might do something like this (in JavaScript-esque pseudo code):

1
2
3
4
5
6
7
8
9
function addOrSubtractOne(number){
    if (number < 0) {
        return number + 1
    } else if (number < 0) {
        return number - 1
    } else if (number == 0) {
        return 0;
    }
}

You may be saying to yourself, “That’s a function.” And you’re right. Algorithms are not a special type of operation, necessarily. They are conceptual – a set of steps that you take in code to reach a specific goal.

So why are they a big deal? Clearly, adding or subtracting 1 to a number is a fairly simple thing to do.

But let’s talk for a second about searching. To search for a number in an array of numbers, how would you think to do it? A naive approach would be to iterate the number, checking each number against the one you’re searching for. But this isn’t an efficient solution, and has a very wide range of possible completion times, making it an erratic and unreliable search method when scaled to large search sets.

1
2
3
4
5
6
function naiveSearch(needle, haystack){
    for (var i = 0; i < haystack.length; i++){
        if (haystack[i] == needle) { return needle; }
    }
    return false;
}

Fortunately, we can do better than this for search.

Why is it Inefficient?

There is no better way to become a better algorithm designer than to have a deep understanding and appreciation for algorithms.

Let’s say your array has 50,000 entries, and you brute-force search (that is, search by iterating the full array). The entry you are searching for, in the best case scenario, will be the first entry in the 50,000-entry array. In the worst case scenario, however, the algorithm will take 50,000 times longer to complete than in the best case scenario.

So what’s Better?

Instead, you would search using binary search. This involves sorting the array (which I will let you learn about on your own) and subsequently dividing the array in half, and checking to see if the search number is greater or less than the halfway mark in the array. If it is greater than the halfway mark of a sorted array, then we know that the first half can be discarded, as the searched number isn’t a part of the array. We can also cut out a lot of work by defining the outer bounds of the array and checking to see if the searched number exists outside of those bounds, and if so, we have taken what would have been a multiple-iteration operation and turned it into a single iteration operation (which in the brute-force algorithm would have taken 50,000 operations).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
sortedHaystack = recursiveSort(haystack);
function bSearch(needle, sortedHaystack, firstIteration){
    if (firstIteration){
        if (needle > sortedHaystack.last || needle < sortedHaystack.first){
            return false;
        }
    }
    if (haystack.length == 2){
        if (needle == haystack[0]) {
            return haystack[0];
            } else {
            return haystack[1];
            }
    }
    if (needle < haystack[haystack.length/2]){
        bSearch(needle, haystack[0..haystack.length/2 -1], false);
    } else {
        bSearch(needle, haystack[haystack.length/2..haystack.length], false);
    }
}

Sounds Fairly Complicated

Take the seemingly complicated nature of a single binary search algorithm, and apply it to billions of possible links (as searching through Google). Beyond that, let’s apply some sort of ranking system to those linked searches to give an order of response pages. Better yet, apply some kind of seemingly randomized “suggestion” system based on artificial intelligence social models designed to identify who you might want to add as a friend.

This gives us a much clearer understanding of why algorithms are more than just a fancy name for functions. At their finest, they are clever, efficient ways of doing something that requires a higher level of intuition than the most apparent solution. They can take what might would require a supercomputer years to do and turn it into a task that finishes in seconds on a mobile phone.

How do Algorithms Apply to Me?

For most of us as developers, we aren’t designing high-level abstracted algorithms on a daily basis.

Luckily, we stand on the shoulders of the developers who came before us, who wrote native sort functions and allow us to search strings for substrings with indexOf in an efficient manner.

But we DO, however, deal with algorithms of our own. We create for loops and write functions every day; so how can good algorithm design principles inform the writing of these functions?

Know Your Input

One of the main principles of algorithmic design is to, if possible, build your algorithm in such a way that the input itself does some of the work for you. For instance, if you know that your input is always going to be numbers, you do not need to have exceptions/checks for strings, or coerce your values into numbers. If you know that your DOM element is the same every time in a for loop in JavaScript, you shouldn’t be querying for that element in every iteration. On the same token, in your for loops, you shouldn’t use convenience functions with overhead if you can accomplish the same thing using (closer to) simple operations.

1
2
3
4
5
6
7
8
9
10
11
// don't do this:
for (var i = 1000; i > 0; i--){
    $("#foo").append("<span>bar</span>");
}
// do this instead
var foo = $("#foo");
var s = "";
for(var i = 1000; i > 0; i--){
    s += "<span>bar</span>";
}
foo.append(s);

If you are a JavaScript developer (and you use jQuery) and you don’t know what the above functions are doing and how they are significantly different, the next point is for you.

Understand Your Tools

At their finest, [algorithms] are clever, efficient ways of doing something that requires a higher level of intuition than the most apparent solution.

It is easy to think that this goes without saying. However, there is a difference between “knowing how to write jQuery” and “understanding jQuery”. Understanding your tools means that you understand what each line of code does, both immediately (the return value of a function or the effect of a method) and implicitly (how much overhead is associated with running a library function, or which is the most efficient method for concatenating a string). To write great algorithms, it is important to know the performance of lower-level functions or utilities, not just the name and implementation of them.

Understand the Environment

Designing efficient algorithms is a full-engagement undertaking. Beyond understanding your tools as a standalone piece, you must also understand the way that they interact with the larger system at hand. For instance, to understand JavaScript in a specific application entirely, it is important to understand the DOM and performance of JavaScript in cross browser scenarios, how available memory affects rendering speeds, the structure of servers (and their responses) you may be interacting with, as well as a myriad of other considerations that are intangible, such as usage scenarios.


Reducing the Workload

In general, the goal of algorithm design is to complete a job in fewer steps. (There are some exceptions, such as Bcrypt hashing.) When you write your code, take into consideration all of the simple operations the computer is taking to reach the goal. Here is a simple checklist to get started on a path to more efficient algorithm design:

  • Use language features to reduce operations (variable caching, chaining, etc).
  • Reduce iterative loop nesting as much as possible.
  • Define variables outside of loops when possible.
  • Use automatic loop indexing (if available) instead of manual indexing.
  • Use clever reduction techniques, such as recursive divide and conquer and query optimization, to minimize the size of recursive processes.

Study Advanced Techniques

There is no better way to become a better algorithm designer than to have a deep understanding and appreciation for algorithms.


Conclusion

If you didn’t know what an algorithm was at the start of this article, hopefully, now, you have a more concrete understanding of the somewhat elusive term. As professional developers, it is important that we understand that the code we write can be analyzed and optimized, and it is important that we take the time to do this analysis of the performance of our code.

Any fun algorithm practice problems you’ve found? Perhaps a dynamic programming “knapsack problem”, or “drunken walk”? Or maybe you know of some best practices of recursion in Ruby that differ from the same functions implemented in Python. Share them in the comments!

Application Initialization Module for IIS 7.5

October 5, 2012 § Leave a comment

Yesterday, One of my colleague found out best and easiest way of Application Initialization and its worth putting into my blog.

“IIS is a demand-driven web server, i.e. IIS does things only when asked for…”

you can download it from Microsoft site http://www.iis.net/downloads/microsoft/application-initialization

This was the start of a blog post back in late 2009 announcing the beta for the IIS 7.5 Application Warm-Up module.  The idea behind this module is to address a common customer need.  Specifically, the demand driven nature of IIS is such that it doesn’t load application code until it’s needed to handle a request.

Many applications do a significant amount of work when they first start.  And in many cases, the framework needed to run the application is loaded in the same way.  Finally, it may be necessary for the application framework to compile some or all of the application code before it can handle that first request.  All of this leads to an all too common situation where the unlucky client that makes the first request the application has to endure a long wait before they see the first response.

So back before IIS 7.5 was released, we asked ourselves what functionality would be needed to help to address this problem.  The results of that thinking were two new features in IIS 7.5, one of them an administrative feature, and one of them a new interface in the IIS pipeline.

I’d like to talk about the pipeline change first.

The IIS pipeline is the heart of the IIS runtime – the part that determines how an IIS worker process responds to events, like the arrival of a request that needs to be served.  The pipeline is a collection of event notifications and application programming interfaces (APIs) that modules can plug into and do work when things happen.  The IIS product team uses these events an APIs to implement all of the interesting parts of what people think of as IIS in the form of modules.  For example, IIS uses a module called StaticFileModule to be able to serve plain files.  It uses a module called DefaultDocumentModule to know how to serve the default document for virtual directory or application.  Modules are also used for things other than serving request.  The WindowsAuthenticationModule implements Windows authentication, and the UriCacheModule implements certain caching that you don’t see, but improved the performance of the pipeline.  If you are a programmer interested in the pipeline, one of the coolest decisions that we made for IIS 7.0 was to make the same interfaces that we use on the product team available to anyone.  You can get started taking a look at it here.

So what does all of this have to do with warming up applications?

IIS 7.5 introduced a new event to the pipeline called GL_APPLICATION_PRELOAD.  This event fires when the worker process is first starting up.  A module plugged in here can register for the event to do work before the worker process notifies WAS that it is ready to handle requests.  At the same time, we added a new pipeline interface that allows a module to create requests and drop them into the pipeline.  These requests work just like requests from a client, except that there is no client, no network connection etc.  Unless they specifically look for it, modules don’t see a difference between these “fake” requests and requests with a live client on the other end.  Data that would normally be sent back to the client is discarded.

These two things together create the opportunity to solve part of the problem that I mentioned at the start of this post.  When a worker process starts up, it can create a bunch of “fake” requests and send them through the pipeline.  These requests will run through their respective applications without having to wait for a live client to create the demand to start.

So this looks good, but there is still a catch.  IIS worker processes (which each host there own pipeline) are themselves demand started.  Prior to IIS 7.5, the only way to start the worker process was for a client to make a request.

Start Mode

The second new IIS 7.5 feature makes it possible to automatically start an IIS worker process without waiting for a requests.  This feature is pretty straightforward.  To enable it, just go to the advanced properties for the application pool in Internet Information Services Manager, and set “Start Automatically” to “True”.  Once you do this, worker processes for the application pool will be started up as soon as the IIS service starts.  You can do the same thing by setting the startMode property in applicationhost.config to alwaysRunning.

So now, if you have a module that can send a list of requests through the pipeline, and you have the application pool set to auto start, all of the applications represented by the list of requests will be touched as soon as IIS starts.

The Application Warm-Up Module

The Application Warm-Up module that I first mentioned at the top of this post was to be the module to send the warmup requests.  Why do I say this in the past tense?  Back in March last year, we pulled the beta release and pointed the download page to a notice explaining that it was temporarily removed.

There were a couple of things that happened leading up to the removal.  The first thing is that the functionality that I’ve listed above only solves a part of the problem.  The remaining puzzle piece is that, even under the best of circumstances, there is still a period of time after starting the application where it cannot respond to client requests.  If you need to restart the IIS service for any reason, even enabling Start Automatically does not help requests that arrive at the moment that the service starts.  To address that, there needs to be a way for IIS to actually send a response during the warmup period.  And there needs to be a way that an application can participate in what that response looks like.  If we wanted to solve that problem, we needed to make a deeper investment in the module.  And since we were fully engaged in the development of IIS 8, we were able to do just that as a part of the next major IIS release.

The other factor is that, when we looked at how the beta module worked, we realized that we would need to make some changes to the new pipeline functionality that we introduced in IIS7.5.  Normally, when we introduce new APIs to IIS, we do so only when we are either going to use them ourselves or when we have a partner that is committed to using them before release.  The pipeline changes for warmup were an exception to this because we didn’t have time to do the module before IIS 7.5 released.  As sometimes happens when there is no code that depends on a new interface, we discovered that there were some things that would need to be fixed before Application Warm-Up could be made ship ready.  This meant that, over and above the new functionality in the module, we would need to ship a QFE for IIS 7.5 (which is included in the setup package for Application Initialization).

Where are we now?

Finally, after almost a year after we pulled the beta, we were able to release the Release Candidate version of Application Initialization.

So that is the history up to this point for the Application Warm-Up/Initialization module.  There are still questions that I’d like to answer:

– What is new in the RC?
– What’s the easiest way to start using it?
– What about advanced usage and troubleshooting?
– Why did the name change?

In my last post, I gave a bit of background on the Application Warm-Up module, now called Application Initialization.  This week, I would like to go into more detail as to what the Application Initialization module does, and how you should think about using it.

As I mentioned earlier, the idea behind Application Initialization is that we want to provide a way that IIS can prepare an application to serve requests without having to wait for an actual client to make a request.  With Application Initialization, we break the problem down into 3 parts:

  • How can I start the worker process that hosts my application without waiting for a request?
  • How can I get the worker process to load my application without waiting for a request?
  • How can my application send some kind of response so that clients don’t see the browser hang until the application is ready?

I would like to address the first two questions here.  The third question is a bit more complex and I will save it for my next post.

Starting a worker process without waiting for a request

This is something that’s not strictly speaking a part of Application Initialization in that we added this capability as a built-in feature of IIS, starting with IIS 7.5.  I will go over it here because it works hand in hand with Application Initialization to make the application available as soon as possible after starting IIS.

This feature is controlled by a the startMode property for the application pool, described (along with other application pool properties)here.  The default value for startMode is OnDemand, which means that IIS will not spin up any worker processes until needed to satisfy a client request.  If you set it to alwaysRunning, IIS will ensure that a worker process is always running for the application pool.  This means that IIS will spin up a worker process when the World Wide Web Service is started, and it will start a new worker process if the existing one is terminated.

Note that this property should not be confused with the autoStart property.  Understanding autoStart requires a bit of background knowledge.  Both application pools and worker processes can be started and stopped.  If an application pool is started, it means that IIS will accept requests for URLs within the pool, but it does not necessarily mean that there are any worker processes started.  If an application pool is stopped, IIS will return a “503 Service Unavailable” for any requests to the application pool and it will not start any worker processes.  The autoStart property is essentially a flag that IIS uses to know which application pools should be started when the World Wide Web Service is started.  When you stop an application pool in IIS Manager, autoStart is set to false.  When you start an application pool, autoStart is set to true.  In this way, IIS ensures that the same set of application pools are running after the World Wide Web Service is started and stopped (or through a machine reboot.)

Now let’s take a quick look at the configuration for an application pool that is set to be always available.  This application pool will start when the World Wide Web Service starts and it will immediately spin up a worker process.

<system.applicationHost> 
  <applicationPools> 
    <add name="DefaultAppPool" autoStart="true" startMode="alwaysRunning" /> 
  </applicationPools> 
</system.applicationHost>

With this configuration, the Default Application Pool will immediately spin up a worker process when IIS is started, and it will spin up a new worker process when the existing one exits.

With IIS 7.5, this property was not exposed in IIS Manager.  It can be set by editing the applicationhost.config file directly or by one of IIS’s scripting or programming APIs, or by the Configuration Editor UI tool.  In IIS 8, we have added the startMode property to the advanced properties page for the application pools UI.

How can I get the worker process to load my application without waiting for a request?

Now that you can see how to get IIS to spin up a worker process without waiting for a request, the next thing to address is how to get an application loaded within that worker process without waiting for a request.  The Application Initialization module provides a solution here, and as above, it is controlled by a single configuration property.

The Application Initialization module extends the IIS configuration by adding a new property to the application settings called preloadEnabled (in IIS 8, this property is built-in.)  Let’s take a look at what this looks like in the configuration where I’ve added a new application to the default web site and enabled it for preload:

<system.applicationHost> 
  <sites> 
    <site name="Default Web Site" id="1"> 
      <application path="/"> 
        <virtualDirectory path="/" physicalPath="%SystemDrive%\inetpub\wwwroot" /> 
      </application> 
      <application name="AppInit" applicationPool="DefaultAppPool" preloadEnabled="true"> 
        <virtualDirectory path="/AppInit" physicalPath="c:\inetpub\wwwroot\appinit" /> 
      </application> 
    </site> 
  </sites> 
</system.applicationHost>

Here’s how Application Initialization uses this property.  When a new worker process spins up, Application Initialization will enumerate all of the applications that it will host and checks for this property.  For any application where preloadEnabled=”true”, it will build a URL corresponding to the default page for the application and run it through the pipeline.  This request does not go through the network, and there is no client listening for a response (IIS discards any data that would have gone to the client.)

This “fake” request accomplishes a few key things.  First, it goes through the IIS pipeline and kicks off an application start event.  This initializes a number of parts inside of IIS, and if the request is for ASP.NET, it will cause global.asax to run.  It also reaches the application, which will see it is the first request after starting.  Typically, I expect that applications will just handle this request just like any other request from a real client, but we do set some server variables into our “fake” request, so an application with awareness of this feature could implement special processing if it chose to do so.

There is another important aspect to this process.  When IIS spins up a new worker process, there is two way communication betweenWAS and the new process.  This allows WAS to know precisely when the worker process is ready to accept new requests.  It also allows the worker process to get information from WAS as to whether it is going to be a new process to start taking requests, or whether it’s a replacement process to take over for an older process that’s being recycled.

This is an important distinction.  In the case of a new worker process, we want to start taking client requests as soon as possible, which is the way that things work outside of Application Initialization.  In the case of a replacement process, though, Application Initialization will prevent the new process from reporting itself ready for new requests, until all of the preload requests (and any warumup requests, which I will discuss later) have completed.  This means that no client will ever have to wait for a process recycle to complete – because the old process will continue to take requests until the new one has completed all application initialization.

In my experience, many applications with a slow startup will do their work even for a simple request to the default page.  For such applications, you can take advantage of improved application recycling simply by setting preloadEnabled=”true” for that application.  Similar to the startMode property above, IIS 7.5 requires you to make this setting via direct edits or applicationhost.config, or via scripting or one of our config APIs, or via the Configuration Editor UI tool.  In IIS 8, we have added “Enable Preload” as a checkbox in the UI for application settings.

Next time…

The two topics that I’ve covered here should get you started with Application Initialization.  The ability to handle worker process recycles has been a highly requested feature.

In my next post, I’ll tackle the topic of what it means to initialize an application and what things an application developer can do to make things responsive during the time everything is warming up.  This is where we’ve made major changes and added a lot of stuff since the original beta release.

-from Wade Hilmo
http://blogs.iis.net/wadeh/archive/2012/04/16/re-introducing-application-initialization.aspx

Programmer Happiness: It’s the Little Things

October 3, 2012 § Leave a comment

Finding and keeping good programmers is a challenge for any business. Salary and promotion opportunities aside, sometimes it’s the small things that add up. Although not the tipping point, they are part of the larger equation. Putting defection aside, happy programmers code faster and produce less bugs. What are those little things?

Proper Hardware
Notice the word “proper.” Programming starts with the right computer. Companies do not need to break the bank. Decisions about CPU, RAM, hard drives, etc. are unique to each company. Choose wisely because adequate is one step away from problematic. Holding a quick yearly review helps avoid future lost time. Additionally holding honest, reasonable conversations about hardware is rewarding. Productivity is the key measurement, but don’t forget to discuss:

  • Utilizing multiple monitors to increase efficiency. This affects video card purchases.
  • The proper keyboard and mouse. This may be unique to each programmer.
  • The use of a UPS to avoid power loss and spikes.

Productive Software
Outside of standard development suites, developers require other applications. Common areas include specialized file zipping/unzipping, complex text editors, graphic manipulators, sophisticated file searching, monitoring tools, and organizational products. These applications increase a programmer’s effectiveness. The purchase of these tools should not be a barrier.

Great Surroundings
Productivity is 50% mental and 50% physical. Programmers remain seated for most of their career. A comfortable chair is a necessity. Most standard office chairs fall short of this goal. Physical health problems translate to lower mental output. Proper desk size, adequate room, and access to natural light are subtle but important factors.

Offer Flexibility
Job flexibility is a rising topic in organizations. Offering work from home options and flexible hours reduces lost effort while supporting a better work-life balance. Flexible hours can include freedom to arrive/leave as necessary, a four day work week, and/or summer hours.

Final Thoughts
Oscar Levant once said, “Happiness isn’t something you experience; it’s something you remember.”
Along the same lines, John Wooden stated, “It’s the little details that are vital. Little things make big things happen.” The sections above are not meant to be an official checklist. They encourage conversation, which leads to higher job satisfaction.

Android – Stock Market Watch (COINS) in C# using Visual Studio 2010

October 2, 2012 § 1 Comment

Source from Code Project

Main Screenshots

Revision History

Revised on 13th September, 2012 – Add Stock Chart (new feature) from Stock Detail Activity

Introduction

Welcome to COINS Mobile – All Exchange Market Watch

“COINS Mobile” allows you to watch Stock Market Data. It illustrates proper application architecture layering and uses a common code base for the Business Layer and Data Layer. It then separates out the User Interface and Application Layer into the appropriate device-applications.

This article discusses the power of C# to build a Professional Application for Android. The purpose of writing this article is to understand what you can do with C# using Visual Studio 2010 similar to how you would develop a Windows Application in C#. All credit goes to Xamarin to provide such a beautiful platform for .NET developers to build application in Android.

Being a .NET developer (even though I started building Android Applications a few years back) I started using Java/Davlink using Eclipse Java. With a little bit effort, within a couple of weeks I built a sample application in Java, but I faced few problems in consuming web methods (.NET Web Services). I had to use Android ksoap (lightweight SOAP client library for the Android platform) which is not very straightforward. Also there are still learning curves to understand and get acquainted with the Java language and Eclipse IDE (specially for .NET developers). So, I started evaluating Xamarin Mono using C# as a base language for Android.

This is not intended to be a comprehensive discussion of each feature but I will try my level best to break down the whole application and elaborate, step by step, how to build a professional Android Application in C#. I am sure you’ll be able to leverage your existing knowledge of C# and Visual Studio to quickly build a Professional Android Application.

Background

This application is based on “Stock Market Watch” – Pulling Real Time Stock Quotes from most of the Exchange. “COINSMobile” is targeted to the millions of Stock Traders in the world who desperately need a system available in their hands to watch their stock details (and in the form of a beautiful Android app no less).

I named it “COINS”. I will use the term “COINS” in several areas in the article description which will actually refer the Application itself.

What COIN Does

It pulls real time stock data through the web service and displays the details of the stock (a multitude of stock data can be viewed in a single screen). It also provides a further drill-down and a detailed view of each stock, along with charts is also one of the important features of the application. The user can create their own custom stock script and view their added stock details.

This Article Covers

  • Using C# and Visual Studio to Develop an Android Application
  • Understanding Activities and Layouts
  • Connect to Web Service
  • Using SQLite Database for Local Data Storage
  • Step by Step Guide to Build Professional Android Application
  • Run Methods in a Thread
  • Interactive Layout Design
  • Creating Action Bar – Menus in Android
  • Run and Test Application in Emulator
  • Building Professional Application “COINS – All Exchange Market Watch”

How to start?

This article is specially written for developers who are working in C#. Whether they are working in Windows, Web, Silverlight, WPF or Windows Tablet, it doesn’t matter. You need to know C# and be familiar with Visual Studio.

So here are two things, you need to start developing Android Apps in C#

If you don’t have Visual Studio, you can still use Mono Development Environment that comes with the SDK.

Creating “COINSMobile” Project

As I have already mentioned the article is also for Beginners so I thought I would include a quick guide on how to create Android Project in Visual Studio. You can jump this step if already have a decent knowledge of using Mono C# for Android.

The download and installation of Mono Android will take a maximum of 25-40 minutes depending upon your internet speed. Once the SDK is installed, open your Visual Studio.

Click on File>New>Project

You will see a screen below. In the left Pane, select “Mono for Android”. Then select “Android Application”. Provide a file name and then click “OK” button.

Here you go and can see the first screen with some generated C# code. As you can see, all the things are quite familiar like namespace, class and also the generated code itself.

The top most part where you see “using namespace” is the default namespace you will be using. If you want to do a special task that is not in the Reference List you need to use “Add Reference” from the solution explorer to add a component (the same as we would do while coding in C#/VB.NET). Like, if you want to do an operation with SQLite (light database), you need to add a reference to “Mono.Data.Sqlite“.

One thing I would like to emphasize in the code is the “OnCreate” overridden method

Collapse | Copy Code
public class MainActivity : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        StartActivity(typeof(MarketWatchActivity));
    }
}

What is OnCreate()?

This is called when the activity is first created. This is where you should do all of your normal static set up: creating views, binding data to lists, etc. This method also provides you with a Bundle containing the activity’s previously frozen state

Oops! Activities, and Views – what are these? I will explain these a bit later. Let’s have a look at the Activity Life Cycle, which is similar to the ASP.NET Page Life Cycle.

For the time being, think of Activity as a Windows Form or ASP.NET Page.

Activity Life Cycle

If we compare Activity with a web page, Activity resembles a web page’s ‘code behind’ in ASP.NET. So, just like a web page we write the code behind in C# and activity is the code behind of Layout.

Layout is an XML called AXML just like in WPF – we call XAML. If you have prior experience working in WPF or Silverlight, it will be easier to understand AXML Layout.

The application starts with an Activity which will typically has a Layout for displaying the Activity. It clearly defines a Model-View-Controller (MVC) pattern. Layout is the form (or page, or whatever you call the screen) we see in Android. The language is XML. You need to understand Layout very thoroughly to build innovative Android applications.

Understanding Files in Solution Explorer

We will be concentrating on three folders

  • Drawable : containing all graphic contents e.g. images
  • Layout  : contains all layouts (screens we see in Android Application);
  • Values : Global variables that we will use throughout the application

Activity1.cs (auto created when you create a project) in the image above is the code behind of the layout. If you need to create a custom class you can create a folder under root and place your classes there.

Understanding Layout – UI

Layout is kind of a foreign concept if you are a Windows/Web developer using C#. It will be easier to understand if you have knowledge in XAML or ASP.NET in MVC.

It doesn’t matter if you are new to this Term. I will try to provide the brief fundamentals of Layouts, but I do prefer to write a separate article on Layout as this is one of the most important things we need to concentrate on, especially when you are shifting from Windows/Web development to Mobile.

Let’s begin with a scenario where we need to place a caption in a line, textbox in the second line and a button in the third line.

It’s simple when you use HTML or aspx to design. You create three divs, make the div style clear right and place each control within the div.

Something like in HTML

Collapse | Copy Code
<div style="clear:right">Code</div> 
<div style="clear:right"><Input type="text" id="text1"/></div> 
<div style="clear:right"><input type="button" id="button1" value="Ok"/></div>

HTML Layout

Here in Android Layout of the above e.g,

Axml Layout

You need to play around a bit with the controls to get a better idea. You can view the controls using View>Toolbox

So in brief, here is the actual definition of Layout:

Layout is the architecture for the user interface in an Activity. It defines the layout structure and holds all the elements that appear to the user.

We can declare layout in two ways:

  1. Declare in AXML
  2. Create controls at runtime

In the “COINS” Application, you will see – heavy use of creating controls dynamically in Activity Classses.

How many types of Layout?

  • LinearLayout (Vertical)
  • LinearLayout (Horizontal)
  • RelativeLayout
  • FrameLayout
  • TableLayout
  • TableRow

Jump to COINSMobile Application

We have some pretty fair ideas of the Android Activity Class and Layouts though, I have not gone into details of Activity.cs. We will gather more in-depth knowledge while showing you step by step method of creating Professional Android Application.

We will be building primarily five screens:

  1. Spash Screen
  2. Market Watch
  3. Stock Script Detail View
  4. Add Stock
  5. Get Stock Quote
  6. Show Stock Charts

First Step – Connecting to Web Service

We will be using a .NET Web Service to get real time stock data. Web Services plays an important role to talk to an external database whatever the database is. If you want to store data into Mobile, you can use Android’s light Database – SQLite. If you would like to talk to external remote database, you need a Web Service or WCF to talk to the database.

In this example, two Web Methods will be consumed from COINS Application

  • StockExists
  • GetStockQuote
  • GetStockChart

The URL we will be using to get the Stock Data and Charts http://stock.webservice.net.in/StockQuoteService.asmx

Because the above web service is a part of a larger project I am not allowed to post the source of StockQuoteWebservice.asmx. But thinking from a Developer’s viewpoint, it would be nicer to give a source for the web service. So I have created an alternate solution to get Market Data Feed from Yahoo API and then uploadthe web service source.

Disclaimer: Although great care has been taken in developing Stock Web Service, it is provided without any guarantee of reliability, accuracy of information, or correctness of operation. I am not responsible for any damage that may occur as a result of using this web service. Use this program entirely at your own risk.

GetStockQuotes(): Send multiple stocks in a comma separated string and pass it as a parameter. This will return the XML of all the Stocks.

StockExist(): Send multiple stock scripts in a comma separated string and pass it as a parameter. This will return the “Exchange” of the Stock. If a stock script is Invalid, the XML will return “NA” (Not Applicable). Well, we now have two Web Methods which will be sufficient to create Market Watch for All Exchange Stock.

Though the web service is an important layer to fetch the stock details in this Application, the URL provided is used for Proof of Concept. There is no guarantee that the Web Service used will fetch real time data.

Well, let’s see, how can we consume Web Methods from Android applications? It is as simple as consuming Web Methods like we all do in Windows or web applications.

Add a Web Reference to the stock service.

add reference

Now we are ready to consume Web Methods. To get the stock data:

Collapse | Copy Code
using COINSMobile.stockwebservice;
string strXML = string.Empty;
stockwebservice.StockWebservice quoteObject = null;
try
{
    quoteObject = new stockwebservice.StockWebservice();
    strXML = quoteObject.GetStockQuote(_stocks);
}
finally
{
    quoteObject.Dispose();
    quoteObject = null;
}
//if error occurred while connect8ing to web service
if (strXML.Substring(0, 5) == "error")
{
    var t = Toast.MakeText(this, "Error connecting to web service. Please check your Internet connection...", ToastLength.Short);
    t.SetGravity(GravityFlags.Center, 0, 0);
    t.Show();
    return;
}
if (strXML.ToLower() == "exception")
{
    var t = Toast.MakeText(this, "Service not available now. Please try after sometime...", ToastLength.Short);
    t.SetGravity(GravityFlags.Center, 0, 0);
    t.Show();
    return;
}
//load the xml to XmlDocument
XmlDocument doc = new XmlDocument();
doc.LoadXml(strXML);

The important thing to note here is we use the GetStockQuote method and load the XML string in the XMLDocument to parse the XML. Thus, you can consume Web Methods to talk to Remote Database.

This is not very simple using Android/Java as there are several steps you need to perform in order to consume .NET Web Service using ksoap.

Before going into further detail, let’s see the XML string returned from Wen Method – “GetStockQuote“. Here I will be sending two scripts – “GOOG,MSFT” as an input parameter to the “GetStockQuote()” web method.

GOOG: Google Inc (Exchange:Nasdaq)
MSFT: Microsoft Corporation (Exchange:Nasdaq)

Sample XML Output from Web Method

A Brief Look at SQLite

SQLite is a relational database management system contained in a small (~350 KiB) C programming library. In contrast to other database management systems, SQLite is not a separate process that is accessed from the client application, but is an integral part of it. SQLite is a popular choice as an embedded database for local/client storage in application software such as web browsers, Mobile Device, Tablet PC. It is arguably the most widely deployed database engine, as it is used today by several widespread browsers, operating systems, and embedded systems.

To start with SQLite, you first need to add a reference to Mono.Data.Sqlite.dll;

Collapse | Copy Code
using Mono.Data.Sqlite;

In the “COINS” application, we will be creating a database and one single Table with subsequent methods to Fetch, Add and Delete stocks that we will be using Market Watch – Favorite List.

Let’s have a look at two classes, one we will be for creating a Data Repository and the other for all Database Operations.

Stock Class in CRMMobile.Core Project within the Business Layer.

Collapse | Copy Code
public class Stock : Java.Lang.Object
{
    public long Id { get; set; }
    public string StockName { get; set; }
    public Stock()
    {
        Id = -1;
        StockName = string.Empty;
    }
    public Stock(long id, string stockName)
    {
        Id = id;
        StockName = stockName;
    }
    public override string ToString()
    {
        return StockName.ToString();
    }
}

The class above is simple enough to understand. Let’s have a look in the StockDatabase class in the DataLayer of the Core Project.

Collapse | Copy Code
public class StockDatabase
{
    private static string db_file = "stockdata.db3";
    private string stockName = string.Empty;
    private static string sMessage;
    public string StockName
    {
        get { return stockName; }
        set { stockName = value; }
    }
    private static SqliteConnection GetConnection()
    {
        var dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal)
                     , db_file);
        bool exists = File.Exists(dbPath);
        if (!exists)
            SqliteConnection.CreateFile(dbPath);
        var conn = new SqliteConnection("Data Source=" + dbPath);
        if (!exists)
            CreateDatabase(conn);
        return conn;
    }
    private static void CreateDatabase(SqliteConnection connection)
    {
        var sql = "CREATE TABLE STOCKTABLE (Id INTEGER PRIMARY KEY AUTOINCREMENT, 
            StockName VARCHAR);";
        connection.Open();
        using (var cmd = connection.CreateCommand())
        {
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();
        }
        connection.Close();
    }
    public static IEnumerable<Stock> GetStocks()
    {
        try
        {
            var sql = "SELECT * FROM STOCKTABLE ORDER BY ID;";
            using (var conn = GetConnection())
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                            yield return new Stock(reader.GetInt32(0), reader.GetString(1));
                    }
                }
            }
        }
        finally
        {
            StockManager.Message = sMessage;
        }
    }
    public static bool IsStockExists(string _stockname)
    {
        bool Ok = false;
        var sql = string.Format("SELECT * FROM STOCKTABLE WHERE STOCKNAME='{0}';", 
            _stockname);
        try
        {
            using (var conn = GetConnection())
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                            Ok = true;
                    }
                }
            }
        }
        finally
        {
            StockManager.Message = sMessage;
        }
        return Ok;
    }
    public static bool SaveStock(string _stockname)
    {
        try
        {
            bool Ok = IsStockExists(_stockname.Trim().ToUpper());
            if (Ok)
            {
                sMessage = string.Format("Stock Script '{0}' is already added.",
                    _stockname);
                return false;
            }
            using (var conn = GetConnection())
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    try
                    {
                        // Do an insert
                        cmd.CommandText = 
                            "INSERT INTO STOCKTABLE (StockName) VALUES (@StockName);";
                        cmd.Parameters.AddWithValue("@StockName", 
                            _stockname.ToUpper());
                        cmd.ExecuteNonQuery();
                        sMessage = string.Format(
                            "Stock Script '{0}' is added successfully.", _ stockname.ToUpper());
                        return true;
                    }
                    catch (SqliteException ex)
                    {
                        sMessage = ex.Message;
                        return false;
                    }
                }
            }
        }
        finally
        {
            StockManager.Message = sMessage;
        }
    }
    public static bool DeleteAllStocks()
    {
        try
        {
            using (var conn = GetConnection())
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    try
                    {
                        // Do an insert
                        cmd.CommandText = "DELETE FROM STOCKTABLE;";
                        cmd.ExecuteNonQuery();
                        sMessage = 
                        "All Stocks are deleted successfully...\nTo view the stocks" +
                        "in Market Watch, you need to add your custom stock";
                        return true;
                    }
                    catch (SqliteException ex)
                    {
                        sMessage = ex.Message;
                        return false;
                    }
                }
            }
        }
        finally
        {
            StockManager.Message = sMessage;
        }
    }
}

I have used SqLite Helper class to do all database operations. The code is self explained and nothing much within the code to detail. If you are new to SQLite, just play around with the code to explore more.

One point to mention: in the application I used only one Table for adding custom stock script.

Collapse | Copy Code
CREATE TABLE STOCKTABLE (
     Id INTEGER PRIMARY KEY AUTOINCREMENT, 
     StockName VARCHAR
);

We will be using Web Service and Database quite frequently in the activity classes.

Now we build the application.

Building Splash Screen (First Tiny Screen with Tiny Code)

Right click solution explorer. Click Add > New Item > Activity (from Android New Window). Name the file MainActivity.cs

Collapse | Copy Code
[Activity(MainLauncher = true, Theme = "@style/Theme.Splash", NoHistory = true)]
public class MainActivity : Activity
{
   protected override void OnCreate(Bundle bundle)
   {
       base.OnCreate(bundle);
       StartActivity(typeof(MarketWatch));
   }
}

Let’s look at the code

Collapse | Copy Code
[Activity(MainLauncher = true, Theme = "@style/Theme.Splash", NoHistory = true)]
Main Launcher=True

This means the startup Activity. When the application loads it launches this activity.

Collapse | Copy Code
Theme="@style/Theme.Splash"

Did you notice in Solution Explorer there is an XML file under Resources>Values? This is Strings.xml where we define global variables that can be accessed by the Application.

To start a theme you need to create a graphics file and add it in Resources>Drawable. Once you add it, you will see a reference in “ResourceDesigner.cs” like

Collapse | Copy Code
public partial class Drawable
{
    public const int splash = 2130837511;
    .....
}

Here is the XML for splash in strings.xml

Collapse | Copy Code
<style name="Theme.Splash" parent="android:Theme">
    <item name="android:windowBackground">@drawable/splash</item>
    <item name="android:windowNoTitle">true</item>
</style>

So, when we write “@style/Theme.Splash” – activity points to the splash image. The name of the image here is splash.png.

StartActivity(typeof(MarketWatch)); – Here MarketWatch is another Activity class which is called from splash screen. So, this is the starting point of the application.

That’s powerful stuff! Isn’t it so simple? Just create a graphics file, add add the file using “Add>Add Existing Item” from Drawable, add the definition of a graphics file in strings.xml and write only two lines of code. Fair enough, let’s look into the next screen “Market Watch”

Start with – Market Watch

Here we will be creating a dynamic control “TableView”. The reason for creating a dynamic control is that we are not sure in design time how many Table Rows we will have. Table Rows will be created dynamically depending upon the records in the stock table (initially the stock table is blank, but it will grow subsequently upon adding stock script into SQLite Database). So, let’s have a look at how we create dynamic control in Android Activity Class.

Collapse | Copy Code
<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:stretchColumns="1"
        android:id="@+id/deatlWatchLayout" />
</ScrollView>

Note: I have used “ScrollView” just at the top of TableLayout. The reason is, if you have stocks that don’t fit in the screen you will see vertical scroll bar, which you can use to scroll the view.

Collapse | Copy Code
private void PopulateDataToControls(string _stocks)
{
    //we have now the stocks delimited by comma
    //this string will be passed to Webservice as a paramete to fetch the stock block in xml
    string strXML = string.Empty;
    stockwebservice.StockWebservice quoteObject = null;
    try
    {
        quoteObject = new stockwebservice.StockWebservice();
        strXML = quoteObject.GetStockQuote(_stocks);
    }
    finally
    {
        quoteObject.Dispose();
        quoteObject = null;
    }
    //if error occurred while connect8ing to web service
    if (strXML.Substring(0, 5) == "error")
    {
        var t = Toast.MakeText(this, "Error connecting to web service. Please check your Internet connection...", ToastLength.Short);
        t.SetGravity(GravityFlags.Center, 0, 0);
        t.Show();
        return;
    }
    if (strXML.ToLower() == "exception")
    {
        var t = Toast.MakeText(this, "Service not available now. Please try after sometime...", ToastLength.Short);
        t.SetGravity(GravityFlags.Center, 0, 0);
        t.Show();
        return;
    }
    //load the xml to XmlDocument
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(strXML);
    tablelayout.RemoveAllViews();
    tablelayout.RefreshDrawableState();
    XmlNodeList xnList = doc.SelectNodes("/stock/symbol");
    foreach (XmlNode xn in xnList)
    {
        if (xn != null)
        {
            TableRow demoTableRow = new TableRow(this);
            TextView tv_l = new TextView(this);
            TextView tv_r = new TextView(this);

            tv_l.SetPadding(3, 3, 3, 3);
            tv_r.SetPadding(3, 3, 3, 3);
            tv_r.Gravity = GravityFlags.Right;
            tv_l.SetTextSize(Android.Util.ComplexUnitType.Px, 9);

            tv_l.Text = xn["code"].InnerText.Trim() + 
                "-" + xn["exchange"].InnerText.Trim();
            tv_r.Text = "(" + xn["change"].InnerText.Trim() + 
                ") " + xn["last"].InnerText.Trim( );
            demoTableRow.Clickable = true;
            demoTableRow.Click += (sender, e) =>
            {
                doRowClick(sender);
            };
            demoTableRow.AddView(tv_l);
            demoTableRow.AddView(tv_r);
            tablelayout.AddView(demoTableRow);
            View vLineRow = new View(this);
            vLineRow.SetMinimumHeight(1);
            vLineRow.SetBackgroundColor(Color.Rgb(88, 88, 88));
            tablelayout.AddView(vLineRow);
        }
    }
}

The code we will be concentrating on is the part where we dynamically create TableView controls. TableView is just like a Table we use in HTML.

TableView contains TableRows. Each Table Row contains TextView

Collapse | Copy Code
TableRow demoTableRow = new TableRow(this);
TextView tv_l = new TextView(this);
TextView tv_r = new TextView(this);
tv_l.Text = "Column 1 data";
tv_r.Text = "Column 2 data"
//here we are adding TextView to TableRow
demoTableRow.AddView(tv_l);
demoTableRow.AddView(tv_r);
//add TableRow control to the Layout we define in MarketWatch.axml
tablelayout.AddView(demoTableRow);

The only tricky part here is to create a Click Event Handler for the TableView control. Remember, we can have multiple TableRows in a TableLayout. Each stock script saved in the database will create one row. So, if we have 20 stock scripts, we will be creating 20 odd Rows by using a “for loop”. To attach an event handler (OnClick) to the TextView,

Collapse | Copy Code
demoTableRow.Clickable = true;
demoTableRow.Click += (sender, e) =>
{ 
    doRowClick(sender);
<span style="background-color: white; ">};</span> 

private void doRowClick(object Sender)
{
    TableRow tr = Sender as TableRow;
    if (tr != null)
    {
        TextView v = tr.GetChildAt(0) as TextView;
        string _script = v.Text.Trim();
        int _index = _script.IndexOf('-');
        if (_index >

You have probably noticed I used Intent to pass a value from one Activity to another.

Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.

So in the StockDetails Activity, we will get the value that we pass from MarketWatch Activity. In brief, when we click a row, we pass the sender to the custom method. From sender, we get the TextView Control and get the “Stock Name”. We then pass the value of the Stock Name to another Activity – “Stock Details Activity” where we will again talk to Web Service to fetch detailed values of the stock.

Now we have a look into “MarketWatch.axml” – Layout for Market Watch. The only concerned part in the Layout is to design a TextView at the top left and a refresh the icon at the top right

Using RelativeLayout will solve our problem of placing two controls side by side.

Collapse | Copy Code
<RelativeLayout
    android:layout_width="fill_parent"
    android:background="@color/medium_gray"
    android:layout_height="30dp"
    android:paddingTop="3dip">
    <TextView
        android:id="@+id/symbolcaption"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:textColor="@android:color/white"
        android:background="@color/medium_gray"
        android:layout_marginLeft="0px"
        android:paddingTop="2px" />
    <ImageView
        android:id="@+id/buttonRefresh"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:lines="1"
        android:clickable="true"
        android:src="@drawable/refresh_icon" />
    <ImageView
        android:id="@+id/buttonHome"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_margin="24dip"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:clickable="true"
        android:src="@drawable/home_icon" />
</RelativeLayout>

Let’s recapitulate, what’s this “@drawable/refresh” in the ImageView Tag? When you dd a Refresh icon, a line is generated automatically in Drawable Class in Resource.Designer.cs

Collapse | Copy Code
public partial class Drawable
{
    // aapt resource value: 0x7f020000
    public const int refresh = 2130837504;
        .......
}

So we have seen how to pass a value from one Activity to another Activity. In the StockDetails Activity, we will see how we get the value that we pass from the MarketWatch Activity. We also have a fair idea of how to create Controls dynamically.

Second Step – Build Stock Detail View Using a Press/Touch

In the screen above, you will probably have noticed that the value we pass from the MarketWatch Activity is to send to Web Service to get the stock details. Let’s look at the code. How will we get the variable and pass it to Web Service to get the XML?

First, you need to create a New Activity from “Add > Add Item > Activity”. Name the file “StockDetailsActivity.cs

Collapse | Copy Code
_script = Intent.GetStringExtra("Script");
if (_script == string.Empty)
{
    var t = Toast.MakeText(this, "Invalid Script...", ToastLength.Long);
    t.SetGravity(GravityFlags.Center, 0, 0);
    t.Show();
    return;
}
ImageView btnRefresh = FindViewById<ImageView>(Resource.Id.buttonRefresh);
btnRefresh.Click += (sender, e) =>
{
    if (!IsLoading)
    {
        ProgressDialog progress = ProgressDialog.Show(this, 
            "", "Loading Quote...", true);
        new Thread(new ThreadStart(() =>
        {
            this.RunOnUiThread(() =>
            {
                doLoadDetails();
                progress.Dismiss();
            });
        })).Start();
        IsLoading = false;
    }
};
ImageView btnHome = FindViewById<ImageView>(Resource.Id.buttonHome);
btnHome.Click += (sender, e) =>
{
    StartActivity(typeof(MarketWatchActivity));
    return;
};
ProgressDialog progressMain = ProgressDialog.Show(this, 
    "", "Loading Quote...", true);
new Thread(new ThreadStart(() =>
{
    this.RunOnUiThread(() =>
    {
        doLoadDetails();
        progressMain.Dismiss();
    });
})).Start();

I hope you have found how we get the value from Indent.

Collapse | Copy Code
_script = Intent.GetStringExtra("Script");
if (_script == string.Empty)
{
    var t = Toast.MakeText(this, "Invalid Script...", ToastLength.Long);
    t.SetGravity(GravityFlags.Center, 0, 0);
    t.Show();
    return;
}

Intent.GetStringExtra("Script") will return the value that we pass from the previous Activity. We will do a simple check before passing the value to Web Service to pull the real time stock data.

What is a Toast?

A toast is a view containing a quick little message for the user. We use “Toast” to display any information or warning message. The text appears for some time and then vanishes so that users can have a good idea of what is going on with the application.

Now we will see how we pass the stock name or script name to a Web Service and pull the XML and show the data in TableView Controls. This part is very similar to Market Watch.

Collapse | Copy Code
//conecting to webservice and get the xml
string strXML = string.Empty;
stockwebservice.StockWebservice quoteObject = null;
try
{
    quoteObject = new stockwebservice.StockWebservice();
    strXML = quoteObject.GetStockQuote(_script);
}
finally
{
    quoteObject.Dispose();
    quoteObject = null;
}
//if error occurred while connect8ing to web service
if (strXML.Substring(0, 5) == "error")
{
    var t = Toast.MakeText(this, 
    "Error connecting to web service. Please check your Internet connection...", ToastLength.Short);
    t.SetGravity(GravityFlags.Center, 0, 0);
    t.Show();
    return;
}
if (strXML.ToLower() == "exception")
{
    var t = Toast.MakeText(this, 
    "Service not available now. Please try after sometime...", ToastLength.Short);
    t.SetGravity(GravityFlags.Center, 0, 0);
    t.Show();
    return;
}
LinearLayout stockdetailsLinearLayout = FindViewById<LinearLayout>(Resource.Id.linearLayoutstockdetails);
symbolCaption = FindViewById<TextView>(Resource.Id.symbolcaption);
symbolCaption.SetTextAppearance(this, Resource.Style.boldText);
priceCaption = FindViewById<TextView>(Resource.Id.pricecaption);
priceCaption.SetTextAppearance(this, Resource.Style.boldText19);
changeCaption = FindViewById<TextView>(Resource.Id.changecaption);
changeCaption.SetTextAppearance(this, Resource.Style.boldText19);

datetimeCaption = FindViewById<TextView>(Resource.Id.datetimecaption);
datetimeCaption.SetTextAppearance(this, Resource.Style.smallText);
//load the xml to XmlDocument
XmlDocument doc = new XmlDocument();
doc.LoadXml(strXML);
XmlNodeList xnList = doc.SelectNodes("/stock/symbol");
foreach (XmlNode xn in xnList)
{
    data[0, 0] = "Symbol";
    data[0, 1] = xn["code"].InnerText.Trim();
    data[1, 0] = "Name";
    data[1, 1] = xn["company"].InnerText.Trim();
    symbolCaption.Text = xn["company"].InnerText.Trim();
    datetimeCaption.Text = DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss");
    priceCaption.Text = xn["last"].InnerText.Trim() + " " + 
        xn["currency"].InnerText.Trim();
    changeCaption.Text = xn["change"].InnerText.Trim();
    View vLinePrice = new View(this);
    vLinePrice.SetMinimumHeight(2);
    vLinePrice.SetBackgroundColor(Color.Rgb(164, 164, 164));
    stockdetailsLinearLayout.AddView(vLinePrice);
    data[2, 0] = "Exchange";
    data[2, 1] = xn["exchange"].InnerText.Trim();
    data[3, 0] = "Open";
    data[3, 1] = xn["open"].InnerText.Trim();
    data[4, 0] = "Day's High";
    data[4, 1] = xn["high"].InnerText.Trim();
    data[5, 0] = "Day's Low";
    data[5, 1] = xn["low"].InnerText.Trim();
    data[6, 0] = "Change";
    data[6, 1] = xn["change"].InnerText.Trim();
    data[7, 0] = "Change %";
    data[7, 1] = xn["changepercent"].InnerText.Trim();
    data[8, 0] = "Volume";
    data[8, 1] = xn["volume"].InnerText.Trim();
    data[9, 0] = "Previous Close";
    data[9, 1] = xn["previousclose"].InnerText.Trim();
    data[10, 0] = "Trade Time";
    data[10, 1] = xn["tradetime"].InnerText.Trim();
    data[11, 0] = "Market Capital";
    decimal marketcapital = 0;
    if (decimal.TryParse(xn["marketcapital"].InnerText.Trim(), out marketcapital))
        data[11, 1] = string.Format("{0:#,0}", marketcapital);
    else
        data[11, 1] = xn["marketcapital"].InnerText.Trim();

    TableLayout tableLayout = FindViewById<TableLayout>(Resource.Id.deatlLayout);
    tableLayout.RemoveAllViews();
    tableLayout.RefreshDrawableState();
    for (int i = 2; i < 12; i++)
    {
        // add all inforamation to your tablerow in such a maaner that you want to display on screen.
        TableRow demoTableRow = new TableRow(this);
        TextView tv_l = new TextView(this);
        TextView tv_r = new TextView(this);
        tv_l.SetPadding(3, 3, 3, 3);
        tv_r.SetPadding(3, 3, 3, 3);
        tv_r.Gravity = GravityFlags.Right;
        tv_l.Text = data[i, 0];
        tv_r.Text = data[i, 1];
        demoTableRow.AddView(tv_l);
        demoTableRow.AddView(tv_r);
        if (i == 0)
        {
            tv_l.SetTextAppearance(this, Resource.Style.boldText);
        }

        tableLayout.AddView(demoTableRow);
        View vLineRow = new View(this);
        vLineRow.SetMinimumHeight(1);
        vLineRow.SetBackgroundColor(Color.Rgb(88, 88, 88));
        tableLayout.AddView(vLineRow);
    }
}

The code is self explanatory and there’s not much detail to it. I would rather explain the refresh icon functionality, which when clicked or touched, refreshes the view. We will also show a “loading message” the time the application does the background process of calling the web service, pulling the XML data and creating the view with the data. “Refresh” is also done in Market Watch, but I thought it would be nicer to explain that a bit later after understanding – “calling of web service” and “creating controls dynamically”.

Collapse | Copy Code
ImageView btnRefresh = FindViewById<ImageView>(Resource.Id.buttonRefresh);
btnRefresh.Click += (sender, e) =>
{
    if (!IsLoading)
    {
        ProgressDialog progress = ProgressDialog.Show(this, "", "Loading Quote...", true);
        new Thread(new ThreadStart(() =>
        {
            this.RunOnUiThread(() =>
            {
                doLoadDetails();
                progress.Dismiss();
            });
        })).Start();
        IsLoading = false;
    }
};

We will be using a new thread to run the method doLoadDetails(). Before that we will use one extra thing, ProcessDialog. A progress dialog is part of the Android API and can be used to display either a progress bar or a spinning progress symbol.

So, the basic idea is to show the process dialog first. Then start a new Thread and Run the Method within that thread. Once the method executes, we will Dismiss the process using progress.Dismiss().

Third Step – View Stock Chart from Action Bar – Menu

When we are talking about Market Watch, it would not be fair if we don’t provide Chart option to user. Users are quite often interested in viewing charts for different Parameters to understand the Stock Movement Trend.

What are the Chart Parameters?

  • 1 Day
  • 5 Days
  • 3 Months
  • 6 Months
  • 1 Year
  • 2 Years
  • 5 Years

The Web Method – “GetStockChart” expects two input parameters – Stck Code and Chart Parameters. The method will return the chart image as byte array. Let’s look at the code,

Collapse | Copy Code
byte[] image_data;
stockwebservice.StockWebservice quoteObject = null;
try
{
    quoteObject = new stockwebservice.StockWebservice();
    image_data = quoteObject.GetStckChart(_stock, _type);
}
finally
{
    quoteObject.Dispose();
    quoteObject = null;
}

So, we have now the byte array and how simple it is to convert the byte array to ImageView Control.

Collapse | Copy Code
//convert byte array to image
Bitmap bitmapChart = BitmapFactory.DecodeByteArray(image_data, 0, image_data.Length);
imgChart.SetImageBitmap(bitmapChart);
imgChart.SetBackgroundResource(Resource.Color.transparent);

Now, we need to place seven buttons and add onClick Handler which when clicked will call the web method – StockGetChart with the different chart parameters.

Collapse | Copy Code
btn1D.Click += (sender, e) => { doLoadChart(sender, "1D"); };
btn5D.Click += (sender, e) => { doLoadChart(sender, "5D"); };
btn3M.Click += (sender, e) => { doLoadChart(sender, "3M"); };
btn6M.Click += (sender, e) => { doLoadChart(sender, "6M"); };
btn1Y.Click += (sender, e) => { doLoadChart(sender, "1Y"); };
btn2Y.Click += (sender, e) => { doLoadChart(sender, "2Y"); };
btn5Y.Click += (sender, e) => { doLoadChart(sender, "5Y"); };

In the above method “doLoadChart” calls the Web Method – GetStckChart” and return image as byte array. Have a look into the web service code, how image is converted to byte array and send back to client. We will run the method in a Thread to show the Process Dialog till the image is fully loaded in the ImageView Control.

Now before going to the next step, let’s have a quick look into the Stock Chart Layout (StckChart.axml)

Collapse | Copy Code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="28dp"
        android:id="@+id/linearLayoutstockdetails"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp">
        <TextView
            android:id="@+id/stockchartcaption"
            android:layout_width="206dp"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:textColor="@android:color/white"
            android:removed="#000000"
            android:layout_marginLeft="0px"
            android:textSize="14dp"
            android:textStyle="bold"
            android:paddingTop="2dp"
            android:layout_gravity="center_horizontal" />
        <Button
            android:text="1D"
            android:layout_width="28dp"
            android:layout_height="18dp"
            android:textSize="12dp"
            android:id="@+id/button1D"
            android:textColor="#ffffff"
            android:padding="3dp"
            android:background="#1C1C1C"
            android:layout_marginTop="4dp"
            android:layout_marginBottom="4dp"
            android:layout_marginRight="2dp"
            android:layout_marginLeft="6dp" />
        <Button
            android:text="5D"
            android:layout_width="28dp"
            android:layout_height="18dp"
            android:textSize="12dp"
            android:textColor="#ffffff"
            android:padding="3dp"
            android:background="#1C1C1C"
            android:layout_marginTop="4dp"
            android:layout_marginBottom="4dp"
            android:layout_marginRight="2dp"
            android:id="@+id/button5D" />
        <Button
            android:text="3M"
            android:layout_width="28dp"
            android:layout_height="18dp"
            android:textSize="12dp"
            android:textColor="#ffffff"
            android:padding="3dp"
            android:background="#1C1C1C"
            android:layout_marginTop="4dp"
            android:layout_marginBottom="4dp"
            android:layout_marginRight="2dp"
            android:id="@+id/button3M" />
        <Button
            android:text="6M"
            android:layout_width="28dp"
            android:layout_height="18dp"
            android:textSize="12dp"
            android:textColor="#ffffff"
            android:padding="3dp"
            android:background="#1C1C1C"
            android:layout_marginTop="4dp"
            android:layout_marginBottom="4dp"
            android:layout_marginRight="2dp"
            android:id="@+id/button6M" />
        <Button
            android:text="1Y"
            android:layout_width="28dp"
            android:layout_height="18dp"
            android:textSize="12dp"
            android:textColor="#ffffff"
            android:padding="3dp"
            android:background="#1C1C1C"
            android:layout_marginTop="4dp"
            android:layout_marginBottom="4dp"
            android:layout_marginRight="2dp"
            android:id="@+id/button1Y" />
        <Button
            android:text="2Y"
            android:layout_width="28dp"
            android:layout_height="18dp"
            android:textSize="12dp"
            android:textColor="#ffffff"
            android:padding="3dp"
            android:background="#1C1C1C"
            android:layout_marginTop="4dp"
            android:layout_marginBottom="4dp"
            android:layout_marginRight="2dp"
            android:id="@+id/button2Y" />
        <Button
            android:text="5Y"
            android:layout_width="28dp"
            android:layout_height="18dp"
            android:textSize="12dp"
            android:textColor="#ffffff"
            android:padding="3dp"
            android:background="#1C1C1C"
            android:layout_marginTop="4dp"
            android:layout_marginBottom="4dp"
            android:layout_marginRight="2dp"
            android:id="@+id/button5Y" />
    </LinearLayout>
    <ImageView
        android:id="@+id/imageChart"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:clickable="true"
        android:layout_marginTop="2dp" />
</LinearLayout>

If you see the TextView and the buttons for showing different charts are kept in a LinearLayout with orientation:horizontal. We have already discussed, placing controls in a Linearayout (orientation:horizontal) simply means the control will be placed side by side.

One vital information, I missed in the beginning of this section is we will be forcing the screen to be viewed in Landscape. As the chart will not be best fitted in portrait, we will be forcing the screen to be opened in Landscape.

The simple trick for doing this,

Collapse | Copy Code
[Activity(Label = "Stock Chart", ScreenOrientation = Android.Content.PM.ScreenOrientation.Landscape)]

Forth Step – Add Custom Stock to SQLite Database

In this Activity we will be adding Stock to SQLite Database. The stocks that are added will be shown in summary in Market Watch and detail in StockDetails Activity.

Let’s focus on the screen first.

Add Stock Layout

The Layout for AddStock Activity is pretty simple. Have a look into the AddStock Layout

Collapse | Copy Code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/linearLayout1">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Enter the full Stock Symbol for your exchange. Valid Stock will be added only."
        android:layout_marginTop="36px"
        android:layout_marginBottom="14px"
        android:layout_marginLeft="8px"
        android:textSize="13sp"
        android:layout_marginRight="8px" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="40px"
        android:id="@+id/textStock"
        android:textColor="@android:color/black"
        android:hint="Enter Stock Symbol"
        android:layout_marginLeft="8px"
        android:layout_marginBottom="12px"
        android:layout_marginRight="80px"
        android:padding="4px"
        android:textColorHint="#323232"
        android:textSize="15sp" />
    <Button
        android:id="@+id/buttonAddStock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Stock..."
        android:layout_marginLeft="8px" />
</LinearLayout>

As we are placing the controls one after another, we only need a Linear Layout orientation “Vertical”. We have primarily three controls,

  • TextView
  • EditText
  • Button

You have probably noticed that some padding has been given to get the spacing between each control.  One thing I will stress here is the Hint, i.e. a grayed-out text within the EditText control. This is something like the “placeholder” attribute of a input text in HTML. While designing the screen layout in a mobile device we need to be very sure about the spaces. We don’t have too many spaces in a screen to fit all controls. So Hint is often used in Mobile where we get rid of one extra control to let the user identify what the EditText does.

Collapse | Copy Code
android:hint="Enter Stock Symbol"
android:textColorHint="#323232"

AddStock Activity Class

We will do some basic validation while we click the Add button. Then we will check whether the stock script the user enters is a valid script. If it is not a valid script, we need to display the Message in a Torch. The last important validation is we need to ensure that users don’t add duplicate stock. So, we will check whether the Stock Script entered exists in the database.

Collapse | Copy Code
private bool doCheckStockScript(string _stockscript)
{
    //conecting to webservice and get the xml
    string strXML = string.Empty;
    stockwebservice.StockWebservice quoteObject = null;
    try
    {
        quoteObject = new stockwebservice.StockWebservice();
        strXML = quoteObject.StockExists(_stockscript);
    }
    finally
    {
        quoteObject.Dispose();
        quoteObject = null;
    }
    //if error occurred while connect8ing to web service
    if (strXML.Substring(0, 5) == "error")
    {
        var t = Toast.MakeText(this, 
        "Error connecting to web service. Please check your Internet connection...", 
        ToastLength.Short);
        t.SetGravity(GravityFlags.Center, 0, 0);
        t.Show();
        return false;
    }
    if (strXML.ToLower() == "exception")
    {
        var t = Toast.MakeText(this, 
        "Service not available now. Please try after sometime...", ToastLength.Short);
        t.SetGravity(GravityFlags.Center, 0, 0);
        t.Show();
        return false;
    }
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(strXML);
    XmlNodeList xnList = doc.SelectNodes("/stock/symbol");
    foreach (XmlNode xn in xnList)
    {
        if (xn["exchange"].InnerText.Trim().ToUpper() == "NA")
            return false;
    }
    return true;
}
private bool AddStockScript(string _stockscript)
{
    bool Ok = false;
    StockManager.Message = string.Empty;
    Ok = StockManager.SaveStock(_stockscript);
    if (StockManager.Message != string.Empty)
    {
        var t = Toast.MakeText(this, StockManager.Message, ToastLength.Short);
        t.SetGravity(GravityFlags.Center, 0, 0);
        t.Show();
    }
    return Ok;
}

Once added successfully we will show a quick message in “Toast” and return back to Market Watch Activity.

Fifth Step – Get Stock Details

Get Stock Details is a customized search of a Stock. The user will enter the script and press the “Get Stock” button and the stock Quote details are displayed on the screen. Here is a screen shot of how Get Stock looks after fetching stock data. In the example I have used script “GOOG” which is the Stock Script of Google Inc.

Let’s look at the GetStockActivity class:

Collapse | Copy Code
private bool IsLoading = false;
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    View titleView = Window.FindViewById(Android.Resource.Id.Title);
    //update the default title
    if (titleView != null)
    {
        IViewParent parent = titleView.Parent;
        if (parent != null && (parent is View))
        {
            View parentView = (View)parent;
            parentView.SetBackgroundColor(Color.Rgb(28, 28, 28));
            parentView.SetMinimumHeight(32);
            parentView.SetMinimumHeight(32);
        }
    }
    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.GetStock);
    ImageView btnHome = FindViewById<ImageView>(Resource.Id.buttonHomeget);
    btnHome.Click += (sender, e) =>
    {
        StartActivity(typeof(MarketWatchActivity));
        return;
    };
    EditText textStock = FindViewById<EditText>(Resource.Id.textGetStock);
    Button btnGetStock = FindViewById<Button>(Resource.Id.buttonGetStock);
    btnGetStock.Click += (sender, e) =>
    {
        if (textStock.Text == string.Empty)
        {
            //message if no text is entered in script
            var t = Toast.MakeText(this, "Please eneter Stock Script", ToastLength.Short);
            t.SetGravity(GravityFlags.Center, 0, 0);
            t.Show();
            textStock.Focusable = true;
            return;
        }
        //check script from webservice to see, if it is a valid script
        if (doCheckStockScript(textStock.Text.Trim()))
        {
            ProgressDialog progressMain = ProgressDialog.Show(this, "", "Loading Quote...", tru                   e);
            new Thread(new ThreadStart(() =>
            {
                //Thread.Sleep(4 * 1000);
                this.RunOnUiThread(() =>
                {
                    doLoadDetails(textStock.Text.Trim());
                    progressMain.Dismiss();
                });
            })).Start();
        }
        else
        {
            //message if no text entered is not a valid script
            var t = Toast.MakeText(this, "You have eneterd invalis Stock Script. Please eneter a valid Stock Script", ToastLength.Short);
            t.SetGravity(GravityFlags.Center, 0, 0);
            t.Show();
            textStock.Focusable = true;
            return;
        }
    };
}
private bool doCheckStockScript(string _stockscript)
{
     //check, if the stock script is Valid 
}
protected void doLoadDetails(string _script)
{
     //connect to web service to pull the real time stock data and display the result on the screen 
}

Nothing much to explain in details. If you look at the method “doCheckStockScript()”, it checks the validity of the stock script entered. If the script entered is invalid, a message will pop out using “Toast”

Wrapping up the Application

So we have almost covered all areas, but there are a few things I didn’t discuss earlier in the article, so I will discuss them now. Did you thought while going through the discussion, how we navigate from one page to another (apart from Home icon at the top right)?

There are several ways we follow for the navigation. But depending on the application requirement, I will be using “OptionMenu” to be visible in Action Bar to navigate or jump from one Activity to another.

Collapse | Copy Code
public override bool OnCreateOptionsMenu(IMenu menu)
{
    menu.Add("Get Quote").SetIcon(Resource.Drawable.ic_stock_get); ;
    menu.Add("Add Stock").SetIcon(Resource.Drawable.ic_quote_add);
    menu.Add("Delete Stocks").SetIcon(Resource.Drawable.ic_stock_delete);
    return true;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
    switch (item.TitleFormatted.ToString())
    {
        case "Delete Stocks":
            doDeleteStocks(); break;
        case "Add Stock":
            doOpenAddStock(); break;
        case "Get Quote":
            doOpenGetStock(); break;
    }
    return base.OnOptionsItemSelected(item);
}
//delete all saved stocks from database 
protected void doDeleteStocks()
{
    StockManager.DeleteAllStocks();
    if (!IsLoading)
    {
        ProgressDialog progress1 = ProgressDialog.Show(this, "", "Deleting Stock...", true);
        new Thread(new ThreadStart(() =>
        {
            this.RunOnUiThread(() =>
            {
                doLoadMarketWatch();
                progress1.Dismiss();
            });
        })).Start();
        IsLoading = false; 
    };
}
protected void doOpenAddStock()
{
    StartActivity(typeof(AddStockActivity));
}
protected void doOpenGetStock()
{
    StartActivity(typeof(GetStockActivity));
}

We are overriding the method OnCreateOptionsMenu(IMenu menu). We will use “menu” to create menu items in Action Bar. IMenu is an interface which exposes three important methods – Add, AddMenu, AddSubMenu. We can further enhance the menu building in an Android application depending upon the requirements.

You are Done – Building Professional Android Application

You have now completed building Professional Android applications. Even though we’ve only covered a small part of the features and controls I have used in this application, it is within everyone’s ability to build upon and enhance their skills to the level of “professional Android developer.” This article will give you a fair idea how to create a professional Android application using C# and Visual Studio 2010. The last step is how you run and test the application. Like all device applications we can run the application in an emulator before installing it into the actual device. In the next section I will describe how to deploy and run the application in the emulator.

Deploy and Run the Application

After you build successfully, go to Debug>Start without Debugging. You can use also Start with Debugging, if you need to debug. Once you click “Start” a window will appear, where you need to select “Start emulator image”.

The API Version denotes the Targeted device – supported Android Version  I will be selecting API 10, means the Android version supported is 2.3. Once you select the version and continue, you will find a screen below, Select Emulator  Click “OK” to continue. It will take some time estimated 1 minute to 4 minutes depending upon your Processor speed. So, I would suggest keeping open the emulator while you work with coding. This will save your valuable time. Once the Emulator loads the Activity it will look like: Running COINS in Emulator

Note:Though it is free to run and test the application free in Emulator, you need a License to install the application to the physical device.

Future Scope

Mobile, iPad, and Tablet PCs are gaining popularity day by day. We are not at all restricted to gaming applications only. We can create powerful business applications for Small/Medium/Enterprise. It is possible to build applications in all the above devices using Mono C#. Apple uses their own O/S iOS. MonoTouch supports C# for writing professional application using Mono C#. We are already developing Windows Mobile applications in .NET. So, in conclusion, Visual Studio(C#) is the language we can explore to develop cross platform applications in almost all the above devices in today’s market.

Where Am I?

You are currently viewing the archives for October, 2012 at Naik Vinay.