If you wonder how to make a GitHub (and other websites) like routes to access to hierarchical paths or files, here’s the way to do it in ASP.NET MVC. GitHub is a GIT hosting service, and allows you to browse the repositories. When doing so, it uses a path as a routing parameter, as seen in this URL: https://github.com/erikzaadi/GithubSharp/blob/master/Core/Models/Commit.cs. This includes slashes and so to represent the directories, and is a parameter that depends on the file location inside the repository. A route like this can be done in ASP.NET using the called catch-all parameter.
The catch-all parameter allows you to use a wildcard on a route, so it takes everything after a given route as a single parameter. You can find the explanation of this feature in the ASP.NET Routing MASDN help page.
All you need to do to make a route like the one in the example to work is add this code to your Global.asax file, in the RegisterRoutes method:
routes.MapRoute(
"Blob",
"{*path}",
new { controller = "Blob", action = "GetContents" }
);
This will pass the controller Blob a parameter called path that will contain the parameter you want (in the example that would be master/Core/Models/Commit.cs. All you have to do now is use this parameter as you wish so you can access the desired file and show it’s contents on a web page.
December 14th, 2010 | tags:
c#,
MVC |
No Comments
If you’ve ever wondered how to get the number of days for a given month in .NET, the solution is pretty easy:
System.DateTime.DaysInMonth(int year, int month)
Hope it helps!
December 2nd, 2010 | tags:
.net,
c# |
No Comments
If you’ve ever used the Ajax.BeginForm code to render a form in ASP MVC using Ajax (via jQuery, for example), you may have wondered there’s an object you can pass to the call called AjaxOptions. This object allows you to pass the BeginForm call some interesting options to further enhance the form when it’s rendered. One of those options is specially useful if you want some javascript to be executed just after the form has been rendered. You can always use the $(document).ready in jQuery, but this code will not be called if, for example, the form is rendered after a postback and you have some validation errors (a missing required field, for example). Fortunately, you can use the AjaxOptions object to tell the form to execute a method right after the form has been loaded (for the first time or after a postback).
If you wonder how many parameters you can use in AjaxOptions you can visit the MSDN Help Page. The option we’re interested in in this post is OnSuccess. Take a look at this code:
<% using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { UpdateTargetId = "someId", InsertionMode = InsertionMode.Replace, OnSuccess = "someFunction" }))
{%>
<%: Html.TextBoxFor(model => model.SomeProperty) %>
<%}%>
This is a typical partial view that is intended to be used using an Ajax call. In it we simply display a TextBox to modify the property SomeProperty of our model. What we’re telling this form is that it should post to the Action action on the Controller controller. Everything is working as usual until here. However, we also pass the BeginForm an AjaxOptions object with some properties. The UpdateTargetId tells the form which DOM element on the page the form should be placed. The InserionMode tells the form what policy should follow when placing the form on the DOM, in this case we tell it that it should replace the contents of the element. And finally, OnSuccess tells the form what javascript code should execute once the form has been placed on the element, in this case we call a method called someFunction.
Imagine this is the HTML page in which we want to place this partial view:
<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<html>
<body>
<div id="someId">
</div>
</body>
</html>
We can then add this javascript script in the page:
$(document).ready( function {
$.ajax({
url: <%: Url.Action("Edit", "Controller" %>,
success: function (data) {
$('#someId').html(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
jAlert('Some error message', 'Error');
}
});
});
What we’re doing here is loading via Ajax the Edit view using jQuery when the page loads. After the page has been loaded, then the Ajax.BeginForm call will look for a javascript method called someFunction and execute it. In there you can put whatever logic you need to be executed right after the form has been placed (for example, binding some elements to events or whatever). In this case, we can write a simple sample function like this one and add it on the partial view:
function someFunction() {
alert('Form loaded');
}
Now each time the form is loaded via Ajax, or in a post, the alert will popup.
November 24th, 2010 | tags:
ajax,
c#,
javascript,
jquery,
MVC |
No Comments
Recently I started working in a project using MVC 2. I found out a very useful feature to retrieve JSON data from the server using an Action in a Controller.
This feature is in the base Controller class, which we inherit when we create a new controller. If you take a look into the different methods this class has you’ll find those ones:
//
// Summary:
// Creates a System.Web.Mvc.JsonResult object that serializes the specified
// object to JavaScript Object Notation (JSON).
//
// Parameters:
// data:
// The JavaScript object graph to serialize.
//
// Returns:
// The JSON result object that serializes the specified object to JSON format.
// The result object that is prepared by this method is written to the response
// by the MVC framework when the object is executed.
protected internal JsonResult Json(object data);
Along with this method, there are some overloads that allow more parameters, you can see them all in here: Controller.Json Method. In this example I’ll use the first one, which is the simplest.
Continue reading “Creating and consuming JSON data in MVC 2” »
November 16th, 2010 | tags:
c#,
jquery,
json,
MVC |
No Comments
Today at work we found a bug. My workmate, not used to C#, usually uses the & operator to compare boolean values. However, in C#, the & operator does not use lazy evaluation.
One curious thing about C# is that it can use two different operators to calculate an and expression: the & operator and the && operator. The difference between both is that the first one (&) can be used both with integer types and boolean types. When used with integer types it will perform a bitwise comparison between the two, and when used with boolean values it will use the logical and operation between the two boolean values, evaluating all the parts of the expression. This means that using a code like this one:
if (someObject != null & someObject.SomeProperty == someValue)
will throw a runtime error if someObject is null, because it will try to obtain the SomeProperty value.
However, the && operator is only available to boolean expressions, and it uses lazy evaluation, this is, if the first condition evaluated is false, it will calculate false without evaluating the rest of the expression, because an and is only true if all the expressions are true.
Conclusion, be sure to always use && when evaluating boolean values if you want to avoid run time surprises
.
October 12th, 2009 | tags:
c#,
programming tips |
1 Comment
The Queue<T> class (and Stack<T> too) of the .NET Framework from Microsoft is implemented using an array. While this is a perfectly good approach, I think that a Linked List based implementation could be desired in some situations (specifically when the size of the queue is not fixed).
Since the implementation alone would be rather simple for a post, I’ll show you how to implement Unit Testing with the class using Nunit. Although this is a rather simple class to test I think it will show the basic concepts behind unit testing.
Continue reading “Creating and testing a Linked List based Queue in C# using Nunit” »
July 9th, 2009 | tags:
c#,
nunit,
unit testing |
No Comments
One of the interesting new things on the .NET platform is the recent addition of Python and Ruby to the CLR. Both versions for .NET are called IronPython and IronRuby respectively, and they provide some new and good things to the platform.
Python and Ruby lovers will see now that they can use all the library and features of the .NET platform programming in their favorite scripting language. Since both of them are object oriented, you can now write fully fledged apps using either of them.
However, there’s another interesting application for IronPython and IronRuby: adding scripting support for your existing .NET applications. This can be a very useful and powerful way to extend your applications and give the user freedom to program their own mini programs, scripts or whatever in your applications. It could be good for defining rules, assigning and calculating values, etc.
I’ll provide a simple class you can use to add scripting to your application. I’ll use IronPython in this example.
First of all, you have to download IronPython and install it, and add the references to the assemblies on your project references.
The usual way to proceed in those cases is to provide the user of some local variables you give them access to, execute the script, and then recover the values of those or new variables. To do so, You can use a class similar to this one:
using System;
using System.Collections.Generic;
using System.Text;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting;
namespace Scripting
{
internal class PythonEngine
{
ScriptEngine m_engine;
ExceptionOperations m_exceptionOperations;
SortedDictionary<string, object> m_inputVariables;
string m_script;
internal PythonEngine()
{
m_engine = Python.CreateEngine();
m_exceptionOperations = m_engine.GetService<ExceptionOperations>();
}
internal SortedDictionary<string, object> ScriptVariables
{
set { m_inputVariables = value; }
}
internal string Script
{
set { m_script = value; }
}
internal ExceptionOperations ExceptionOperations
{
get { return m_exceptionOperations; }
}
internal SortedDictionary<string, object> Execute()
{
//Create structures
SourceCodeKind sc = SourceCodeKind.Statements;
ScriptSource source = m_engine.CreateScriptSourceFromString(m_script, sc);
ScriptScope scope = m_engine.CreateScope();
//Fill input variables
foreach (KeyValuePair<string, object> variable in m_inputVariables)
{
scope.SetVariable(variable.Key, variable.Value);
}
SortedDictionary<string, object> outputVariables = new SortedDictionary<string, object>();
//Execute the script
try
{
source.Execute(scope);
//Recover variables
foreach (string variable in scope.GetVariableNames())
{
outputVariables.Add(variable, scope.GetVariable(variable));
}
}
catch (Exception e)
{
string error = m_exceptionOperations.FormatException(e);
//Do something with the pretty printed error
throw;
}
return outputVariables;
}
}
}
Usage of this class is pretty simple. You have to provide the object the script you want to execute and the input variables the script will have available as local variables. Once this is done, you have to call the Execute method, and this method will either return the output variables of the execution of the resulting script, or throw an exception.
By default in C# 3.0 ComboBox controls don’t provide support for showing drop-down list items if they exceed the width of their parent ComboBox, like this one:

Cropped ComboBox
This is annoying because users cannot read properly the information. To solve that problem, all we have to do is derive the ComboBox class and override the DropDown event as follows:
public class ComboBoxEx : ComboBox
{
public ComboBoxEx()
: base()
{
DropDown += new EventHandler(event_DropDown);
}
void event_DropDown(object sender, EventArgs e)
{
try
{
ComboBox comboBox = (ComboBox)sender; // Catch the combo firing this event
int width = comboBox.Width; // Current width for ComboBox
Graphics g = comboBox.CreateGraphics(); // Get graphics for ComboBox
Font font = comboBox.Font; // Doesn't change original font
//checks if a scrollbar will be displayed.
int vertScrollBarWidth;
if (comboBox.Items.Count > comboBox.MaxDropDownItems)
}
//If yes, then get its width to adjust the size of the drop down list.
vertScrollBarWidth = SystemInformation.VerticalScrollBarWidth;
}
else
{
//Otherwise set to 0
vertScrollBarWidth = 0;
}
//Loop through list items and check size of each items.
//set the width of the drop down list to the width of the largest item.
int newWidth;
foreach (string s in comboBox.Items)
{
if (s != null)
{
newWidth = (int)g.MeasureString(s.Trim(), font).Width + vertScrollBarWidth;
if (width < newWidth)
width = newWidth;
}
}
// Finally, adjust the new width
comboBox.DropDownWidth = width;
}
catch { }
}
}
The following picture shows the results of using the above control instead of the default one:

Non Cropped ComboBox
November 18th, 2008 | tags:
.net,
c#,
programming tips |
1 Comment
This morning I was working on a project at work. It’s a Web Application using the ASP .NET 2.0 framework and C# as a code behind language. My friend Ioannis came over to see what was I doing and when he saw I was appending some strings together he asked me this question: “are you using a StringBuilder to use those strings?“. And I replied with this answer: “no, I am not“. This kind of stupid dialog came over because last week we were discussing about using StringBuilders instead of the default String class operators to append strings each other in Java. It seemed using the StringBuilder class resulted in an overall performance gain. It was then when I asked: “don’t tell me this happens with C#, too?“. And he answered: “yes, it does!“.
So, what’s the matter with StringBuilders in C#?
Continue reading “C# and the StringBuilder class” »
One of the deficiencies of actual programming languages, specially those ones still widely used that are old, such as C or C++, is that they were designed having in mind the sequential programming paradigm. This usually means that those languages don’t have standard ways to work with multithreading features, and you usually have to rely on third party libraries to develop thread safe software.
Today I’ll be discussing a design pattern called Double Check, which can be widely used to manage the resource access, elimination and initialization in a safe thread way.
Continue reading “The Double Check Design Pattern” »