Mohammad Hoque

Few things I like to talk about

About the author

Mohammad Hoque is a Information Technology consultant in Minneapolis, MN.

He offers his services through Hoque Consulting

He has more than 10 years of experiences in Web and Web related technologies.

He currently lives in Lakeville with his adorable twins Isaac and Tiara.

Month List

Page List

    Issues with the MvcScaffolding

    Technorati Tags:
    I was trying to add a class and repository pattern for the class. But for some reason I wasn’t able to execute the command without error.

    I tried separate different way to execute the Scaffolder and unable to get it going.

    Tried to Update-MvcScaffolder from Package manager console and Enable Migration from the Package Manager console also. No  Luck.

     

    Finally, I closed the solution , reopened it as admin and then update each installed item from the Tools –> Library Package Manager –> Manage Nuget Packages for Solution.

    image

     

    After that I tried the same command and it worked.

    image

     

    I am not sure why, since I haven’t dig deep in the issue yet. But at least this got me going again.

    WordPress Tags: Issues,repository,error,Scaffolder,Update,MvcScaffolder,Package,manager,Enable,Migration,Nuget

    Permalink | Comments (0) | Post RSSRSS comment feed

    Leveraging Scaffolders to Implement Repository pattern for your project

    I have shown in last couple of posts how to use

    1. MVCScaffolding to scaffold your MVC 4 project with Razor View Engine,

    2. Use the Migration tool to use code first approach.

     

     

    I still want to show you how to use the repository pattern using the Scaffolding technique

    Here is the outline of what we are doing.

    • Installing MvcScaffolding
    • Scaffold each model

    On your project from the last post run the following command on your package manager console

    PM> Install-Package MvcScaffolding

    This will install all the necessary component for the MvcScaffolding for the project.

     

    Now run following for each model

    PM> Scaffold Repository Role

    PM> Scaffold Repository user

    PM> Scaffold Repository UserRole

     

    Here is an example of the repository what it will look like

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Web;
     
    namespace TestService.Models
    { 
        public class RoleRepository : IRoleRepository
        {
            AuthenticationContext context = new AuthenticationContext();
     
            public IQueryable<Role> All
            {
                get { return context.Roles; }
            }
     
            public IQueryable<Role> AllIncluding(params Expression<Func<Role, object>>[] includeProperties)
            {
                IQueryable<Role> query = context.Roles;
                foreach (var includeProperty in includeProperties) {
                    query = query.Include(includeProperty);
                }
                return query;
            }
     
            public Role Find(int id)
            {
                return context.Roles.Find(id);
            }
     
            public void InsertOrUpdate(Role role)
            {
                if (role.Id == default(int)) {
                    // New entity
                    context.Roles.Add(role);
                } else {
                    // Existing entity
                    context.Entry(role).State = EntityState.Modified;
                }
            }
     
            public void Delete(int id)
            {
                var role = context.Roles.Find(id);
                context.Roles.Remove(role);
            }
     
            public void Save()
            {
                context.SaveChanges();
            }
     
            public void Dispose() 
            {
                context.Dispose();
            }
        }
     
        public interface IRoleRepository : IDisposable
        {
            IQueryable<Role> All { get; }
            IQueryable<Role> AllIncluding(params Expression<Func<Role, object>>[] includeProperties);
            Role Find(int id);
            void InsertOrUpdate(Role role);
            void Delete(int id);
            void Save();
        }
    }

    This will create all 3 repositories for the models under the model folder. You will see one more file that is [your project name]Context,

    if you already have a context file remove this file and on each repository replace this file type with your class name.

     

    Now build the project and you just implemented the repository pattern.


    Permalink | Comments (0) | Post RSSRSS comment feed

    Using Code first approach with Entity Frameworks Migration tool

    In one of my previous post I have done a simple overview of how to use Entity Frameworks code first approach for MVC4 project. I did a simple overview on how to use the Scaffolding to generate Views, Controllers and update database from model classes.

     

    On this post I will make things a little simpler, I will show you how easy it is to use the Entity Frameworks Migrations to use the code first approach. Hopefully you will get some sort of benefits from it.

     

    For this project, I created a simple WCF class library project ( you can do just class library too).

     

    First step, go to Tool –> Library Package Manager –> Manage NuGet packages for Solution

     

    This will open up the Nuget Package window, Find Entity Framework and install it.

    image

     

    Next I went to the App.Config file and added the following lines under the <congifuration>

     

    <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </configSections>
      <connectionStrings>
        <add name="HowToUseMigration" connectionString="Server=[your server];Database=[Database Name];Uid=[user];Pwd=[password];" providerName="System.Data.SqlClient" />
      </connectionStrings>

     

    Now on your project you have your connectionstring that is pointing to a Database.

    You need to create the Database shell on your SQL server.

     

    Next thing you need is a way to tell the project that you want to use the Migration tool.

     

    go to Tool –> Library Package Manager –> Package Manager Console

    This will open the a windon on the bottom (depends on your setting), and You will see PM>

    Make sure you are pointing at the proper project, if you have more than one project

     

    image

     

    You need to specify a class that is derived from DbContext, Migration will use this to setup the database activity.

    I manually created a Folder called Models, add a class as following

    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Text;
     
    namespace TestService.Models
    {
        public class AuthenticationContext : DbContext
        {
            public AuthenticationContext()
                : base("name=[Connectionstring name goes here")
            {
                
            }
     
        } 
    }

     

    Now we are ready to type again

    PM> Enable-Migrations

    No context type was found in the assembly ‘TestService’.

     

    This is ok, it means that we haven’t defined any class that the migration tool can use to create the database tables. If you look in your project you should have a Migration folder with

    Configuration.cs file in it. This is where we can change settings add Seed data.

     

     

    We will basically create a User, Role and UserRole Table. Simple one to many relationship with UserRole reference table.

    image

     

     

    Our User Class will look like this, if you look closely you will see that I am using DataAnnotation to define data properties for the item. You can control a lot of things this way. I have an abstract base class that has some basic things that I want on each table.

     

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
     
    namespace TestService.Models
    {
        public class User :BaseClass
        {
            const string EmailPattern = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
            [MaxLength(50),Required]
            public string FirstName { get; set; }
     
            [MaxLength(50)]
            public string MiddleName { get; set; }
     
            [MaxLength(50), Required]
            public string LastName { get; set; }
     
            [MaxLength(16), Required]
            public string UserName { get; set; }
     
            [MaxLength(16), Required]
            public string Password { get; set; }
     
            [MaxLength(50), Required]
            [RegularExpression(EmailPattern)]
            public string Email { get; set; }
     
            [Required]
            public Guid UserGuid { get; set; }
        }
    }

     

    Here is the Role table looks like, very simple.

     

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
     
    namespace TestService.Models
    {
        public class Role : BaseClass
        {
            [Required]
            public string RoleName { get; set; }
            public string Description { get; set; }
        }
    }

     

     

    Before I get too deep here is the base class. It supply the Id field, Created By, Create Date, Updated By and Updated Date for all the classes

     

     

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
     
    namespace TestService.Models
    {
        public abstract class BaseClass
        {
            public int Id { get; set; }
     
            [MaxLength(50),Required]
            public string CreatedBy { get; set; }
     
            [Required]
            public DateTime CreateDate { get; set; }
     
            [MaxLength(50)]
            public string UpdatedBy { get; set; }   
            
            
            public DateTime? Updated { get; set; }
        }
    }

     

    Fun part is to set the one to many relations for the Migration.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
     
    namespace TestService.Models
    {
        public class UserRole : BaseClass
        {
            public bool IsActive { get; set; }
     
            //1-* relation with User table
            public int UserId { get; set; }
            public virtual User User { get; set; }
     
            //1-* relation with Roles
            public int RoleId { get; set; }
            public virtual Role Role { get; set; } 
     
        }
    }

     

     

    Now we need to tell the Migrations which classed should create table in the DB

    We have to go back to the AuthenticationContext that was derived from DbContext

    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Text;
     
    namespace TestService.Models
    {
        public class AuthenticationContext : DbContext
        {
            public AuthenticationContext()
                : base("name=[ConnectionString name")
            {
                
            }
            public DbSet<User> Users { get; set; }
            public DbSet<Role> Roles { get; set; }
            public DbSet<UserRole> UserRoles { get; set; } 
     
        } 
    }

     

    That is all the setup in the code we need. Now if you run the following command

     

    PM> Update-Database –Verbose –force

     

    This will create your Database tables. Now if you want to get the the database created everytime and add seed data go to the Migrations folder and click on the Configuration.cs  and change the seed

    and change AutomaticMigrationEnabled to True on constructor.

     

     

    using TestService.Models;
     
    namespace TestService.Migrations
    {
        using System;
        using System.Data.Entity;
        using System.Data.Entity.Migrations;
        using System.Linq;
     
        internal sealed class Configuration : DbMigrationsConfiguration<TestService.Models.AuthenticationContext>
        {
            public Configuration()
            {
                AutomaticMigrationsEnabled = true;
            }
     
            protected override void Seed(Models.AuthenticationContext context)
            {
                //This add one default role for seed data
                var defaultRole = new Role
                                      {
                                          RoleName = "Default",
                                          Description = "Default Role",
                                          CreateDate = DateTime.Now,
                                          CreatedBy = "System"
                                      };
     
                context.Roles.Add(defaultRole);
     
            }
        }
    }
     
     
    Now you are all set.
     
    run the command again
     
    PM> Update-Database –Verbose –force
     
     
    Check your Database and you will like what you see.
     
    Hope this helps you.

    Permalink | Comments (0) | Post RSSRSS comment feed

    Creating an Android app with C# and Mono–Part 2

    This is a continuation from part 1.

     

    Since in part one we got the Requirements and the Prototype, we will create a simple technical Document and then follow it to create our activities and the app.

     

    Here is our simple technical document:

    1. Screen 1:

      1. Title – Optional.
      2. TextArea for name of medicines.
        1. This is where the user will put note down with medicine names. Auto Text will send this note content to the contact if missed.
        2. Textarea will be 100 character long.
      3. TimePicker for the alarm.
        1. Must be able to set a specific time.
        2. Hour, min, AM/PM.
      4. TextBox for contact phone.
        1. this will be a phone field. We will have format.
      5. Button for saving value.
        1. Text: Enter.
        2. OnClick : Capture screen values and move on to the next screen.

    2. Screen 2:

      1. Title – Optional
      2. Button for Edit
        1. Cancel alarm schedule.
        2. OnClick: go back to Screen 1.
      3. Button for Save.
        1. Save the time to start the alarm.
        2. Show message via Toast.
      4. Button for Cancel alarm.
        1. Cancel any alarm that was set in the past.
        2. Go back to screen 1.

    3. Screen 3:

      1. Title – Optional.
      2. Button for acknowledge the alarm.
        1. Acknowledge the action and
        2. Keep the alarm as it.
        3. If not pressed within 2 hours, the app will send a Text to the phone number provided.
      3. Button to snooze the alarm.
        1. Sbooze for 5 min.

     

    Now let’s dive down in the code

    Start Visual Studio and create a new project.

    image

     

    I am targeting Min Android 2.1, you can support other ones if you wish. This mean my min supported device will have 2.1 version of Android.

    I called the project SimpleMedicineTracker.

    image

     

    I also changed the package name to com.simple.medicinetracker and set the version to 1. API target level is 7.

    image

     

    Change the activity name to MainPage and Layout name to Main.

    You need to add a label, text area, Text box, button and a label for debug purpose.

    You can use the designers in Visual Studio to create the main screen, I have set the display as following

    image

    image

    Your xml file should look something like the following.

       1: <?xml version="1.0" encoding="utf-8"?>
       2: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       3:     android:orientation="vertical"
       4:     android:layout_width="fill_parent"
       5:     android:layout_height="fill_parent"
       6:     android:minWidth="25px"
       7:     android:minHeight="25px">
       8:     <TextView
       9:         android:text="@string/EnterMedicinesLabel"
      10:         android:layout_width="wrap_content"
      11:         android:layout_height="wrap_content"
      12:         android:id="@+id/EnterMedicinesLabel" />
      13:     <EditText
      14:         android:text="@string/EnterMedicines"
      15:         android:inputType="textMultiLine"
      16:         android:layout_width="fill_parent"
      17:         android:layout_height="wrap_content"
      18:         android:id="@+id/TextEnterMedicineNames" />
      19:     <TimePicker
      20:         android:layout_width="fill_parent"
      21:         android:layout_height="wrap_content"
      22:         android:id="@+id/MedicineTime" />
      23:     <TextView
      24:         android:text="Enter Phone Number"
      25:         android:layout_width="wrap_content"
      26:         android:layout_height="wrap_content"
      27:         android:id="@+id/EnterPhoneLabel" />
      28:     <EditText
      29:         android:inputType="phone"
      30:         android:layout_width="fill_parent"
      31:         android:layout_height="wrap_content"
      32:         android:id="@+id/PhoneNumber"
      33:         android:phoneNumber="true" />
      34:     <Button
      35:         android:text="@string/Enter"
      36:         android:layout_width="fill_parent"
      37:         android:layout_height="wrap_content"
      38:         android:id="@+id/EnterMedicinesButton"
      39:         android:gravity="center"
      40:         android:capitalize="characters" />
      41:     <TextView
      42:         android:text="@string/ShowMedicinesLabel"
      43:         android:layout_width="wrap_content"
      44:         android:layout_height="wrap_content"
      45:         android:id="@+id/ShowMedicinesLabel" />
      46: </LinearLayout>

    Few things to note here

      • all the android:text are coming from strings.xml file under Values folder

     

      • image

     

      • Android declaration will have the button as wide as the screen and specific size.
         
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

     

    So at this point you should have a project with Main Activity in it. This is screen 1.

     

    Let’s keep this going on the next post.


    Categories: Android | C# | Mono
    Permalink | Comments (0) | Post RSSRSS comment feed

    Creating an Android app with C# and Mono–Part 1

    I have been so excited to have some time between my contract and actually find out about Mono framework for C#. I really wanted to jump in to make a simple app so I know what it is all about. I worked with Android in the past but had to use Eclipse with Java. I was little clunky with Java since I work with C# a lot more.

    First thing for me was to figure out how Mono works.

    Mono virtual machine sits on top of Linux kernel and communicate with Dalvik virtual machine and .NET API using some bindings and settings. There are some mappings going on under the hood. For example if you look at the Intent class that is generated it will look like this

    image

     
     

    Here ACTION_BATTERY_CHANGED is similar to ActionBatteryChanged method in C#.

     

    So in java if you were calling android.intent.action.BATTERY_CHANGED in C# you will call Intent.ActionBatteryChanged.

     
    image

     

     

     

     

     

     

     

     

     

     

     

    Android has this concept called Activity, each activity is inherited from Activity class that does certain things on the phone. You usually have a layout related with an activity. Other important piece is the BroadCastReceiver class, that will handle any BroadCast, for example if you are set and alarm, this class can listen for it. I will use it in my example.

     

    Let’s just get going. Our goal is to create a simple Medicine Tracker App.

     

    Here are the requirements :

    1. Have a note field where you just type name of medicines you need to take

    2. Select a time for the alarm to go off

    3. Add a contact number that will get a text message if you miss the medicine on a day (didn’t hit confirm button within 2 hours).

    4. Reminder alert to take medicine

    5. Big button to say I have taken the medicine

    6. Ability to snooze.

    7. Ability to Cancel an alarm.

     

    Here is simple prototype screens:

    imageimageimage

     

     

    From this prototype, I know that I will need 3 Activities and following abilities

    1. Be able to use the datetime control

    2. Pass data between screens.

    3. Ability to set Alarm.

    4. Be able to broadcast and listen for an event.

    5. Be able to send a Text message.

     

    This is the first part of the app. Next time I will walk through the code to show how we can get this app going.


    Categories: Android | C# | Mono
    Permalink | Comments (0) | Post RSSRSS comment feed

    Mono for Android

    So far I was trying to work with Eclipse and using Java to code for my Android apps. But I have to admit that it wasn’t too easy. I just missed the simplicity of Visual Studio and how easy it is to work with it. Maybe it is because I am so use the that IDE  and I am more at home with Visual Studio. I was craving to find out if there was a way to use Visual Studio to code for Android. I found MONO. I did not know much about it in the past. I was reading a post online and seemed to catch the Visual Studio, Mono and Android on the same sentence. Well, now I am writing my first app with Mono and Visual Studio few days later. I will point out the obvious installation process for you.

     

    Here are the things you need.

    1. Need to go to the following site where you can get the installer.

    http://xamarin.com/trial

    this is a trial. You can do all the coding you want and use the emulator to test your code and app while you are using the trial. But you have to pay when you are trying to go to market.

    image

     

    2. There are few pre-requisite for the Mono framework , but don’t worry the installer will install all that for you

    image

     

    image 

     

    3. Once the installation is done, you should be able to use Mono Develop to create your app Or you can use Visual Studio 2010 and C# to create your Android app. You will see new templates under your C#

    image

     

    Well, that is the beginning. Go explore if you want. You should have all the item you need to create Android app.


    Categories: C# | Android | Mono
    Permalink | Comments (0) | Post RSSRSS comment feed

    How to use Migrations to implement Code First for Entity framework and MVC

    Code first is the way to write your code first and let the code take care of the Database and such for you. You shape your objects and you run custom tool to generate the Database for you.

    Now, you should have the basic idea on how database tables , views and relationship works, but when you are using code first techniques you are flowing freely on your code and not have to be very concerned about the database.

    Well, enough said, let’s just dive in…..

    There are 2 paths…

    1. If you are using nHibernate, you can use roundHouse for this (I will have a different post for that).

    2. If you are using Entity Framework then you can use migrations tool supplied by Microsoft.(I am showing this here).

    Here is how I do it.

    I will have 2 objects, Person and address and the relationship will be very simple one to many. Keeping it simple for now.

    image_thumb1

    Simply, an address can have multiple Person.

    I am using MVC 3 with RAZOR.

    image_thumb6

    image_thumb8
     
     
    So if you look at the above classes you can definitely tell that I just over simplified these.
     
    Here is the important part. To use the Migration tool you need to do the following
    1. Create an constructor on your DbContext for EF to point to your Database. You will find the connectionstring name on your web.config fiel.

      for example

      image_thumb4
    2.  

    Open Package Manager Console

    Activate the migration by typing in the following

    Enable-Migrations –DataContext [DbName] (You find the dbName from your connectionstring).

    3.

    You will now have a Migration Folder with a Configuration.cs file that has your migration code.

    Open that file and you will find the following constructor

    public Configuration()         {             AutomaticMigrationsEnabled = false;         }
    Change the AutomaticMigrationsEnabled to true for now.
    4.

    Configuration is where you control what happens and also can seed your data.

    Once you have any changes, you can run the following command to update the database

    Update-Database –Verbose

    This will create the database for the first time.

    From next time if you make any changes that require the whole database changes you have to pass in –Force key

    Update-Database –Verbose –Force

    This should get you started.


    Categories: ASP.NET | C# | Razor | MVC | Code First | Migrations
    Permalink | Comments (0) | Post RSSRSS comment feed

    How to fix Android NFC Demo Reference issue

    I am trying to play around with Android’s NFC(Near Field Communitcation) demo program. But I was having issue just compiling the demo.

    Issue is in the references.

    import com.google.common.base.Charsets;
    import com.google.common.base.Preconditions;
    import com.google.common.primitives.Bytes;

    The SDK comes with the guavalib.jar. We have to add reference to that file.

     

    I am using IntellijIDEA and I will show you how you can do that from that IDE.

    On the IDE go to File –> Project Structure

     

    Select Dependency Tab

     

    Select “Add” –> Select Single Entry Module

    navigate to guavalib.jar ( [Your SDK LOCATION]\android-sdk-windows\tools\lib\guavalib.jar).

    Run the project.

     

     

     

    Your emulator should show the following.

     

     

    Hopefully this helps you. Thanks.


    Categories: Android
    Permalink | Comments (0) | Post RSSRSS comment feed

    Checking your connection string

    As a developer you will run into various types of issues. Some of them are database connection related as you are trying to set up your local environments some are staging or live site.

    Here is a quick way for you to test your connectionstring without having to open the Database.

    1. Open a notepad.

    2. Save as ConnectionTest.udl (make sure you select all type)

    3. Close the docuemnt.

    3. Right click on the file and select properties.

    image

     

    4. Select Provider tab and select your provider.

    image

     

    5. Click connection tab and select connection

    image

     

    Once you are done selecting all the fields , click “Test Connection” Button.

     

    If it doesn’t succeed you have an issue. Fix it and move on.

     

    Good luck.


    Permalink | Comments (0) | Post RSSRSS comment feed

    Happy New Year 2011

    Happy New Year

    Shuvo Noboborsho

    Feliz Navidad

     

    To Everyone.


    Permalink | Comments (0) | Post RSSRSS comment feed