Archive for the ‘ASP.NET’ category

Moving to JSON with Client Side Templating for Views

April 10th, 2010

I was Google ‘Buzzing’ today on this and figured I’d post the same here :

My new frontier in asp.net mvc (and hopefully asp.net 4) will be implementing templates and moving to a more rich client ‘json’ experience vs. partials views.

couple of resources:

http://www.west-wind.com/Weblog/posts/509108.aspx

http://weblogs.asp.net/dwahlin/archive/2009/04/17/minimize-code-by-using-jquery-and-data-templates.aspx

http://weblogs.asp.net/dwahlin/archive/2009/05/03/using-jquery-with-client-side-data-binding-templates.aspx

http://starterkit.jsonfx.net/

http://jbst.net/

The Telerik MVC controls use JSON I think behind the scenes.  They have source code – I am interested in evaluating that as well. (I’m using their controls, I mean evaluate as in see the source and how they implement their controls with JSON – in particular their grid control)

What you might appreciate here is that you could, in theory, use this approach as your view for any backend framework.

Also, I know ExtJS has some rich controls, they are all Json related, I think Phil Haack had an article on using mvc with ext.

Basically, today, if you add for example, an item to a ‘grid’, I go behind the scenes, add it – then redisplay the grid.  In these approached, you’d literally just append a row to the grid instead.  Very interesting.   The value is going to be less traffic, as partial views create more traffic.

I see this as well:
ASP.NET AJAX And Client-Side Templates by Dino Esposito:
http://msdn.microsoft.com/en-au/magazine/cc546561.aspx

The HTML Message Pattern by Dino Esposito:
http://msdn.microsoft.com/en-au/magazine/cc699560.aspx

Of course, this all assumes you opt for a rich experience with jSON/jQuery vs. something like Flex or Silverlight  :)

Error Logging Modules and Handlers for ASP.NET (Webform/MVC)

June 6th, 2009

I just implemented ‘Elmah’ for my ASP.NET MVC project.   I’m using the SQL logging feature (a script comes with the download).  A sample with asp.net webforms comes with the download.

I followed Darrell Mozingo’s blog post here http://darrell.mozingo.net/2009/02/19/elmah-with-aspnet-mvc/ for setting it up with asp.net mvc.

Additionally I used Dan Swatik’s excellent post on integrating Elmah  using the controller/action  ‘HandleError’ attribute to customize the HandleError attribute (see ‘Action Filtering in Mvc Applications’)

ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.

Once ELMAH has been dropped into a running web application and configured appropriately, you get the following facilities without changing a single line of your code:

  • Logging of nearly all unhandled exceptions.
  • A web page to remotely view the entire log of recoded exceptions.
  • A web page to remotely view the full details of any one logged exception.
  • In many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrors mode turned off.
  • An e-mail notification of each error at the time it occurs.
  • An RSS feed of the last 15 errors from the log.

Check out the Elmah Wiki writeup by Simone Busoli for a good overview of the features.

Basically I signal all my errors (using a custom Exception object) to Elmah to help assist in an easy way to write errors to SQL, send emails out, and provide a rss feed of the errors.   (I am still using Log4Net, but might just convert everything to Elmah)

This is a ‘must have’ for an asp.net application.

The ‘Flavors’ of ASP.NET

October 17th, 2008

Back a year ago when I was preparing for my Monorail presentation at CINNUG (see Monorail: part Ipart II – in particular part II), it was greatly impressed on me that Monorail sat on top of ASP.NET, just like WebForms sits on top of ASP.NET. The key being that Webforms does not equal asp.net – WebForms != ASP.NET

ASP.NET has a great design to it, as it is a the underlying ‘pipeline’, handling the HttpRequest/HttpResponse, and all the core stuff like Authentication, Authorization, Session, Caching, etc.

WebForms, Monorail, MVC, Dynamic Data, etc… all sit on top of asp.net.  This is brilliant, as I’m able to incorporate different parts and pieces – ie. when mvc first came out, I was able to progressively upgrade parts of my webform project – in a hybrid manner.  Some pieces I didn’t really want to upgrade, as it worked fine – other parts made it cleaner and easier to test and maintain.  It made refactoring possible.

