Saturday, March 31, 2012

Formatting with String.Format and ToString

        static void Main()
        {
            //
            // Format a ratio as a percentage string.
            // ... You must specify the percentage symbol in the format string.
            // ... It will multiply the value by 100 for you.
            //
            double ratio = 0.73;
            string result = string.Format("string = {0:0.0%}",
                ratio);
            Console.WriteLine(result);

            int value = 123;
            string a = string.Format("{0:0000}", value); // Too complex
            string b = value.ToString("0000"); // Simpler
            Console.WriteLine(a);
            Console.WriteLine(b);

            // Format as currency
            double expense = 1234.56;
            string str = expense.ToString("C");
            Console.WriteLine("Expense: {0}", str);

            // Format with parentheses
            str = String.Format("{0:(#####0.000)}", expense);
            Console.WriteLine("Expense: {0}", str);
        }
Output:
string = 73.0%
0123
0123
Expense: $1,234.56
Expense: (1234.560)

Standard Numeric Format Strings

Thursday, June 23, 2011

F# Code: Hindley Milner Type Inference Sample Implementatio...

F# Code: Hindley Milner Type Inference Sample Implementatio...: "// Learn more about F# at http://fsharp.net // Hindley Milner Type Inference Sample Implementation // ************************************..."

Tuesday, January 25, 2011

SQL Server Reporting Services

In this post, I will be talking about SQL Server Reporting Services (SSRS) 2008. Before I start discussing SSRS, I should mention that most of my reports development experience was with Crystal Reports, so I will compare SSRS features to those of Crystal Reports from time to time.

Overview & Features
SSRS Toolbox provides the following controls: Textbox, Line, Table, Matrix, Rectangle, List, Image, Subreport, Chart, Gauge. The most frequently used controls are the Textbox and Table.

Textbox -- can be used as both, a textbox and a label (if you make it readonly).
Table -- used for displaying data in a tabular format. It has Header Row and Detail Row, which is nice, because I can use just a Table in SSRS where I would have to use a subreport in Crystal Reports.

SSRS provides a powerful expressions engine based on Visual Basic syntax, a capabilty to add some vb.net code, and it also allows to add a reference to a dll. Also, there are quite a few built-in functions, similar to those in Crystal Reports. Although, if you have a Crystal Reports background and are switching to SSRS reports, some things will require getting used to. For example, to display current page number you would need to place a textbox control in the report's footer, go into expressions for that textbox and code it there instead of just dragging and dropping as it is done in Crystal Reports. This is what the expression for something like "Page 2 of 5" would look like:

="Page " & Globals!PageNumber & " of " & Globals!TotalPages

SSRS Development
To develop SSRS, you need to have BIDS (Business Intelligence Development Studio) installed. It can be part of SQL Server 2008 install.

Once you have it, you can create a couple of different types of projects: Report Server Project and Report Server Project Wizard. My preference is the Report Server Project, because it allows for more customization.

Before you begin designing and developing a new SSRS report, you have to create a DataSource. If you are planning to use this datasource in more than one report, make it shared.

Once you are done creating a datasource, you will have to create a dataset that you will use with the report. Here is the confusing part: you can't create a dataset without having a report, so you have to add a report to your project first and then create a dataset based on the datasource you created earlier. When creating a dataset, SSRS allows you to either type your SQL into a text field or you can choose the option to enter a stored procedure name. I personally prefer using stored procedures, since they allow to do much more than a plain SQL statement.

Let's create a simple report consisting of a table and a header. The header will contain the report name and will be placed in the header of the report; the data will be displayed in a table and will be placed in the body of the report. In order to do that, we'll drag a textbox control from the toolbox and position it within the header section and type a name for the report in it; then, we'll drag a table control from the toolbox and put it in the body section of the report. Once that's done, let's specify what data will be displayed in each table column. Assume that we are displaying customer info from Northwind database, we'll have 3 columns: First Name, Last Name, and Phone Number.

