Why NoSQL?

Why NoSQL?

NoSQL term is supposed to stand for “Not Only SQL.” . This term is used to designated DBMS that differ from classic RDBMS in some way. These DBMS may not require fixed table schemas, and usually avoid join operations and typically scale horizontally.

Architecture

NOSQL databases tend to have two key attributes across the board. One is that they’re non-relational, so they’re not doing joins on the server. And second, they have light transactional semantics. So complex, long-running, serialized transactions are not part of any of these NoSQL products. Those two differences, put together, allow you to take a very different approach to how databases are created, which means you can make horizontally scalable databases — the kind that run across large clusters of machines.

RDBMS have shown poor performance on certain data-intensive applications, including indexing a large number of documents, serving pages on high-traffic websites, and delivering streaming media. Typical RDBMS implementations are tuned either for small but frequent read/write transactions or for large batch transactions with rare write accesses. NoSQL on the other hand, services heavy read/write workloads

NoSQL architectures often provide weak consistency guarantees, such as eventual consistency, or transactions restricted to single data items. Some systems, however, provide full ACID guarantees, in some instances by adding a supplementary middleware layer (e.g., CloudTPS).

Core NoSQL Systems

Wide Column Store/Column Families

1.Cassandra
2.Cloudera
3.Amazon SimpleDB

Document Store

1. CouchDB
2. MongoDB
3. OrientDB

Key Value/ Tuple Store

1.Redis
2.MemcacheDB
3.Tokyo Cabibnet

Posted in Uncategorized | Tagged , , | Leave a comment

Rake Migration: Track Rake Tasks with versions

I have started working on a plugin which helps rails projects to maintain the list of rake tasks.

We are working on a project there are four to six teams at different geo-locations Bangalore, Kolkata, Edmonton etc.For the same project we have different environments like Developemnt, Testing, Staging, QA, QA2, Beta etc.All teams are working with new features, as well as bug fixes.

Many times we found a situation that a specific rake task should be run on a specific environment to fix the data. A lot of time team members forgot to shoot a mail and tell every team about a rake task which will fix a bug on specific environment. As other people update code base and start using the application they got stuck and it take a lot of time to resolve the issue that a specific task was not run because team did not get any information as such.

To resolve this issue we got a idea form rake tasks to migrate database (db:migrate). So if we can manage rake tasks with versions and if we can keep track of tasks those have been run, and yet to run on system. One can generate a ruby file write there any ruby code or invoke any rake task, and upload to repository other people only take update from repo and run a simple commend and the system will update.

Here we don?t have to worry to inform everybody about new task to fix bug or update system.

Here is the URL for plugin

http://github.com/vatrai/rake_migration

By using generators one can generate blank ruby files prefix with time-stamped version. ?Version helps to keep track of tasks that are?Run,?yet to Run on the system. One can specify Rails environment in ruby files, specify what data fix should be run on a specified environment using simple?if condition.

To generate simple ruby file use:

ruby script/generate rake_migration <file_name>

This command creates a blank ruby file in {RAILS_ROOT}/rake/migrate directory. ?Write ruby code or invoke rake task in the generated ruby file.

To run generated?files run rake command:

{RAILS_ROOT} rake rake_migration:migrate

This command runs remaining(yet to run) ruby files in?{RAILS_ROOT}/rake/migrate and saves version in rake_migrations table in database.


Posted in Uncategorized | 1 Comment

Custom title for your apps(Android)

The default title bar for the apps might not suit the theme of your app. You also might want to add a few more things to the title bar which the default title bar doesn’t help you with. This example will help you develop your own Title Widget which you can directly embed in your layouts containing a left icon, a title text and a progress bar. You can also control the contents of these three widgets and change it as required in your activities. Here we go.

1. The first thing you should do is to switch off the default title. You can do this easily by specifying in your AndroidManifest.xml file that do not intend to use it.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.beanie.samples.titlewidget" android:versionCode="1"
	android:versionName="1.0">
	<application android:icon="@drawable/icon" android:label="@string/app_name"
		android:theme="@android:style/Theme.NoTitleBar">
		<activity android:name=".TitleWidgetActivity"
android:label="@string/app_name">
		<intent-filter>
		<action android:name="android.intent.action.MAIN" />
		<category android:name="android.intent.category.LAUNCHER" />
		</intent-filter>
	</activity>
	</application>
	<uses-sdk android:minSdkVersion="4" />
</manifest>

Here, in the application tag, set the theme of your app to use the NoTitleBar theme.

2. Create a title_widget.xml which would be the custom layout for your title bar. You can technically add any number of widgets here and finally display it with your custom title. As an example, we will add an ImageView, a TextView and a ProgressBar here.

3. Create a TitleWidget.java class which extends LinearLayout(you can use any Layout) which loads this layout file and exposes methods to modify the contents of the widgets.

4. Add the TitleWidget class as the first view in all your activity layouts’ files to display your custom title bar.

<?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">
	<com.beanie.samples.titlewidget.TitleWidget
android:id="@+id/titleWidget"
		android:layout_width="fill_parent"
