Feed

I've been working on an ASP.NET MVC web service that uses EF for persistence. Been using a good old repository class for handling the connection and returning the entities. At some point I decided to change my repository connection to a singleton.

At first, I thought it would make sense to always reuse the same connection all over the place. However, as days passed, the system started raising creepy EF exceptions at times and eventually entered on an inconsistent state where I had to restart IIS in order to return the system back up. This was really weird and scared the hell out of me.

So, as a note to self, please remember that using a singleton pattern for managing large application's DAL may not be a good idea. Please do not ask me why, because I don't have a clue for the reason why these problems happened. Instead, I decided just to revert changes back and just instantiate a new repository instance whenever I needed to access the data entities.

If anyone out there had a different experience or can explain why this can happen, please do not hesitate to leave me a comment as I would appreciate a lot!

Thanks! 

Hello,

I've written a simple JQuery plugin for a progress bar slider. It was inspired on Ben's CSS progress bar, but I needed a more complete one that should be interactive, so I built this one that also leverages JQuery UI's vertical slider.

You can see the plugin demo here. TIP: Inspect the source code to see how it works.

You can download the plugin code here.

Usage: 

<script type="text/javascript">
    $(function () {
        $("your element selector").progressbarslider();
    });
</script>

Please feel free to leave me a feedback, suggestions and/or use it at your own will on your projects :)

Tags: ,

During the last few weeks, I found myself more and more inside a stream that takes me to Ruby on Rails, when it comes to the best platform option for agile web development. My current language and platform or proficiency are C# and ASP.NET MVC, however, while getting introduced to the Rails world, I started seeing things from a different perspective, as well as finding out such great tools and practices that I really would like to have when working with ASP.NET MVC. I'm gonna list some the topics and differences I have been analyzing:

  1. Community support: I found the RoR and the Open Source community to be far more unite and open to teaching and sharing knowledge than the .NET community. Starting with the assumption that there are probably more people working with ASP.NET right now than with RoR, it is surprising to see that it is easier to find RoR help online and learning communities than ASP.NET ones. Also, as far as I know, the ASP.NET MVC code is not open to community contributions right now, so people created the MvcContrib project to acoomodate this code, which is a shame. This is said, despite the fact that it's under the MS-PL license, I found it hard to provide suggestions and feedback to the project, since there is not an official place for it.

  2. Productivity: Frequently I have hard times fighting the framework just to be able to get the job done. Rails has proven to me to be more productive and succint in terms of framework design. For example: named routes and database migrations are VERY helpful and I miss this kind of tool in ASP.NET MVC.

  3. Tight Model integration: I see many people argue that ASP.NET MVC is just VC, since the Model is not tightly coupled to the project. It's the developer's task to choose the right tool for the job, be it LINQ to SQL, Entity Framework or even MongoDB, for example. This flexibility is useful, however, a more integrated scenario could improve productivity a lot, perhaps we could use Entity Framework and SQL Server by default and change the provider later, if needed.

  4. Dynamic typing: This is a more subjective item, since it is wrong to say that static typing is worse that dynamic typing, or vice versa. It is just a matter of choosing the right tool. However, It seems to me that, in general, static typing and compilation doesn't free you from actual real world errors. It is a cost/benefit tradeoff, so, IMHO, the productivity benefit you get with dynamic typing is worth the trade for the static typing checks that you lost.

Wrapping up, I think that RoR is still an emerging technology that has a great future ahead and an incredible supporting community. I'm seeing daily more and more events, talks and conferences around this technology. This, summed up to all the points argumented above, makes me believe that at least it is worth learning. And this is what I'm working on right now.

