My presentation at Code Camp 5 of CT .net user group

Over the last couple of days, I had been working on my presentation and demo for the ct .net user group code camp5. I presented it today at 9.00am. yay!

The packet has a code,slides and a CSS file that can help the menu with boxes. I hope enough code is there to get you started on some the ideas I had in the presentation.
You can download the whole packet at Slides and Code Link

For any questions/issues, Contact Me

Thanks!

Over the last couple of days, I had been working on my presentation and demo for the ct .net user group code camp5. I presented it today at 9.00am. yay! The packet has a code,slides and a CSS file that can help the menu with boxes. I hope…

Read More

MVC4 SQL migrations step by step

In my earlier post , I showed how to use code first with the server where the app cant create a database.

Now, we are looking to migrate our schema on to the server. It would be nice if it we can get a nice DDL script for this that we can walk through the test envrironments to production. Our DBA friends will definitely allow this.

Let's see how to do this step by step.

Step 1: Open the Package Manager Console (Tools=> Library Package Manager => Package Manager Console)

Step 2: run Update-Package EntityFramework
This updates the EF to 4.3.1 version.

Step 3: Restart vs after the update (important!)

Step 4: run Enable-Migrations -EnableAutomaticMigrations

It generates Migrations folder with Configuration.cs class. It looks like:

namespace MvcApplication4.Migrations
{ using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq;

internal sealed class Configuration : DbMigrationsConfiguration<MvcApplication4.Models.CompStoreDBContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(MvcApplication4.Models.CompStoreDBContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}

}

Step 5: Build the project (important!) as we have added new stuff in the project. If we dont build, the up and down method are empty. It will get clearer after next step

Step 6: run Add-Migration "InitialCreate"
It creates a file with a time stamp such as 201205261630323_InitialCreate.cs. This file looks like below:

namespace MvcApplication4.Migrations
{ using System.Data.Entity.Migrations;

public partial class InitialCreate : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "Computers",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Name = c.String(),
                    Descr = c.String(),
                    Type = c.String(),
                })
            .PrimaryKey(t => t.Id);

    }

    public override void Down()
    {
        DropTable("Computers");
    }
}

}

This file has Up and down methods. The up method is for applying the change and the down is there if we need to roll back. It also helps in managing the destructive db changes such as changing the datatype of decimal column to int.

Step 7: run Update-Database -Verbose
This is going to work only if you have ddl permissions on the db. If not, the next step shows a way to create a DDL script. Note : You cant create another migration untill the previous ones are applied.

Step 8: run Update-Database -Script -SourceMigration:$InitialDatabase -TargetMigration:"InitialOne"It generates a nice looking script for our model that we can take to production.

Hope this helps.. Again, dont forget to build after the Enabling the migration otherwise up and down methods get created empty!..

Update:

I used VS 2010 for this demo. If you use VS 2012, building the project after the enabling the migrations is not required.

In my earlier post , I showed how to use code first with the server where the app cant create a database. Now, we are looking to migrate our schema on to the server. It would be nice if it we can get a nice DDL script for this that we…

Read More

Code first with no create DB permissions on the server

The hosting services or the production database servers do not give create db rights to the app for a lot of reasons. So, when our code first MVC app gets deployed it does not work as it tries to create a database.

There are a lot of posts about code first with existing database. They often get too much into class structure for the models and how looks like on db. The solution of this is too burried or not there at all. So I decided to post about only this issue.

In order to handle this, we need to make it use the existing database and we also need the schema.

Here's how I accomplished it:

I used a computer store as an example. As it sells computers(do we even use that word), I created a model as

public class Computer { [Required] public int Id { get; set; }

 public string Name { get; set; }

 [AllowHtml]
 [DataType(DataType.MultilineText)]
 public string Descr { get; set; }

 public string Type { get; set; }

 public Decimal Price { get; set; }
}

Then I created a controller for the with a new db context as CompStore. The db context is the key here and it looks like:

public class CompStoreDBContext : DbContext {

public CompStoreDBContext(): base("name=DefaultConnection")
{

}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

}

 public DbSet Computers { get; set;  }

}

Notice the constructor. It inherits from the base and the connection string name is passed to it.

If there's something special we need to such as define table names on in DB, we can use OnModelCreating event. Here, I left it alone.

Now, it uses the database passed in the connection string but it still doesnt have the schema. Sometimes we dont even have DDL rights.

No issues MVC4 migrations made this all easy. I will show it in nextpost.