android:layout_height="wrap_content">
	</com.beanie.samples.titlewidget.TitleWidget>
</LinearLayout>

5. Now, in your activity, you can initialize this TitleWidget as any view, since it is a LinearLayout now, and can control the contents of all the widgets.

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Initialize title Widget
        TitleWidget titleWidget = (TitleWidget)findViewById(R.id.titleWidget);

        // Call the methods to change the underlying widgets
        titleWidget.setTitle("My Custom Title");
        titleWidget.setIcon(R.drawable.icon);
        titleWidget.showProgressBar();
        titleWidget.hideProgressBar();
    }

Now you have your own custom title. On the surface, it doesn’t actually feel like a title bar, and yes, it isn’t. It’s just a custom view, that you are trying to make it look like a title bar. Remember!! We switched off the titles by specifying that our app’s theme to “NoTitleBar”. :)

You can find the whole source code here.

Posted in Uncategorized | Tagged , , | 4 Comments

Configure Static Analyzer to ignore certain wanings

A clean green build without any warning will be a developers inspiration when his continuous integration gives him a build status. In Xcode 3.2, a static analyzer is in-built and every build includes a verification by the analyzer which in turn might deprive a developer his much needed inspiration. There will be some warnings which will be nagging you, especially when you are using some third party code and you don’t want to change anything in it.? There are quite a few ways to inform the analyzer to drop certain warnings on certain part of the code. I will try to explain one of them here.

Warning :
“Value stored to ‘zombie’ during its initialization is never read”

This is a warning which is very much necessary to be dealt with but, as i mentioned, in certain scenarios we may not want to change that piece of code (usually happens with legacy code). One way to avoid this warning is by adding a pragma like,? “#pragma unused (zombie)” .

Yet another way is to add something like?
“NSNumber* zombie __attribute__((unused));”
to the code.

You can get more information on configuring the Analyzer from http://clang-analyzer.llvm.org/annotations. Also you can type in? “Analyzing Code”? in your Xcode help,?and it will give you more information on the Analyzer.

Happy coding.

Posted in Uncategorized | Tagged , , , | Leave a comment

MySql DB Indexing

Working with a online tutorial with a huge amount of data, product owners always used to? raise issues for application performance. After looking in to different scenerios like apache configurations, hardware, network issues, and mysql performance as a backend server, we got to know that there are a lot of opportunities to improve mysql db performance. To see why db performance slow I turned on slow quiry logging in my.cnf:

log-slow-queries
long_query_time = 5

The slow quesies log file became huge in size in Gigs after only two or three days, and queries was like:

# Query_time: 5 Lock_time: 0 Rows_sent: 1 Rows_examined: 40508

SELECT quize_id as total_quizes FROM student_quizes WHERE exam_id IN(1,2,3,11)

In abouve example its whowing that ?Rows_sent: 1 Rows_examined: 40508?. So, after examining 40508 and returning just 1 row is not a good job done by db server. If there are 200 visitors using the application then multiply this figure with 200, in this case MySQL is examining 8,101,600 rows! Then the Mysql performance is in misurable situation.

To see why MySQL queries are too slow we can explain them:

?? mysql> EXPLAIN
       -> SELECT quize_id as total_quizes FROM student_quizes
?????? -> WHERE exam_id IN (1, 2, 3, 11);
   +-------------------+-------+---------------+-------------------+---------+------+-------+--------------------------+
   | table             | type  | possible_keys | key               | key_len | ref  | rows  | Extra                    |
   +-------------------+-------+---------------+-------------------+---------+------+-------+--------------------------+
   | student_quizes ?? | index | NULL          | quize_id_exam_id? |       6 | NULL | 40508 | Using where; Using index |
   +-------------------+-------+---------------+-------------------+---------+------+-------+--------------------------+

Here MySQL telling us there’s no possible keys but it’s using key quize_id_exam_id? And if it’s using a key then why does it suspect it will have to examine 40508 rows (by performing a full index scan, denoted by “type: index”)? It seems there’s a problem with the keys so we must now understand them:

mysql> DESCRIBE student_quizes;
   +-------------+-----------------------+------+-----+---------+-------+
   | Field       | Type                  | Null | Key | Default | Extra |
   +-------------+-----------------------+------+-----+---------+-------+
   | quize_id?   | mediumint(8) unsigned |      | MUL | 0       |       |
   | exam_id     | mediumint(8) unsigned |      |     | 0       |       |
   | created_at? | datetime ? ? ? ? ? ?? |      |     | 0       |       |
   | updated_at? | datetime ? ?          |      |     | 0       |       |
?? +-------------+-----------------------+------+-----+---------+-------+

   mysql> SHOW INDEX FROM student_quizes;
   +-------------------+------------+-----------------------+--------------+-------------+-----------+-------------+
   | Table             | Non_unique | Key_name              | Seq_in_index | Column_name | Collation | Cardinality |
   +-------------------+------------+-----------------------+--------------+-------------+-----------+-------------+
   | student_quizes ?? |          1 | quize_id_exam_id ?    |            1 | quize_id?   | A         |?????? 40508 |
   | student_quizes ?? |          1 | exam_id_quize_id?     |            2 | exam_id     | A         |?????? 40508 |