The table control will display little buttons in each table column for you to choose what data will be feeding this column, such as First Name, Last Name, or Phone Number in our case. Let's display First Name in the first column, Last Name in the second column, and Phone Number in the third column, and give those columns appropriate headings. Now the report is ready and you can run it by clicking the Preview tab. Optionally, you may add a page number in the footer and a date of last execution of the report in the header.

To display the execution date and time, simply add a textbox to the report that will display this information, right-click on the textbox and choose Expressions; in the expression text area enter the following code:

= Globals!ExecutionTime

This will display the date and time when the report was last executed in a General Date format (something like 1/26/2011 11:15:05 AM).

Monday, November 15, 2010

String Manipulation in .NET

String is one of the most frequently used data types in programming. There are quite a few string functions out there and all of those functions are implemented differently in different programming languages. I am going to show here how this is done in .NET Framework.
In the example below I am going to demonstrate the use of StringBuilder class. The below example receives a string as a parameter and then reverses it:
private string ReverseString(String str)
{
    if (str != string.Empty)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = str.Length - 1; i >= 0; i--)
        {
            sb.Append(str.Substring(i, 1));
        }
        str = sb.ToString();
    }
    return str;
}



Here is another example that accepts a string, splits it, and then reverses the order of words in that string:
private void ReOrderString()
{

string str = "Token A#$%@&Token B#$%@&Token C#$%@&Token D#$%@&Token E"; 
string[] Split = str.Split(new string[] { "#$%@&" }, StringSplitOptions.None);
    StringBuilder sb = new StringBuilder();
    for (int i = Split.Length - 1; i >= 0; i--)
    {
        sb.Append(Split[i]);
        if (i > 0)
            sb.Append("#$%@&");
    }
    lblOriginalString.Text = "Token A#$%@&Token B#$%@&Token C#$%@&Token D#$%@&Token E";
    lblProcessedString.Text = sb.ToString();
}

Wednesday, July 14, 2010

Technical Interview: Frequently Asked Questions & Answers

Most of the time, when applying for software development jobs, be prepared to answer the following questions:
1. General Programming Questions:
  1. What is the difference between passing parameter by value versus passing it by reference?
  2. What is boxing / unboxing?
  3. What is implicit conversion?
  4. What is explicit conversion?
  5. Late Binding vs. Early Binding in VB.NET
2. OO Questions:
  1. What are the main concepts of Object Oriented development?
  2. What is an Abstract Class?
  3. What is an Interface?
  4. What is Reflection?
  5. What design patterns do you know?
  6. What is the difference between value types vs. reference types?
3. SQL Questions:
  1. How do you join two tables (SQL)?
  2. What are the differences between different types of join?
  3. What is UNION?
4. HTML Questions:
  1. How do you make a table cell that runs across several columns?
  2. How do you make a table cell that spans across multiple rows?
OO Answers:
1. Object-oriented programming (OOP) is a programming paradigm that uses "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, modularity, polymorphism, and inheritance.

2. Abstract classes are closely related to interfaces. They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. One key difference between abstract classes and interfaces is that a class may implement an unlimited number of interfaces, but may inherit from only one abstract (or any other kind of) class. A class that is derived from an abstract class may still implement interfaces. Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.

An abstract class is denoted in Visual Basic by the keyword MustInherit. In C#, the abstract modifier is used. Any methods that are meant to be invariant may be coded into the base class, but any methods that are to be implemented are marked in Visual Basic with the MustOverride modifier. In C#, the methods are marked abstract. The following example shows an abstract class:

' Visual Basic
Public MustInherit Class WashingMachine

Sub New()

' Code to instantiate the class goes here.

End sub

Public MustOverride Sub Wash
Public MustOverride Sub Rinse (loadSize as Integer)
Public MustOverride Function Spin (speed as Integer) as Long

End Class

// C#
abstract class WashingMachine
{
    public WashingMachine()
   {
         // Code to initialize the class goes here.
    }
    abstract public void Wash();
    abstract public void Rinse(int loadSize);
    abstract public long Spin(int speed);
}
 
