Saturday, June 29, 2013 with Model First Entity Framework, Oracle DB

These days I started working on developing a website from scratch using MVC4 and Entity Framework. I was planning to use Oracle database and realized that "officially" only Model-First entity framework approach is supported so decided to go ahead with that only.

As soon as I started working on developing database, I realized most of the examples or knowledge resources are based on Code First approach and Model First resources are very scarce. Considering that I decided to prepare a document listing all of my major issues with the links that helped me in fixing the same.

I am using MVC4, Razor, BootStrap, Model-First Entity Framework, Oracle db.

As the list of issues is extensive, this document is not even 1% of total issues but I believe over the time I will improve it and will definitely help some.

Google Doc: MVC4 with Model First EF, Oracle, Razor, Bootstrap from scratch

Tuesday, June 18, 2013

Nullable vs int?, C#

Today I generated code from the designer surface using DbContext template and realized that all of my nullable fields are declared as Nullable<int>. Kind of surprise to me "why it did not declare <int?>".

Found that both syntax are similar and there is no difference between the operation of two syntax. So feel free to use any one of them. They both represent an integer variable which can have null value too.

Mind, there is a difference between having a default value i.e. 0 or being null.

Friday, June 14, 2013

edmx file orgainzation, Entity Framework

Many times you are in need of making change in edmx file xml instead of simple designer surface. To get better understanding of how edxml's XML is organized, here is a brief overview.

edmx file is composed of three separate entities:

  1. Store details (SSDL Content): Content of this xml section has information about your database, what all tables are included in database, their column names, data types etc.
  2. Conceptual Model (CSDL content): This xml section has information about all properties and entities that you see in designer surface of a model in visual studio. For example you create a property of an entity named "comment" and declare it of "string" type. Now conceptual model will store details as "comment" -> "string". However Store Model will store the same property as "comment"-> "nvarchar2" (assuming comment is <2000 chars) i.e. datatype of property in SQL table.
  3. Conceptual - Store Mapping (C-S Mapping Content): It has information about mapping between the above two described model.
XML Organization:

<edmx: StorageModels>  Store Model (SSDL) details
     -- Entity Type        Table Name for an entity
                -- Property           Column name for a property 
     -- Association        Association table declaration i.e. relation b/w two tables.
                -- Referential Contraint        table's column declaration.

<edmx: ConceptualModels>       Conceptual Model (CSDL) details
     -- EntityContainer
                 -- Entity Set
     -- Entity Type          Class declaration for an entity
                 -- Properties       Property of model class

<edmx: Mappings>            C-S Mapping details
     -- EntityContainerMapping
                 -- Entity Set Mapping            Entity name; table name, class name for entity
                            -- Entity Type Mapping
                                     -- Mapping Fragment
                                                -- Scalar Property             Relation b/w CSDL table property and SSDL table column

Thursday, June 6, 2013

Using ORACLE database with Visual Studio for ASP.NET MVC4 website using Entity Framework

These days Microsoft's ASP.NET MVC4 is being used for latest cutting edge website development. Because of the ease that Entity Framework provides it is very well adopted by the developer community. Though it is fully compatible with Microsoft SQL Server database and other databases are still trying to provide support of EF. In case you want to use Oracle with Entity Framework then you need to install Oracle Data Access Components (ODAC) and Oracle Developer Tools.

Please note, as of now, Oracle support for Entity Framework only supports Model First approach. Though there are ways to approach Code-First too but it is not very well supported yet.

To install ODAC and ODET, it might get somewhat confusing and reaching to the appropriate knowledge document might get difficult. Here is the link by Oracle discussing how to install .NET components:

Share your experience with installation.

Wednesday, June 5, 2013

Ruby on Rails learning resources