?? +-------------------+------------+-----------------------+--------------+-------------+-----------+-------------+

Understanding indexes is two part: Understanding the structure of the table then understanding the indexes. You can’t just slap an index on a table and think everything will be wonderful. In this example it looks like everything should be wonderful with key quize_id_exam_id. Given that the SELECT statement is selecting quize_id and exam_id and that’s just what this key indexes, so why isn’t it working? It is working, just not how we’re intending; it’s working for MySQL which is why in EXPLAIN it says “Using index.” When MySQL says this in “Extra” is means “The column information is retrieved from the table using only information in the index tree without having to do an additional seek to read the actual row.” In other words: It finds and returns matching columns from the index in memory not the table on disk, which is a good thing, unless it’s doing this 12 million times for 1 matching column.

How very annoying: MySQL is using the index but still in effect examing every row of the table. The reason why in this example deals with how MySQL uses multiple column indexes. From DESCRIBE we see “MUL” for multi-column index, and from SHOW INDEX we see quize_id_exam_id twice, first for quize_id second for exam_id. A multiple column index acts like a single column index if the columns were put end-to-end in the order specified by “Seq_in_index” from SHOW INDEX. In this example if quize_id were 100 and exam_id were 200 this is indexed as “100 200″. Throw this in the mix: MySQL will only use a multi-column index if a value is specified for the first column in the index. In this example the first column in the index is quize_id and we’re not specifying a value for this column which is why MySQL won’t use the index like we want it to. What MySQL does do, and why it’s able to use the index at all, is use any value for quize_id and the values we gave it for exam_id. In effect it looks for ‘*? 1′, ‘*? 2′, ‘*?? 3′, ‘*?? 11′. Since quize_id is unique MySQL really does have to look at every single one, all 40,00+. While doing that if it comes across one with a matching exam_id lucky for us. I hope you see the obvious and simple solution: Swap the order of columns in the key, exam_id then quize_id. Later we’ll do this but first it’s good learning to examine another possibility.

If exam_id is what we’re matching rows on, just index exam_id. The command would be “CREATE INDEX test_index ON student_quizes (exam_id);”. Then EXPLAIN the exact same slow query again:

?? mysql> EXPLAIN
       -> SELECT quize_id as total_quizes FROM student_quizes
?????? -> WHERE exam_id IN (1,2,3,11);
   +-------------------+-------+---------------+------------+---------+------+------+-------------+
   | table             | type  | possible_keys | key        | key_len | ref  | rows | Extra       |
   +-------------------+-------+---------------+------------+---------+------+------+-------------+
   | student_quizes ?? | range | test_index    | test_index |       3 | NULL |    5 | Using where |
   +-------------------+-------+---------------+------------+---------+------+------+-------------+

That output speaks volumes: 5 rows to examine. This is the index that saved the server. I have not seen the server’s load go above 4 and the website is running faster with more users at once. The difference was night and day. But why stop there? The query is no longer slow but it could be better. Notice how MySQL is not “Using index” anymore. This is because quize_id is not in the index its using. Whereas it’s in the quize_id_exam_id index MySQL has wisely chosen to examine fewer rows at the cost of doing a few disk seeks. The solution is a multiple column index on both exam_id and quize_id, with exam_id first.

?? mysql> CREATE INDEX exam_id_quize_id ON student_quizes (exam_id, quize_id);
   Query OK, 40508 rows affected (0.53 sec)
   Records: 40508  Duplicates: 0  Warnings: 0

   mysql> EXPLAIN
       -> SELECT quize_id as total_quizes FROM student_quizes
?????? -> WHERE exam_id IN (1,2,3,11);
   +-------------------+-------+------------------------------+-------------------+---------+------+------+--------------------------+
   | table             | type  | possible_keys                | key               | key_len | ref  | rows | Extra                    |
   +-------------------+-------+------------------------------+-------------------+---------+------+------+--------------------------+
   | student_quizes ?? | range | test_index,exam_id_quize_id? | exam_id_quize_id? |       3 | NULL |    5 | Using where; Using index |
   +-------------------+-------+------------------------------+-------------------+---------+------+------+--------------------------+

As we can see MySQL still considers the test_index key but chooses exam_id_quize_id because doing so will allow it to get matching quize_id from the index instead of the disk. A simple swap of column orders in the index made all the difference. As the saying goes, it takes one tree to make a thousand matches and one match to burn a thousand trees down.

Posted in Uncategorized | Tagged | Leave a comment

MySQL 5.5 Feature List

The Current MySQL Server 5.5 is currently available in pre-release (as of June 2010).

As we know that MySQL is a well-known DBMS, having good reputation for being easy-to-use and its unmatched performance and scalability. With MySQL 5.5, InnoDB becomes the default storage engine(previous ver. MyISAM was used as default engine).  Because of InnoDB, the default settings deliver the benefits users expect from their RDBMS ? ACID Transactions, Referential Integrity, and Crash Recovery. Lets explore how using InnoDB tables improves your life as a MySQL user, DBA, or developer.

