Friday, December 9, 2011

How to write readable code? 5 Tips to improve your code readability.

Written by Alberto Gutierrez

Readability is one of the most important characteristics of good code. These are a few tips that may help you to produce it.

1.- Use a top down approach (TDD).

Using a top down approach is similar to TDD you start with the highest level logic: the validation of what your code has to perform (The unit test), and then you add layers of abstraction, which as you keep coding become more separated from the domain problem and more related with implementation details. This approach helps to produce more readable code because:

  1. Producing the unit tests will give you a general idea about how readable is your code. Readable unit tests generally mean readable code.
  2. Separating the implementation details and the domain logic makes them easy to understand.

2.- Make your design match your domain (LRG and DDD).

In the excellent book applying UML and patterns, Craig Larman introduces the concept of Low Representational Gap (LRG). The representational gap is how different is the domain logic of an application from its design, having a low representational gap means that the design has very few differences with the domain logic it represents. LRG and Domain Driven Design DDD are much related concepts as they both focus on designing a domain model that matches the real model.

An application that has a LRG will be much easier to read because the actual domain logic will match the implementation domain logic.

3.- Use abstractions only when necessary (YAGNI and KISS).

Sometimes is tempting to make everything too much flexible. As software developers we always have to have in mind these two principles: You Are Not Going to Need It (YAGNI) and Keep It Short and Simple (KISS), remember: Code is not better because it has abstraction layers that may be useful in the future, they are going to make your code harder to read, just use abstraction layers when you need them now, not just in case they are necessary in the future.

4.- Use good names.

Using good names in your code is critical, it will make a difference between a code which will be read as plain English and a code where you will be shouting WTF?!! every two lines.

In this article: tips to write variable names, there are a few tips that can actually be applied to name any named element not only variables.

5.- The 5 minutes explanation test.

Apart from using the previous 4 tips and some other guidelines you may think appropriate to create readable code, I like to pass the 5 minutes explanation test to my code to know how readable it is.

  1. Grab a fellow programmer who spares some time to review your code
  2. Walk him through your code, just a high level introduction.
  3. Ask him if he understood your code.

After following these steps you can evaluate how readable your code is based on how much it took you to explain it. I call it the 5 minutes explanation test because as a rule of thumb if it takes more than 5 minutes for the other programmer to have a high level idea of the design, assume that the code is not readable.

10 commandments for creating good code

Written by Alberto G

1.- DRY: Don't repeat yourself.

DRY is usually the easiest principle to understand, but it is quite harder to apply. It means that when finding similar code in two or more places, we should abstract them into a new method and change the previous code fragments so they will now call the new method with the appropriate parameters.

DRY is maybe the most universal coding principle, I have never found a developer who would argue that repeating code is good, but, I have found developers that forget about this principle when coding unit tests, as an example: imagine that you have changed the interface of a class which had lots of unit tests, if you haven't used DRY, you will have to manually change the call to this class interface to match the new signatures to each test case.

2.- Write short methods.

There are three very good reasons for writing short methods.

  1. Your code will be easier to read.
  2. Your code will be easier to reuse (short methods are likely to produce loose coupling).
  3. Your code will be easier to test.

3.- Use good names for your classes, methods and variables.

There is nothing nicer than using some other developer code and not having to read its documentation because the names of the classes and the methods are telling us everything, so, make everyone's life easier and take this approach, expend always a few seconds before naming any element in your code.

4.- Assign the right responsibility to each class.

One class, one responsibility, that will sound familiar to those who know about the SOLID principles, but not any responsibility, the right responsibility, so if we have the class Customer, we won't assign to it the responsibility to create a new sales action, we will just assign it the responsibility to handle all the data related with a customer.

5.- Keep your code organized.

This organization is at two levels.

  • Physical organization: Whatever the structure you are using, packages, namespaces, folders… Organize your classes in such a way that is easy and intuitive to find where the code is stored.
  • Logical organization: Whatever belongs logically together should have access to each other members, but what belongs to a different logic structure has to access them by an interface. These logic groups are commonly implemented as layers, services…

6.- Create lots of unit tests.

The most tests you have, the better, they are our safety net for all the changes we will have to perform in the code in the future.

7.- Refactor often and sooner.

Software development is a continuous discovery process, in order to keep up to date with good code that matches the new/changing requirements is essential to refactor the code as we go. As this is a risky task there are 2 main preconditions to avoid entering new bugs into the system.

  1. Have lots of unit tests.
  2. Do small refactor steps at a time. In software development there are very few things more annoying than start refactoring 2000 lines of code to after 3 hours of work realize that is necessary to roll back to the original version because now nothing works and the track of which change is causing the problem is lost.

8.- Comments are evil.

This particular one is a bit controversial, most of us were taught that comments are good, and actually it's better to have a comment in an obscure piece of code than just having the code by itself, what this point means is that: even better than having a comment for an obscure piece of code is to not to have that code at all, just refactor it until is a nice and readable piece of code. [EDIT] Please read this other post for a better explanation of what "comments are evil" means.

9.- Code to an interface, not to an implementation.

This is a classic one, coding to an interface will free us from the implementation details, we just define a contract and rely on calling the defined operations on the contract, expecting that the actual implementation will be passed to our code or decided at runtime.

10.- Have code reviews.

We all make mistakes, and there's nothing better than asking some other person to have a quick and informal review in our code to find them, in order to make the reviews,  it's better not to wait until the code is completed, it's better to ask for reviews whenever some important part of the code has been completed or when a few days have passed from the previous review.

5 Tips for creating good code every day; or how to become a good software developer

Written by Alberto G

Being a good developer is like being any other good professional, it's all it's about doing as much quality work as possible. There is a popular sentence that summarises it: "Do it. Do it right. Do it right now".

1.- Have your own to do list for the day.

The best approach to complete complex activities is to break them down into simple activities. Do this every morning by breaking down the different activities you would like to complete for the day and assign them a schedule. This will help you to:

  • Have a better understanding of the activity.
  • Have a focused goal for the day
  • Improve your estimating skills. After a few days you will find that you can predict how much work you can do in a day.

2.- Do one thing at a time.

It's been proven by different studies and published in different media (ie CNN) that it  is more productive to be focus only on one task than to do multitasking.

Work in short batches of intense work of about 25 minutes with a 5-10 minutes rest. There are popular techniques like the pomodoro technique to help you manage the time. There are also tools to help you measure the time you spent on the different tasks, my favorite one is CoolTimer.

3.- Do it right.