I started learning Ruby on Rails last year and till date I'm still learning more on it. Here are few good online resources which I found helpful:

  1. First Ruby book I read:
  2. Agile Web development with Rails: Amazon link. I really like this book because of pragmatic approach. Worth buying.
  3. Code School 
  4. Once been through above books I started working on an Open Source project and where I believe actually I got chance to implement what I've learned so far.
  5. Revision after a break of 3-4 months from Ruby I again started learning from CodeAcademy which I found very wonderful and easy to learn tutorials.
  6. Also I've just started reading this book which now I believe is must read for a ruby enthusiastic. 
Will add more resources as I will find any but I guess if you are done with all these then you are at pretty much good level in programming RoR. 

Friday, May 31, 2013

Using ViewModel pattern in MVC 4 website, .net

It is very helpful to use ViewModel and to implement in an website with MVC 4 is pretty easy. Found this resource very helpful for using ViewModel in MVC4:

Will publish my post on same soon.

Thursday, May 30, 2013

Double question mark operator ??, .NET

The double question mark operator is used to provide default value for nullable type. e.g. done? is a nullable type and to provide a default value to it, we use done??false. It will return false when done is null. MVC 4 website using SQL Server Express instead of SQL Compact Edition

I was working on a sample MVC 4 application and on first run it used SQL Server Express by default for the database. Later I created seed data and set my config file to use SQL Server Compact Edition instead of SQL Server Express. I deleted .mdf from the APP_DATA folder and tried everything I could but application was still using the same old data instead of seed data.
My initializer code:
public class DBInitializer: DropCreateDatabaseIfModelChanges<xxxx>
Here is the small trick I used to fix this issue.

Update the seed data initializer to:
public class DBInitializer: DropCreateDatabaseAlways
and run the application, now your previous data base gets drop and new database using the new configuration will load up. Though its a work around but it fixed the issue. Once you got your new database working you can update the initializer to DropCreateDatabaseIfModelChanges in order to avoid creating database every single time. 

Friday, May 24, 2013

Preventing javascript as a query parameter, ASP

Suppose your web page is using this controller action

public string Browse(string queryParam)
     string message = HttpUtility.HtmlEncode(" = " + queryParam);
     return message;

Here HttpUtility.HtmlEncode utility is used to avoid illegal user input. For example, if someone deliberately uses: /home/user?queryParam=<script>window.location=''</script> then this utility will prevent such access.

Unit of Work and Repository Patterns, Entity Framework

Recently I started working on learning with MVC 4 and couple of other interesting stuff for my current assignment. There has been significant improvement in data access layer in C# since the time I last used it (probably 1 year back).

Here are the links of couple of helpful posts:
a) Unit of Work design pattern:
b) Repository Pattern

Sunday, May 5, 2013

Updating forked repository with parent repository, Github

Suppose you have a team working on a repository name "Base" and a particular team member wants to work on specific module. He forks the Base repository to his account. Later he needs to get latest changes done by developers on Base repository to his repository. Here are the steps to follow:

a) In Github, you name repositories like 'origin', 'remote' etc. Add Base repository as remote to your repo.
git remote add teambranch git://
Here teambranch is the name of remote and you can get the git link info from the base repo web ui.

b) Use git fetch to download objects and ref from another repository
git fetch teambranch
It will fetch all branches of remote into remote-tracking branches.

c) Rewrite your master branch
git rebase teambranch/master
And your repository will be updated.

I am still learning Git and will post more helpful post as come across. Also I read couple of post to achieve this merging task but still don't have complete understanding on working of  various git commands. Will keep on posting as I will learn.

Thursday, April 25, 2013

Toggle button with Gradient and Image, Android

To create an android toggle button with a bitmap image and gradient follow the following steps:
1. Create new xml file in drawable-mdpi folder say mybutton.xml.
2. Add gradient and image to this file with selector and layer-list based on behavior you want to achieve. For example:

<selector xmlns:android="">
    <item android:state_checked="true">
        <layer-list >
               android:color="#a276eb" />
               android:color="#6a3ab2" />
               android:radius="3dp" />
               android:bottom="5dp" />
           <bitmap android:gravity="center_vertical|center_horizontal" android:src="@drawable/dollar" android:tileMode="disabled"/>
    <item android:state_checked="false">
                android:angle="270" />
                android:color="#6a3ab2" />
                android:radius="1dp" />
                android:bottom="10dp" />

