Sunday, March 31, 2013

Dynamic property or Extended property in C#



I was busy to create architecture of asp.net (C#) project. In the time of development, I faced a situation where it will be good to have a dynamic property generation. I did some search, and found many examples. But after going through all, I found something, which is really nice and solve my problem. My problems are-
1>  I need to get all the data fetched from table in DB in a custom and pre-defined model in c#, but sometime DB queries can return some columns which are not in the defined properties of predefined model.
2>  When I do serialization of the model in c#, it should serialize in normal and proper way, with or without extra columns returned from DB.
Example-
Suppose, I define a model –
Public class EmpModel{
Public string EmpName{get; set;}
Public string EmpId{get; set;}
}
And I also write three SQL queries-
SELECT EmpName,EmpId,EmpAddress from tbl_Employee
SELECT EmpName,EmpId,EmpDept from tbl_Employee
SELECT EmpName,EmpId,EmpDOB from tbl_Employee
Now, as you can see, the queries are returning three columns, but the model only has two properties. I cannot manage EmpAddress, EmpDept and EmpDOB in model. As well as, the 3rd field will be different in type also. To manage this situation, I found-
1>     AssemblyBuilder
2>     ModuleBuilder
3>     TypeBuilder
4>     FieldBuilder
5>     PropertyBuilder
6>     MethodAttributes
7>     MethodBuilder

These are the main building blocks of my solution.

The theory of the solution is, I have to create a class which will have EmpModel as a base class and with the properties (Extra properties) needed. All these, need to be done dynamically.

For all these, I managed to write two method sets(Three methods), which will handle everything for me-
MethodSet 1 (to bind DB columns with Model properties)-[Contains two methods]
public void getModelFromObject<T, T1>(object valu, ref List<T> el,Dictionary<string,Type> props) where T1 : T, new()
        {
            DataTable dt = ((DataSet)valu).Tables[0];
            Type dynamicType = getType(typeof(T).Name+ "Ext", props, typeof(T1));
            foreach (DataRow dr in ((DataSet)valu).Tables[0].Rows)
            {
                T item = (T)Activator.CreateInstance(dynamicType);
                getObject<T>(dr, ref item, dt);
                T tsts = item;

                ((List<T>)el).Add(item);

            }
        }

public void getObject<T>(DataRow dr,ref T obj, DataTable dt)
        {
          
            foreach (DataColumn dc in dt.Columns)
            {
                if (obj.GetType().GetProperty(dc.ColumnName) != null)
                {
                   
                        obj.GetType().GetProperty(dc.ColumnName).SetValue(obj, dr[dc.ColumnName], null);
                 
                }
            }
        }

MethodSet 2(to create extended properties)-[Contains one method]
  public Type getType(string dynamicClassName, Dictionary<string, Type> propertyList, Type baseClassType)
        {
            bool isNewProperties = false;

            AssemblyBuilder assemblyBilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly
            (new AssemblyName(dynamicClassName + "Assembly"), AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBilder = assemblyBilder.DefineDynamicModule(dynamicClassName + "Module");

            TypeBuilder typeBilder = moduleBilder.DefineType(dynamicClassName, TypeAttributes.Public | TypeAttributes.Class, baseClassType);

            string propertyName = null;
            Type propertyType = null;
            var baseClassObj = Activator.CreateInstance(baseClassType);
            foreach (var prop in propertyList)
            {
                propertyName = prop.Key;
                propertyType = prop.Value;

                var propExist = baseClassObj.GetType().GetProperty(propertyName);
                if (propExist != null)
                {
                    continue;
                }

                FieldBuilder filedBilder = typeBilder.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

                PropertyBuilder propertyBilder = typeBilder.DefineProperty(propertyName, System.Reflection.PropertyAttributes.None, propertyType,
                            new Type[] { propertyType });
               
                MethodAttributes GetSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig;

                MethodBuilder currGetPropMthdBilder = typeBilder.DefineMethod("geter", GetSetAttr, propertyType, null);

                ILGenerator currtGetIL = currGetPropMthdBilder.GetILGenerator();
                currtGetIL.Emit(OpCodes.Ldarg_0);
                currtGetIL.Emit(OpCodes.Ldfld, filedBilder);
                currtGetIL.Emit(OpCodes.Ret);


                MethodBuilder currSetPropMthdBilder = typeBilder.DefineMethod("seter", GetSetAttr, null, new Type[] { propertyType });


                ILGenerator currSetIL = currSetPropMthdBilder.GetILGenerator();
                currSetIL.Emit(OpCodes.Ldarg_0);
                currSetIL.Emit(OpCodes.Ldarg_1);
                currSetIL.Emit(OpCodes.Stfld, filedBilder);
                currSetIL.Emit(OpCodes.Ret);


                propertyBilder.SetGetMethod(currGetPropMthdBilder);
                propertyBilder.SetSetMethod(currSetPropMthdBilder);
                isNewProperties = true;
            }

            if (isNewProperties == false)
            {
                return baseClassType;
            }
            return typeBilder.CreateType();
        }
And now, the use of these methods-
     List<IEmp> obj = new List<IEmp>();

            Dictionary<string, Type> props= new Dictionary<string, Type>();
            props.Add("EmpAddress", typeof(string));//if more then one add more.
            modelPlatform.init().getModelFromObject<IEmp,Emp>(ds, ref obj, val);//ds- is the dataset returned from DB
           
            return obj;


Same for two other queries also.
That’s it, Enjoy.

Tuesday, March 19, 2013

Advance LED display


I did some betterment in Led display. By using 8051/52, this display is working smoothly. All the code and the character generation is done by C. I used only 15 pins of Micro-controller for this display. Another important component used here is 74HC595. To use minimum amount of PINs, I used parallel to serial conversion. 74HC595 is basically used as a parallel to serial converter. 

Demo is here- youtu.be/WFTibkb-cx4


To get the code provide your mail id in comment section-

Tuesday, March 5, 2013

MVPC (semi- MVVM) implementation for Android app Development


Introduction
When I was trying to implement MVC for Android Application, the concept of “Observer” really attracts me. It really put me in a situation, where, I have to think, should I go for MVC or MVPC.  Because, I think, MVPC would be more organized and maintainable way for this Android application.  Along with this thinking, possibility of total segregation of event listeners in code, make me think about MVPC for this project seriously.
[Note: Observer is the interface to be implemented by objects that receive notification of updates on an Observable object. (Observer Triggers, when Observable notifies any changes on it)]

Why MVPC?
Model-View-Presenter-Controller. In MVC, View notifies Controller, Controller notifies Model, and Model notifies View. It is really very compact and smart enough Architecture. But, Presenter is another useful architecture entity. It will give another level of abstraction to the project between View and Controller. This will make the view much independent and make controller more flexible.  With this architecture, we can replace the existing view with a new one, so smartly, that we may have to do no changes in Controller.

Do we really need MVPC in Android Application?
We may not need MVPC for today or tomorrow, but day after tomorrow. As year goes, a View of an application becomes monotonous to the user, or else, we may need to implement different views (Theme) to the project. To do all the above, we really don’t want to hamper any application flow.  MVPC will be one of the best fit architecture for this.


Code Example-
In MainActivity.java-
public class MainActivity extends Activity  {

       public User mUser;
       UserController controller;
       UserPresenter presenter;
      
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              mUser= new User();
              controller= new UserController(this);
              mUser.addObserver(controller);
              presenter= new UserPresenter(mUser);
             
              Button test_btn=(Button) findViewById(R.id.btn_Test);
              Button test_btn2=(Button) findViewById(R.id.btn_Test2);
              test_btn.setOnClickListener(presenter);
              test_btn2.setOnClickListener(presenter);
       }

In UserPresenter.java-

public class UserPresenter implements OnClickListener {

       private User _model;
       public UserPresenter(User model)
       {
              _model=model;
       }
      
       @Override
       public void onClick(View v) {
              switch(v.getId())
              {
              case R.id.btn_Test:
                     _model.setCount();
                     break;
              case R.id.btn_Test2:
                     _model.setCount();
                     _model.setCount();
                     break;
             
              }
       }

}


In UserModel.java-

public class User extends Observable {
       public int count=0;
       public User(){
             
       }
       public void setCount()
       {
              count++;
              setChanged();
              notifyObservers();
       }
}                     

In UserController.java-

public class UserController implements Observer {
    public User mUser;
    private Activity _act;
    public UserController(Activity act )
    {
       _act=act;
    }
   
       @Override
       public void update(Observable observable, Object data) {
              TextView lbl= (TextView)_act.findViewById(R.id.lbl_Text);
              lbl.setText(""+((MainActivity)_act).mUser.getCount());
       }

}





Monday, February 11, 2013

8x8 LED Display using 8051 and c



Basic Idea:
Creating simple things is always good for a learner like me. I created a simple Led display using 8051. Total pin used is 2 ,for character generation. So, as we can see we can use 2051 for this kind of display. One set of pin is to scan through row and another set of pin to handle LED (On/Off) by column. The basic catch behind this circuit is serial data transmission, which makes this project cost effective.
Demo:
http://youtu.be/epC1AdFCQTw

Thursday, March 1, 2012

Objective-C basic - [import from library and user created file]

Now we will discuss about objective –c in more details.  If we will see a code in objective-c ,at the top , then we will get import key word followed by file names. Here we may find two different pattern of declaration.
#import <someFileName.h>
And
#import “someFileName.h”      
What is the difference between these?
Nothing tough, first one is for a header file from library folder and second one is for a header file from application folder itself.
Very easy, right?
Example-
#import <foundation/foundation.h> //import foundation header file from library
#import “myHeader.h” //import myHeader.h file from my project/app folder.
That’s it. See you in next post.

Sunday, January 15, 2012

What is MVC? How it is implemented in iPhone development?


MVC, a much known term in software industry right now.  I will not spend much time to explain MVC; rather, how it is implemented in IPhone will get more priority in this article. Let’s start.
MVC - simply Model View Controller.
Now take a simple example. Suppose a car. It has a body, four wheels, one steering and one engine. Now, engine is a module, steering is a controller, wheel is a separate module and guess what, body is view. Pretty simple, right. Now come out from the car. In software, an object which represents project entities is module. Controller will do various operations with modules depending on different commands and commands will be sending user interface [view] and the output result will be shown in view itself.
It’s done.
mvc iphone
MVC Architecture 



Cocoatouch is a building block of iPhone development. It is solely following MVC for development. As we understood previously, it has model, view and controller, iPhone development follows the same.  When we create an application using xCode, it will give us a specific folder structure with the support of MVC itself. In the folder one can see view and viewController files.  There will be two kinds of file or rather we can say same named files with two different extensions [*.h , *.m].



Now, let’s see ,what is in it.
[.H] file will contain something like ----

@interface MainViewController : UIViewController {
UILabel *label;// label is added to it
}

@property (nonatomic, retain) IBOutlet UILabel *label;
 //will be used as a reference to controller
@end

Here we can see, it is an interface which inherits UIViewController[Master class for all view]. It also contains a label[Added by us].

[.m]file will contain ---
#import "MainViewController.h"
#import "MainView.h"

@implementation MainViewController
@synthesize label; //to do sync properties in interface

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}

- (void)dealloc {
[label release];
[super dealloc];
}

@end

Here, we implement the created interface in .H file as far as MVC concerns.  And it will work with all the properties declared in interface. Here we use @synthesize to synchronize attributes in [.m] and [.h].
Now in this way we created a controller and an interface for view. Sounds confusing?  Yes , View.h file will work as an interface for view [normal MVC concept].  
We will have .xib files too. It is basically an xml which represents the actual UI.

Now , from the toolbox we can get all available controls ,which we can drag and drop to the UI to design as per our requirement. [The process of designing will not be here in this article. It’s all about MVC in iPhone]
Now it is the time to connect the UI to View to interact with controller.


In view controller connection window, we can find all the added controls in a list. By dragging the listed control reference to the View object cube we can map the UI objects to view properties. All the code related to it will be auto generated. So in this way view and controller will be connected.
Now, we can create a custom model to interact with values sent from view. To do that we need to create an interface of a model in myCar.h file-
#import <foundation/Foundation.h>

@interface myCar : NSObject {
    NSString *name;
}

@property (nonatomic, retain) NSString *name;

+ (myCar *)sharedModel;

@end

Now we are ready to implement the interface in myCar.m file.
#import "myCar.h" 
@implementation myCar \\    here the implementation
@synthesize name;\\ synthesize with interface implementation

- (id) init
{
    self = [super init];
    if (self != nil) {
        name = @"";
    }
    return self;
} 
- (void) dealloc
{
    [name release]; \\release memory from device
    [super dealloc];
}
 @end
Our model is also created.  It’s the time to implement model in our code. See bellow-
- (IBAction)textChanged:(id)sender
{
    myCar *car = [myCar sharedModel];
    model.text = textField.text;
}

It is just an over view. Explore much by creating an app.
Enjoy