There are two keys to know if something is done right

  1. To be proud of the solution; it is not just any solution, it is a good solution. It follows the principles of the "Pyramid of the software quality".
  2. The solution passes at least one review. Ask one of your colleagues that you respect as a good developer to review your solution and for his sincere opinion.

4.- Don't finish something until it's completely done.

We all know that if there's still a glass to wash, we cannot say that we have done the dishes, the same applies for painting a wall or driving to a destination but in software development we don't do that, we say that we are done even when we haven't completed all the unit tests or when we haven't checked if the implementation is correct with the customer, that's a typical behavior from Hope Driven Development and that's evil.

Something is only done when you are 100% sure that it won't be necessary to work at all on that solution unless the requirements change.

5.- Better late than sorry BUT better sorry than never.

If it's going to take you an extra day to complete the testing of some code, or to refactor a class which is unreadable, do it, that's an investment in time for the future, but if you are stuck with something and you are delaying the project too much, just find an easier solution. It may not be as elegant as the one you are implementing, but at least you will have a solution. Make sure to document it as future risk for the project and something that will probably need to be revisited.


7 best practices for taking decisions in the development team

Written by Alberto G

During the software development process, a lot of decisions have to be taken, they may be related to design or architectural issues, testing approaches and many other different areas… What follows is the 7 best practices for making the most when you are about to take a decision in your team

The 7 Good practices.

1.- Have a clear goal. (A vision statement)

Good Example: "We need to decide on what technology we are going to use for the UI of the next product".

Bad Example: "What are we going to do next week?".

Write it in a board making sure that everyone can read it. (Importance of boards are highlighted in the 6th point)

2.- Gather all the inputs.

As explained in my previous article about inputs, outputs and actions, inputs are the clues that leads us to find the best solution, in order to take the best decision we need to make sure that we  have the appropiate inputs.

Good Examples: "We are not tight to use the same technology for the backend and the frontend", "Inside the team there is strong expertise in technologies x,y and z", "The dead line for the UI is in one month"…

Write them in the board as well. (Importance of boards are highlighted in the 6th point)

3.- Keep the discussion objective

Opinions should be translated into facts and numerical arguments, if not it will be impossible to compare with each other, keep an eye on the following symptoms of a non objective discussion

- Don't use Buzz words/be vague/use the word "should".

Some examples: "This approach should be easy", "performance is going to be bad", "what I am suggesting is a best practice in the industry"….

- Don't let people speaking in future terms (if they are outside of the scope).

If the scope of the solution doesn't include any point that states that the solution has to be time proof, then don't let people use that argument to discuss. Example: "Well, I don't like this logging approach because there is too much overhead data, and maybe in one year we will run out of space".

- Avoid people from first being understood rather than to understand.

Lots of time two persons argue about something but they are basically saying the same thing with different words, two tricks to avoid this are:

- Don't let people interrupt
- Make them rephrase other people point with polite questions like: "Sorry Tom, just to make sure you understood Andrew point could you rephrase it?".

4.- Don't make it personal

If deciding A or B becomes deciding if Bob is better having good ideas than Harry, your may be discussing for the next two weeks.

- Separate opinions from people.

Write them in the board and call them with letters or numbers, NEVER write besides them who suggested the idea. Try to mix the best from all the ideas rather than selecting just one person approach.

- Be careful with the egos.

Software developers usually have huge egos, actually the better is a developer, the bigger is his ego.

5.- Timebox the decision, make the decision process takes as short as possible.

As we will see in the last part of the article it's not about the idea is about the execution, but we still want a good enough decision, as a rule of thumb, if the vision is clear, the inputs have been discovered and every one have expressed their opinion, it shouldn't take longer than 15 minutes to make a decision.

6.- Keep Focused

Book a room with a board. The idea of having a board is to picture all that has been discussed, at least in the board there should be the "Vision" (Point1), "Inputs" (Point2), all the different alternatives, and the final decision.

Don't discuss anything outside the scope of what needs to be decide.

Focus on "why" rather than "how" or "what", just make them explain why a solution is better or worse, is very easy to get stuck in implementation details.

Make people describe their opinions in short sentences and write them on the board.

7.- Make everyone participant of the final decision.

Have a final solution that includes the best from every alternative, thank everyone for their effort.

At the end all is about the execution, not the idea.

Even being important to have a good decision, what matter is the execution, that's why point5 focus on make the decision making process as quick as possible.


Monday, October 31, 2011

Working with CSS3 background images

By Ryan Boudreaux

Takeaway: Ryan Boudreaux goes over some examples of writing CSS3 code for background images that you can begin to implement now.

This segment of the CSS3 series will focus on images, specifically CSS3 background images which can be implemented in many browsers today. Check out the previous posts in the CSS3 series:

CSS3 background images

Background images and textures can be utilized to layer a background without the use of separate divs, often adding a nice graphic touch to websites. In CSS3 we can now apply dimensions as well for images and define multiple background images within a single rule. There are two methods which allow for establishing rules. They are the CSS3 individual background rule and the CSS3 shorthand background rule; I will review both of them in this segment.

Browser support for CSS3 multiple backgrounds includes Mozilla Firefox (3.6+), Safari/Chrome (1.0/1.3+), Opera (10.5+), and Internet Explorer (9.0+).

The CSS3 background individual method is essentially a comma separated list of layered images written in the syntax form:

background: url(%path%/image1.xxx), url(%path%/image2.xxx);

And with the background individual method, we can include a comma separated list of background properties including background-repeat, background-attachment, background-position, background-clip, background-origin, and background-size.

In the example below, the background is defined by class with width of 800, height of 500, and a background containing three images layered, with background-position and background-repeat defined as shown in this CSS3 code:

.mBg_1 {
      width: 800px;
      height: 500px;
      background:
      url(images/barn.png),
      url(images/clouds.png),
      url(images/grass.png);
      background-position: bottom, left top, bottom;
      background-repeat: no-repeat;
}

The above code results in this example of the barn, cloud, and grass images displayed in Chrome:

Figure A

The other way of presenting background images utilizes what is known as the background shorthand method. The W3C CSS3 Backgrounds and Borders specification provides this explanation of the background shorthand syntax:

The number of comma-separated items defines the number of background layers. Given a valid declaration, for each layer the shorthand first sets the corresponding layer of each of 'background-position', 'background-size', 'background-repeat', 'background-origin', 'background-clip' and 'background-attachment' to that property's initial value, then assigns any explicit values specified for this layer in the declaration. Finally 'background-color' is set to the specified color, if any, else set to its initial value.

If one <box> value is present then it sets both 'background-origin' and 'background-clip' to that value. If two values are present, then the first sets 'background-origin' and the second 'background-clip'.