Scott Hanselman has been pushing this message, and I’m glad to see it.  In this blog post "Plug-In Hybrids: ASP.NET WebForms and ASP.MVC and ASP.NET Dynamic Data Side By Side" he outlines this:

I wanted to write this post because there seems to be a lot of confusion about how ASP.NET WebForms, MVC and Dynamic Data all fit together. Folks may have WebForms applications and want to start looking at ASP.NET MVC but aren’t sure if they need to start from scratch or not. Folks might look at Dynamic Data but mistakenly assume it’s just for scaffolding administrative sites.

You can (and should) feel free to have Hybrid applications. You can have single Web applications that have all of these inside them (if it makes you happy):

  • ASP.NET MVC
  • ASP.NET WebForms
  • ASP.NET Web Services (ASMX)
  • WCF Services
  • ASP.NET Dynamic Data
  • ASP.NET AJAX

I hope this helps and it’s more clear now that it’s just "an ASP.NET application."

You can feel free to mix and match. Not everyone can (or should) rewrite an existing ASP.NET application, so it is nice that everyone can use some new features in the same ASP.NET application as their existing functionality.

I think all of this is very interesting, and the more one grasps what ‘asp.net’ is – the best underlying of how all of these different ‘frameworks’ work.

ASP.NET Dynamic Language Support

October 11th, 2008

From Codeplex:

In this release, we’ve updated the DLR support to the latest versions of the DLR and IronPython. Currently, this release does not include Language Services Support and project templates, though we plan to update this project with the new language services support when it become ready.
Instead, we’ve included two examples that make use of the DLR, a WebForms example and an ASP.NET MVC example.

I’m excited to see this because I like the syntax and capability of Python – this to me is a major milestone.  I look forward to seeing more releases – especially with the ASP.NET mvc samples (to include controller support as well as intellisense/Visual studio integration)

ASP.NET MVC IronPython Sample*
example, 3560K, uploaded Sep 23 – 213 downloads

ASP.NET WebForms IronPython Sample*
example, 956K, uploaded Sep 23 – 168 downloads

ASP.NET Dynamic Language Runtime Support Documentation*
documentation, 34K, uploaded Sep 23 – 189 downloads

(* All three links can be found here: http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=17613 )

(Side note, I’ve been learning more about python, using some tools from ActiveState, ie. Komodo Edit)

Spring.NET and DI with WebForms

March 8th, 2008

Typically with a tool like Castle Windsor you have to setup the container in the Global handlers. For instance:

public class GlobalApplication : HttpApplication, IContainerAccessor
    {
        private static IWindsorContainer container;

        /// <summary>
        /// Provides a globally available access to the <see cref="IWindsorContainer" /> instance.
        /// </summary>
        public static IWindsorContainer WindsorContainer
        {
            get { return container; }
        }

        #region IContainerAccessor

        public IWindsorContainer Container
        {
            get { return container; }
        }

        #endregion

        public void Application_OnStart()
        {
            container = new WindsorContainer(new XmlInterpreter());
        }


Then on any corresponding page, you can retrieve the container, for example, I tend to create a basepage and access the factory, something like this:

public abstract class BasePage : Page
    {
        /// <summary>
        /// Exposes accessor for the <see cref="IDaoFactory" /> used by all pages.
        /// </summary>
        public IDaoFactory DaoFactory
        {
            get { return GlobalApplication.WindsorContainer.Resolve<IDaoFactory>(); }
        }


This pulls from the config to get the IDaoFactory, ie.

<components>
    <component id="primaryDaoFactory"
               type="FSData.DaoFactory, FSData"
               service="FSData.IDaoFactory, FSData">
      <parameters>
        <connectionString>#{connString}</connectionString>
      </parameters>
    </component>
  </components>

Inside the page, I would then use that factory:

IMissionDao dao = DaoFactory.GetMissionDao();

With Spring.NET’s Spring.Web this is all diverted into the configuration with no code required:

First, you setup the correct context – notice I’ve commented out the default context to instead using the webcontext:

<sectionGroup name="spring">
            <!--<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>-->
      <section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web"/>
            <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
        </sectionGroup>

A description of this can be found in the Spring.NET help:

"The instantiation and configuration of the Spring.NET IoC container by the Spring.Web infrastructure is wholly transparent to application developers, who will typically never have to explicitly instatiate and configure an IoC container manually (by for example using the new operator in C#). In order to effect the transparent bootstrapping of the IoC container, the Spring.Web infrastructure requires the insertion of the following configuration snippet into each and every Spring.Web-enabled web application’s root Web.config file"

Next, you add the HttpHandler:

<httpHandlers>
      <add verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/>
        </httpHandlers>


and HttpModule:

<httpModules>
      <add name="SpringModule" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
    </httpModules>

(Both of these are in the web.config)

Once these are setup once, you don’t have to worry about it again.

Now we need to actually use our DaoFactory in our page:

<spring>
        <context>
            <resource uri="config://spring/objects"/>
        </context>
        <objects xmlns="http://www.springframework.net">
            <description>An  example that demonstrates simple IoC features.</description>

      <object type="Default.aspx">
        <property name="DaoFactory" ref="primaryDaoFactory"/>
      </object>

      <object  name="primaryDaoFactory"
               type="FSData.DaoFactory, FSData">
        <constructor-arg name="connectionString" value="server=.SQLEXPRESS;database=dbFW;Integrated Security=true"/>
      </object>

        </objects>
    </spring>


This shows that the Default.aspx page has a dependency on ‘DaoFactory’ that will be injected into the page. I setup a property on the page:

public partial class _Default : System.Web.UI.Page
    {
        private IDaoFactory daoFactory;

        public IDaoFactory DaoFactory
        {
            set { daoFactory = value; }
            get { return daoFactory; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            IAircraftDao acDao = daoFactory.GetAircraftDao();
            List<Aircrafts> ac = acDao.SelectAllAircraft();
        }
    }

* Update:

If you notice, I did have to add the ‘object type=Default.aspx’ above.  Well, let’s say you had a ton of pages and didn’t want to add every page in order to inject this daoFactory.  An alternative is to use a basepage class that inherits from Spring.Web.UI.Page with the following:

        private IDaoFactory daoFactory;
        public IDaoFactory DaoFactory
        {
            get
            {
                //return this.ApplicationContext.ConfigureObject(this, typeof(IDaoFactory).FullName);
                return daoFactory;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            daoFactory = (IDaoFactory)this.ApplicationContext.GetObject("primaryDaoFactory");
            base.OnInit(e);
        }

Since i want the DaoFactory to be a singleton and it’s scope to be the application, I updated the config as well:

<object  name="primaryDaoFactory"
           type="FSData.DaoFactory, FSData" scope="application" singleton="true">
    <constructor-arg name="connectionString" value="server=.\SQLEXPRESS;database=dbFW;Integrated Security=true"/>

This allows me to inject the DaoFactory into every page that uses the base class (granted I’ve probably not want this code in my code behind but that is another topic…)

So there you have it – the daoFactory is injected into the page, and is accessible. I find this to be a better approach than Castle Windsor once you get through the configuration aspects. Both however, are very powerful, so if anything, this shows an alternative way of handling DI in webforms.

Side note: Curious about Spring.NET with MS MVC ? Here is an approach one programmer has used…

also http://fredrik.nsquared2.com/ViewPost.aspx?PostID=465

Spring.NET bi-directional Databinding

March 8th, 2008

I’ve decided Spring.NET has a ton of features, that I would consider it over Windsor now.
One thing that is very cool is that they have a web framework that supports the bi-directional binding.
If you download it, it comes with a full set of examples to see how it works.

ie. here is a sample page:

public partial class DataBinding_RobustEmployeeInfo_Default : Spring.Web.UI.Page
{
    private EmployeeInfo employee = new EmployeeInfo();

    public EmployeeInfo Employee
    {
        get { return employee; }
    }

    /// <summary>
    /// In order to declare data bindings, all you need to do is
    /// override InitializeDataBindings method and add all necessary
    /// data bindings to the BindingManager.
    /// </summary>
    protected override void InitializeDataBindings()
    {
        BindingManager.AddBinding("txtId.Text", "Employee.Id")
            .SetErrorMessage("ID has to be an integer", "id.errors");
        BindingManager.AddBinding("txtFirstName.Text", "Employee.FirstName");
        BindingManager.AddBinding("txtLastName.Text", "Employee.LastName");
        BindingManager.AddBinding("txtDOB.Text", "Employee.DateOfBirth")
            .SetErrorMessage("Invalid date value", "dob.errors");
        BindingManager.AddBinding("txtSalary.Text", "Employee.Salary", new CurrencyFormatter())
            .SetErrorMessage("Salary must be a valid currency value.", "salary.errors");
        BindingManager.AddBinding("rbgGender.Value", "Employee.Gender");
        BindingManager.AddBinding("ddlAddressType.SelectedValue", "Employee.MailingAddress.AddressType");
        BindingManager.AddBinding("txtStreet1.Text", "Employee.MailingAddress.Street1");
        BindingManager.AddBinding("txtStreet2.Text", "Employee.MailingAddress.Street2");
        BindingManager.AddBinding("txtCity.Text", "Employee.MailingAddress.City");
        BindingManager.AddBinding("txtState.Text", "Employee.MailingAddress.State");
        BindingManager.AddBinding("txtPostalCode.Text", "Employee.MailingAddress.PostalCode");
        BindingManager.AddBinding("txtCountry.Text", "Employee.MailingAddress.Country");
    }

    protected void Page_Load(object sender, EventArgs e)
    {}

    protected void btnSave_Click(object sender, EventArgs e)
    {
        // do something with employee such as:
        // employeeDao.Save(Employee);

        Debug.Write(Employee);
    }
}


Then if someone clicks a button it binds those fields to the employee. This is very clean and as you can see it also lets you setup some validation with error messages.

Spring.NET is an entire Application framework, including DI/IoC, AOP, NHibernate support, ADO.NET support, Transactional support, as well as a web framework.

Scott Guthrie : ASP.NET MVC Framework Road-Map Update

February 12th, 2008

The ASP.NET MVC Framework is looking better and better. Check out Scott Guthrie’s latest blog post on some upcoming features added in for the next preview release:

Link to Post

SubSonic

February 2nd, 2008

Rob Conery has had his open source ORM/MVC code called ‘SubSonic’ around for awhile. I must say, the documentation, tools,etc… are excellent. He has released beta version 2.1. The new release has a nice ‘LINQ’ type query language (fluent interface style).

The latest tool is SubStage – which helps configure the ORM aspects of SubSonic. Tooling like this makes the job easier.

Read more here.

ASP.NET MVC Framework and Spring.NET

November 17th, 2007

Great blog post here – this is but one of the parts of the MVC Framework I’m looking forward to!

public IController CreateController(RequestContext context, Type controllerType)
        {
            IResource input = new FileSystemResource(context.HttpContext.Request.MapPath("objects.xml"));
            IObjectFactory factory = new XmlObjectFactory(input);

            return (IController)factory.GetObject(controllerType.Name);
        }

This is quite impressive. This is very straightforward and simple to grasp. Later it shows here

protected void Application_Start(object sender, EventArgs e)
{
   ControllerBuilder.Current.SetDefaultControllerFactory(
                           typeof(MvcApplication.Models.Infrastructure.SpringControllerFactory));
   ...
}

how easy it is to setup your own controller factory.

The attention that MS is paying to allowing Spring.NET/Windsor, etc… to use MS MVC is music to my ears.

What I’m not looking forward to: convincing coworkers who only know Webforms what the value of all this is. Sometimes I feel like I’m the only guy on the island… :)

IIS and ASP.NET

October 30th, 2007

In my Part II post, I spoke about IHttpHandler, IHttpModules, etc…

I found a good article to read up on that explains the entire process in detail.

Link here