3. In activity or Fragment where you want to place this button, add a normal button and set background to the custom view that we have defined above as:
and you are all set.

Thursday, April 11, 2013

Using multiple fragments and replacing/swapping with other fragments eventually, android

I found this very interesting post on stackoverflow about how to use multiple fragments and replace fragments on the go:

Excerpt: While using multiple fragments don't declare them in layout (or activity which will have fragment) instead add fragment to an activity programmatically and swap/switch with other fragments by fragment transaction manager. In case you define fragment in the XML of activity then it won't allow you to switch fragments dynamically (ofcourse by Java code) because once you define any fragment in XML that fragment is like static for that activity.

Very interesting thought while designing UI of your application.

Tuesday, April 9, 2013

XML, KML database for android

While working on an android application development, I researched about the possibilities of database for an android application to store geolocation of various points. During the research, first I started with keeping an XML (not KML) file with all values and use JAXB for reading and writing the XML. Following links are wonderful resources for learning XML access using JAXB:

However later I realized that you should not use JAXB for android app. It will increase the size of application by 9MB.

Then a work around of using XML in android app using SIMPLE. and it is a wonderful way to use XML for android.

Meanwhile following tutorial will help you to learn about KML in android. KML is the best way for storing geolocation in an android app but there are not major dummy application to get an understand of how to use it. Here is a link for simple usage of KML :

As JAXB is an api for accessing and modifying an XML file in java similarly we have a JAK (Java Api for KML) to access and update KML. Here is the code and more details about the JAK project (open-sourced)

I am not done with the application database and would update the post once I got go ahead with the best strategy.

 Update: Finally we decided on to use SQLite itself. Also got to know from some people that KML is not a database :O

Sunday, April 7, 2013

Google Maps Android API v2. Failed to load Map. Could not connect to Google Servers

If you are facing this error then follow these post thoroughly and you will definitely end up running your application. Though it took almost half day to get it fixed.

update: Complete tutorial for setting up Google Maps Android API2 : Google doc Android Map Api setup steps complete


In case you need reference, here is the link to my Android.manifest file for a dummy Map test application. Github Link:

NEXUS 4 device not detected in ADB devices list, eclipse, android development

If this is the first time you are trying to connect your NEXUS 4 (or any other google device) to eclipse for application deployment then you need to do following steps in order to have successful driver installation. (Sources: Multiple posts on stack overflow and other user-community)

1. Open 'SDK Manager' (from 'adt-bundle' directory).
2. Go to the bottom of list and install 'Google USB driver'.
3. In case you have already tried to install USB driver for your device then we first need to uninstall them. Go to device manager (right click "My Computer" > Device Manager). Then select "<device name>" from Portable devices tab. Right click and select uninstall driver.
4. Now on your phone, enable USB debugging. To enable, Go to "about phone", tap 7 times on "build number".
5. Connect phone to your machine and after connection, select "CAMERA (PTP)" on phone. This is important.
6. System will install the driver for the new device.
7. Again go to device manager and select the <device name> device under "Portable devices" tab. Select 'Update Device driver' and provide the manual path to search for driver. Path is : <android-sdk-directory>\extras\google\usb_driver.
8. Let it install the driver and android composite driver will be installed on your device.
9. Now open eclipse and start deploying apps to your phone.

Saturday, March 30, 2013

Difference between @+id and @android:id, android

While working on a test android application, I noticed two different way of defining ids i.e. @+id and @android:id. Out of curiosity, I googled differences between them and highlighted good differences between two.

1. @+id:
Example <Button android:id="@+id/button_add" ..../>
By defining @+id/button_add we are creating an id named button_add in the namespace of our application which can be referred in our application as @id/button_add.