(I think I'll have to buy a MacBook soon :)

Till next time!

During the last days, I've been watching some cool MIX'10 videos with Scott Hanselman. One of them took my attention specially, which is this one: Beyond File | New Company: From Cheesy Sample to Social Platform.

Scott takes a simple website like nerddinner.com and shows how they tuned it up to enable several different social collaboration, integration and emergent features in it. It is really worth the time watching.

One of the points that really made me curious, was the new OData protocol. It was introduced in.NET 4 with WCF Data Services (formerly ADO.NET Data Services) and aims to unlock data from its silos that exist in major applications today. What's really impressive about it, is that you are able to query it as a web service and perform complex Linq queries against it (even inserting, updating and deleting are supported!). All this, over a common RESTful Http interface. OData is built upon the AtomPub format, so there is nothing being invented here. This presentation at PDC'09 with Pablo Castro provides further techincal details and I definitely recommend watching if you plan to make use of this technology.

I'm planning on implementing this on a Website CMS I'm working on and will write about my findings, barriers found and solutions here in the near future. Stay tuned.

Pure as3 Lightbox clone

by Felipe Lima 29/03/2010 19:04

There are a plenty of lightbox implementations around the web. Whenever you need one, you won't need to make up your own for sure. Just pick one of the available options. However, if you're restricted to flash only, the options get reduced drastically. This is why I came up with my own lightbox implementation with ActionScript. You can see it in action in my company's website.

Flash Lightbox screenshot

It works just like the regular lightbox versions:

var:Lightbox myLb = new Lightbox(
    _sTitle: String,    // lightbox title
    _sLinkToVisit: String = null,     // link to the page that will be visited upon click
    _sImageText: String = "Imagem", // 'Image' text   
    _sOfText: String = "de");        // 'Of' text    

// shows the lighbox with the provided array of images
myLb.show(['image1.jpg', 'image2.jpg', ...]);

myLb.hide(); // closes the lightbox

Please be aware that, in order to use it, you'll have to create a Lightbox movieclip in the Flash IDE with the following elements inside it:

_txtClientName, _txtCurrPos, _btnNext, _btnPrev _btnClose, _bg and _btnAcesse.

These elements are referenced inside the Lightbox class, so you'll need to create elements that match these names in the IDE so that the class will find them.

Additionally, you'll need two static variables containing the stage original width and height. This is needed in order to automatically reposition the lightbox in the middle of the screen on stage resize.

Also, you'll need to download TweenLite for the all the effects to work!

Please let me know if you have any suggestions of bug fixes and/or improvements and I will be happy to answer your requests.

If I summed it all up, I must have spent more than a day struggling to disable request validation with asp.net mvc. It is just ridiculously hard to disable it. 

It turns out that the only way to disable it once and for all is a combination of a setting in the web.config and the ValidateRequestAttribute. 

 

  1. Add the following line to your web.config file right after <system.web>: <httpRuntime requestValidationMode="2.0" />
  2. Add the [ValidateInput(false)] attribute to the controller and the action method you want to expose
  3. Rebuild the project and go drink a beer.

 

Remember it may be unsafe to disable request validation due to potential vulnerability XSS and XSRF attacks.

Note: This is targeted to ASP.NET 4, when the requestValidationMode attribute was introduced. In .NET 3.5, you can skip the first step and only do 2 and 3, but I'm not 100% positive about that.

Happy coding :) 

During the last couple days I've been experimenting with MongoDB and its C# driver, cleverly written by Sam Corder. I'm investigating it as a replacement for a SQL Server database I am using in a web application that is higly community driven. This specific characteristic is the one that makes the NoSQL movement rise atop regular RDBMS systems like SQL Server or MySQL, since it is hard to mantain relational integrity in these scenarios. Other key features of MongoDB are focus on performance and scalability.