The hosting services or the production database servers do not give create db rights to the app for a lot of reasons. So, when our code first MVC app gets deployed it does not work as it tries to create a database. There are a lot of posts about code…

Read More

jQuery Ajax is simple to implement

The contact page and create blog are using ajax now.

Here's how I did it:
-Created Contact Model with Name, Email and Message -Created a controller with two actions Index for the initial view and send(note HttpPost annotation) as follows:

public ActionResult Index()
{
  Contact cc = new Contact();
  return View(cc);
}

[HttpPost]
public bool Send(Contact c)
{    
  if (ModelState.IsValid)
  {
   WebMail.SmtpServer = "smtp server";
   WebMail.UserName = "account Used To Send the email";
   WebMail.Password = "password";
   WebMail.Send("myAddress", "From-mvcdeveloper.net-UserName-" 
 + c.Name, c.Message, c.Email, "myCCAddress");
 return true;
}
else
throw new Exception("Invalid Email");
//return View(c);
}

-Created Index view page with HTML5 input types

-Here's the fun part. On the view page, I am posting the contents with matching parameters. MVC finds the matching model(Very cool stuff). It is called model binding and,routing as shown here takes care of it from there.

  • jQuery is as follows: $('#btnsend').click(function () {

        if ($("#sendForm").validate().form()) {
    
    
    
        var contact = {
            Name: $('#Name').val(),
            Email: $('#Email').val(),
            Message: $('#Message').val()
        };
    
    
        $.post('/Contact/Send', contact, function () {
    
    
            UserMessage("&lt;h2&gt;The message
    

    is sent. Thank you!");

            }).error(function () {
                UserMessage("<h2>The message sending failed. : (</h2>");
    
    
    
        });
    }
    else {
        return;
    }
    
    }); function UserMessage(msg) { $('#cSet').fadeOut(1000, "", function () { $('#success').delay(1000).fadeIn(1000, "", function () { $('#success').html(msg); }); }); }

One gotcha here is the bug in the version of jQuery validator plugin. Anything below 1.9.0 has a bug. It just doesnt validate the HTML5 input types properly. I spent a lot of time on this. I thought I was doing something wrong.

Try to use my contact page to see the demo.

Hope this helps! :)

The contact page and create blog are using ajax now. Here's how I did it: -Created Contact Model with Name, Email and Message -Created a controller with two actions Index for the initial view and send(note HttpPost annotation) as follows: public ActionResult Index() { Contact cc = new Contact(); return View(…

Read More

Archiving items and a routing lesson

I started rolling up the older blog posts into archive. While doing so, I learned a valuable lesson about routing. We have to put the most specific route first and most general last.

It is very easy to make mistake here. If you do up the entire routing and older links start either looking funky or worse end up breaking the functionality. The reason is asp.net routing maps the request url to the first matching route entry. It doesn’t go beyond that.

My goal was to achieve the following url for the Archived items
http://mvcdeveloper.net/Blogs/Archives/2012/4
While the individuals still point to my details view as it does from the home page
http://mvcdeveloper.net/Blogs/Details/11/It's-all-about-Metro!

I achieved it by have routes defined as follows:

public static void RegisterRoutes(RouteCollection routes)
{ routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

     // put the least greedy route first 
     // in other words put the least general route first
     routes.MapRoute(
      "Archives", // Route name
      "Blogs/Archives/{year}/{month}", // URL with parameters
      new { controller = "BlogItem", action = "Archives", year = 0, month = 0 } // Parameter defaults
     );


     routes.MapRoute(
      "Blog Details", // Route name
      "Blogs/{action}/{id}/{slug}", // URL with parameters
      new { controller = "BlogItem", action = "Details", id = 0, slug = "" } // Parameter defaults
     );



     routes.MapRoute(
      "Default", // Route name
      "{controller}/{action}/{id}", // URL with parameters
      new { controller = "BlogItem", action = "Index", id = UrlParameter.Optional } // Parameter defaults
     );

 }

Notice the order here. The most general route is at the bottom and very specific at the top.

Here's another gotcha!
If you are testing locally and routes don't get picked up, just restart whatever server(ASP.net development server,IIS,etc) you are using and that should take care of it.

Questions? Fire away!

I started rolling up the older blog posts into archive. While doing so, I learned a valuable lesson about routing. We have to put the most specific route first and most general last. It is very easy to make mistake here. If you do up the entire routing and older…

Read More