SlideShare ist ein Scribd-Unternehmen logo
1 von 43
A Real World MVC Application
       with some other groovy stuff thrown in


                                         James Johnson
                                   Developer Advocates
                              Los Angeles C# User Group
                             Tuesday, November 1, 2011
Who I am


Founder and President of the Inland Empire .NET User’s Group

Three time and current Microsoft MVP – CAD

Software developer by day

Serial netrepreneur by night

Partner in Developer Advocates

Easily distracted by acronyms and shiny objects
Developer Advocates


Helping small to medium size software companies through

•   Evangelism and Advocacy
•   Blog Articles
•   Webcasts
•   Presentations
     • User group meetings
     • Code Camps
     • Regional Tech Conferences
Agenda


•   Demo of web site
•   Comparing Web Forms to MVC
•   Entity Framework
•   Administration
•   Bad words
•   Uploading images
•   Ajax and JavaScript
•   Ratings
•   Paging
•   Searching
•   Tweeting
Aphirm.it


•   New thought and spiritual affirmations
•   Always have been a new thinker and hippie
•   Sister site to Windows Phone 7 app
•   Some bad words will be shown for the demo
Aphirm.it


• Rotating aphirm.its
• Simple registration
• Beginner badge
ASP.NET MVC


•   Models
•   Views
•   Controllers
•   ViewModels
•   No Postbacks
•   Very limited use of existing server controls
•   Clean HTML makes CSS and JavaScript easier
•   What all the cool kids are using these days
ASP.NET MVC
  ViewState
ASP.NET MVC
 No ViewState
Entity Framework


• Version 4 released with .NET 4.0
• New version (4.1) allows for model-first, code-first or
  database-first development
• Maps POCO objects to database objects
• A collection of things instead of a dataset of rows
• “things” are the entities
Entity Framework


• Why?
  • Adds a layer of abstraction between database and code
  • DBA can structure database how they want
  • Developer can map to the database how they want
     • Rename entities for more comfortable use
  • Entity Framework handles the mappings
Entity Framework


• Entity Data Model – EDM
   • Deals with the entities and relationships they use
• Entities
   • Instance of EntityType
   • Represent individual instances of the objects
       • Customer, book, shoe, aphirmit
   • Fully typed
• Relationships between look up tables are mapped as
  associations in the EDMX
Entity Framework


• csdl
   • Conceptual Schema Definition Language
   • The conceputal schema for the EDM
       • EntityContainer, EntitySet, EntityType definitions
• ssdl
   • Store Schema Definition Language
       • Schematic representation of the data store
• msl
   • Mapping Specification Language
       • Sits between the csdl and ssld and maps the entity
         properties
Entity Framework
                           Lazy Loading
A design pattern to defer initialization until needed


context.ContextOptions.DeferredLoadingEnabled=true;
List<BookCase> cases = context.BookCase.ToList();
foreach(var bookcase in cases)
{
      var books = bookcase.Books;
}
Entity Framework
                          Eager Loading
Use if you will be needing every related entity


List<BookCase> cases =
context.BookCase.Include(“Books”).ToList();

foreach(var bookcase in cases)
{
      var books = bookcase.Books;
}
Entity Framework
                              Contexts
• The context is the instance of the entity

• Passing an entity around to tiers breaks the context

• Just like the song, make sure the context remains the same
Entity Framework
                            Contexts
public class ModelHelper
{
   private static CourseEntities _db;
   public static CourseEntities CourseEntities
   {
       get
       {
           if(_db == null)
             _db = new CourseEntities();
             return _db;
           }
           set { _db = value; }
       }
   }
private readonly CourseEntities _db = new CourseEntities();
Entity Framework
                                     Contexts
private Student AddStudent(Student student, Course course)
{
    student.Courses.Add(course);
    _db.SaveChanges();
}


Didn’t work because course was in a different context

private Student AddStudent(Student student, Course course)
{
    var newStudent = GetStudent(student.Id);
    var newCourse = GetCourse(course.Id);
    newStudent.Courses.Add(newCourse);
    _db.SaveChanges();
}
Entity Framework
                            LINQ to Entities

• Very similar to LINQ to SQL
• Major difference
        LINQ to SQL – SingleOrDefault()
        LINQ to Entities – FirstOrDefault()
Entity Framework
                   LINQ to Entities

Selecting
Thing thing = _db.Things.Single(x=>x.Id == id);