Performance gain

At 1024 Connections
188% performance gain for MySQL 5.5 over 5.1.40 (InnoDB 1.0)
200% performance gain for MySQL 5.5 over 5.1.40 (InnoDB built in)

CPU scalability

MySQL 5.5.4 is better prepared now to scale up to 32 cores and reaching higher TPS levels than others.

Better Metadata Locking within Transactions.

If a table is referenced within a transaction, no other transaction can perform DDL such as DROP TABLE or ALTER TABLE until the first transaction commits. Previously, the lock was released at the end of a statement rather than the whole transaction.

Replication Heartbeat.

replication, the heartbeat is a message sent at regular intervals from a master node to the slave nodes. You can configure the heartbeat period. If the message is not received, the slave knows that the master node has failed. You can now avoid the spurious relay log rotation when the master is idle, rely on an more precise failure detection mechanism, and have an accurate estimation for seconds behind master. (This is a different feature than Linux heartbeat, which is a similar health-checking system for cluster nodes.) To use this feature, you issue commands like:
STOP SLAVE;
CHANGE MASTER TO master_heartbeat_period= milliseconds;
START SLAVE;
SHOW STATUS like ?slave_heartbeat period?
SHOW STATUS like ?slave_received_heartbeats?

More Partitioning Options

With the new RANGE COLUMNS and LIST COLUMNS clauses of the CREATE TABLE statement, partitioning is now more flexible and also can optimize queries better. Instead of expressions, you specify the names of one or more columns. Both of these clauses let you partition based on DATE, DATETIME, or string values (such as CHAR or VARCHAR). Partition pruning can optimize queries on tables that use RANGE COLUMNS or LIST COLUMMS partitioning, and WHERE conditions that compare different columns and constants,

Extended Change Buffering

Now with Delete Buffering and Purge buffering InnoDB uses indexes to make queries faster. Secondary indexes, those on columns other than the primary key, require work (meaning disk writes) to keep them up to date when those those columns are inserted, deleted, or updated. For example, if you run the command DELETE FROM t WHERE c1 = ?something?;, and you have a secondary index on column c2, what?s the rush to update that secondary index? Its contents might not be in the buffer pool, and maybe the index won?t be read for a long time.

New Features in InnoDB

  • Multiple Buffer Pool Instances.
  • Improved Recovery Performance
  • Extended InnoDB Change Buffering
  • Support for Native AIO on Linux
  • Multiple Rollback Segments
  • Separate Flush List Mutex
  • Improved Purge Scheduling
  • Improved log_sys mutex
  • Performance Schema Support.

for more details please refer following links

http://dev.mysql.com/tech-resources/articles/introduction-to-mysql-55.html
http://planet.mysql.com/entry/?id=22648
http://blogs.innodb.com/wp/2010/04/innodb-multiple-rollback-segments/
http://blogs.innodb.com/wp/2010/09/mysql-5-5-innodb-as-default-storage-engine/
http://dev.mysql.com/tech-resources/articles/introduction-to-mysql-55.html#innodb

 

Thanks for visiting
Happy Reading
Sachin Singh

Posted in Uncategorized | Leave a comment

Re-binding jQuery Events

This post is not of great interest to web developers who extensively use jQuery in their daily routines. But myself being a mobile application developer got first hand experience on using jQuery and the interesting mistake I made.

We are developing the Solaro Study web content to be displayed ?in a “webview”. Now our motto was to bring in the new web content for lessons,notes or assessments on user swipe gestures without a blink while changing contents. Initially we were loading the contents?every-time?a user gesture occured, that introduced a delay as the page used to refresh. So we took to jQuery, although it is already there in our project but I needed to shine my?armor. So instead of loading the entire page content, I was changing the content using innerHTML of the parent “div”.This worked nice as every time the user swiped, we simply changed the inner HTML of the div and it worked like charm, so no latency or blinks. Heavenly it felt and I too felt good. But the new thing that emerged out of this was, for some of these web content, required user to click on options or select answers while giving assessments. Now these clicks are different from the user swipe gestures which are internal to the iphone SDK, but the event handling in web pages are all related to DOM events.

So now whenever the page loaded, for the first time i was able to click on the options and sending request back to server, but not again once I swipe and the inner HTML changes, not even going back to the same page from where I started.

Our click event was something like this :

$(function(){
       $("#someDiv").bind('click',function(){
       /*This method supposedly changes the innerHTML*/
               sayCheese('Got new content, so replace my contents');
       })
});

The thing that came to my rescue is:live() method.

If you have not heard of jQuery’s live() method, it’s an event delegation mechanism that allows you to bind event handlers not just to all existing instances of a given node type, but also to any future instances of a given node type (by “type” I mean a set of DOM nodes matched by a given jQuery selector). This is a very cool thing, both from a development standpoint as well as from a memory and performance standpoint;

So we changed that piece of code slightly to:

$("#someDiv").live(
     "click", function(event){
         sayCheese('Got new content, so replace my contents');
});