2. @android:id
 By defining @android:id/list means you are referring to an id defined in the android framework namespace. The android framework knows only about the ids in the android namespace. Android framework identifies a list element using android:id/list. It won't work if you change list to any other id like @android:id/listAddNew.

Will add more details about it in future post.

Tuesday, March 26, 2013

Redirecting output from standard output to text file, Java

There are times when you need to redirect all your output to a text file. It is very easy with command line execution by using  '>' output. However in case you want to do it programatically there is very easy way.

Following are the steps to follow:
Add following code block in starting of main function of your application (assuming you want to redirect all of your output to a text file in case not add the code at point from where you want your output to redirect to text file).
1. Create new file where you want your output to store, say out.txt here
File file = new File("out.txt");
2.  Now get output stream of this file. Using this stream, output will be sent to out.txt
FileOutputStream fileOutputStream = new FileOutputStream(file);
PrintStream printStream = new PrintStream(fileOutputStream);
3. And the last step is to update the output stream of system to our file stream instead of default console stream.
Now all is done and all of your console output will be redirected to the out.txt file. In case you want to revert the output to default console you can do by:

Sunday, March 10, 2013

src refspec master does not match any, Github

Got this error while pushing changes to newly created repo using windows Github client tool.

This stackoverflow post helped out:

$~ mkdir repo && cd repo
$~ git remote add origin /path/to/origin.git
$~ git add .
Oops! Never committed the origin (source) branch!
$~ git push -u origin master
error: src refspec master does not match any.
$~ git commit -m 'initial commit'
$~ git push origin master
Hope it helps

Friday, March 8, 2013

Goodle Drive SDK

Google drive SDK is easy to use API for integrating google drive service to existing web server. Following links are helpful for understanding drive sdk
1. Creating a new file using drive API service (by Google):


Thursday, March 7, 2013

Garbage collection in C#

Useful links to summarize Garbage collection working:

1. Dispose Pattern (used for freeing up unmanaged resources) :
2. Dispose Method (exist with each disposable object) :

3. In case we are using Dispose method call then order of dispose method call is significant. E.g. If object A allocates object B which in turn allocates object C then dispose method of object A should call dispose method of object B, dispose method of object B should call dispose method of object C.

4. Most common memory leaks in WPF and their fixes:
Brief: 1. Event handlers registered with parent object.
2. Registering event with static objects. Static members never releases memory so window won't be able to dispose properly.
3. Timers: Associating events with timers can cause memory leaks because timer won't stop automatically and event will keep on calling.
4. Data Binding: Make sure data binding on control should use the dependency property because only they are disposed by the GC. If you bind a control with a non dependency property then that control will not be disposed.
5. Changing text property too much. Keep limit on no. of operations to keep in undo stack. 

Monday, March 4, 2013

Object oriented programming concepts (part 1)

1. Program to an interface, not an implementation
This literally means program to a supertype i.e. the declared type of the variables should be a supertype, usually an abstract class or interface, so that a particular variable holding interface object can have any type during runtime and our code should not be limited to any particular data type. Using this concept, we can exploit the polymorphism in OOPS.

2. Is Java, pass by value or pass by reference?
Java is pass by value but in true sense, it is passing value of references of objects.
More details: stackoverflow/is-java-pass-by-reference

3. Primitive data types are passed by value while non primitive types (like class, interface, string) are passed by reference.Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .

4. Encapsulation and Abstraction
"encapsulation is concrete, abstraction is...abstract! ;-) encapsulation is an object you can use, abstraction is an ideal you can only discuss. encapsulation is why you wear underwear, abstraction is how you explain the difference between underwear and swimsuits". By a stackoverflow user comment

5. Abstract class vs Interface
No implementation in interface however abstract class have both implementation as well as declarations. Total Abstract class is almost similar to interface with an exception that abstract class can inherit only one super class however interface can inherit as much number of interface as required. Abstract class does not have instance.
a) Interface
Interface cannot be final.
Interface can have variables but they must be static, public, final which means interface can declare only constants.
An interface can extend only other interfaces.
Interface can't be instantiated.
Interface methods could be only public and abstract. No other modifier permitted.
All methods of interface are abstract methods.
Adding a new method necessitate to modify subclasses.
Cannot contain Constructor.
Interfaces are somewhat slow as they require method finding process before calling actual method
Used when something in design changes more frequently.

