Wednesday, September 28, 2011

jQuery Mobile Displaying A Dialog

While working on a mobile web app that is using jQuery Mobile I wanted to display a dialog without making an Ajax call to the server to load it which is the "out of the box" way to do it.

Initially I couldn't figure out how to do this but after some reading and thinking it's ridiculously easy.

You have to use a multi-page template which means you have more then one jQuery Mobile "page" container. Example:
<div data-role="page" data-theme="a">
    <div data-role="header" class="header">
        <a href="#menu" data-icon="grid" data-theme="b" data-iconpos="notext" data-transition="pop">&nbsp;</a>
        <h1>My Web App</h1>
        
    </div>

    <div id="map" data-role="content" data-theme="d">
        <p>This is my main content</p>
    </div>
    
    <div data-role="footer">
        <div>
        by <a href="http://cdeutsch.com" rel="external">CDeutsch</a>
        </div>
    </div>
</div>

<!--start menu-->
<div id="menu" data-role="dialog" data-theme="a" data-url="menu">
    <div data-role="header" class="header">
        <h1>Main Menu</h1>
    </div>
    <div data-role="content" data-theme="d">
        <ul data-role="listview" data-theme="c">
            <li><a href="http://blog.cdeutsch.com" rel="external">My Blog</a></li>
            <li><a href="http://twitter.com/cdeutsch" rel="external">Twitter</a></li>
        </ul>
    </div>
</div>

I'm using a button on the left side of the header to trigger showing the dialog. Just set the href to the id of the dialog (in this case menu) and you're all set. No more repeatedly hitting the server for a frequently used resource.

See this jsfiddle for a working example.

Tuesday, September 6, 2011

Entity Framework Code First Error: Could not create constraint

While using Entity Framework Code First you will run into an error similar to the one below if you create objects that have a circular reference.

Introducing FOREIGN KEY constraint 'File_Folder' on table 'Filess' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.


The fix is pretty simple but not very intuitive.

Add the following line to your OnModelCreating override of your DbContext:

modelBuilder.Entity<File>().HasRequired(oo => oo.Folder).WithMany(oo => oo.Files).WillCascadeOnDelete(false);

So it looks something like this:

public class FilesystemDB : DbContext
{
 public DbSet<File> Files { get; set; }
 public DbSet<Folder> Folders { get; set; }
 
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
  modelBuilder.Entity<File>().HasRequired(oo => oo.Folder).WithMany(oo => oo.Files).WillCascadeOnDelete(false);
 }

}

For the best information on Entity Framework Code First read Morteza Manavi's blog.