This event cycle is excellent for event delegation but, it comes with a cost; because it relies completely on the ability for the given event to bubble up to the document object, it is imperative that the bubbling remains in tact. If the event bubbling breaks anywhere within the ancestor chain, the live-bound event handlers will not be triggered.

Posted in Uncategorized | Tagged , | 1 Comment

Design Patterns

What is Design Pattern?

In Software Engineers, a design pattern is a general reusable solution to a commonly occurring problem in software Design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object Oriented design patterns typically show relationships and interactions between Classes or objects, without specifying the final application classes or objects that are involved.

Design patterns reside in the domain of modules and interconnections. At a higher level there are Architectural Pattern that are larger in scope, usually describing an overall pattern followed by an entire system.

Design patterns gained popularity in computer science after the book Design Patterns: Elements of Reusable Object-Oriented Software was published in 1994 by the so-called ?Gang of Four? (Gamma etal.). That same year, the first Pattern Languages of Programming Conference was held and the following year, the Portland Pattern Repository was set up for documentation of design patterns. The scope of the term remains a matter of dispute. Notable books in the design pattern genre include:
Gamma, Erich; Design patterns gained popularity in , Ralph Johnson, and John Vlissides (1995).

Design Patterns ware originally grouped in the following categories:

?Design Pattern types
Description of Factory: Factory Method defines an interface for creating an object, but lets subclasses decide which of those to instantiate.

  • Creational patterns abstract the object instantiation process. They hide how objects are created and help make the overall system independent of how its objects are created and composed.
  • Class creational patterns focus on the use of inheritance to decide the object to be instantiated factory method.
  • Object creational patterns focus on the delegation of the instantiation to another object abstract factory.

Iimplementation Of Factory Pattern:

interface IBase
{
string Perform();
}
Implement the Interface
Listing 1
class Algorithm1: IBase
{
public string Perform()
{
return ?Algorithm1 Performed?;
}
}

class Algorithm2: IBase
{
public string Perform()
{
return ?Algorithm2 Performed?;
}
}

class Algorithm3: IBase
{
public string Perform()
{
return ?Algorithm3 Performed?;
}
}
CODE    interface IBase
{
string Perform();
}
Implement the Interface
Listing 5
class Algorithm1: IBase
{
public string Perform()
{
return ?Algorithm1 Performed?;
}
}

class Algorithm2: IBase
{
public string Perform()
{
return ?Algorithm2 Performed?;
}
}

class Algorithm3: IBase
{
public string Perform()
{
return ?Algorithm3 Performed?;
}
}

In Listing 1, the three classes Algorithm1, Algorithm2 and Algorithm3 are defined which implements the IBase interface (refer to Listing 4).
Define the Factory Class
First, define the Factory class. This class is responsible for instantiating the required object and returning it to the client. Once the object is returned, the client code will call the object methods without knowing how these objects methods are implemented. This provides the encapsulation mechanism.
Listing 2

class Factory
{
public IBase GetObject(int AlgorithmType)
{
IBase objbase = null;
switch (AlgorithmType)
{
case 1:
objbase = new Algorithm1();
break;
case 2:
objbase = new Algorithm2();
break;
case 3:
objbase = new Algorithm3();
break;
default:
throw new Exception(?Unknown Object?);
}
return objbase;
}
}

Create the Client Application
Add the form to the Windows Applications project and then add the button btnClient. To this button, add the below code.
Listing 3

private void btnClient_Click(object sender,EventArgs e)
{
try
{
Factory objfactory = new Factory();
IBase objBase = objfactory.GetObject(2);
MessageBox.Show(objBase.Perform());

objBase = objfactory.GetObject(3);
MessageBox.Show(objBase.Perform());
}
catch (Exception objex)
{
MessageBox.Show(objex.Message);
}
}

The Factory pattern can almost be seen as a simplified version of the Builder pattern.
In the Factory pattern, the factory is in charge of creating various subtypes of an object depending on the needs.
The user of a factory method doesn?t need to know the exact subtype of that object. An example of a factory method createCar might return a Ford or a Honda typed object.
In the Builder pattern, different subtypes are also created by a builder method, but the composition of the objects might differ within the same subclass.
To continue the car example you might have a createCar builder method which creates a Honda-typed object with a 4 cylinder engine, or a Honda-typed object with 6 cylinders. The builder pattern allows for this finer granularity.

Description Of Abstract Factory :By contrast, an Abstract Factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.

  • The Abstract Factory pattern is very similar to the Factory Method pattern. One difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.
  • Actually, the delegated object frequently uses factory methods to perform the instantiation

Implementation of Abstract Factory Pattern:

///
/// The ?AbstractFactory? abstract class
/// 

abstract class AbstractFactory
{
public abstract AbstractProductA CreateProductA();
public abstract AbstractProductB CreateProductB();
}

///
/// The ?ConcreteFactory1? class
///
class ConcreteFactory1 : AbstractFactory
{
public override AbstractProductA CreateProductA()
{
return new ProductA1();
}
public override AbstractProductB CreateProductB()
{
return new ProductB1();
}
}

