Recent Updates RSS Toggle Comment Threads | Keyboard Shortcuts

  • Steve Lydford 3:28 pm on March 30, 2012 Permalink | Reply
    Tags: javascript   

    Detecting Touch Hardware in IE 10 

    In order to provide the user with a different experience for web pages viewed on touch-enabled devices many JavaScript techniques are available on the web. One of the most popular of these is the Modernizr.touch method, which you can see here: http://modernizr.github.com/Modernizr/touch.html.

    However, as the list on the Modernizr Touch tests page shows, there is no support for Internet Explorer. In order to test for touch in Internet Explorer 10, which will ship with the first batch of Windows 8 tablets later this year, you can call the window.navigator.msMaxTouchPoints method:


    if (window.navigator.msMaxTouchPoints) {
    // touch device
    }
    else {
    // non-touch device
    }

    This method will also return the number of touch-points supported. For example:


    if (window.navigator.msMaxTouchPoints >= 2) {
    // device supports two or more touch points
    }
    else if (window.navigator.msMaxTouchPoints) {
    // device supports one touch points
    }
    else {
    // non-touch device
    }

    In order to get touch detection to work across a large cross-section of browsers you could obviously combine this technique with Modernizr. Something like this:

    var hasTouch = window.navigator.msMaxTouchPoints || Modernizr.touch;

    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)
     
    • Jonah 7:39 pm on April 30, 2012 Permalink

      Steve hi, I’m not actually responding to the current post I need to make a post/request to you. I purchased your book because I’m a complete newbie but I keep getting similar error msgs while in ch9. The errors are: “There was an error parsing the query”. they all seem to be related to querying the dbase. This particular err msg dosen’t seem to accept the “LIKE” keyword. Please help me correct this err msg.

      Thank you,
      Jonah

  • Steve Lydford 11:27 pm on January 17, 2012 Permalink | Reply
    Tags: Book, TechieTogs,   

    TechieTogs on GitHub 

    Anyone who has witnessed my mad, sleep-deprived ramblings on Twitter over the last few months will probably already know that I have written a WebMatrix book: Building ASP.NET Web Pages with Microsoft WebMatrix

    Three chapters of the book contain a tutorial where the reader builds a complete ecommerce app, TechieTogs, from start to finish. TechieTogs is a fully-featured ecommerce app built using ASP.NET WebPages and Microsoft WebMatrix. The site features all of the elements you would usually expect to find on a shopping site, such as a catalog, shopping cart, and checkout. The product catalog is managed using a series of pages that are only accessible to site administrators.

     

    TechieTogs Home PageTechieTogs catalog view

    TechieTogs product viewTechieTogs checkout

     

    The guys at Apress have agreed that I can make the sample app available on GitHub for anyone who wants to have a mess around with it. The repository contains all the files you need to run the app. Simply download the ZIP file, extract it to a suitable place and open in WebMatrix to run.

    https://github.com/stevelydford/TechieTogs

    Have fun with it and let me know if you find it useful.

    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)
     
    • Sid Conner 7:48 am on January 18, 2012 Permalink

      Thanks for sharing this steve!

    • Steve Lydford 7:10 pm on January 24, 2012 Permalink

      You are welcome! I hope you find it useful.

    • Gus 10:36 am on January 26, 2012 Permalink

      Hello Steve I have purchased your book and it is awesome , I have no experience in coding yet I can slowly grasp the code and move things around where I want them to be!! Here is my question , I want the categories also to have an image that relates to them…

      I have added this to the Edit Category Page

      @Html.Label(“Category Image:”, “categoryImage”)
              

      then after reviewing the productImage code… I am completely lost on how to program so that i can upload the image and it relate to the category!!! Can you please help me??

    • Steve Lydford 11:27 am on January 26, 2012 Permalink

      Hi Gus, so glad you are enjoying the book. Rather than try and explain everything here, I’ll put together a blog post to show how to add this feature to TechieTogs. I’ll try and get it up in the next couple of days. Watch this space.

      It’s great that you are digging through the code and making changes. It is, without a doubt, the best way to learn!

    • Gus 4:35 pm on January 27, 2012 Permalink

      Thank you very much Steve!!!

    • Gus 2:05 am on February 8, 2012 Permalink

      Hello steve while i am going back and forth in your book a question arose I was trying to use Html.DropDownList read from the TechieTogs database

      I setup a Options table which has optionId optionTitle

      optionId 1 optionTitle = Red
      optionId 2 optionTitle = Blue
      optionId 3 optionTitle = Green

      how do i make a dropdownlist helper read those options?? and present it to the user in dropdown form in razor??

    • Gus 6:26 am on February 8, 2012 Permalink

      I must be annonying but here goes again :)

      I got an example

      var sql = “SELECT ProductId, ProductName FROM Products”;
      var data = Database.Open(“Northwind”).Query(sql);

      @foreach(var row in data){
      @row.ProductName
      }

      but your productdetails.cshtml has this

      @{

      Layout = “~/Shared/Layouts/_Layout.cshtml”;

      var productID = !UrlData[0].IsEmpty() ? UrlData[0] : “0″;

      var db = Database.Open(“TechieTogsData”);
      var sqlSelect = “SELECT * FROM Products WHERE productID = @0″;

      var product = db.QuerySingle(sqlSelect, productID);

      }

      how in the world do i change it?? so it can get fix..

    • awadesh 3:08 pm on February 9, 2012 Permalink

      thanks

  • Steve Lydford 12:12 pm on June 4, 2011 Permalink | Reply  

    Displaying CSV in an Excel Worksheet from ASP.NET 

    Several times in the past I have needed to provide CSV data to users for use in MS Excel. Previously I have written code to create the physical file on the server and then redirect the user’s browser to that file for download/opening. However this approach has two major drawbacks.

    1. You must have rights to create files on the server.
    2. You can easily end up with loads of temporary files on the server which need clearing.

    This morning I discovered a new way to achieve this without creating any physical csv files on the server by changing the content type and page header. The following code demonstrates this:

     

    @{
        Response.ContentType = "application/vnd.excel";
        Response.AddHeader("Content-Disposition", "attachment; filename=filename.csv");
    
        Response.Write("aaa,bbb,ccc,ddd,eee,fff,ggg");
        Response.Write("hhh,iii,jjj,kkk,lll,mmm,nnn");
        Response.Write("ooo,ppp,qqq,rrr,sss,ttt,uuu");
    } 


    This way no physical file is ever created and the document will be displayed in an Excel worksheet. It is important to note though that the user must have Excel installed for this to work or they will receive an operating system message asking them to choose a program to use to open the file.

    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)
     
  • Steve Lydford 8:20 pm on May 24, 2011 Permalink | Reply
    Tags:   

    Creating a Data Access Layer using Dynamics in WebMatrix 

    Introduction

    So we’ve all seen the WebMatrix demo where we put some inline SQL in the page and pull back some records right? And I’m guessing that most of you just looked at that and thought, “YUK! What happens if the schema changes or I want to access the same set of data in different places? I want all my code in one place.”

    Well, we could spend a couple of hours writing a traditional old-school data access layer, using classes to represent our domain model and methods to query and persist to the database, etc., etc…. but that is the way your Dad did it! WebMatrix is supposed to be all about cool, dynamic, quick scripting groovyness – so lets do it the dynamic way… 

    The Setup

    First off, lets create a SQL Compact database in our WebMatrix project called “Catalog” and give it a table called “Products” (original huh?):

    dalTable

    And we’ll add a few records:

    dalData

    And that’s it, we’re all set.

     

    The “5 Minute Demo” way

    Following the form of the usual demo code we do something like this to display a list of product names:

    @{
        var db = Database.Open("Catalog");
        var sql = "SELECT * FROM Products";
        var qry = db.Query(sql);
    }
    
    <ul>
        @foreach (var product in qry) {
            <li>@product.Name</li>
        }
    </ul>

    So what’s the problem? Well, if this was a one page site then it wouldn’t really be a issue at all. The problem comes when you want to get data in different places across multiple pages – it becomes a maintenance nightmare. Kittens may die. 

    Imagine that you have data access code in 20 different places in your site (which is a realistic number for a smallish site) and you change the database or rename the products table? What happens when you have products queries on several different pages and the spec changes to include an ‘inStock’ column and you need to amend all your product lists to only show items that have this field marked as true? I realise that I am probably “preaching to the converted” here, but you get my point.


    This is how the cool kids are doing it….

    Let’s create a new Razor file in our App_Code folder (create one if it doesn’t already exist) called ProductsData.cshtml and add the following code:

     

    @using System.Dynamic;
    
    @functions {
    
        public static Database Catalog {
            get {
                return Database.Open("Catalog");
            }
        }
    
        public static IEnumerable<dynamic> GetProducts() {
            var sql = "SELECT * FROM Products";
            return Catalog.Query(sql);
        }
    }

     

    Now if we need to change our product list SQL we only need to do it in one place and it makes the Razor view file much easier to read. The GetProducts() method returns IEnumerable<dynamic> which, in the crazy world of dynamics, binds at runtime so our view now looks like:

    <ul>
        @foreach(var product in ProductsData.GetProducts()) {
            <li>@product.Name</li>
        }
    </ul>


    Now that’s better! What else can we do? Well, we could add a method to ProductsData.cshtml to pull out a single product by passing in it’s Product Id:

    public static dynamic GetProductById(int id)
    {
        var sql = "SELECT * FROM Products WHERE Id = @0";
        return Catalog.Query(sql, id).Single();
    }


    Which we can use like this in the content page:

    
    @{
        var productId = 1;
        var product = ProductsData.GetProductById(productId);
    
    }
    
    <div>@product.Name - @product.Price</div>
    

    And again, all our data access code is in one place and our content pages are much cleaner. We have saved many kittens.

    Inserts and Updates

    We can achieve the same benefits with inserts and updates with a bit of Expando magic! The following method in ProductsData.cshtml gives us inserts:

    public static void AddProduct(dynamic product) {
        var sql = "INSERT INTO Products (Name, Description, Price) " +
                    "VALUES (@0, @1, @2)";
        Catalog.Execute(sql, product.Name, product.Description, product.Price);
    }


    The method has one parameter which accepts a dynamic. The awesomeness of dynamics means that we can pass it an ExpandoObject, which will have it’s members resolved at runtime. By using dynamics in this way the compiler simply doesn’t care whether it can resolve product.Name, product.Price, etc. and just leaves it to the runtime to sort out.

    In our view we can get the data we need from the user in a “New Product” form and use the AddProduct method like so:

    @using System.Dynamic;
    @{
        if(IsPost) {
    
            dynamic product = new ExpandoObject();
            product.Name = Request["Name"];
            product.Description = Request["Description"];
            product.Price = Request["Price"];
    
            ProductsData.AddProduct(product);
        }
    }


    Here we just create a new ExpandoObject, add members to it from the submitted form data and pass it to the AddProduct method. Easy peasy.

    Updates are achieved in a very similar manner. This is the SaveProduct method:

    public static void SaveProduct(dynamic product) {
        var sql = "UPDATE Products SET Name=@0, Description=@1, Price=@2 WHERE Id=@3";
        Catalog.Execute(sql, product.Name, product.Description, product.Price, product.Id);
    }


    And this is the code in the view:

    @using System.Dynamic;
    @{
        if(IsPost) {
    
            dynamic item = new ExpandoObject();
            item.Id = Request["Id"];
            item.Name = Request["Name"];
            item.Description = Request["Description"];
            item.Price = Request["Price"];
    
            ProductsData.SaveProduct(item);
    
            Response.Redirect("~/Index.cshtml");
        }
    }

     

    Again we are creating a new ExpandoObject, adding members to it from the submitted form data and passing it to the SaveProduct method in ProductData.cshtml.

     

    Summary

    So that’s how we can use dynamics and Razor @functions to create a simple Data Access Layer for our WebMatrix web sites. All kittens saved, time for bed.

    Please feel free to download the source code and take a look.

    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)
     
  • Steve Lydford 12:42 am on March 19, 2011 Permalink | Reply
    Tags: ,   

    First look at Microsoft Visual Studio LightSwitch 

    Illuminate Me

    (See what I did there?)

    Visual Studio LightSwitch is a new platform designed to make it simpler to create line-of-business applications for the desktop and the cloud.

    It is currently in Beta 2 and can be downloaded from the Microsoft site free of charge.

    LightSwitch contains pre-configured screen templates and other re-usable components to handle many routine business application tasks. You can write code in C# or VB.NET and deploy it to the desktop, web or Windows Azure.

    So that’s enough of the marketing headlines, you can read plenty more of them on the official web site, let’s have a go at making something and see what it is really like….

     

    Getting Started

    Once you have downloaded and installed LightSwitch (you must have Visual Studio SP1 installed first), open Visual Studio and you will notice a new set of templates under LightSwitch.

     

    lsNewProject

     

    Choose your preferred language, give your app a name and click ‘OK’. This will take you to the LightSwitch Home Page (View > Home Page).

    From the Home Page you can choose to connect to an existing external datasource, such as MS SQL Server (no support for Stored Procedures at present), SharePoint or a WCF RIA Service, or create a new table in an internal SQL Express database.

     

    Defining the Data

    Choose the ‘Create new table’ option and add the following fields:

    Name Type Required
    Surname String Y
    Forenames String Y
    Phone Phone Number Y
    Email Email Address Y

    Click the title of the table in the Data Designer or Properties Window and change it to “Contacts” and save the table.

     

    lsDesignerToolbar 
    Next, click the ‘New Table’ button in the Application Designer toolbar and create the following table and name it ‘Companies’:

    Name Type Required
    Name String Y
    Address String Y
    Town String Y
    County String Y
    Postcode String Y
    RenewalDate Date Y

     

    Finally, click the ‘Relationship…’ button in the Designer toolbar and configure the relationship as follows:

     

    lsRelationships

     

    Adding a Screen

    When you click the ‘Screen…’ button in the Designer toolbar, you will be shown this dialog:

    lsAddScreen

     

    Choose a ‘List and Details Screen’ and set the Screen Data to ‘Companies Set’. Ensure that the check boxes to include both sets of additional data are checked and click ‘OK’ to add the screen to the application. This will take you to the Screen Designer, which displays a representation of the layout and commands for the screen:

     

    lsScreenDesigner

    But don’t worry about the Screen Designer right now – we can have a look at all that another day. For now let’s just run the application…

     

    The Result

    The application created for us by LightSwitch allows us to view our company contact data in a master-detail format and has a lot of functionality for very little effort:

     

     lsAppHome

     

    We can add, edit and delete companies and contacts, as well as performing various other tasks such as searching and exporting:

     

    lsAddCompany

     

    And the user interface contains some basic validation, based on the data we defined:

     

    lsValidation 

    Conclusion

    There has been a mixed reception to LightSwitch from the developer community, with many perhaps justifiably worried that it may lead to a new plaque of ‘Office Expert’ Access Forms-style mini-applications of the type that many organisations have tried so hard to eradicate. However, there is no doubting that this is a very impressive piece of technology that allow you to build a functional application very quickly.

    As I mentioned at the beginning of the post, LightSwitch apps run in C# or VB.NET and can use a variety of datasources, so perhaps the instructions to the ‘Office Experts’ should be as Dave Mendlen, Microsoft Senior Director of Developer Tools and Platform Marketing suggests: “if you are going to go rogue, use LightSwitch”. That way at least it can be handed over to a more experienced .NET developer if necessary.

    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)
     
  • Steve Lydford 12:51 pm on February 11, 2011 Permalink | Reply
    Tags: , , ,   

    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)

  • Steve Lydford 4:15 pm on February 7, 2011 Permalink | Reply
    Tags: ELMAH, errors,   

    Error Logging and Google Chrome 9.0 

    Today I created an ASP.NET MVC 3 default Web Application with the intention of testing a couple of ideas I had, without making a mess of any actual ‘live’ projects.

    Once the application had been created the next thing I did was to use (the brilliant) NuGet to install the (also brilliant) ELMAH error logging facility. I then ran the application and had a browse around by typing URLs into the Google Chrome Omnibox (Address Bar to you and me). I was somewhat surprised when I browsed to elmah.axd to see a whole bunch of errors, particularly as I hadn’t even had a chance to break anything yet!

     

    elmah

     

    I then recalled the checkbox I had ticked in the Options dialog in Chrome 9 to ‘Enable Instant for faster searching and browsing’.

     

    chrome_options

     

    It seems that, if I am not fast enough when typing URLs into the address bar, Chrome requests pages from my application that don’t exist and these are being logged by ELMAH. In fact, you can catch a brief glimpse of a 404 as you type, if you get the timing right. A quick test by disabling ‘Instant’ proves this theory.

    This will (should!) not be a problem for deployed sites, but is annoying for locally hosted applications as it makes it hard to ‘see the wood for trees’. If you are desperate to keep ‘Instant’ enabled you can, if you like, filter out the ‘not found’ errors programmatically during development with the following code:

     

    
    void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e)
    {
        if (Request.IsLocal)
        {
            if ((e.Exception.GetType() == typeof(HttpException)) && (((HttpException)e.Exception.GetBaseException()).GetHttpCode() == 404))
                e.Dismiss();
        }
    }
    

    You must bear in mind though that it you use this code it will filter out ALL 404 errors on the local machine during testing, so you should use another strategy to compensate for this.

    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)
     
    • Betty 10:18 am on February 9, 2011 Permalink

      Surely they’re just HEAD requests and not full GET requests, couldn’t you filter it that way?

    • Steve Lydford 10:45 am on February 10, 2011 Permalink

      @ Betty. I was getting back 404 error pages as I typed, so surely full GET requests. As if, using the top line from the ELMAH screenshot abouve, I had actually browsed to http://localhost/e

  • Steve Lydford 11:18 am on February 3, 2011 Permalink | Reply
    Tags: ,   

    What’s Happening to Reflector? 

    So Red Gate have made the announcement that the next version of their excellent Reflector application will be a “paid for” product. This is OK, I totally understand the reasons for this – they have a business to run and have tried the free model, but it’s just not working out for them.

    Neil Davidson, Co-CEO of Red Gate Software said this in an “Open Letter to the .NET Community“:

    “As many of you know, our original intention was to maintain .NET Reflector as a free tool. But, after two-and-a-half years of providing it without charge, we realized that we could not make the free model work. We know that this will cause pain for some people in the .NET community, and we apologize for the change in policy.”

    So my initial thoughts were, “You know what? It’s only $35 and I have been using it free for a couple of years, so I’ll take the hit if I want to upgrade. No hard feelings.”

    And then I read this in the FAQs:

    “A free version will be available for download until the release of Version 7, scheduled for early March. The free version will continue working until May 30, 2011.”

    So the version I have on my machine will cease to function on the 30th May!

    I will spend $35 on the new version, but I won’t be happy doing it, I have little choice. I like Reflector, a lot of people do. It is a very useful tool for looking behind the scenes of an assembly to see whats going on (both for debugging and educational purposes). I recommended it as an essential .NET development tool in my last blog post.

    In my opinion, disabling the free version of the software on 30th May is not a good way to go. Why not make the new version so awesome that I NEED it? Don’t FORCE me to begrudgingly pay you money – make me WANT to pay you for an even better product. Maybe the new release is going to be that good, but let me decide for myself.

    You have only got to look at Twitter or search around a few blogs to see that this has already annoyed a lot of people. All that Red Gate is doing is giving someone the incentive to start, or improve an existing Open Source project (like Monoflector) to give equivalent functionality because they don’t give out a free version anymore. Someone could make a big name for themselves by writing the new Reflector.

    I hope that Red Gate have a strategy re-think. Reflect on it, if you will.

    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)
     
    • Alex 9:32 pm on February 4, 2011 Permalink

      Well, JetBrains has ‘hinted’ at the fact that they may be including a ‘Reflector’ in ReSharper. It’s also not free, but if you already are using ReSharper (like me), it’s one less thing to buy…

  • Steve Lydford 4:02 pm on January 31, 2011 Permalink | Reply
    Tags: ,   

    My Developer Toolbox 

    I guess the title of my blog is a giveaway to the fact that I am primarily an ASP.NET developer; at the moment mostly MVC 3, which is all kinds of awesome, for all kinds of reasons.

    So here is a list of the tools that I can’t do without and that I think would be useful for anyone else out there who is wanting to build web apps on the Microsoft stack. This is the stuff that I would automatically install onto a new machine before I started development work on it.

    Post any tools you love in the comments and I will check them out. I’ll keep the list updated as I find new cool stuff ™, so keep checking back. So here they are, in the order that my mind blurted them out:

     

    Microsoft Visual Studio 2010

    http://www.microsoft.com/visualstudio/en-us

    It’s Visual Studio. If you can afford it get it – it’s the best. If not, have a look at BizSpark, WebsiteSpark or Visual Web Developer 2010 Express (below).


    Microsoft Visual Web Developer 2010 Express

    http://www.microsoft.com/express/Downloads/

    The Microsoft Express products are basically FREE cut-down versions of full applications (in this case Visual Studio 2010). It is not as feature-rich as Visual Studio, but has all the tools necessary to develop ASP.NET applications. Ideal if you are a hobbyist programmer or a student. All projects created in Visual Web Developer Express 2010 are compatible with Visual Studio 2010. And did I mention it’s FREE?


    Notepad++

    http://notepad-plus-plus.org/

    Notepad++ is a free code editor, designed as a replacement for Windows Notepad with code syntax highlighting. Ideal for those times when you just want to edit a bit of source code, some HTML, or some CSS without having to fire up the whole of Visual Studio.


    NuGet

    http://nuget.codeplex.com/

    NuGet is a free open-source package manager for Visual Studio and Visual Web Developer Express that just makes it so ridiculously easy to integrate third-party libraries and tools into your projects it is untrue. Truly brilliant, I can’t recommend this enough.

    Take a look at this brief introduction to NuGet by Phil Haack (note that this is for an older version)

    Firebug and IE8 Developer Tools

    http://getfirebug.com/ or press F12 in IE8

    Firebug and the IE8 Developer Tools both do essentially the same job, although each has it’s own strengths – they both let you inspect the source code, CSS and Scripts of any web page and any element within it. This is a fantastic way to learn how other developers have achieved a certain CSS effect or to inspect your output at runtime to find out what is really going on.


    .NET Reflector

    http://www.red-gate.com/products/dotnet-development/reflector/

    Another tool aimed at helping you to find out what is really going on. Reflector enables you to analyse compiled .NET assemblies in C#, Visual Basic and MSIL and is an invaluable learning and debugging tool.


    Ninject

    http://ninject.org/

    I love Ninject. It is a Dependency Injection container which makes it possible to achieve real separation of concerns between your applications components. Ninject is very easy to use and does a good job of all the usual dependency chain resolution and object lifetime management stuff that you would expect from a DI container. Also very simple to install, thanks to NuGet!


    NUnit

    http://www.nunit.org/

    NUnit is a unit-testing framework for .NET, ported from JUnit – the popular Java based framework. This is a completely standalone product, which is particularly useful if you are using Visual Web Developer 2010 Express which has no built in unit-testing.


    Moq

    http://code.google.com/p/moq/

    If you are doing Test Driven Development then life is going to be even harder without a good mocking library. Moq is one.


    Fiddler

    http://www.fiddler2.com/fiddler2/

    Fiddler allows you to inspect all incoming and outgoing HTTP traffic. I find this particularly useful for debugging ASP.NET applications on your local machine by inspecting the HTTP requests and responses to localhost to look at cookies, header information, etc.


    ELMAH

    http://code.google.com/p/elmah/

    ELMAH stands for Error Logging Modules and Handlers and is an open-source error logging facility for ASP.NET. It will log almost any unhandled exceptions and display them back to you via the web. In many cases you can look back to see the original "Yellow Screen of Death", even if you have customErrors turned off. If you have NuGet installed (which you really should), just type “install-package elmah” into the Package Manager Console” and browse to elmah.axd to see the error logs. It really is that easy.


    FileZilla

    http://filezilla-project.org/

    At some point you gotta ship stuff right? And to the web developer that means uploading it. Well there are loads of free FTP solutions out there, but my favourite at the moment is FileZilla.


    SketchFlow

    http://www.microsoft.com/expression/products/SketchFlow_OverView.aspx

    SketchFlow is a prototyping tool released by Microsoft as part of Expression Studio. It gives you the ability to quickly map out workflow and basic functionality to show end users, without having them concentrate on the UI. For once you may get some useful feedback instead of, "Can we try that in green?".


    XMind

    http://www.xmind.net/

    I was never a fan of mind-mapping, but I sat at in a meeting with an avid user of XMind and was very impressed. I have used it a few times since just to blurt out all my "neat ideas" about an application before I start a more formal design.


    Ultramon

    http://www.realtimesoft.com/ultramon/

    If you are a real hardcore developer you will run at least two monitors. I run three and I don’t think I could go back to anything less than that now. Windows can handle all this extended desktop goodness for you, but Ultramon just does a far, far better job. Go and download the free trial and you’ll see what I mean.

    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)
     
  • Steve Lydford 9:56 pm on January 25, 2011 Permalink | Reply
    Tags: , , , Enitity Framework,   

    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!!!

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