Deleting
public void DeleteThing(Thing thing)
{
         _db.DeleteObject(thing);
         _db.SaveChanges();
}
Entity Framework
                   LINQ to Entities

Adding (Inserting)
public void AddThing(Thing thing)
{
     _db.AddToThings(thing) //this will be a list
     _db.SaveChanges()      // of AddTo<Entities>
}
Editing (Updating)
public void EditThing(Thing thing)
{
     _db.Things.Attach(new Thing{Id=thing.Id});
     _db.Things.ApplyCurrentValues(thing);
     _db.SaveChanges();
}
Entity Framework
                                    Repositories

•   Repository pattern encapsulates code into a separate class
•   Allows for easy changes
•   Can use it to swith database providers or new technologies
•   Stephen Walther – ASP.NET MVC Framework, Sams
     •   stephenwalther.com
     •   “Download the code” link


• Add the two projects to your solution
• Add references to your project
Entity Framework
                        Repositories
using GenericRepository
public class MyController
{
   private readonly IGenericRepository _repo;
   private readonly CourseEntities _db;

    public MyController()
    {
      _repo = new
        EFGenericRepository.EFGenericRepository(_db);
    }
}
Entity Framework
                         Repositories

// get
 _repo.Get<Thing>(id);

// edit
 _repo.Edit(thing);

// create
 _repo.Create(thing);

// delete
 _repo.Delete(thing);

// list
 var list = _repo.List<Thing>().Where(x =>
             x.Name.Contains(myName));
Aphirm.it


•   New thought and spiritual affirmations
•   Always have been a new thinker and hippie
•   Sister site to Windows Phone 7 app
•   Some bad words will be shown for the demo
Aphirm.it


• Administration
   • Approve aphirm.its
      • Set IsApproved to true
      • Send email to user
      • Check for badges
      • Tweet new aphirm.it
Aphirm.it
                              SetBadges
public void SetBadges(Aphirmit affirmation)
{
         var memberId = affirmation.MemberId;
         _db.ResetPostBadges(memberId); //SP in database

        //get all the aphirmations the user has created
         var aphList =
                  _aphirmitHelper.GetAphirmitsByMember(memberId)
         .Where(x => x.IsApproved.Equals(true)).ToList();
         var aphCount = aphList.Count;
         if (aphCount >= 0) //beginner
                  AddPostBadge(100, memberId);
}
Aphirm.it
                             AddPostBadge
private void   AddPostBadge(int badgeId, int memberId)
{
  // BadgeIdis the internal Id
         varbadge = _db.Badges.Single(x => x.BadgeId.Equals(badgeId));
         varnewBadge = new MemberBadge()
                 {        MemberId = memberId,
                 BadgeId = badge.Id
                 };
        _db.AddToMemberBadges(newBadge);
        _db.SaveChanges();
}
Aphirm.it
                       Uploading Images
• Using Telerik MVC Upload control

@Html.Telerik().Upload().Name("attachments")
.Async(async => async.Save("UploadAvatar", "Profile"))
.ClientEvents(events => events.OnSelect("onSelect"))
.ClientEvents(events => events.OnComplete("onAvatarComplete"))
.ShowFileList(false)
Aphirm.it
                       Uploading Images
[HttpPost]
public ActionResult
UploadAvatar(IEnumerable<HttpPostedFileBase> attachments)
{
   if (attachments == null)
      return Content("no file was uploaded");

    HttpPostedFileBase img = attachments.ElementAt(0);
    var imagePath = _generalHelper.UploadAvatar(img);

    return Json(new { status = imagePath }, "text/plain");
}
Aphirm.it
                      Uploading Images