///
/// The ?ConcreteFactory2? class
///
class ConcreteFactory2 : AbstractFactory
{
public override AbstractProductA CreateProductA()
{
return new ProductA2();
}
public override AbstractProductB CreateProductB()
{
return new ProductB2();
}
}

///
/// The ?AbstractProductA? abstract class
///
abstract class AbstractProductA
{
}

///
/// The ?AbstractProductB? abstract class
///
abstract class AbstractProductB
{
public abstract void Interact(AbstractProductA a);
}

///
/// The ?ProductA1? class
///
class ProductA1 : AbstractProductA
{
}

///
/// The ?ProductB1? class
///
class ProductB1 : AbstractProductB
{
public override void Interact(AbstractProductA a)
{
Console.WriteLine(this.GetType().Name +
? interacts with ? + a.GetType().Name);
}
}

///
/// The ?ProductA2? class
///
class ProductA2 : AbstractProductA
{
}

///
/// The ?ProductB2? class
///
class ProductB2 : AbstractProductB
{
public override void Interact(AbstractProductA a)
{
Console.WriteLine(this.GetType().Name +
? interacts with ? + a.GetType().Name);
}
}

///
/// The ?Client? class. Interaction environment for the products.
///
class Client
{
private AbstractProductA _abstractProductA;
private AbstractProductB _abstractProductB;

// Constructor
public Client(AbstractFactory factory)
{
_abstractProductB = factory.CreateProductB();
_abstractProductA = factory.CreateProductA();
}

public void Run()
{
_abstractProductB.Interact(_abstractProductA);
}
}
}

public static void Main()
{
// Abstract factory #1
AbstractFactory factory1 = new ConcreteFactory1();
Client client1 = new Client(factory1);
client1.Run();

// Abstract factory #2
AbstractFactory factory2 = new ConcreteFactory2();
Client client2 = new Client(factory2);
client2.Run();

// Wait for user input
Console.ReadKey();
}
}

Description of Singletone: This pattern are responsible for creating single object.The main purpose to create lazy initialization of an object.

Implementation of Singletone Pattern:

 ///
/// Thread-safe singleton example created at first call
///
public sealed class Singleton
{
private static Singleton instance;

private static readonly Object mutex = new Object();

private Singleton() { }

public static Singleton Instance
{
get
{
lock(mutex)
return instance == null ? (instance = new Singleton()) : instance;
}
}
}

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that?s less common IME), so you can pass around the singleton as if it were ?just another? implementation


Description of Builder Pattern
: The Builder Pattern is quite confusing. There is a very subtle difference between Builder Pattern and Factory Pattern. I am not discussing Factory Pattern in this article but will soon write about Factory Pattern as well.
In Builder Pattern the user is given the choice to create the type of object he wants but the construction process is the same. We consider an example ? suppose you went to buy a car. First you will choose the model of the car and then it?s color and you consider it?s price that whether it?s feasible for you or not. If you want some extra luxuries in the car you will note them down as well and in the end you will place the order. Now you are isolated with the manufacturing process. You are not bothered by the manufacturing process. It?s the duty of the company because they have the assembly plant, which is programmed to manufacture cars of the model you choose and the manufacturing process is the same for a specified model of car.
In Builder, the client instructs the builder class how to create the object and then asks it for the result. How the class is put together is up to the Builder class.

Implementation of Builder Pattern:

using System;
using System.Windows.forms;

namespace BuilderPattern
{
///
/// Summary description for IBuilder.
///
public interface IBuilder
{
void ManufactureCar();
}
}

Classes that extends from IBuilder interface
1)    SuzukiMehran Class

using System;
using System.Windows.forms;

namespace BuilderPattern
{
///
/// Summary description for SuzukiMehran.
///
public class SuzukiMehran:IBuilder
{
public void ManufactureCar()
{
MessageBox.Show(?Suzuki Mehran Model 2002 ?
+?Color Balck ?
+ ?Air Conditioned ? );
}
}
}
2)   SuzukiKhyber Class

using System;
using System.Windows.forms;

namespace BuilderPattern
{
///
/// Summary description for SuzukiKhyber.
///
public class SuzukiKhyber:IBuilder
{
public SuzukiKhyber()
{
}

public void ManufactureCar()
{
MessageBox.Show(?Suzuki Khyber Model 2002 Standard ?
+?Color Red ?
+?Air Conditioned ?
+?Alloy Rim ?);
}
}
}
3) Director class

using System;

namespace BuilderPattern
{
///
/// Summary description for Director.
///
public class Director
{
public void ConstructCar(IBuilder build)
{
build.ManufactureCar();
}
}
}
4) Client Class

private void button1_Click(object sender, System.EventArgs e)
{
if(cmbChooseCar.Text==?Suzuki Mehran?)
{
Director car=new Director();
IBuilder build=new SuzukiMehran();
car.ConstructCar(build);
}

if(cmbChooseCar.Text==?Suzuki Khyber?)
{
Director car=new Director();
IBuilder build=new SuzukiKhyber();
car.ConstructCar(build);
}
}

