Tagged: MVC RSS

  • Steve Lydford 12:51 pm on February 11, 2011 Permalink | Reply
    Tags: , , MVC,   

    Fun With WebMatrix Helpers in ASP.NET MVC 3 

    It’s nearly the weekend, and it’s been long week, so let’s have a bit of fun…

    So I take it you’ve all had a chance to look at WebMatrix? If you haven’t then you should really make the effort to have a play around with it. I will admit that I was a bit snobby about it when I first read about it, but it is actually a really great way to build small, simple web sites. For the uninitiated, here are a few useful links:

    You can install WebMatrix through the Web Platform Installer. It has loads of really great features, which are much better explained in the links above than I could ever do, but the one that hit me immediately as being really fun was the WebMatrix Helpers feature and I wondered if there was a way to use them in MVC.

    Well, WebMatrix is built on ASP.NET, so it is actually a trivial task to add them to an ASP.NET MVC application.

    Getting Going

    There are loads of helpers available, today we are going to look at the Microsoft Web Helpers. This package gives you the ability to quickly and easily add basic functionality for services such as Twitter, Bing, Gravatar, Facebook, Google Analytics and XBox Live to your site. The awesomeness of NuGet makes it easy to add the Microsoft Web Helpers package to our project by typing:

    Install-Package microsoft-web-helpers

    into the the Package Manager Console.

    Next you will need to add references to WebMatrix.Data and WebMatrix.WebData and set the “Copy Local” property to true for both of them. If you fail to do this step you will receive a compilation error, “The type or namespace name ‘SimpleMembershipProvider’ could not be found” in App_Code\Facebook.cshtml.

    And that’s it! You are now ready to start using the Web Helpers in your Views. So let’s have a look at a few of them…

    Gravatar

    You can add a Gravatar image to your page by simply using the Gravatar.GetHtml() method in your Razor view. For example:

    @Gravatar.GetHtml("stevelydford@gmail.com")


    displays this handsome chap (and no the glasses and bandito moustache are not real!):

    gravatar

    If the email address supplied to the method doesn’t have a corresponding Gravatar account the default Gravatar image will be returned, i.e.

    But you can also set the default image to be the URL of any image you desire. For example, the following code:

    @Gravatar.GetHtml
        ("you@me.com", defaultImage: "http://blog.stevelydford.com/content/noGrav.jpg")
      

    Returns this stunning example of programmer art:

    noGrav


    Optional parameters allow you to set the size of the image, the Gravatar rating and a couple of other attributes.

     

    XBox Live GamerCard

    This is a very simple method which returns an XBox Live GamerCard. It has one parameter which is a string containing the required XBox Live GameTag. For example:

    @GamerCard.GetHtml("stinky53")


    returns this:

    gamercard

    which does nothing if not prove that I don’t get enough time to work on my GamerScore!

     

    Microsoft Bing

    Web Helpers has a Bing class that enables you to easily let users Google your site with Bing.

    First, we need to add the following code to our Razor view:

    @{
        Bing.SiteTitle = ".NET Web Stuff, Mostly";
        Bing.SiteUrl = "http://blog.stevelydford.com";
    }


    We can then use either the Bing.SearchBox() or Bing.AdvancedSearchBox() methods to display a Bing search box in our View.

    @Bing.SearchBox()


    displays a Bing search box which takes the user to Bing.com to displays it’s results:


    bingSearch

    @Bing.AdvancedSearchBox()


    displays a Bing search box which renders a <div> on your page containing the search results:

    bingAdvSearch

     

    Analytics

    The Analytics class of Microsoft.Web.Helpers contains methods which generate scripts that enable a page to be tracked by Google Analytics, Yahoo Marketing Solutions and/or StatCounter.

    They all work in a very similar way and just require you to pass the method the relevant account details. For example:

    @Analytics.GetGoogleHtml({your-analytics-webPropertyId-here})
    @Analytics.GetYahooHtml({your-yahoo-accountId-here})


    This will inject the necessary JavaScript into your view at runtime to enable tracking by the relevant service.

     

    Twitter

    The Microsoft.Web.Helpers namespace contains a Twitter class with two methods – Twitter.Profile() and Twitter.Search().

    Twitter.Profile() injects some JavaScript into your view which displays the feed for the Twitter user specified in the userName parameter:

    @Twitter.Profile("stevelydford")


    twitterProfile


    There are a whole raft of parameters, which allow you to customise the output in various ways, such as setting the width and height, colors, number of tweets returned, etc. A full list of these parameters can be found here.

    Twitter.Search() displays the Twitter search results for the search string specified in the searchQuery parameter:

    @Twitter.Search("London 2012")


    twitterSearch


    Again, there are a bunch of optional parameters to allow you to customize the output to your requirements.

    When you use NuGet to install the microsoft-web-helpers package a TwitterGoodies Razor file is added to your App_Code folder. This class contains helpers which provide additional Twitter functionality. These helpers include TwitterGoodies.TweetButton(), TwitterGoodies.FollowButton(), TwitterGoodies.Faves() and TwitterGoodies.List(), all of which can have their outputs customised using various optional parameters:

    @TwitterGoodies.TweetButton
        (tweetText: "I'm reading Steve Lydford's blog", url:"http://blog.stevelydford.com")


    displays a Tweet Button which opens a new window to allow the user to send a Tweet about your site. The URL passed to the helper is automatically shortened using the Twitter t.co URL shortner:

    tweetButton

    @TwitterGoodies.FollowButton("stevelydford")


    displays a button which redirects them to Twitter:

    followButton

     

    @TwitterGoodies.List("stevelydford", "f1-4")


    displays a form which shows a public Twitter list:

    twitterList

     

    There are a few other methods in the TwitterGoodies Razor file, which you can view in App_Code/TwitterGoodies.cshtml.

     

    Facebook

    As well as the TwitterGoodies.cshtml page, the microsoft-web-helpers package also installs Facebook.cshtml to your App_Code directory. This file contains many useful Facebook helpers. I will look at a couple here, a full list can be found on the facebookhelper codeplex site.

    One of the easiest to use out of the box is the Facebook.LikeButton() helper, which displays a ‘Like’ button that either automatically ‘likes’ the URL supplied, or opens a new Facebook window ’on click’ if the user is not currently signed in:

     

    @Facebook.LikeButton("http://blog.stevelydford.com")

     

    likeButton

     

    Next up is Facebook.ActivityFeed() which displays stories when users ‘like’ content on a site or share content from a site on Facebook.

    @Facebook.ActivityFeed("http://www.bbc.co.uk")


    activityFeed

     

    Most of the rest of the Facebook helpers require initialization. In order to do this you will require a Facebook Application ID. You can get one by browsing to http://www.facebook.com/developers/createapp.php and creating a new Facebook Application:

    facebookCreateApp

     

    When you are setting up your app ensure that you enter the URL of your site, including the correct port number if you are working on localhost:

     

    facebookCreateApp2

     

    You can then add the following code to your Razor view to initialize:

    @{
        Facebook.Initialize("{your-application-id-here}", "{your-application-secret-here}");
    }


    Then it’s just a matter of adding a couple of lines of code to the view to add Facebook Comments to the page:

    @Facebook.GetInitializationScripts()
    @Facebook.Comments()

    fbComments

     

    Or, to show a Facebook LiveStream to allow users of your site to communicate in real time:

    @Facebook.LiveStream()

    fbLiveStream

     

    Conclusion

    This post shows just a small fraction of what can be achieved very quickly and very easily using WebMatrix Web Helpers in an MVC application. The Microsoft Web Helpers package makes it incredibly easy to add a whole load of functionality to you site for very little effort.

    Have fun! Let me know how you get on.

    Go play….

    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)
     
    • William 10:01 am on April 17, 2011 Permalink

      Hello, Guys!
      I have a question that I wonder if anyone can answer!
      I have just started using M-Soft WebMatrix … very nice; however!
      I am not sure if this is a bug, or, I am doing something wrong!
      Quite simply, it is this: …
      I have down-loaded WebMatrix on to my new Pc … no problems.
      I load a ‘new’ WordPress site to my Pc … no problems.
      When I click on ‘Run’, the site appears in a browser, and runs very nicely. And, at the top of the site screen, there are the options to go back to “Dashboard”, and do whatever that I want to with this site … no problems.
      So, quite simply, I can ‘up-an-run’ the site, and get back to Dashboard to do whatever I want, as many times as I want … no problems.
      However, and this is a ‘big’ however: …
      Whilst I have the site ‘up-an-running’; if I close the browser, WITHOUT GOING BACK TO DASHBOARD, (and at this moment in time, I have no other browser up-on-screen), and that just leaves the WebMatrix control window (if you will) up and running; if I then click on ‘Run’ to bring the site back … yes it appears, ”’however”’ there are now; ”’NO”’ options at the top of the browser screen for me to get back into ‘Dashboard’. Quite simply, guys, I cannot get back to Dashboard at all. I have to delete the whole site and start again … wow!
      What happens if you have built; and taken many hours, to build the site of your dreams, only to find that, if you close the browser, deliberately or by mistake, or by having to reboot your machine, you then cannot get back to Dashboard, and your site is completely lost!!! Wow, scary!
      Or, guys, am I doing something wrong?

      Desperately need some help from you, most learned, and qualified guys.

      Best wishes…
      Kind regards…

      William (Hampshire UK)

    • Green coffee bean storage 4:46 am on April 10, 2013 Permalink

      hmoejcmph, Meta gen pure green coffee bean extract with svetol, jCdnPKV, [url=http://greencoffeewarning.ca/]Green coffee bean extract for weight loss[/url], NryFhYK, http://greencoffeewarning.ca/ Green coffee bean extract leave a comment website, PNtjIwi.

    • Xanax online overnight shipping 5:02 am on April 10, 2013 Permalink

      ijhajcmph, Xanax, JrrvkPA, [url=http://www.xanaxblog2013.com/]Buy cheap xanax[/url], EpRYArk, http://www.xanaxblog2013.com/ Xanax, lgIZStK.

    • pure green coffee extract 6:03 am on April 27, 2013 Permalink

      This way, once you have started taking up these elements.
      Clinacallix contains three separate compounds
      that are 25 to 100 times the antioxidant power of vitamins C and E.
      People are buying it online then make sure that
      you will be slim in a natural manner is possible with the help of pure green coffee extract
      the oral medications. Most green pure green coffee extracts are
      standardized to their EGCG content.

  • Steve Lydford 9:56 pm on January 25, 2011 Permalink | Reply
    Tags: , , , Enitity Framework, MVC   

    Entity Framework Mapping Entities To Specific Database Tables 

    I have been playing around with the Entity Framework Code First CTP 4 in ASP.NET MVC 3 for a couple of days and have come across across a need to map an entity to a specific database table.

    Entity Framework Code First automatically pluralizes all entity names when it creates database tables from your domain model. However, I had an entity called Accommodation which I did not want pluralized. It wasn’t really a big deal, just really that Accommodations sounded wrong, but it gnawed at my borderline-OCD perfectionist mind until I was forced to go looking for a solution. And here it is, you simply need to change the name of the DbSet and override the OnModelCreating method like this:

     

    public class AccommodationEntities : DbContext
    {
        public DbSet<Accommodation> Accommodation { get; set; }
        public DbSet<Address> Addresses { get; set; }
    
        protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Accommodation>().MapSingleType().ToTable("Accommodation");
        }
    }
    

     

    While I’m on the subject of the EF Code First CTP 4, here is another thing that caught me out.

    EF Code First creates a table called EdmMetadata which stores a hash of the database schema created by EF. If you change your domain model entities EF Code First will automatically re-create all the tables in the context. I mean re-create as in drop the tables first, then create new. This is fine as long as you haven’t got any data you want to keep hold of, as you get no warning that this is going to happen.

    To stop EF re-creating the tables (and I suppose to bring it out of Code First mode) I dropped the EdmMetadata table and added the following to the Application_Start() method of my global.asax:

    Database.SetInitializer<AccommodationEntities>(null);

    This seems to have done the trick!

    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)
     
    • bioff 3:43 am on February 2, 2012 Permalink

      hi!!!

  • Steve Lydford 10:20 pm on January 22, 2011 Permalink | Reply
    Tags: , , MVC   

    ASP.NET MVC 3 Internationalization 

    I have been doing some work with internationalization (globalization, localization, whatever you want to call it, and yes I do know they all mean something slightly different) in ASP.NET MVC 3 and thought I would share a couple of tips.

    The Past

    Internationalization has always been a bit of a pain in the #youknowwhat with ASP.NET MVC up to now. For me it’s always been like, “it’s so close I can smell it, but it’s not quite there yet”. In the past I have created custom HTML Helpers to let me do something like this in the View:

    <%: Html.LabelFor(model => model.Surname, PersonResources.Surname ) %>

    This custom helper allowed me to describe the the property that I wish to associate the label to and the text I wish to display. It turns out that a lot of people must have requested this as this functionality is now provided out-of-the-box in ASP.NET MVC 3.

    I have also heard of people doing all sorts of workarounds, like creating localized copies of each View (surely a maintenance nightmare!), using JavaScript to look up localized versions of UI text in XML files, etc., etc. ….

    But there is now a better way!

    The problem actually all stems from the DisplayNameAttribute, which you can use to decorate the properties in a model with a user-friendly name which is displayed in the UI by default instead of the actual name of the property. For example, if you had a property called ContactEmail and you decorated it with [DisplayName(”Email Address”)], whenever you referred to the ContactEmail property in the UI (maybe using an HTML Helper) the string “Email Address” would be displayed in place of the property name (ContactEmail).

    The problem is DisplayNameAttribute has only one constructor (barring the empty one):

    DisplayNameAttribute(string displayName)

    Since there was no way to pass in a reference to a resource file we could only pass hard-coded strings to the UI – no good for a UI that is supposed to be multi-language.

    The Solution

    This problem has been resolved with ASP.NET MVC 3 which, because it is built on .NET Framework 4, has access to the DisplayAttribute class.

    This class has several properties, including the Name and ResourceType properties to look at a particular resource file and name/value pair within it. For example:

    [Display(Name="Surname", ResourceType=typeof(PersonResources))]
    public string Surname { get; set; }

    This will use the relevant resource file (in this instance called PersonResources.resx), according to the current language, to display the localized value for Surname wherever it is referred to in the UI.

    @Html.LabelFor(model => model.Surname)

    Summary

    I really hope this makes sense. Internationalization is a job that developers often try to avoid, but these improvements in ASP.NET MVC 3 make, at least this bit of the job, much, much easier.

    Leave any questions you may have in the comments and I will do my best to answer them for you.

    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)
     
    • D Clumsy 1:48 pm on January 26, 2011 Permalink

      I usually subclass the attribute to use translations which are stored in a database rather than a .resx text file.

    • Ricardo 4:42 pm on May 17, 2011 Permalink

      Very nice, thank you for sharing. How do you go about getting translated strings from a database? will this approach still work and how does differ from using resource files? Thanks!

    • Nobels 9:20 pm on November 23, 2011 Permalink

      Hello,

      Your example works indeed. But when you forget 1 word in your resourece you get an error. :-(

      Is there a way to catch that problem, and returns the key as value?

      i would like to here an anwser to my question.

      Thanks

  • Steve Lydford 10:37 am on August 10, 2010 Permalink | Reply
    Tags: , , MVC   

    ASP.Net MVC 3 Preview 1 

    Wow, these guys move fast!

    ASP.NET MVC 3 Preview 1 has been released on CodePlex. This release includes global Action filters, support for the new .Net 4 Data Annotation and Validation attributes and the Razor View Engine which everyone has been blogging about in the last few weeks.

    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)
     
c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
l
go to login
h
show/hide help
esc
cancel