K. Scott Allen already wrote a quick intro on using the C# driver, so I used it as a tutorial for my first steps. Here are some thoughts I'd like to share on this topic:

  • I don't like being held by the verbosity of instantiating Document objects every time I want to manipulate the database, so I've written method overloads for the main operations, like Insert, Update, Find and Delete that receive a plain object and only then convert them to Document. This allows us to leverage anonymous objects in C# and makes the code cleaner:
   1:  Mongo mongo = new Mongo();
   2:  mongo.Connect();
   3:  Database db = mongo["testdb"];
   4:  var col = db["users"];
   5:   
   6:  foreach(Document d in col.Find(new { name = "John Doe"}).Documents)
   7:  {
   8:      int johnId = d["_id"];
   9:      int johnName = d["name"];
  10:  }

  The code with this implementation is available on my fork of the driver at github an will hopefully be merged with the master soon.

  • MongoDB allows storage of files in the database, as well, through the GridFS specification. The C# api is already implemented and functional. Follow an example for writing a file to the database:
   1:  void Main()
   2:  {
   3:      Mongo mongo = new Mongo();
   4:      mongo.Connect();
   5:      Database db = mongo["test"];
   6:      var collection = db["testcollection"];
   7:      GridFile file = new GridFile(db);
   8:      
   9:      using(GridFileStream fs = file.Create("mycv")) // define the file name
  10:      {
  11:          ReadWriteStream(File.OpenRead(@"C:\Data\felipelima_en.doc"), fs);
  12:      }
  13:  }
  14:   
  15:  public static void ReadWriteStream(
  16:      Stream readStream, 
  17:      Stream writeStream)
  18:  {
  19:      Byte[] buffer = new Byte[Int16.MaxValue];
  20:      int bytesRead = readStream.Read(buffer, 0, Int16.MaxValue);
  21:      // write the required bytes
  22:      while (bytesRead > 0)
  23:      {
  24:          writeStream.Write(buffer, 0, bytesRead);
  25:          bytesRead = readStream.Read(buffer, 0, Int16.MaxValue);
  26:      }
  27:      readStream.Close();
  28:      writeStream.Close();
  29:  }

Database files work just like plain Documents and will be assigned an Id upon creation. Therefore, they can be later queried just like a regular document.

This was just a quick glance over MongoDB and C# integration. I'm planning on using it on a large project and will post here my findings. More to come.

Tags: , , ,

During the last days I had to implement a custom model binding for a dynamic view model in a project I'm working on. This had me diving deep in the DefaultModelBinder implementation and how binding works in ASP.NET MVC.

Basically the request carries the data you controller action needs to perform its work. It may come from several different locations, like form variables, the query string and route data, in the form of key/value pairs, string-encoded.

Usually, the DefaultModelBinder implementation will be just fine for you and no additional work will be needed. However, there are situations where we need to tweak settings a bit. Model binding works in a associative manner, where you can assign a binder to a specific type, like this:

   1:  ModelBinders.Binders.Add(
   2:      typeof(DateTime),
   3:      new DateTimeModelBinder());

Here, we're saying that all DateTime values should be bound using the DateTimeModelBinder class. DefaultModelBinder will figure that out and call this class when it sees a property of DateTime type. We could say that it works recursivly by looking for the appropriate binder for each property. If no custom binder is found, DefaultModelBinder will take care of it anyway.

The IModelBinder interface defines a single method:

   1:  object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext);

The bindingContext argument contains information about the mode (type, metadata, name, etc). All you have to do is to use the bindingContext.ValueProvider collection to retrieve the correct data for the given model and return it.

Apart from everything, I strongly recommend building the asp.net mvc source code instead of using the installer, so you can debug/step into the mvc classes. You can download the latest MVC 2 RC 2 source code from codeplex. Just do not forget to uninstall MVC from the GAC before building or you'll get ambiguous references.

Ever since I started discovering the MVC world I decided to completely forget Web Forms and actually adopt asp.net MVC as my web programming framework of choice. What's great about it is that you have complete control over the generated html output and absolute separation of business logic, presentation layer and model. It's all about convention over configuration! This is one of the reasons why I decided to learn Ruby on Rails some time ago. It is clear that the ASP.NET MVC .NET Framework 3.5 SP1 release was somewhat influenced by Rails.