The AbstractFactory is for a family of related products. The Builder is for one product.
The Builder is for building a complex product step by step, while the AbstractFactory is to build in an abstract way (that is, once for several implementations) a less complex product
Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
Description of Prototype Pattern:

The prototype pattern is used when creating an instance of a class is very time consuming or complex in some way. Then rather than creating more instances, it is possible to make copies of the original instances and modifying them as appropriate.

Implementation of Prototype Pattern :

using System;
namespace DoFactory.GangOfFour.Prototype.Structural
{
///
/// MainApp startup class for Structural
/// Prototype Design Pattern.
///
class MainApp
{
///
/// Entry point into console application.
///
static void Main()
{
// Create two instances and clone each

ConcretePrototype1 p1 = new ConcretePrototype1(?I?);
ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone();
Console.WriteLine(?Cloned: {0}?, c1.Id);

ConcretePrototype2 p2 = new ConcretePrototype2(?II?);
ConcretePrototype2 c2 = (ConcretePrototype2)p2.Clone();
Console.WriteLine(?Cloned: {0}?, c2.Id);

// Wait for user
Console.ReadKey();
}
}

///
/// The ?Prototype? abstract class
///
abstract class Prototype
{
private string _id;

// Constructor
public Prototype(string id)
{
this._id = id;
}

// Gets id
public string Id
{
get { return _id; }
}

public abstract Prototype Clone();
}

///
/// A ?ConcretePrototype? class
///
class ConcretePrototype1 : Prototype
{
// Constructor
public ConcretePrototype1(string id)
: base(id)
{
}

// Returns a shallow copy
public override Prototype Clone()
{
return (Prototype)this.MemberwiseClone();
}
}

///
/// A ?ConcretePrototype? class
///
class ConcretePrototype2 : Prototype
{
// Constructor
public ConcretePrototype2(string id)
: base(id)
{
}

// Returns a shallow copy
public override Prototype Clone()
{
return (Prototype)this.MemberwiseClone();
}
}
}

This helps to copy or clone the existing objects to create new ones rather than creating from the scratch.
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. ? ?Design Patterns? Gamma etal., Addison-Wesley, ISBN:0-201-63361-2?

When we are not in a position to call a constructor for an object directly, we could alternatively clone a pre-existing object (a prototype) of the same class. When there are many subclasses that differ only in the kind of objects they create a Prototype Pattern can be used to reduce the number of subclasses by cloning a prototype. Prototype Design Pattern helps in reducing number of classes.

For example suppose we have to do say Sales Analysis on a set of data in the database. Normally we will create an object encapsulating this data and do the Sales Analysis. Suppose now we have to do another type of analysis say Promotion Analysis on the same data. Now instead of creating another object corresponds to the data from the scratch, we can clone the existing object and do the analysis. This is one of the classical use of prototype pattern.

Posted in Uncategorized | Tagged | Leave a comment

Deploying a Rails application on Google App Engine

Google App Engine is a platform for developing and hosting web applications in Google-managed data centers. App Engine applications are easy to build, easy to maintain, and easy to scale as your traffic and data storage needs grow. With App Engine, there are no servers to maintain: You just upload your application, and it’s ready to serve your users.

Google App Engine supports apps written in several programming languages. Currently, the supported programming languages are Python and Java(and, by extension, other JVM languages such as Groovy, JRuby, Scala, Clojure, Jython, and special version of Quercus).

App Engine is free up to a certain level of used resources. Fees are charged for additional storage, bandwidth, or CPU cycles required by the application.

Since the App Engine supports the Java Runtime Environment, it can be used as a good platform for building and deploying a Rails application using JRuby.

Getting started

In this article we are going to create a Rails application and deploy it on App Engine. For accessing database we need to use either DataMapper or TinyDS as the ORM of choice, ActiveRecord is not fully supported.

Assign an app identifier

First of all we need to create an application and get the identifier. Simply go to http://appengine.google.com/start/createapp and register the application with the name of your choice. This name will be used as the subdomain of the url when the application is deployed and running.

By default, when an app is registered it will be available on http://{identifier}.appspot.com. It is also possible to run the application using a custom domain.

Prepare the Development Environment

The App Engine comes with an SDK to build and deploy the application. The SDK itself is very useful for creating Java or Python based applications. Since we are going to use Rails along with JRuby and the SDK has no inbuilt support for the language, we need to use another alternative – appengine-jruby. This project aims to make using JRuby as easy as any of the native App Engine languages. To use this library we need to install a rubygem using the following command.

[sudo] gem install google-appengine
  

Install Rails with required dependencies

As of this writing, Rails 2.3.9 is fully supported.

[sudo] gem install rails -v '2.3.9'
  

As mentioed before, we will be using DataMapper for accessing database.

[sudo] gem install rails_dm_datastore
[sudo] gem install activerecord-nulldb-adapter
  

IMPORTANT:All the above rubygems should be installed in to the system MRI. There is no need to install JRuby separately. The appengine-sdk gem itself includes a complete Java app server.

Create the application