In the above example, an abstract class is declared with one implemented method and three unimplemented methods. A class inheriting from this class would have to implement the Wash, Rinse, and Spin methods. The following example shows what the implementation of this class might look like:
 
' Visual Basic
Public Class MyWashingMachine
                 Inherits WashingMachine

Public Overrides Sub Wash()

    ' Wash code goes here

End Sub

Public Overrides Sub Rinse (loadSize as Integer)

' Rinse code goes here

End Sub

Public Overrides Function Spin (speed as Integer) as Long

' Spin code goes here

End Sub

End Class

// C#
class MyWashingMachine : WashingMachine
{
    public MyWashingMachine()
   {
    // Initialization code goes here.
   }

    override public void Wash()
   {
        // Wash code goes here.
    }

    override public void Rinse(int loadSize)
    {
        // Rinse code goes here.
    }

    override public long Spin(int speed)
    {
        // Spin code goes here.
    }
}
 
When implementing an abstract class, you must implement each abstract (MustOverride) method in that class, and each implemented method must receive the same number and type of arguments, and have the same return value, as the method specified in the abstract class.

3. An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface, as shown in the following example:

interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation:

    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
   {
        // Declare an interface instance.

        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}

Remarks

 An interface can be a member of a namespace or a class and can contain signatures of the following members:
•Methods
•Properties
•Indexers
•Events

An interface can inherit from one or more base interfaces.
When a base type list contains a base class and interfaces, the base class must come first in the list.

A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface, for example:

For more details and code examples on explicit interface implementation, see Explicit Interface Implementation (C# Programming Guide).

Example
 The following example demonstrates interface implementation. In this example, the interface IPoint contains the property declaration, which is responsible for setting and getting the values of the fields. The class Point contains the property implementation.

// keyword_interface_2.cs
// Interface implementation
using System;

interface IPoint
{
// Property signatures:
    int x { get; set; }
    int y { get; set; }
}

class Point : IPoint
{
    // Fields:
    private int _x;
    private int _y;

// Constructor:
public Point(int x, int y)
{
    _x = x;
    _y = y;
}
// Property implementation:
public int x
{
    get
    {
        return _x;
    }
    set
    {
        _x = value;
    }
}

public int y
    {
        get
        {
            return _y;
        }
set
        {
            _y = value;
        }
    }
}

class MainClass
{
    static void PrintPoint(IPoint p)

    {
        Console.WriteLine("x={0}, y={1}", p.x, p.y);
    }
    static void Main()
    {
        Point p = new Point(2, 3);
        Console.Write("My Point: ");
        PrintPoint(p);
    }
}

4. Design Patterns: check this MSDN  resource: http://msdn.microsoft.com/en-us/magazine/cc301852.aspx


SQL Answers:
1 & 2. SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables. Different SQL JOINs:
JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
FULL JOIN: Return rows when there is a match in one of the tables
 
SQL INNER JOIN Keyword
The INNER JOIN keyword return rows when there is at least one match in both tables.
SQL INNER JOIN Syntax
SELECT column_name(s) FROM table_name1
INNER JOIN table_name2 ON table_name1.column_name = table_name2.column_name

SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).

 SQL LEFT JOIN Syntax
SELECT column_name(s) FROM table_name1
LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name

PS: In some databases LEFT JOIN is called LEFT OUTER JOIN.

SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no matches in the left table (table_name1).

SQL RIGHT JOIN Syntax
SELECT column_name(s) FROM table_name1
RIGHT JOIN table_name2 ON table_name1.column_name = table_name2.column_name

PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

SQL FULL JOIN Keyword
The FULL JOIN keyword return rows when there is a match in one of the tables.

SQL FULL JOIN Syntax
SELECT column_name(s) FROM table_name1
FULL JOIN table_name2 ON table_name1.column_name = table_name2.column_name

3. UNION
The UNION operator is used to combine the result-set of two or more SELECT statements.

Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.

Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.

SQL UNION Syntax
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

SQL UNION ALL Syntax
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2

Note: The column names in the result-set of a UNION are always equal to the column names in the first SELECT statement in the UNION.