b) Abstract Class
Abstract class can provide complete default functionality or details to be overridden.
Contains both implementation methods as well as abstract methods.
In a class if there is even a one abstract method, whole class should be declared as abstract class.
Cannot mark a class as both abstract and final
It cannot be instantiated.
Abstract class could be public, private or protected.
Adding a new method does not necessitate to modify subclasses.
Can contain CONSTRUCTOR.
Used when various implementation are of the same kind and use common behavior.
A non abstract method can access an abstract method.

"Imagine a software firm that is composed of different Business Units (or departments) like Storage BU, Networking BU. Automobile BU. The life time of these Business Units is governed by the lifetime of the organization. In other words, these Business Units cannot exist independently without the firm. The firm is COMPOSED OF business units."

"The software firm may have external caterers serving food to the employees. These caterers are NOT PART OF the firm. However, they are ASSOCIATED with the firm. The caterers can exist even if our software firm is closed down. They may serve another firm! Thus the lifetime of caterers is not governed by the lifetime of the software firm."

"Consider a Car manufacturing unit. We can think of Car as a whole entity and Car Wheel as part of the Car. (at this point, it may look like composition..hold on) The wheel can be created weeks ahead of time, and it can sit in a warehouse before being placed on a car during assembly. In this example, the Wheel class's instance clearly lives independently of the Car class's instance. Thus, unlike composition, in aggregation, life cycles of the objects involved are not tightly coupled."

9. Overloading
a) MUST change the argument list
b) CAN change the return type
c) CAN change the access modifier
d) CAN declare new or broader checked exceptions
e) A method can be overloaded in the same class or in a subclass

10 Overriding
a)The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex:  Cannot override a method marked public and make it protected).
b) Cannot override a final method.
c) Cannot override a static method.
To prevent a method from getting over ridden use "final" keyword.

11 Constructor
a) Constructor cannot be inherited and they do not have any return type.
b) Cannot be final, abstract, static in comparison to methods
c) "this" keyword is used to access constructor in the same class. "Super" keyword is used to access constructor in super class.

Tuesday, February 12, 2013

Reversing a linked list recursively

Very nice solution for reversing a linked list recursively :

Understanding Dynamic Programming using C#

Dynamic Programming is quite a cool technique to solve pretty complex problem. One of such problem is Coin Change problem which first seems to be easily solvable using Greedy approach but involves Dynamic Programming in order to get the perfect result in every case. I'm running out of time so posting only code to do that using C#. Will explain next time.

int[] coins;

        public CoinChange()
            coins = new int[5];
            coins[0] = 5;
            coins[1] = 10;
            coins[2] = 20;
            coins[3] = 25;
            coins[4] = 50;

        public int CoinCentral(int input)
            int[] tempCoins = new int[input + 1];
            for (int a = 1; a < tempCoins.Length; a++)
                tempCoins[a] = int.MaxValue;
            tempCoins[0] = 0;

            for (int currentNumber = 1; currentNumber <= input; currentNumber++)
                for (int currentCoin = 0; currentCoin < coins.Length; currentCoin++)
                    if (currentNumber >= coins[currentCoin] && 1 + tempCoins[currentNumber - coins[currentCoin]] < tempCoins[currentNumber])
                        tempCoins[currentNumber] = tempCoins[currentNumber - coins[currentCoin]] + 1;
            return tempCoins[input];

Sunday, February 3, 2013

Float variables dilemma, C/C++

I came across an amazing post. Guess what will be the answer of following program:

float fx = 4.5;
if ( fx != 4.5)
      printf(" WTH ? Something wrong with assignment");