To create the application, instead of using the standard rails command, we need to follow these steps.

1. Create a folder for your app.

mkdir rails_app; cd rails_app
  

2. Download and run the setup script.

curl -O http://appengine-jruby.googlecode.com/hg/demos/rails2/rails239_appengine.rb
ruby rails239_appengine.rb
  

3. Open app.yaml from the WEB-INF directory and replace ‘application-id’ on line 1 with the identifier you have created while registering the application.

Lets create a simple movie list

1. Create a restful controller.

./script/generate scaffold movie title:string description:text --skip-migration
  

2. Create a model for DataMapper.

./script/generate dd_model movie title:string description:text
  

Run and deploy the application

It’s time to check the application locally to see how it works. Then we are going to deploy it on the App Engine server.

1. Start development server

./script/server.sh
  

When the server is started the application will be available on http://localhost:8080

2. Deploy to production

./script/publish.sh
  

The above command will ask for you Google account credentials and then deploy the application on the server. After successful deployment, the application can be accessed live from http://{identifier}.appspot.com/movies.

It was just a small example of using the App Engine service to run a Rails application. Using the power of JVM/JRuby and the robust infrastructure provided by Google, it’s very easy to create and deploy Rails applications on the App Engine server.

Posted in Uncategorized | Tagged , , , | 2 Comments

Generic Methods

Generic in C#? means common to or applicable to an entire class. As most of the developers think Generic is to define type-safe data structures without committing to actual data types, but is it the only reason why Generics are for?
The answer is BIG NO

In this article we will focus on what other important aspect can be achieved in our daily programming by using Generic. We will see how to use Generic and avoid method overloading.
The below program shows the use method overloading to display content of int, double and char array.

using System;
class OverloadedMethods
{
    static void Main(string[] args)
    {
        // create arrays of int, double and char
        int[] intArray = { 1, 2, 3, 4, 5, 6 };
        double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
        char[] charArray = { 'H', 'E', 'L', 'L', 'O' };

        Console.WriteLine("Array intArray contains:");
        DisplayArray(intArray); // pass an int array argument
        Console.WriteLine("Array doubleArray contains:");
        DisplayArray(doubleArray); // pass a double array argument
        Console.WriteLine("Array charArray contains:");
        DisplayArray(charArray); // pass a char array argument
    } // end Main
    // output int array
    static void DisplayArray(int[] inputArray)
    {
        foreach (int element in inputArray)
            Console.Write(element + " ");
        Console.WriteLine("n");
    } // end method DisplayArray
    // output double array
    static void DisplayArray(double[] inputArray)
    {
        foreach (double element in inputArray)
            Console.Write(element + " ");
        Console.WriteLine("n");
    } // end method DisplayArray
    // output char array
    static void DisplayArray(char[] inputArray)
    {
        foreach (char element in inputArray)
            Console.Write(element + " ");
        Console.WriteLine("n");
    } // end method DisplayArray
} // end class OverloadedMethods

When we run the program output would be following:
For Array intArray contains:
1 2 3 4 5 6

For Array doubleArray contains:
21.1, 22.2, 23.3, 24.4, 25.5

For Array charArray contains:
C A S T L E R O C K


This looks pretty simple, but did you notice we had to write the same logic thrice for int, double and char. What if we had do write similar processing for all the data types, it would have taken hundreds of lines.

To overcome this with C# 2.0 Generic methods have been introduced. If we have similar operation to be performed by several overloaded methods we can write a single generic method declaration that can be called at different times with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. All generic method declarations have a type parameter list delimited by angle brackets (< E > in this example) that follows the method’s name.

Below we see the same code written using Generic method.

using System;
using System.Collections.Generic;

class MethodGeneric
{
    static void Main(string[] args)
    {
        // create arrays of int, double and char
        int[] intArray = { 1, 2, 3, 4, 5, 6 };
       double[] doubleArray = { 21.1, 22.2, 23.3,24.4, 25.5};
       char[] charArray = { 'C', 'A', 'S',  'T',  'L',  'E',  'R' ,  'O', 'C', 'K' };

        Console.WriteLine("Array intArray contains:");
        PrintArray(intArray); // pass an int array argument
        Console.WriteLine("Array doubleArray contains:");
        PrintArray(doubleArray); // pass a double array argument
        Console.WriteLine("Array charArray contains:");
        PrintArray(charArray); // pass a char array argument
    } // end Main

    // output array of all types
    static void PrintArray(E[] inputArray)
    {
        foreach (E element in inputArray)
            Console.Write(element + " ");
        Console.WriteLine("n");
    } // end method PrintArray
} // end class MethodGeneric

This program has the same output as the previous one, but we reduced the number of lines in the program. A generic method’s body is declared like that of any other method. Just like type declarations, method declarations can be generic i.e., parameterized by one or more type parameters. A type parameter is an identifier that is used in place of actual type names. The type parameters can be used to declare the return type, the parameter types and the local variable types in a generic method declaration. The type parameters act as placeholders for the types of the arguments passed to the generic method.

Posted in Uncategorized | Tagged , , , , , | Leave a comment