Of note here, the background-color must be the last layer in the declaration using the shorthand method.

One way to represent the background shorthand method specifying images with each one given a precise position is represented in the following syntax:

background:  url(%path%) Xpx Ypx, where Xpx = x-axis and Ypx = y-axis;

For example, the CSS background rule below defines the html of the document with a number of small images including a grid and several color swatch chips layered above.

html {
      background:
      url(images/ffccff_swatch.png) 175px 25px no-repeat,
      url(images/ff9933_swatch.png) 125px 425px no-repeat,
      url(images/cccc33_swatch.png) 325px 325px  no-repeat,
      url(images/669966_swatch.png) 325px 125px no-repeat,
      url(images/cccccc_swatch.png) 175px 275px no-repeat,
      url(images/ffffcc_swatch.png) 425px 125px no-repeat,
      url(images/ccffcc_swatch.png) 575px -25px no-repeat,
      url(images/ffccff_swatch.png) 225px 425px no-repeat,
      url(images/ff9933_swatch.png) -25px 225px no-repeat,
      url(images/ffccff_swatch.png) 525px 325px no-repeat,
      url(images/ff9933_swatch.png) 375px 225px no-repeat,
      url(images/cccc33_swatch.png) 125px 225px  no-repeat,
      url(images/grid.png) repeat;
}

This example, using the shorthand background method, results in a graphic background, incorporating some of the content from previous CSS3 segments within the HTML, including the blockquote and multi-column layout, and is rendered as seen below in Chrome:

Figure B

Positioning of images using the CSS3 shorthand background properties method can also take on the form of utilizing a position for each image as in this form:

.mBg_2 {
      width: 800px;
      height: 500px;
      background:
      url(images/barn.png) bottom right no-repeat,
      url(images/clouds.png) top left no-repeat,
      url(images/grass.png) bottom no-repeat;
}

The above code results in the following as displayed in Chrome:

Figure C

As you can see from the examples given above, there are two ways to present the layered images utilizing CSS3. The next segments on CSS3 will review border images, rounded corners, 3D text, transitioning and other features and functions, which can be implemented today.


CSS3: New properties for text-overflow and text-wrap

Takeaway: Ryan Boudreaux illustrates the CSS3 text-overflow and text-wrap properties in these code examples.

Continuing in our CSS3 series, I want to cover a few more aspects of the W3C Text Module; in particular, this segment will review the text-overflow and word-wrap properties. The Text Module document presents a set of text formatting properties for CSS3, and while many of these properties already existed in CSS2, many of the new properties have been added to address basic requirements in international text layout, particularly for East Asian and bidirectional text. The Text Module specification is a Candidate Recommendation, which means W3C believes the specification is ready to be implemented.

Text-overflow

On occasion text will need to be clipped and the text-overflow property determines if an ellipsis needs to be represented. There are several methods for representing overflow of textual content, using clip, ellipses, and ellipsis-word. Text overflow handles situations where some textual content gets clipped when it overflows an element's container such as a fixed width box, or within its inline-progression within a given layout area. This situation only occurs when the overflow property has the values: hidden, scroll or auto. Text-overflow allows the web author to introduce a visual hint at the two ending boundaries of the text flow within the element box (after an end). Text clipping is usually provided to the user in the form of a visual hint, which typically is represented with an ellipsis character (…).

The following guidelines are provided by the W3C for each instance and use for text-overflow:

  • Clip: This is the default value, and will clip text as appropriate for the text content and given area. Any glyphs in the representation of text may be only partially rendered.
  • Ellipsis: Is a visual hint which is inserted at each area boundary where text overflow occurs. The text-overflow-ellipsis property determines the content of the hint, and the insertions take place after the last letter that entirely fits on the line.

The syntax for representing the text-overflow is

text-overflow:  ellipsis | clip

Opera currently has a vendor prefix for text overflow that is specified in the form:

-o-text-overflow:

Text overflow gets applied when:

  1. The area has the overflow property value set to either hidden, scroll, or auto.
  2. The area has the white-space property value set to nowrap.

Using the ellipsis for text overflow, the example CSS3 code below defines a style for a paragraph with a solid 1px color border, an area width of 400px, with 5px padding:

p {
      border: 1px solid #CC33CC;
      width: 400px;
      padding: 5px;
      white-space: nowrap;
      overflow: hidden;
      o-text-overflow: ellipsis;
      text-overflow: ellipsis;
}

Along with the following HTML:

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean egestas blandit ipsum.</p>

Here is the result as displayed in Firefox 7.0.1:

Figure A

Now, replace the value ellipsis with clip in the text overflow property code:

o-text-overflow: clip;
text-overflow: clip;

And here is the result as displayed in Firefox 7.0.1:

Figure B

The examples above demonstrate that the ellipsis is a better user design with the visual hint, whereas the clip cuts off the next word to fit the defined area or box.

Another option for user centric design would be to add a title for the content where a mouse-over exposes more of the textual content or a description, for example, in the HTML below:

<p title="Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean egestas blandit ipsum.">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean egestas blandit ipsum. </p>

Here is the result with a mouse-over as displayed in Firefox 7.0.1:

Figure C

Word-wrap

With cross-browser support including IE as far back as version 5, the word-wrap property can be applied with the default value normal, or with the break-word value. In addition to the word-wrap property, CSS3 has several new properties controlled by both the overflow-wrap and the text-wrap property.

Word-wrap is probably not going to be the most widely used CSS3 property but it definitely has a practical use, for example, in controlling the styling of comment sections within blog posts or forms.

The syntax for the word-wrap property is:

word-wrap: normal | break-word;

The example below shows how text content is handled without the word-wrap property applied, where a paragraph is styled with a width of 200px, and a solid border to define the area as displayed in Firefox 7.0.1:

Figure D

Here is the same HTML when applied to the styling word-wrap property with the break-word value applied:

.word_wrap {
      word-wrap: break-word;
}

This is the result as displayed in Firefox 7.0.1:

Figure E

As previously mentioned, the practical application for the word-wrap property can be utilized within coding for comment sections for blogs in particular or for forms, which will help in preventing long strings of text that might be entered by hackers trying to vandalize sites.

Overflow-wrap specifies whether the browser or user agent may break within a word to prevent overflow when an otherwise unbreakable string of characters is too long to fit within the line. It only has an effect when the values for text-wrap are either normal or avoid. The values for overflow-wrap include normal hyphenate, and break-word.

Currently the use of overflow-wrap does not appear to be supported by any browsers.