One of the great things about ASP.NET MVC is model binding. K. Scott Allen wrote a great blog post with tips on binding. Basically, it collects your request data and fills up your view model with the incoming data.

There is a search pattern that the DefaultModelBinder uses to look for the data in the request. Basically you need to name your form elements with the same name of your model properties. For example:

1. The view model:

   1:  public class NewsModuleViewModel
   2:  {
   3:      [ScaffoldColumn(false)]
   4:      public int ID { get; set; }
   5:   
   6:      [DisplayName("News Date")]
   7:      [DisplayFormat(DataFormatString = "d", ApplyFormatInEditMode = true)]
   8:      [Required(ErrorMessage = "Por favor selecione uma data")]
   9:      public DateTime? Date { get; set; }
  10:   
  11:      [DisplayName("Title")]
  12:      [Required(ErrorMessage = "Por favor digite um título")]
  13:      public string Title { get; set; }
  14:   
  15:      [DisplayName("Resume")]
  16:      public string Resume { get; set; }
  17:   
  18:      [DisplayName("My Text")]
  19:      [UIHint("HtmlText")]
  20:      [Required(ErrorMessage = "Por favor digite um texto para a notícia")]
  21:      public string Text { get; set; }
  22:   
  23:      [DisplayName("Image")]
  24:      [UIHint("DbImage", null, "AspectRatio", 1.0)]
  25:      public string ImagePath { get; set; }
  26:  }

2. The form:

   1:  <form action="/uac/NewsModule/Edit/12" enctype="multipart/form-data" method="post">
   2:   
   3:  <p class="datalist-form">
   4:      <label for="Date">Date</label>
   5:      <input type="text" id="Date" name="Date" value="22/1/2010" />
   6:  </p>
   7:  <p class="datalist-form">
   8:      <label for="Title">Title</label>
   9:      <input class="text-box single-line" id="Title" name="Title" type="text" />
  10:  </p>
  11:  <p class="datalist-form">
  12:      <label for="Resume">Resume</label>
  13:      <input class="text-box single-line" id="Resume" name="Resume" type="text" />
  14:  </p>  

(I've reduced the HTML markup snippet for the sake of simplicity).

Please note that the input field name properties match the view model property names. The DefaultModelBinder will look for these names when doing the data binding!

You can even bind complex objects like lists, for example, but, in this case, you'll have to name your input fields according to the element index on the list! Eg.:

   1:  <input type="text" name="ImageList[0].FileName" size="44" />

It is really straightforward once you get used to it. Just always make sure to create a ViewModel class for you, instead of using the data classes directly (eg.: with LINQ to SQL).

If you need to bind uploaded files as well, it gets a bit more complicated. The best solution I've found so far was not to bind file input control and later retrieve the uploaded file in the controller action from the Request.Files collection.

Tags:

With ASP.NET Dynamic Data you get an entire dynamic data-driven website for free with almost no effort. Of course this has drawbacks, which is that in fact you lose some flexibility and need to do things in the way they can be done.

Recently I needed to improve the default List.aspx template GridView with some different colors and per-line selection for entry details, instead of clicking through an DynamicHyperlink. The first step was to attach an OnRowDataBound event in the grid, in order to set up on onmouseover event in the data rows:

DynamicData\PageTemplates\List.aspx:

<asp:GridView ID="GridView1" runat="server" DataSourceID="GridDataSource" EnablePersistedSelection="true" OnRowDataBound="GridView_RowDataBound">

Next, attach the event and set up the event (DynamicData\PageTemplates\List.aspx.cs):

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onclick"] = "location.href = '" + table.GetActionPath("Details", e.Row.DataItem) + "'";
    }
}

And I'ts all done. You get an entire row click selection for the entry details :)

 

About the Author

myself
My name is Felipe Lima and I am a Software Engineer and co-founder at Quavio, a digital agency at Porto Alegre, Brazil. I am interested in technology, programming with the .Net Framework and sports. Check out my full profile.

Powered by BlogEngine.NET 1.4.5.0