function onSelect(e) {
    var extArray = new Array(".png", ".gif", ".jpg", ".jpeg");
    var $status = $("div.status");
    $status.hide();
    var file = e.files[0];
    var inArray = $.inArray(file.extension, extArray);
    if (inArray == -1) {
        $("div.status").html("Sorry, only PNG, GIF, or JPG
               images are allowed.").show();
        e.preventDefault();
        return false;
    }
}
Aphirm.it
                      Uploading Images
function onAvatarComplete() {
    var userName = $("#avatarPath").val();
    var url = "/Profile/GetMemberAvatar/" + userName;
    $.getJSON(url, function (json) {
//append something to the string so that the image will be
refreshed.
        json = json + "?" + new Date();
        $("#memberAvatar").attr("src", json);
    });
}
Aphirm.it
                          User Registration

• Be as minimal as possible
• Don’t ask for all possible data at start
• Go easy, can always come back for more
Aphirm.it
                          User Registration

• Use Ajax/JavaScript to help the user
• Check for existing username before submitting




• Check for existing email and format
Aphirm.it
                        Ajax/JavaScript
Validate username

function validateUserName(elem) {
    var $elem = $(elem);
    var userName = $elem.val();
    $elem.attr("valid", true);
    var url = "/Account/IsExistingUser/";
    $.get(url, { name: userName }, function (json) {
        if (json) {
            $("#userNameTaken").fadeIn();
            $elem.attr("valid",
               false).removeClass("valid").addClass("invalid");
        } else {
            $("#userNameTaken").fadeOut();
            $elem.removeClass("invalid").addClass("valid");
        }
    });
}
Aphirm.it
                       Ajax/JavaScript

Validate username


[HttpGet]
public JsonResult IsExistingUser(string name)
{
   return Json(_memberHelper.IsExistingUser(name),
       JsonRequestBehavior.AllowGet);
}
Aphirm.it
                                    Paging

• Use paging when there is more data than can easily be viewed

• Easy to add page to display

• There are several jQuery grids available

    •   I just like mine
Aphirm.it
                               Paging
[HttpGet]
public ActionResult All(int? id)
{
 int pageIndex;
 if (id == null)
    pageIndex = 0;
 else
    pageIndex = (int)id - 1;
 var pageSize = _generalHelper.GetListSize();

 var affirmationList =
_affirmationHelper.GetAphirmitRange(pageIndex, pageSize);
 decimal totalAffirmations = _affirmationHelper.GetApprovedCount();
 var pageNumbers = Math.Ceiling(totalAffirmations / pageSize);
 ViewBag.PageNumbers = pageNumbers;
 ViewBag.CurrentPage = pageIndex;
 ViewBag.ListCount = pageSize;
 ViewBag.Total = totalAffirmations;
 return View("View", affirmationList);
Aphirm.it
                            Bad Words
Need to check text for any bad words the user may have used

var status = false;
var badWords = _repo.List<BadWord>().ToList();

foreach (var bWord in badWords.Where(bWord =>
aphirmit.Text.IndexOf(bWord.Word) > -1))
{
 status = true;
}
Aphirm.it
                           Bad Words

var hasBadWords = _affirmationHelper.HasBadWords(affirmation);
if (hasBadWords)
{
   TempData["HasBadWords"] = true;
   return RedirectToAction("Edit", new {id = affirmation.Id});
}
Aphirm.it
                        Bad Words
if(TempData["HasBadWords"]   != null && (bool)
TempData["HasBadWords"])
{
  <div class="editor-label   error">
    Your Aphirmit has some   unsavory words. If you would
like to have it published,   you will need to clean it up.
  </div>
}
Questions?
Thank you

James Johnson
Email: james.johnson@developeradvocates.com
Blog: www.latringo.me
Twitter: latringo
PayPal: members@iedotnetug.org
Slides: www.slideshare.net/latringo/real-world-mvc

Inland Empire .NET User’s Group
        2nd Tuesday of each month
        www.iedotnetug.org

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryZeeshan Khan
 
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateEffiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateThorben Janssen
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorialKat Roque
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryAlek Davis
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
 
Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Sven Efftinge
 
Barcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationBarcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationSociable
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsMark Rackley
 
Nothing Hard Baked: Designing the Inclusive Web
Nothing Hard Baked: Designing the Inclusive WebNothing Hard Baked: Designing the Inclusive Web
Nothing Hard Baked: Designing the Inclusive Webcolinbdclark
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introductionTomi Juhola
 
JavaScript!
JavaScript!JavaScript!
JavaScript!RTigger
 
Domain Driven Design using Laravel
Domain Driven Design using LaravelDomain Driven Design using Laravel
Domain Driven Design using Laravelwajrcs
 

Was ist angesagt? (20)

Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateEffiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
jQuery
jQueryjQuery
jQuery
 
Jquery
JqueryJquery
Jquery
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]
 
Barcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationBarcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentation
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
 
Jquery
JqueryJquery
Jquery
 
jQuery
jQueryjQuery
jQuery
 
J query module1
J query module1J query module1
J query module1
 
Nothing Hard Baked: Designing the Inclusive Web
Nothing Hard Baked: Designing the Inclusive WebNothing Hard Baked: Designing the Inclusive Web
Nothing Hard Baked: Designing the Inclusive Web
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
JavaScript!
JavaScript!JavaScript!
JavaScript!
 
Learn css3
Learn css3Learn css3
Learn css3
 
Domain Driven Design using Laravel
Domain Driven Design using LaravelDomain Driven Design using Laravel
Domain Driven Design using Laravel
 

Andere mochten auch

Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overviewukdpe
 
Introducing the Entity Framework
Introducing the Entity FrameworkIntroducing the Entity Framework
Introducing the Entity FrameworkLearnNowOnline
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVCKhaled Musaied
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentationivpol
 

Andere mochten auch (7)

Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
Introducing the Entity Framework
Introducing the Entity FrameworkIntroducing the Entity Framework
Introducing the Entity Framework
 
Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
ASP.NET MVC for Begineers
ASP.NET MVC for BegineersASP.NET MVC for Begineers
ASP.NET MVC for Begineers
 
For Beginers - ADO.Net
For Beginers - ADO.NetFor Beginers - ADO.Net
For Beginers - ADO.Net
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 

Ähnlich wie Real World MVC

Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4James Johnson
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4James Johnson
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsRichie Rump
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity FrameworkJames Johnson
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web appsIvano Malavolta
 
Prairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API ResponsesPrairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API Responsesdarrelmiller71
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake School
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disquszeeg
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldChristian Melchior
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO DevsWO Community
 
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...SPTechCon
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenchesIsmail Mayat
 

Ähnlich wie Real World MVC (20)

La sql
La sqlLa sql
La sql
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
 
Local Storage
Local StorageLocal Storage
Local Storage
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity Framework
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 
Prairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API ResponsesPrairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API Responses
 
Hibernate
HibernateHibernate
Hibernate
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
 

Kürzlich hochgeladen

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 

Kürzlich hochgeladen (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 

Real World MVC

  • 1. A Real World MVC Application with some other groovy stuff thrown in James Johnson Developer Advocates Los Angeles C# User Group Tuesday, November 1, 2011
  • 2. Who I am Founder and President of the Inland Empire .NET User’s Group Three time and current Microsoft MVP – CAD Software developer by day Serial netrepreneur by night Partner in Developer Advocates Easily distracted by acronyms and shiny objects
  • 3. Developer Advocates Helping small to medium size software companies through • Evangelism and Advocacy • Blog Articles • Webcasts • Presentations • User group meetings • Code Camps • Regional Tech Conferences
  • 4. Agenda • Demo of web site • Comparing Web Forms to MVC • Entity Framework • Administration • Bad words • Uploading images • Ajax and JavaScript • Ratings • Paging • Searching • Tweeting
  • 5. Aphirm.it • New thought and spiritual affirmations • Always have been a new thinker and hippie • Sister site to Windows Phone 7 app • Some bad words will be shown for the demo
  • 6. Aphirm.it • Rotating aphirm.its • Simple registration • Beginner badge
  • 7. ASP.NET MVC • Models • Views • Controllers • ViewModels • No Postbacks • Very limited use of existing server controls • Clean HTML makes CSS and JavaScript easier • What all the cool kids are using these days
  • 8. ASP.NET MVC ViewState
  • 9. ASP.NET MVC No ViewState
  • 10. Entity Framework • Version 4 released with .NET 4.0 • New version (4.1) allows for model-first, code-first or database-first development • Maps POCO objects to database objects • A collection of things instead of a dataset of rows • “things” are the entities
  • 11. Entity Framework • Why? • Adds a layer of abstraction between database and code • DBA can structure database how they want • Developer can map to the database how they want • Rename entities for more comfortable use • Entity Framework handles the mappings
  • 12. Entity Framework • Entity Data Model – EDM • Deals with the entities and relationships they use • Entities • Instance of EntityType • Represent individual instances of the objects • Customer, book, shoe, aphirmit • Fully typed • Relationships between look up tables are mapped as associations in the EDMX
  • 13. Entity Framework • csdl • Conceptual Schema Definition Language • The conceputal schema for the EDM • EntityContainer, EntitySet, EntityType definitions • ssdl • Store Schema Definition Language • Schematic representation of the data store • msl • Mapping Specification Language • Sits between the csdl and ssld and maps the entity properties
  • 14. Entity Framework Lazy Loading A design pattern to defer initialization until needed context.ContextOptions.DeferredLoadingEnabled=true; List<BookCase> cases = context.BookCase.ToList(); foreach(var bookcase in cases) { var books = bookcase.Books; }
  • 15. Entity Framework Eager Loading Use if you will be needing every related entity List<BookCase> cases = context.BookCase.Include(“Books”).ToList(); foreach(var bookcase in cases) { var books = bookcase.Books; }
  • 16. Entity Framework Contexts • The context is the instance of the entity • Passing an entity around to tiers breaks the context • Just like the song, make sure the context remains the same
  • 17. Entity Framework Contexts public class ModelHelper { private static CourseEntities _db; public static CourseEntities CourseEntities { get { if(_db == null) _db = new CourseEntities(); return _db; } set { _db = value; } } } private readonly CourseEntities _db = new CourseEntities();
  • 18. Entity Framework Contexts private Student AddStudent(Student student, Course course) { student.Courses.Add(course); _db.SaveChanges(); } Didn’t work because course was in a different context private Student AddStudent(Student student, Course course) { var newStudent = GetStudent(student.Id); var newCourse = GetCourse(course.Id); newStudent.Courses.Add(newCourse); _db.SaveChanges(); }
  • 19. Entity Framework LINQ to Entities • Very similar to LINQ to SQL • Major difference LINQ to SQL – SingleOrDefault() LINQ to Entities – FirstOrDefault()
  • 20. Entity Framework LINQ to Entities Selecting Thing thing = _db.Things.Single(x=>x.Id == id); Deleting public void DeleteThing(Thing thing) { _db.DeleteObject(thing); _db.SaveChanges(); }
  • 21. Entity Framework LINQ to Entities Adding (Inserting) public void AddThing(Thing thing) { _db.AddToThings(thing) //this will be a list _db.SaveChanges() // of AddTo<Entities> } Editing (Updating) public void EditThing(Thing thing) { _db.Things.Attach(new Thing{Id=thing.Id}); _db.Things.ApplyCurrentValues(thing); _db.SaveChanges(); }
  • 22. Entity Framework Repositories • Repository pattern encapsulates code into a separate class • Allows for easy changes • Can use it to swith database providers or new technologies • Stephen Walther – ASP.NET MVC Framework, Sams • stephenwalther.com • “Download the code” link • Add the two projects to your solution • Add references to your project
  • 23. Entity Framework Repositories using GenericRepository public class MyController { private readonly IGenericRepository _repo; private readonly CourseEntities _db; public MyController() { _repo = new EFGenericRepository.EFGenericRepository(_db); } }
  • 24. Entity Framework Repositories // get _repo.Get<Thing>(id); // edit _repo.Edit(thing); // create _repo.Create(thing); // delete _repo.Delete(thing); // list var list = _repo.List<Thing>().Where(x => x.Name.Contains(myName));
  • 25. Aphirm.it • New thought and spiritual affirmations • Always have been a new thinker and hippie • Sister site to Windows Phone 7 app • Some bad words will be shown for the demo
  • 26. Aphirm.it • Administration • Approve aphirm.its • Set IsApproved to true • Send email to user • Check for badges • Tweet new aphirm.it
  • 27. Aphirm.it SetBadges public void SetBadges(Aphirmit affirmation) { var memberId = affirmation.MemberId; _db.ResetPostBadges(memberId); //SP in database //get all the aphirmations the user has created var aphList = _aphirmitHelper.GetAphirmitsByMember(memberId) .Where(x => x.IsApproved.Equals(true)).ToList(); var aphCount = aphList.Count; if (aphCount >= 0) //beginner AddPostBadge(100, memberId); }
  • 28. Aphirm.it AddPostBadge private void AddPostBadge(int badgeId, int memberId) { // BadgeIdis the internal Id varbadge = _db.Badges.Single(x => x.BadgeId.Equals(badgeId)); varnewBadge = new MemberBadge() { MemberId = memberId, BadgeId = badge.Id }; _db.AddToMemberBadges(newBadge); _db.SaveChanges(); }
  • 29. Aphirm.it Uploading Images • Using Telerik MVC Upload control @Html.Telerik().Upload().Name("attachments") .Async(async => async.Save("UploadAvatar", "Profile")) .ClientEvents(events => events.OnSelect("onSelect")) .ClientEvents(events => events.OnComplete("onAvatarComplete")) .ShowFileList(false)
  • 30. Aphirm.it Uploading Images [HttpPost] public ActionResult UploadAvatar(IEnumerable<HttpPostedFileBase> attachments) { if (attachments == null) return Content("no file was uploaded"); HttpPostedFileBase img = attachments.ElementAt(0); var imagePath = _generalHelper.UploadAvatar(img); return Json(new { status = imagePath }, "text/plain"); }
  • 31. Aphirm.it Uploading Images function onSelect(e) { var extArray = new Array(".png", ".gif", ".jpg", ".jpeg"); var $status = $("div.status"); $status.hide(); var file = e.files[0]; var inArray = $.inArray(file.extension, extArray); if (inArray == -1) { $("div.status").html("Sorry, only PNG, GIF, or JPG images are allowed.").show(); e.preventDefault(); return false; } }
  • 32. Aphirm.it Uploading Images function onAvatarComplete() { var userName = $("#avatarPath").val(); var url = "/Profile/GetMemberAvatar/" + userName; $.getJSON(url, function (json) { //append something to the string so that the image will be refreshed. json = json + "?" + new Date(); $("#memberAvatar").attr("src", json); }); }
  • 33. Aphirm.it User Registration • Be as minimal as possible • Don’t ask for all possible data at start • Go easy, can always come back for more
  • 34. Aphirm.it User Registration • Use Ajax/JavaScript to help the user • Check for existing username before submitting • Check for existing email and format
  • 35. Aphirm.it Ajax/JavaScript Validate username function validateUserName(elem) { var $elem = $(elem); var userName = $elem.val(); $elem.attr("valid", true); var url = "/Account/IsExistingUser/"; $.get(url, { name: userName }, function (json) { if (json) { $("#userNameTaken").fadeIn(); $elem.attr("valid", false).removeClass("valid").addClass("invalid"); } else { $("#userNameTaken").fadeOut(); $elem.removeClass("invalid").addClass("valid"); } }); }
  • 36. Aphirm.it Ajax/JavaScript Validate username [HttpGet] public JsonResult IsExistingUser(string name) { return Json(_memberHelper.IsExistingUser(name), JsonRequestBehavior.AllowGet); }
  • 37. Aphirm.it Paging • Use paging when there is more data than can easily be viewed • Easy to add page to display • There are several jQuery grids available • I just like mine
  • 38. Aphirm.it Paging [HttpGet] public ActionResult All(int? id) { int pageIndex; if (id == null) pageIndex = 0; else pageIndex = (int)id - 1; var pageSize = _generalHelper.GetListSize(); var affirmationList = _affirmationHelper.GetAphirmitRange(pageIndex, pageSize); decimal totalAffirmations = _affirmationHelper.GetApprovedCount(); var pageNumbers = Math.Ceiling(totalAffirmations / pageSize); ViewBag.PageNumbers = pageNumbers; ViewBag.CurrentPage = pageIndex; ViewBag.ListCount = pageSize; ViewBag.Total = totalAffirmations; return View("View", affirmationList);
  • 39. Aphirm.it Bad Words Need to check text for any bad words the user may have used var status = false; var badWords = _repo.List<BadWord>().ToList(); foreach (var bWord in badWords.Where(bWord => aphirmit.Text.IndexOf(bWord.Word) > -1)) { status = true; }
  • 40. Aphirm.it Bad Words var hasBadWords = _affirmationHelper.HasBadWords(affirmation); if (hasBadWords) { TempData["HasBadWords"] = true; return RedirectToAction("Edit", new {id = affirmation.Id}); }
  • 41. Aphirm.it Bad Words if(TempData["HasBadWords"] != null && (bool) TempData["HasBadWords"]) { <div class="editor-label error"> Your Aphirmit has some unsavory words. If you would like to have it published, you will need to clean it up. </div> }
  • 43. Thank you James Johnson Email: james.johnson@developeradvocates.com Blog: www.latringo.me Twitter: latringo PayPal: members@iedotnetug.org Slides: www.slideshare.net/latringo/real-world-mvc Inland Empire .NET User’s Group 2nd Tuesday of each month www.iedotnetug.org

Hinweis der Redaktion

  1. This model helper creates the context if it is null, otherwise it just returns the context
  2. This is how you setup the controller to use the repository. Create instances to the repository and context, then new up the repository with the context
  3. As you can see, using the repository, greatly streamlines your code in how you interact with the entities.
  4. Show code – AphirmitController – 139, Views/Aphirmits/View.cshtml - 74
  5. Show code, Aphirmits/View.cshtml, line 80
  6. AphirmitsController Line 69