Text-wrap specifies the mode for wrapping text, and includes the following possible three values, normal, none, and avoid. Normal is used where lines may break at allowed break points, as determined by the line-breaking rules in effect. None is utilized where lines may not break; text that does not fit within the block container overflows it. Avoid applies where line breaking is suppressed within the element: the UA may only break within the element if there are no other valid break points in the line. If the text breaks, line-breaking restrictions are honored as for normal.

CSS3: Working with text-decoration properties


Takeaway: Ryan Boudreaux shows some examples of the CSS3 text-decoration properties and different ways of styling text.

This segment of the CSS3 series will review several of the text-decoration styling properties. The text-decoration specification is included within the CSS Text Level 3 specification, and includes properties for lines, color, style, shorthand, line continuity, underline position, and emphasis. This segment will cover several but not all of the text-decoration styles available for use in most modern browsers today, and some that are only available in Mozilla Firefox.

Text-decoration

The W3C specifications on text-decoration provide several means of applying styles to text, including the following:

  • Line Decoration: Underline, Overline, and Strike-Through
  • Color
  • Style
  • Shorthand property
  • Line Continuity
  • Underline Position
  • Emphasis Mark Style, Color, Shorthand, Position, and Skip
  • Text Shadow Properties

Mozilla Firefox is the only browser offering support for the new CSS3 text-decoration properties when using the -moz- prefix before any styling declarations.

Line decoration

Line decorations specify what line styles if any are added to the element and the syntax is expressed in the form along with the following value options as described in the specification and presented below:

Syntax example:

p {text-decoration-line: underline;}

Available values and their descriptions:

Value

Description

None (default value) Neither produces nor inhibits text decoration.
Underline Each line of text is underlined.
No-underline Inhibits propagated underlines.
Replace-underline Inhibits propagated underlines and produces an underline.
Overline Each line of text has a line above it (i.e. on the opposite side from an underline).
No-overline Inhibits propagated overlines.
Replace-overline Inhibits propagated overlines and produces an overline.
Line-through Each line of text has a line through the middle.
No-line-through Inhibits propagated line-throughs.
Replace-line-through Inhibits propagated line-throughs and produces a line-through.
Remove-all Inhibits all propagated text decorations.

According to the line decoration specification the underlines, overlines, and line-throughs are applied only to text (including white space, letter spacing, and word spacing), while margins, borders, and padding are skipped. Elements containing no text, such as images, are likewise not decorated. And when specified on or propagated to an inline box, such decoration affects all the boxes generated by that element, and is further propagated to any in-flow block-level boxes that split the inline element. When specified on or propagated to a block container that establishes an inline formatting context, the decorations are propagated to an anonymous inline element that wraps all the in-flow inline-level children of the block container. For all other elements, the decorations are propagated to any in-flow children.

The example below demonstrates the use of text-decoration with the following styles:

p {
      font-size: 16px;
      font-family: Arial, Helvetica, sans-serif;
      font-style: normal;
      margin-left: 100px;
      width: 500px;
      border: solid #666666;
      padding: 5px;
}
article {
      text-decoration: underline; color: #0066FF;
}
em {
      display:block;
}
span.green_text {
      color:#336600;
}

And this HTML document snippet:

 <article>
      <p>
      <span>
        The article element is propagated to an anonymous inline element that surrounds the span element causing the text to be blue along with the blue underlining from the anonymous inline underneath it.<br /><br />
            <em>The color is being taken from the article element. The em block is also underlined as it is in an in-flow block to which the underline is propagated. The final line of text is green, but the underline underneath it is still the blue underline from the anonymous inline element.</em><br /><br />
            <span class="green_text">The text color is green!</span>
      </p>
 </article>

Figure A shows the result of the text-decoration underline example as displayed in both Chrome 14.0 and Firefox 7.01:

Figure A

The specification goes on to state that relatively positioning a descendant moves all text decorations affecting it along with the descendant's text; it does not affect calculation of the decoration's initial position on that line. The 'visibility' property, filters, and other graphical transformations likewise affect text decorations as part of the text they're drawn on, even if the decorations were specified on an ancestor element.

Here's an example of the text-decoration-line property styling with the overline value and using the moz prefix:

.text_decoration_overline {
      -moz-text-decoration-line: overline;
}

Figure B shows the result as displayed in Firefox 7.01:

Figure B

Text-decoration-color

According to the specification, the text-decoration-color property specifies the color of text decoration (underlines, overlines, and line-throughs) set on the element with text-decoration-line, and any computed color value is applied. An example of the text-decoration-color property in use is displayed below.

Text-decoration-style

The text-decoration style property specifies the style of the line(s) drawn for text decoration specified on the element. Values have the same meaning as for the border-style properties. The values available for the text-decoration-style are: solid, double, dotted, dashed, and wavy.

The following CSS3 declaration:

.snazzy {
    -moz-text-decoration-line: underline;
    -moz-text-decoration-style: double;
    -moz-text-decoration-color: green;
}

Figure C shows the result as displayed in Firefox 7.01:

Figure C

Google presentations wants to be your slide making tool of choice


Takeaway: Google has recently released a new version of Google presentations for their Google Apps suite of office tools that emphasizes collaboration.

Like it or not, the presentation is a necessary form of business communication that just about everyone has to create and deliver at least a few times during their career. The default tool used to create those presentations has for many years been Microsoft PowerPoint. Well, not to be outdone, Google has recently released a new version of Google presentations for their Google Apps suite of office tools.

New features

The primary new features added to Google presentations include:

  • Character-by-character collaboration
  • Drawing on canvas
  • Transitions
  • Shape linking
  • Better animations

Like all of the Google Apps, the presentations tool takes a minimalist approach to the user interface. When you click Create a new presentation you are presented with the basic slide creation view shown in Figure A.

Figure A

The basic slide creation screen