If you expect that WTH?... won't be printed ever then check this link doubles-are-not-floats-so-dont-compare-them


Very nice post related to floating values.

Float: These are the single precision variables occupying 4 bytes (32 bits) with 24 bits for mantissa or significant part.
Double: These are the double precision variables occupying 8 bytes (64 bits) with 53 bits reserved for mantissa.

Min Value of float in C#: Single.MinValue

Sunday, January 27, 2013

Printing a string integer in comma separated format

Input: 12345667800000
Output: 12,34,56,78,00,000


import java.lang.*;

public class Program
    public static void main(String args[])
        System.out.println("Hello world! From");
        String str = "1234567800000";
    public static String getStr(String str1)
      if(str1.length()  <=3)
            return str1;
            if(str1.length() % 2 == 1)
                return str1.substring(0,2) + "," + getStr(str1.substring(2,str1.length()));
                return str1.substring(0,1) + "," + getStr(str1.substring(1,str1.length()));      

Permutation of possible string using a phone keypad, Java

Print all possible combinations of letters that a particular phone number could represent.
<pre class="brush:java">

import java.util.*;

public class permutation {
public static String[] mapping1[] = {{"0"},{"1"},{"A","B","C"},{"D","E","F"},{"G","H","I"},{"J","K","L"},{"M","N","O"},

public List<String> GetPermutation(String phoneNumber)
List<String> combo = new ArrayList<String>();
GeneratePermutation(combo, "", phoneNumber);
return combo;
public static void main(String[] args)
String phonenumber = "3456789";
permutation abc = new permutation();
List<String> comboList = abc.GetPermutation(phonenumber);

for(String permutation: comboList)

public void GeneratePermutation(List<String> combo, String prefix, String endPhone){
Integer currentInt = Integer.parseInt(endPhone.substring(0,1));

if(endPhone.length() == 1)
// Reached string end add all possible combination
for(int temp = 0; temp < mapping1[currentInt].length; temp++)
combo.add(prefix + mapping1[currentInt][temp]);
for(int temp = 0; temp < mapping1[currentInt].length; temp++)
GeneratePermutation(combo, prefix + mapping1[currentInt][temp], endPhone.substring(1));

Major intention of this post is to test the new script in blogger which can display code block. But it does not seems to work. Will update it soon.


Multidimensional arrays, Java

You must have used multidimensional arrays in whichever programming languages you use. Here is a brief about different ways of declaring and accessing multi-dimensional arrays in java.

Say you want to represent the following data in 2-D array

which in fact represent the keys on your phone.

You can declare such mapping as:

public static String[] mapping1[] =
{  {"0"},

public static String mapping2[][] =

{  {"0"},

public static String[][] mapping3 =

{  {"0"},

Note the difference in declaration but all these represent the same data (or same 2D array).
If you do:


then output will be same for all three wiz:
[[0], [1], [A, B, C], [D, E, F], [G, H, I], [J, K, L], [M, N, O], [P, Q, R, S], [T, U, V], [W, X, Y, Z]]

Also one more point worth noticing here is in order to access data there will be same accessor i.e.
if you want to access element 'B' (whose position in 2 D array is [2][1]) then accessor for three mappings will be same wiz

Output: B


Friday, January 18, 2013

Idea: Phone to TV over Wifi

Wouldn't it be great if you can see your phone screen on big tv just by using a simple app on your phone? I searched for such an app but there is n't any as such. You can browse your phone on your machine, see all its content but what if you want to show the world what you are watching on your phone either on your laptop screen or say projector connected to your laptop.

This is very much possible using an HDMI cable but how about doing this wireless - over wifi. I have seen such stuff in manufacturer's keynote (like on new android release) where they show off cool features of new mobile OS on projector. But I don't have much idea what they use to do that.

As a novice, I searched a bit on google but couldn't figure out a way to connect. Will surely work on building such app as soon as got time =). It will involve cross-platform implementation so first need to look for available alternatives.

Just realized this is my first post of 2013. Happy New Year.