Tagged: asp.net mvc Toggle Comment Threads | Keyboard Shortcuts

  • danielsaidi 8:50 pm on December 1, 2011 Permalink | Reply
    Tags: api, asp.net mvc, , fredrik mörk, , , nathan totten, neil ford, , phil haack   

    Øredev 2011 in the rear-view mirror – Part 2 

    Øredev logo

    This is the second part of ny sum-up of Øredev 2011.

    I will label each session with day:order to satisfy all structure freaks (myself included) that read this.

    1:4 – Phil Haack – Building Mobile applications with ASP.NET MVC4, HTML5 and jQuery Mobile

    This session was quite interesting, since Phil discussed a lot of aspects of mobile browsing and how ASP.NET MVC4 can help you out by introducing .

    Adaptive rendering will be added to the default web application template, which will cause the page to automatically render differently depending on the size of the screen. If you want to view how adaptive rendering works, check out Zurb Foundation. In other words, ASP.NET MVC4 does not introduce adaptive rendering to the world – there are already plenty of free options that you can greb and use directly after reading this post. It’s just a convenience.

    Another new, cool feature is that it is possible to create device-specific variations of the same view, so that Index.cshtml is the default one and Index.iphone.cshtml is the variation that you’ll see when viewing the site in your iPhone. Custom modes can be registered in global.asax, which means that you are entirely free to tailor your own set of custom views.

    Phil also demonstrated using iBBDemo2 for simulating an iPhone when browsing the web. Quite handy if you want to easily be able to try out your custom views.

    All in all, a quite interesting session, although Phil did not seem too enthusiastic about it. Also, the wifi at Øredev was a disaster, and caused several speakers a lot of problems. I really hope they improve this until next year.

    1:5 – Nathan Totten – Facebook Development

    Nathan was yet another speaker who got hit hard by the wifi problems, as he demonstrated how to develop apps for Facebook. I really enjoyed this session, despite the technical problems and the fact that I already have developed Facebook apps. Since I am self-taught in doing so, though, listening to Nathan explaining several parts that I have not gotten around to work with before, was a great take-away.

    Nathan talked about various types of Facebook applications, like iFrame apps, web sites with Facebook Connect, mobile applications, desktop applikations (like Spotify) etc. and how they use OAuth 2.0, REST services, the Facebook Graph API and FQL to integrate with Facebook. He also discussed the JavaScript and C# Facebook SDK:s. His advice was to use the JavaScript SDK whenever possible, and to a server-side SDK whenever the integration should be more invisible.

    Finally, Nathan demonstrated how he works with local and live applications, e.g. if you are developing an application locally (running on localhost) and have it live as well. He then creates two separate FB apps – one that is bound to the live site and one that is bound to localhost. Quite convenient. He also told us that  FBML is dead, so do not use it ever again 🙂

    1:6 – Fredrik Mörk – API – the hidden UI

    The first Swedish speaker I got around to listen to was Fredrik Mörk, who spoke about how we have to give our API:s the same tender loving care that we give our UI:s. Users shun bad GUI:s, while developers shun bad API:s, so we should put some effort into our API designs.

    An API must be discoverable, but how? Always assume that the user knows nothing. So, adapt conventions used by other API:s, so that developers instantly recognize the API instead of having to remember it. even if they have not used it before. This involves making it possible to navigate through the API, adapting naming conventions (delete or remove, store or save etc.), put an equal amount of attention to all parts of the API and…take care of the API like you do with other parts of your systems.

    Fredrik advised us to always expose as primitive as possible, to make the API accessible to as many as possible. Always choose abstract before concrete…and choose your abstraction according to the purpose. For instance, if you expose an IList instead of an IEnumerable, you are communicating that you expect your users to insert stuff into it.

    Fredrik’s view upon an API is that once it is out there, it is no longer yours to change. A GUI can change…an API cannot. But, be careful with inserting stuff into your API just because a user wants it in there. It will ultimately bloat your API. And when you insert stuff, be intentional. Do not let chance determine where a feature ends up and what it is called.

    All in all a good session…and quite liberating with a Swenglish accent instead of the spotless American, Scottish and British ones that dominated the rest of the day.

    1:7 – KEYNOTE: Neil Ford – Abstraction Distractions

    After a long day, we decided to skip this session and go for a short nap before hitting a meat restaurant. I have not spoken with anyone who attended it either, so I am at a loss whether it was good, bad or just meh. It will be interesting to check out the video once it is released.

     
  • danielsaidi 4:49 pm on August 28, 2011 Permalink | Reply
    Tags: asp.net mvc, editorblockfor, editorfor, , html helper, labelfor,   

    EditorBlockFor HTML helper 

    In ASP.NET MVC, Microsoft has done a great job with the various HTML helpers that can be used in a form context, such as LabelFor, EditorFor, ValidationMessageFor etc.

    However, despite these helpers, the HTML markup still tend to become rather tedious and repetitive. For instance, this HTML generates a form that can be used t0 create groups in a web application that I am currently working on:

        @using (Html.BeginForm())
        {
            @Html.ValidationSummary(true)
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Name)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.CollectionName)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.CollectionName)
                @Html.ValidationMessageFor(model => model.CollectionName)
            </div>
    
            <div class="form-buttons">
                <input type="submit" value="@this.GlobalResource(Resources.Language.Create)" />
            </div>
        }
    

    That is quite a lot of code for handling two single properties…and the two editor blocks look rather similar, don’t you think?

    I therefore decided to write a small HTML helper extension method – EditorBlockFor – that can be used to generate an editor block (label, editor and validation message).

    Using this new helper, the resulting form becomes a lot shorter and a lot easier to handle:

        @using (Html.BeginForm())
        {
            @Html.ValidationSummary(true)
            @Html.EditorBlockFor(model => model.Name);
            @Html.EditorBlockFor(model => model.CollectionName);
    
            <div class="form-buttons">
                <input type="submit" value="@this.GlobalResource(Resources.Language.Create)" />
            </div>
        }
    

    As you see, the method is only to be used if you want to follow the conventions that are used for auto-generated ASP.NET MVC form code. But if you do…you can save a lot of keystrokes.

    I am not that familiar with the MvcHtmlString type, which the native methods return, so returning an IHtmlString instead of MvcHtmlString could be a big no no that I do not know about.

    Please let me know if I have ruined the order of the universe.

     
  • danielsaidi 10:56 am on January 14, 2011 Permalink | Reply
    Tags: asp.net mvc, project template,   

    Flush the Visual Studio Template Cache 

    After my last blog post about adding Spark to an ASP.NET MVC 2 project, I decided to create a project template that uses Spark instead of the default Web Forms view engine.

    However, even though I added my new template to the Visual Studio project template folder, it still did not turn up in the project list when I wanted to create a new project.

    What you have to do is to flush the Visual Studio Template Cache, which will make Visual Studio update the list of project templates that are available. It is really easy to do.

    In the command prompt, just execute the following:

       devenv /installvstemplates

    If your command prompt does not find devenv, just navigate to the .exe file, for instance:

       C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE>

    After doing so, just choose to create a new project in Visual Studio and the template should appear in the list.

     
  • danielsaidi 12:58 pm on January 13, 2011 Permalink | Reply
    Tags: asp.net mvc, , razor, , , validationsummary   

    Adding Spark to ASP.NET MVC 2.0 

    After almost a year’s curiosity, with other stuff stealing my time, I have finally some time to have a look at the Spark View Engine. Since the Razor View Engine will be shipped together with ASP.NET MVC 3.0, I decided to give Spark a shot before Razor.

    I will not go into detail about what Spark is, what it does etc. etc. The official web site has some good info and this blog helped me get started. I will just describe how to get Spark up and running and get it to play alongside a default ASP.NET MVC application.

    Get Spark up and running

    The first thing we have to do is to add Spark to our application. Visit the Spark web site, download and unzip the latest release, add it to your solution and add references to Spark.dll and Spark.Web.Mvc.dll.

    Of course, if you use NuGet, just right-click the references folder and choose Add package reference…

    …then search for spark and install sparkmvc.

    This will automatically add most of what you need. Really convenient!

    However, for Spark to work, we need to register it when the application starts. Do this by adding the following to Application_Start in global.asax.cs:

       ViewEngines.Engines.Add(new SparkViewFactory());

    Finally, I recommend adding the following to web.config, although it is optional:

       <configSections>
          <section name="spark" type="Spark.Configuration.SparkSectionHandler, Spark"/>
       </configSections>
       <spark>
          <compilation debug="true" />
          <pages automaticEncoding="true" />
       </spark>

    That’s it – Spark is now added to your app and runs alongside the default Web Forms view engine. Any views not using Spark will still work.

    Converting views to Spark

    In short, all you have to do to convert your views (master pages, user controls and pages) to spark is to:

    • Rename Site.master to Application.spark
    • Rename all user controls to _NAME.spark (the underline makes it possible to add user controls as HTML elements)
    • Rename all pages to NAME.spark
    • In all master page, user control and page files, remove the topmost tag
    • In Application.spark, replace all ContentPlaceHolders tags with use spark tags
    • In all pages, replace all Content tags with contentspark tags

    You also have to replace:

       <%   =>   ${

    For strongly types views,you can type ViewData and the Model like this:

       <viewdata Message="string" model="SparkTemplate.Models.LogOnModel" />

    Note that the name of the ViewData key is defined as is while the model tag is defined in lower-case. You can then access the model like this:

       ViewData.Model
    

    Other than that, everything just seem to work.

    Worth noticing is that you should use ! instead of $ for ValidationSummary and ValidationMessageFor – otherwise, empty strings will render the full Spark expression.

     
  • danielsaidi 9:35 pm on August 15, 2010 Permalink | Reply
    Tags: action, asp.net mvc,   

    Get the name of the current controller and action in ASP.NET MVC 

    I have been Googling my a** off to find how you get the name of the current controller and action. Eventually, I found this short, great page:

    http://w3mentor.com/learn/asp-dot-net-c-sharp/c-asp-net-mvc/get-name-of-current-controller-and-action-in-mvc/

    Not that straightforward…maybe time to create a small helper 🙂

     
    • torm 4:08 pm on January 5, 2011 Permalink | Reply

      Just curious – why would you need to check current controller ?

      • danielsaidi 9:09 am on January 11, 2011 Permalink | Reply

        When I wrote this post, I used the name of the current controller and action to highlight selected menu items.

  • danielsaidi 11:37 am on July 5, 2010 Permalink | Reply
    Tags: asp.net mvc, constraintexception, , , ,   

    ConstraintException thrown when posting empty data for non-nullable properties 

    I am currently working with model validation, using an EF4 entity model, DataAnnotations and partial classes with MetadataType connections.

    In my model, I have an Employee entity for which some of properties are non-nullable. I have also created a partial class and a meta data class for model validation, as is described in this blog post.

    This works great. The Employee class is validated properly, with minimum effort. My entities are validated with standard validation attributes as well as custom ones. Lovely.

    However, the application crashes when I post empty text input elements in my Create/Edit views. A ConstraintException is thrown before my view controller actions are executed, which means that I cannot act on the constraint exception within my action.

    The exception is caused by the fact that empty posted data will cause the corresponding model properties to be set to null, which conflicts with the non-nullable properties in the entity model.

    However, since I have custom model validation classes in which I add Required attributes to mandatory properties, I do not need the non-nullable attributes in my entity model. As such, I set the nullable property to (None)…and the ConstraintException is history!

     
    • Thomas 3:29 pm on September 24, 2010 Permalink | Reply

      Surely this is the incorrect approach, as it means you have no constraints set at the root database level. Which seems wrong.

      There is actually no problem with a constraint exception being thrown, that’s exactly what is supposed to happen.

      • danielsaidi 11:57 am on October 4, 2010 Permalink | Reply

        Hi Thomas! Thank you for your input, you are absolutely right. I have updated the post according to your feedback.

    • temStetLody 10:05 pm on June 21, 2011 Permalink | Reply

      Hello all! I like this forum, i found numberless interesting people on this forum.!!!

      Large Community, good all!

    • Hector 4:47 pm on June 3, 2012 Permalink | Reply

      I know, I know, it has been almost two years since this was posted.
      But just in case someone else is looking here for a solution, I just managed to get around.
      You may use the “DisplayFormat” DataAnnotation in order to override the default behavior (empty posted data causes corresponding model properties set to null), like this:

      [DisplayFormat(ConvertEmptyStringToNull = false)]

      Add the annotation for each non-nulleable attribute of the model. Then, EntityException is gone, and validation still works.

      Best regards.

      • danielsaidi 4:53 pm on June 3, 2012 Permalink | Reply

        Yeah, the post is rather old…and invalid. I should update it, but…well 😉

        Thank you so much for your comment!

  • danielsaidi 12:15 pm on July 1, 2010 Permalink | Reply
    Tags: asp.net mvc, blueprint, bundler, , less, mixins   

    Trying out Blueprint, Bundler and LESS CSS 

    I am currently trying out some nice CSS tools that will simplify working with CSS in ASP.NET MVC.

    First, Blueprint seems like a nice, basic CSS framework that provides a nice foundation. I will give it a try and hope that I can use it in project after project from now on.

    Second, Bundler can be used to bundle CSS and JavaScript in ASP.NET MVC. It looks promising and would be a nice alternative to the web form theme approach.

    Finally, LESS CSS provides you with variables, mixins etc. It will hopefully be the key to avoiding some frustrating CSS issues.

     
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
shift + esc
Cancel