Just like PowerPoint presentations, themes are often where your slide building starts, and Google presentations has several basic themes to choose from (Figure B), although you can see there are not nearly as many as there are in PowerPoint. (I'll leave it to you to determine if that is a good thing or a bad thing.)

Figure B

There are several basic themes available in Google presentations

Bottom line

Google presentations, even with the new features, is still a fairly basic tool for creating slides. However, it does have one advantage over PowerPoint that could make it more valuable to you and/or your organization and that is the collaboration features. The ability to share your presentation and collaborate on it simultaneously can be a real time saver and productivity booster.

Perhaps Google presentations is worth a try as an alternative to PowerPoint.


How Microsoft could (but probably won't) take over the world again

Takeaway: Microsoft could be uniquely positioned to take over a number of market segments if they properly leveraged some of their existing product lines.

Once upon a time, it was popular to joke (or rant) about how Microsoft was bent on total world domination. Today, that is not so much the case. To the contrary, as I've noted here before, now it seems to be a popular misconception that Microsoft is a failing company.

Despite that belief, Microsoft could be uniquely positioned to take over a number of market segments — if they properly leveraged some of their existing product lines and recent acquisitions. Will they do that? Well, I'm not holding my breath, but I do think they might get it right with one or two of those markets. I guess I'm not the only one who thinks so, since many investment advisers are currently saying to buy Microsoft stock.

Microsoft has its fingers in many pies — some say too many — so there is potential for big success (or a big flop) on a number of different fronts. Here are some areas where I think the company could come to dominate (or continue to do so), if they play their cards right. I said last week that I don't think Microsoft should try to do this by emulating Apple. This week, I'll talk about what I think they should do to achieve domination in at least some parts of the technology world.

Tablets

Microsoft was pushing tablet PCs way back in the early 2000s, and a portable computer that could be operated easily when you weren't sitting at a desk was one of Bill Gates' dreams. They tried, with heavy, expensive slates and convertible laptops, then later with smaller Ultra Mobile PC (UMPCs), and the devices became quite popular in some vertical markets, but never quite caught on in the broader business world or with the general public.

Apple gets the credit for bringing tablets to the masses (on their third try, after the failure of the Newton and the Modbook). The iPad currently enjoys 73.4 percent of the tablet market share, but there are rumblings. Many users don't like the locked-down nature of Apple products. They want to know why they have to buy a whole new device to increase their storage capacity, instead of just popping in a flash card as they can do with most Android tablets. And they'd like it even better if they could connect their tablets to an external USB hard drive as they can do with their Windows laptops.

In fact, it seems that there are a lot of people out there who really, really want Windows on their tablets. That's the conclusion you have to draw from the result of recent surveys by Boston Consulting Group and Forrester, with percentages of those who prefer Windows ranging from 42 to 46 percent, iOS coming in at 16 to 27 percent, and Android at 9 to 20 percent.

That seems to indicate that, if Microsoft does tablets right with Windows 8, they could climb to the top of that market over the next several years. It won't happen overnight, but in typical Microsoft "slow-and-steady" fashion, they could overtake the mighty iPad. This is particularly true with Steve Jobs no longer there to lead Apple.

Phones

We already know that Gartner thinks Windows Phone has a good chance of overtaking the iPhone by 2015. Microsoft's "do over" of its mobile operating system got off to a slow start — in part because of bad experiences with Windows Mobile, in part because many consumers are wary of a first-generation anything, and in part because Windows Phone 7 was lacking many essential features, such as tethering and multitasking. These features (although they were also missing in the first versions of other operating systems) were standard on Android and/or iOS at the time WP7 hit the market. There were also rumors that salespeople with the major cellular carriers were actively discouraging customers from buying Windows phones.

But I think another important reason for slow sales among those "in the know" (who are also influential in what technology their less tech-savvy friends and relatives buy) has been the uncertainty surrounding the Windows Phone 7.x operating system.

There has been a general consensus that, with Windows 8, Microsoft's objective is "one operating system to rule them all" (more on that later). Does that mean the next version of Windows Phone will run Windows 8, and will it be backward-compatible with Windows Phone 7.x? Then there was the Nokia partnership. Will the Windows phones that come out of that be far better than the ones that are available today? I think many folks who are interested are taking a "wait-and-see" approach.

With the Mango (WP 7.5) update, though, Microsoft has proven that they're serious about making Windows Phone a contender. With more than 500 improvements, including the longed-for Wi-Fi tethering and multitasking capabilities, it might just be the beginning of the long road to world phone domination.

Gaming

The Xbox 360 has been on the top of the gaming console heap for the past many months, coming in at 42 percent in September, and the gaming business was credited with being an important factor in the record revenues that Microsoft posted for the most recent quarter. Although the total gaming market has been on the decline since 2008, it's still big business — a $43-billion business in 2010, to be exact. Market forecasts expect it to hold steady and increase slightly over the coming years.

The gaming market is dominated by software sales, and Microsoft is the software company with more experience than almost anyone. A recent trend has been toward games marketed as smartphone and tablet apps (e.g., Angry Birds), an area where Microsoft hasn't had much of a presence.

But with Windows 8 on the horizon and the new push to court Metro developers, that could change. If Microsoft makes Metro a platform that's friendly to game developers, we could see some exciting new low-cost game apps for casual game players, along with the more sophisticated console games that serious gamers prefer.

The integration of Xbox Live on Windows Phone is also a step in the right direction if Microsoft wants to dominate the gaming market. The ability to use your same avatars and play the same games from the phone would certainly attract hard-core gamers. In fact, the idea of using the same "virtual you" (avatar) across all your applications, not just games, is something that might just catch on.

I don't play games, but one of the most interesting and fun things that I did with my Windows Phone was create an avatar that I thought nicely represented my personality and general look. I would love to be able to use it in Internet communications where live video isn't possible or isn't desirable but where some sort of visual presence would add to the interaction.

TV and home entertainment

I've been a big fan of Windows Media Center since the original Windows XP WMC Edition. I was thrilled when Microsoft included it as a standard part of (some editions of) Vista and then Windows 7. I've tried a number of DVRs and PVR software, and I think WMC is the best.

We have a computer with four tuners running WMC on Windows 7 attached to our 65-inch Sharp Aquos in our media room and use it for all our TV recording and a Media Center Extender attached to the bedroom TV so that we can also watch our recorded programs there. We just recently invested in a HD Homerun Prime Ethernet network tuning device so that we can use a CableCARD to view and record premium HD channels on our Windows Media Center PCs.

I've been saddened by rumors that WMC either wouldn't be included in Windows 8 (since dispelled by Steven Sinofsky) or is not the focus of any new development (still up in the air). My hope is that Microsoft is not getting ready to ditch WMC entirely, but perhaps has other plans for it, such as incorporating it more fully into Xbox.

The Xbox can currently function as a Media Center Extender. How about making it a full-fledged Media Center itself that can record programs without being connected to a PC and then stream them (and your music, photos, home videos, Internet TV programs, and movies) to the other TVs in your home via DLNA?

If Microsoft turns the Xbox into much more than just a gaming console (which is certainly the direction they seem to be headed) and makes it a true home entertainment hub that can take the place of your TiVo or cable company-provided DVR, Windows Media Center might finally get the respect it deserves and Microsoft might take over the TV/home entertainment market. Neither Apple TV nor Google TV seems to have made much of a splash in the marketplace, so it's a segment that's there for the taking.

One OS to rule them all?

With the right strategy, Microsoft could pull this off and gain dominance in all these markets, along with the (shrinking but not going away anytime soon) desktop and laptop computing markets. Will Windows 8 be the linchpin that ties it all together? The same Windows that works across all your computing platforms would be a wonderful thing — if it works well on all of them. Microsoft would be positioned to integrate its products so tightly that it would seem silly to buy anything else.

It would also put Microsoft in a position where perhaps they could consider some really innovative ideas. Here's one that's really "out there": What about a smartphone that doesn't depend on the wireless carriers?

Most of the people I talk to hate their carriers. They feel they're overcharged for basic service and nickeled and dimed to death for extras. They hate the way they're locked into contracts in order to get affordable devices. They hate the way the carriers cripple features that are built in to the devices by the vendors or charge extra for you to use them (e.g., Wi-Fi tethering). They hate the new tiered data plans.

If Microsoft put a fully functional Skype on its Windows Phones and perhaps invested in helping to build out ubiquitous low-cost Wi-Fi coverage in all major cities and sold the devices outside the wireless carrier channels, how many people could and would dump their plans with AT&T or Verizon or Sprint? Sure, there would be some technological and regulatory hurdles to overcome, but if we're dreaming about world domination, what better way than to do an end run around the telcos?

Saturday, October 29, 2011

The 20 most useful Android smartphone apps of 2011


Takeaway: Jason Hiner provides his list of the top 20 tried-and-true Android smartphone apps that are worth your time to download.

The Android Market may not have as many apps as the iPhone App Store yet, but there are still more than enough to be overwhelmed, and it continues to grow at a breakneck pace. To help you sort through them all, here is my latest list of the 20 most useful Android apps (this is an update of my 2010 Android list). I've also recently updated my list of the most useful iPhone apps and you'll notice several of the same apps on both lists.

Remember that I primarily had business professionals in mind when making this list and also keep in mind that this is a snapshot in time. The Android platform is developing so quickly that I guarantee my home screen will look different a month from now.

Still, here's my list of tried-and-true Android apps that I can highly recommend.

1. Google Voice

Google Voice is a service that is so useful I consider it one of the top benefits of Android itself. The service gives you a phone number that can ring to multiple places or devices and it allows you to access all of your voicemail and text messages from the Web. The Android app integrates even deeper. It can make outgoing calls look like they're coming from your Google Voice number so that you can keep your real mobile number private.

2. Advanced Task Killer

One of the realities of having a multitasking mobile OS is that you have to manage your apps so that they don't hurt performance or battery life. Advanced Task Killer (ATK) is my favorite on Android. It even comes with a widget that you can tap once to kill all open apps and you can also set up ATK to kill all apps at periodic intervals. Some people will argue that task managers are irrelevant and unneeded in Android, but I still prefer to use ATK.

3. Dropbox

Dropbox is a great cloud service that automatically syncs a folder of files between multiple computers (Windows, Mac, or Linux). This app extends Dropbox to Android and interacts with other apps (such as Documents To Go) to open the files. It allows you to access PDFs, image files, and business documents by simply dragging them to a folder on your computer and then you immediately have access to them from your mobile phone, once you have this app installed.

4. Evernote

Once you get used to typing on a virtual keyboard (and it honestly took me over a year to do it), then these devices are great for note-taking, and Evernote is a great note-taking app. It is similar to Dropbox in that it saves data locally but syncs it across all your machines and devices.

5. Taskos

There are plenty of to-do apps to choose from on Android but I now prefer Taskos because of the clean, easy, Android-friendly user experience. It also has a few extras that give it an advantage over apps. The biggest one is voice recognition, which lets you speak a task that the app turns into a to-do item (you might have to correct a word or two).

6. DroidAnalytics

For some reason Google doesn't have an official app for Google Analytics (for either Android or iPhone). The best one I've found on Android is DroidAnalytics. Another good one is mAnalytics.

7. Documents To Go

The free version of Documents To Go offers a great little reader for Microsof Word and Excel files. You can upgrade to the full version (for $15) if you want to be able to create and edit files and add PowerPoint files to the mix. If you do want editing capability, I'd also recommend taking a look at QuickOffice.

8. Google Docs

If you mostly work with Google Docs (including uploading Microsoft Office files to your Google Docs repository) then the only app you'll really need is the Google Docs app. It's a nice mobile implementation of document management, although the one annoyance is that always open up files in a web browser rather than within the app itself, which would be a little smoother.

9. Tripit

I dig Tripit. It is by far the best app I've found for keeping track of all my travel itineraries. It runs on some great backend systems. You simply forward your confirmation emails for your flights, hotels, rental cars, and more to Tripit and it automatically organizes them into trips with all your details and confirmation numbers. Or, if you use Gmail, you can even use a plugin to automatically catch confirmation emails and turn them into Tripit trips.

10. Places

This is an awesome app for finding shops and services near your current location. From restaurants to medical facilities to taxis, this app is very accurate and takes advantage of the business information from Google Local. This app is better than the info you get from a GPS unit (or app) and better than any of the similar apps available on the iPhone. It's also integrated into Google Maps.

11. Astro File Manager

Another one of the great things about Android (if you're a geek or a tinkerer) is that you have lower-level access to the system itself. Astro is an app that lets you navigate the Android file system, which is mostly just interesting, but can be handy once in a while.

12. Speed Test

I'm obsessed with running speed tests to check my bandwidth in various places, both to see 3G/4G fluctuations and to check the quality of Wi-Fi. There are a number of really good speed test apps, but my favorite is the Speedtest.net app. It's generally consistent and it has some of the best graphics and options.

13. Amazon Kindle

I've never completely warmed up to the Amazon Kindle e-reader, but I'm a big fan of the Kindle mobile app. Since it was released I've read a lot more books simply because my smartphone is always with me and I can pull it out and read a few pages anytime I've got a couple minutes free.

14. Google+

I've written a lot about Google+ since it launched in July and I'm pretty active over there (+Jason Hiner). One of the great things that Google did was to release a Google+ Android app at the same time it launched the service as a beta. And, surprisingly, the app was actually pretty good and has been improved since. It immediately became one of my most used mobile apps and definitely stole some of my time away from Android's Twitter app, mostly because Google+ is a little more interactive.

15. TED Air

The TED conference features a meeting of the minds of some of society's most influential thinkers. You'll disagree with some of them since there's a large diversity of viewpoints, but many talks are worth listening to in order to catch the latest creative thinking on society's biggest challenges. The cool thing is that they've taken the videos from the conference and made them freely available on the Web. The TED Air app provides a great way to access the videos on a mobile device. I hope more conferences follow TED's lead on this.

16. Google Goggles

This is a fun app that is a little bit ahead of its time. It does visual searches. You can take pictures of things and then the app tries to tell you what they are. It's limited in its scope but it is pretty cool, and it's definitely a peek into the future. One of the coolest features is the ability to take pictures of text in a foreign language and let the app translate it for you. In a foreign country, this can help you read street signs and avoid going into the wrong bathroom. :-) On a more practical level, Goggles is a QR code reader.

17. Photoshop Express

Photoshop is, of course, the best known photo editor in the world and its mobile app doesn't do anything to hurt that reputation. But while the desktop version is known for having a zillion features, the mobile app is distinguished by its simplicity. It's the best Android (and iPhone) photo editing app for simple crops, brightness adjustments, and sharpens, for example.

18. Audible

As much as I like the Kindle ebooks, I actually consume more books as audiobooks via Audible. With the Audible app you can connect to your Audible library and download over the air. The app also gives you a self-contained player optimized for audiobooks, with a skip-back-30-seconds button and the opportunity to make notes and bookmarks (although I wish the app would store these online so that they could be accessed from the Audible site).

19. Shazam

If you want to impress your friends with a mobile app, show them Shazam. Ever hear a song being played at a store or on the radio and ask yourself, "Oh, what song is that?" That's where Shazam comes in. Just hit the button and let it listen for 15 seconds, query its database, and then return the name of artist and the song. It has about an 80% success rate. This one isn't particularly productive, but it is really cool. (You have to live a little, every once in a while.)

20. Google Finance

This is a great little app that regularly gets overlooked. It connects to your Google Finance account, where you can set up a list of stocks and companies to follow and sort them into groups (portfolios). The app provides three simple tabs — a look at the market, a look at your portfolios, and the latest market news. It even does real-time updates when you have the app open.

Friday, September 30, 2011

Debug and interact with Web apps via Opera Dragonfly

Takeaway: Tony Patton provides an overview of Opera Dragonfly's features and explains why it replaced Firebug as his Web development tool of choice.

I have been a big fan of Firebug for quite some time, but I have quickly fallen in love with the Opera alternative Dragonfly. The comprehensive set of Web development tools are finally out of beta and ready for prime time. This article provides an introduction and overview of the tool with a focus on specific features in future articles.

Let's go to the Opera

I liked Opera, but I stopped using the browser when they started charging for it. That strategy was quickly dropped, and the free Opera browser currently sits at version 11.51 and is available for Windows, Mac, and Linux, as well as mobile and tablet platforms.

While it only commands a small percentage of the browser market, Opera offers a lightweight browser with a slick user interface. In addition to the developer toolset, it provides hardware acceleration, stacked tabs, and mouse gestures; it also works great on mobile platforms and claims the fastest JavaScript engine called Carakan. The latest version is now my preferred browser on both my Windows and Mac laptops.

What more do you need?

Opera Dragonfly is installed with the browser; it is available from the Tools | Advanced dropdown menu, a keyboard shortcut (on Windows, it's [Ctrl][Shift][I]), or by right-clicking an element within a Web page and selecting Inspect Element from the popup menu.

Figure A

The Opera Dragonfly toolset is accessible via the Opera Tools dropdown menu. (Click the image to enlarge.)

A quick survey of Opera Dragonfly's features makes you wonder what else a Web developer could possibly need to thoroughly develop, test, and debug Web applications. The following list provides a sampling of these features, which are accessible via the main toolbar in the Opera Dragonfly interface (Figure B).

Figure B

The Opera Dragonfly main toolbar provides access to the main features. (Click the image to enlarge.)

You see all of the features discussed below in Figure C.

  • DOM Inspector: The feature is available via the Documents panel in the toolbar. DOM Inspector displays the DOM tree for the current document as interpreted by the Opera browser. The Opera site has a great description of this feature, which they call "View Source on steroids." The option's Style Inspector feature, which is displayed in the lower right window, shows the corresponding style for an element selected in the left window (DOM Inspector).
  • JavaScript Debugger: The full-featured debugger is available via the Scripts panel. It provides access to JavaScript for the current Web page and allows you to control flow via breakpoints and so forth. The source code is displayed in the left portion of the window; the right side provides features such as breakpoints, state (watches, call stack, etc.) and allows you to easily search the code.
  • Network Inspector: The Network panel opens this feature, which is described as an HTTP dashboard. Network Inspector allows you to view and inspect all HTTP requests associated with the page, as well as a visualization of download times/duration for all resources used by the page; you can view all of this via the Network Log tab. A neat feature is the ability to send your own HTTP requests via the Make Request tab.
  • Resources Inspector: The Resources panel selection provides access to this feature. Resources Inspector displays all resource requests initiated by the Web page. It displays the host for the resource and full URI along with type and size. This can be used along with the Network Inspector to see the large resources and their associated download times, allowing you to pinpoint issues.
  • Storage Inspector: This feature provides an overview of the client-side storage utilized by the page. This includes cookies and HTML 5 Web storage.
  • Error Log: The Errors panel provides access to the Error Log, which is one of the more important features for working with your own Web applications. The panel header includes a number of the total number of errors returned. It displays the error and its source. You can configure the Error Log via Settings to not display certain CSS errors, and the Filter box can be used to refine the error list.
  • Console: The console allows you to evaluate JavaScript statements on the fly and inspect objects and properties.
  • Remote Debugging: This cool feature allows you to debug separate instances of Opera on the same or other computer, mobile devices, or a television. When used, Remote Debugging listens for connections to a specified IP address and port and connects and passes debugging information across the connection. It debugs remotely just like a local instance.

Figure C

The DOM Inspector opened for the TechRepublic home page. (Click the image to enlarge.)

This list just scratches the surface at what is included in the Opera Dragonfly toolset. Each feature has its own set of functionality. Opera Dragonfly is completely open source, and there is a lot of good documentation for the tools available online.

Feature overload

Opera Dragonfly seems to offer all of the tools necessary to properly debug and interact with Web applications. It follows the path blazed by Firebug and offers even more features, which is why Opera Dragonfly has become my preferred tool. In future posts, I'll cover specific features of Opera Dragonfly in more detail. In the meantime, if you haven't already, I encourage you to install Opera and try Dragonfly.


Top IT skills wanted for 2012

Takeaway: A new Computerworld survey indicates the nine IT skills that will be in demand in 2012.

Nearly 29 percent of the 353 IT executives who were polled in Computerworld's annual Forecast survey said they plan to increase IT staffing through next summer. (That's up from 23% in the 2010 survey and 20% in the 2009 survey.)

Here are the skills that the IT executives say they will be hiring for:

  1. Programming and Application Development–61% plan to hire for this skill in the next 12 months, up from 44% in the 2010 survey. This covers the gamut from website development to upgrading internal systems and meeting the needs of mobile users.
  2. Project Management (but with a twist)– The twist is that they're not going to just be looking for people who can oversee and monitor projects. They also want people who can identify users' needs and translate them for the IT staffers-the increasingly popular business analysts.
  3. Help Desk/Technical Support–Mobile operating systems have added a new dimension to help desk and tech support.
  4. Networking-This demand is being fueled partially by virtualization and cloud computing projects. The survey also revealed that execs will be looking for people with VMware and Citrix experience.
  5. Business Intelligence-Computerworld interprets this uptick to a focus shift in many companies,  from cost savings to investing in technology. That will be nice if it pans out that way.
  6. Data Center-Virtualization and the Cloud could also be behind the increased need for IT professionals with backgrounds in data center operations and systems integration.
  7. Web 2.0-Tech skills centered around social media will be in demand, with .Net, AJAX and PHP as key back-end skills, with HTML, XML, CSS, Flash and Javascript, among others, on the front end.
  8. Security-Although down from 32 percent in the 2010 survey, security stays a top concern of IT executives.
  9. Telecommunications-The survey indicates a demand for people with IP telephony skills, and for those familiar with Cisco IPCC call center systems.

Friday, September 2, 2011

Add Subheader into Gridview (Groupwise Gridview)

Now its simple to add subheader into grid or make a groupwise gridview using only two functions.




Step 1: Create Sample Table to Test 

/****** Object: Table [dbo].[tblType] Script Date: 09/01/2011 23:09:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tblType]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tblType](
[ID] [int] IDENTITY(1,1) NOT NULL,
[TypeName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[GrpCode] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[GroupName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PID] [int] NULL
)
END
GO
SET IDENTITY_INSERT [dbo].[tblType] ON
INSERT [dbo].[tblType] ([ID], [TypeName], [GrpCode], [GroupName], [PID]) VALUES (1, N'All Residential', N'-1', N'All Residential', -1)
INSERT [dbo].[tblType] ([ID], [TypeName], [GrpCode], [GroupName], [PID]) VALUES (2, N'Residential Plot', N'AR', N'All Residential', 1)
INSERT [dbo].[tblType] ([ID], [TypeName], [GrpCode], [GroupName], [PID]) VALUES (3, N'Raw House', N'AR', N'All Residential', NULL)
INSERT [dbo].[tblType] ([ID], [TypeName], [GrpCode], [GroupName], [PID]) VALUES (4, N'All Commercial', N'-2', N'All Commercial', NULL)
INSERT [dbo].[tblType] ([ID], [TypeName], [GrpCode], [GroupName], [PID]) VALUES (5, N'Office', N'AC', N'All Commercial', NULL)
INSERT [dbo].[tblType] ([ID], [TypeName], [GrpCode], [GroupName], [PID]) VALUES (6, N'Space', N'AC', N'All Commercial', NULL)
INSERT [dbo].[tblType] ([ID], [TypeName], [GrpCode], [GroupName], [PID]) VALUES (7, N'All Agricultural', NULL, N'All Agricultural', NULL)
INSERT [dbo].[tblType] ([ID], [TypeName], [GrpCode], [GroupName], [PID]) VALUES (8, N'Farm', N'AA', N'All Agricultural', NULL)
SET IDENTITY_INSERT [dbo].[tblType] OFF


Step 2: Copy and paste below code (Create function) DataTable AddRow(DataTable dt,string group)
{
if (dt != null && dt.Rows.Count > 0)
{
string cGroup="", pGroup="";
cGroup = dt.Rows[0][group].ToString().Trim();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i != 0)
{
cGroup = dt.Rows[i][group].ToString().Trim();
}
if (i > 0)
{
pGroup = dt.Rows[i - 1][group].ToString().Trim();
}
if (cGroup != pGroup)
{
DataRow dr = dt.NewRow();
//dr = dt.Rows[i].;
dr[1] = "$#$"+cGroup+"$#$";
dt.Rows.InsertAt(dr, i);
i += 1;
}
}

}
return dt;

}
Step 3: Code to fill a grid

void fillgrid()
{
string qry = "select * from tbltype";
DataTable dt= dal.fillDataTable(qry); //Do a code to get data using SqlCommand and DataAdapter

GridView1.DataSource = AddRow(dt, "GroupName"); //Call a created function,1st arg:DataTable,2nd : fieldname on which you want to group
GridView1.DataBind();
}

Step 4: Create below function to better look of grid


///
/// Use to Merge grid Cells
/// Gridview RowDataBound Event
/// Provide string to compare with cell text
/// Special text to identify for Sub header
/// Cell index which contains sub header text
/// number of columns want to span
/// Cell index of start to remove
/// Last cell index of remove cell
/// True to merge all cells
///

public static void MergeCells(GridViewRowEventArgs e, string CompareText, string symbol, int textcellindex, int colspan, int startcellindex, int lastcellindex, bool mergeallcells,string HeaderCssClass)
{
if (CompareText.Contains(symbol) == true)
{
if (mergeallcells == true)
{
e.Row.Cells[0].Attributes.Add("colspan", (e.Row.Cells.Count).ToString());
e.Row.Cells[0].Text = CompareText.Replace(symbol, ""); ;
for (int i = e.Row.Cells.Count - 1; i > 0; i--)
{
e.Row.Cells.RemoveAt(i);
}
}
else
{
e.Row.Cells[textcellindex].Text = e.Row.Cells[textcellindex].Text.Replace(symbol, "");
e.Row.Cells[textcellindex].Attributes.Add("colspan", colspan.ToString());
for (int i = lastcellindex; i >= startcellindex; i--)
{
e.Row.Cells.RemoveAt(i);
}
}
e.Row.Attributes.Add("class", HeaderCssClass);
}
}

Step 5: Create RowDataBound Event of grid

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = e.Row.FindControl("lblTypeName") as Label;
//MergeCells(e, "$#$", 3, e.Row.Cells.Count, 3, 4, false,"tdHeader");
GridviewGroupwise.MergeCells(e,lbl.Text, "$#$", 3, e.Row.Cells.Count-1, 2, 4, true,"tdHeader");
}
}
HAPPY CODING

ITWORLD
If you have any question then you put your question as comments.

Put your suggestions as comments