Using LESS on a .Net project

Web programming
I was checking which CSS pre-processor to use on a .Net project and looks like LESS is the best option as it doesn't require Ruby like SASS does. So here we go: 1. Install it using the NuGet package. Install dotLess, which is the one prepared for .Net projects, not the less.js one. Also install System.Web.Optimization.Less which we'll need later. 2. Create a .less file at your Content root just as an example: default.less with this code: [sourcecode language="css" wraplines="false"] @color: #0808b9; //blue @errorColor: red; h2 { color: @color; } p { color: @color; } p.error { color: @errorColor; } [/sourcecode] 3. Now add a controller/action/view with this on the view: [sourcecode language="html" wraplines="false"] <h2>Index</h2> <p class="error">This paragraph should be red!</p> <p>This should be blue!</p> [/sourcecode] 4. That was just…
Read More

Rhino Mocks Stubs

Web programming
There are different ways to create and use stubs, you can use a repository to create stubs and handle all together, or use .Net Generics to create an independent stub. Creating a MockRepository [sourcecode language="csharp" wraplines="false"] [Test] public void CanSendMessageWithoutTextButWithAttachment2() { var mockRepository = new MockRepository(); var myStub = mockRepository.Stub<IMyClassType>(); // Creating a stub: myStub.Stub(x => x.MyMethod(null)).IgnoreArguments().Return(0); // Also you can create an expectation if you are expecting this method to be called: myStub.Expect(x => x.MyMethod(null)).IgnoreArguments().Return(0); mockRepository.ReplayAll(); // THIS IS VERY IMPORTANT!! var service = new MyService(myStub); // injecting the dependency var response = service.PerformRequest(); Assert.AreEqual(0, response); mockRepository.VerifyAll(); // THIS IS IMPORTANT TOO!! } [/sourcecode] In this way of working we create a repository for mocking that works as a workarea, we can create stubs on it and verify all…
Read More

Caching with memcache

Web programming
In general, if we were to add some manual caching to our system, there are some steps we need to take: 1. Try to get that value from cache. 2. Check if the value was retrieved. 3. If it wasn't, get it from database and add it to cache. 4. Handle the expiration time. 5. Return the value. Memcache will do all of that in just a line, freeing you from having to repeat the same steps all the time: [sourcecode language="csharp" wraplines="false"] public List<AdminProfile> GetAdminProfiles() { MemcachedItem<List<AdminProfile>> profiles = new MemcachedItem<List<AdminProfile>>("adminProfiles", cacheLifeTime, memcacheExpiryTime, cacheClient, () => noncachedObject.GetProfiles()); return profiles.Value; } [/sourcecode] Well, maybe I lied a little bit, as you need other preparations to make it work, but the idea continues the same. When you create a memcache object,…
Read More

Rhino Mocks expectations

Web programming
One of the most powerful tools you can use with Rhino Mocks is its "Expect" tool. So that instead of setting what should be returned when calling a method/property on a stub/mock object, you can set that you expect that to be called and what should it return, useful in different ways: [sourcecode language="csharp" wraplines="false"] SetupResult.For(User.Name).Return("Ruben"); // This works when setting up the object. User.Expect(x => x.Name).Return("Ruben"); // This is setting an expectation User.Stub(x => x.Name).Return("Ruben"); // Yes, Rhino Mocks is so flexible. [/sourcecode] Each one of those ways of setting a return value will have its uses and limitations, but I'm going to focus on the Expect() on this post. The expect as it is there will return that value just once, so that if you call "User.Name" more…
Read More

Refactoring: Removing dependencies

Web programming
I came to a code where the method was internally making a call to HttpContext which was hard to unit test, so had to remove such dependency. To do that I could have added the dependencies on the constructor but to avoid excessive refactoring (one step at a time!) I decided to do the inversion of control over the method only. (more…)
Read More

Composing a request with Fiddler4

Web programming
We can build up our own requests using Fiddler Composer, just click on the tab "Composer" which is between to "Autoresponder" and "Filters". Now on the given panel you can write a header and a body, the body is used to set the contents of a post so if you are filling the body make sure you remember to select the "POST" method on the combo. If you need to add a cookie, just add it on the header, a very good approach to this is to make a real request to the website you want to check and copy-paste its header/body, then modify what you need on the composer. That way you can make sure the request will work. Once you are done preparing the request, just click "Execute"…
Read More

Selenium tricks

Web programming
Waiting until the page loads [sourcecode language="csharp" wraplines="false"] WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete")); [/sourcecode] Selecting a sibling using xPath [sourcecode language="csharp" wraplines="false"] // Just in one sentence: var sibling = driver.FindElement(By.XPath("//input[@id='myId']/following-sibling::span[@class='someClass']")); // Or if you already had the first one: var someElement = driver.FindElement(By.Id("myIdentifier")); var icon = someElement.FindElement(By.XPath("//following-sibling::span[@class='someClass']")); [/sourcecode] Hovering over an element I found myself in trouble when trying to test a feature that required hovering the mouse over an element. It seems there is an easy way of doing it using Selenium with an action and: [sourcecode language="csharp" wraplines="false"] var icon = driver.FindElement(By.Id("myIcon")); var action = new Actions(driver); action.MoveToElement(icon); //I think in theory this is how it should be done action.MoveToElement(icon).Click().Build().Perform(); // Though many people around stackoverflow suggested to use this other one.…
Read More

Styling a checkbox using CSS3

Web design, Web programming
Got this idea from tutsplus but found a problem with iPad so just wanted to save it on my blog: Taking advantage of the ":checked" selector at CSS3 we can now style a checkbox using this: [sourcecode language="css" wraplines="false"] input[type="checkbox"] {display:none;} input[type="checkbox"] + label .fakeCheckbox { display:inline-block; cursor:pointer; vertical-align:middle; width:19px; height:19px; margin:-1px 4px 0 0; background:url(check_radio_sheet.png) left top no-repeat; } input[type="checkbox"]:checked + label .fakeCheckbox { background:url(check_radio_sheet.png) -19px top no-repeat; } [/sourcecode] The idea is quite similar to what we would do using javascript but instead of using a script to set the "on/off" we just use the CSS3 :checked selector to know if the radio is on/off and determine the background position of the span (fake checkbox). A nice improvement on previous method. That said, there is a bug on…
Read More

Introduction to MVC for Web Forms developers

Web programming
Oh yes, there are lots of guides, tutorials and videotutorials out there explaining you (or trying to) what MVC is or how it works, but when you have been for many years developing with Visual Studio and Web Forms you feel like if you are missing something and feel uncomfortable. So I decided to write this guide for Web Forms developers getting into .Net MVC. Breaking the Forms limit First of all, forget it. If WebForms was called WebForms was for a reason, and the reason is (as you know) that it depends a bit too much on web forms. Every page in WebForms has a Form covering all the page, every postback, button, textbox is included into that form and, if you want to use two different forms for…
Read More

Installing a local script with Greasemonkey

Other, Web programming
Though greasemonkey is thought to share your scripts with the community, you may prefer to have some script for personal websites, local applications or just very personal customization of a page. Most greasemonkey tutorials show you how to install a script stored online but forget about how to create your own script and install it in local: Quick guide Install Greasemonkey Click on Greasemonkey icon -> Manage scripts -> New User Script... Create your script following GM rules and save it. If you already have the script, open it with the browser (you can drag and drop the file into the browser or use "Open with...") and the install window will appear immediately (install button has a few seconds wait for security issues though). Writing your own script If you…
Read More

Requesting to C# MVC.Net using jQuery.Ajax

Web programming
Basic Call Let's just make a call to the server to get a single value: We'll call this JS function, for example, using a button like <input type="button" onclick="SingleCall();"/>: [sourcecode language="js" wraplines="false"] function SingleCall() { var url = '@Url.Action("AJAXRequest", "AJAX")'; jQuery.ajax({ url: url, success: function (data) { console.log('Returned data is: ' + data); //Note: Remember though data is an int it's returned as a string, // so if you want to get it as int you need to use parseInt() } }); } [/sourcecode] And have this simple Controller (I've created a Controller called AJAX, but you can use any Controller for these requests). [sourcecode language="csharp" wraplines="false"] public partial class AJAXController : Controller { public virtual int AJAXRequest() { return 5; } } [/sourcecode] Adding parameters to our call The…
Read More

SQL Server Quick statements

Web programming
Change Table name [sourcecode language="sql" wraplines="false"] EXEC sp_rename 'OriginalName', 'NewName' [/sourcecode] Change Column name [sourcecode language="sql" wraplines="false"] sys.sp_rename 'TableName.ColumnName', 'NewColumnName' [/sourcecode] Add Foreign Key [sourcecode language="sql" wraplines="false"] ALTER TABLE dbo.[TableName] ADD CONSTRAINT FK_Table1Name_Table2Name FOREIGN KEY (Table1ForeignColumnName) REFERENCES dbo.[Table2Name](ID) ON UPDATE NO ACTION ON DELETE NO ACTION GO [/sourcecode] Note: The name of the constraint "FK_Table1_Table2" should have the name of the table with the foreign key first, and the table with the main id second as a standard. Removing Foreign Key Constraint As these constraints normally have a standarized name we should be able to do this: [sourcecode language="sql" wraplines="false"] ALTER TABLE tablename DROP CONSTRAINT ConstraintName -- Normally ConstraintName is FK_Table1Name_Table2Name where Table1 references Table2 Primary Key [/sourcecode] In case you want to get the constraint name programatically: // TODO…
Read More

Removing constraints programatically in SQL Server

Web programming
Default Constraint [sourcecode language="sql" wraplines="false"] declare @key nvarchar(200); select @key = c.name from sys.all_columns a inner join sys.tables b on a.object_id = b.object_id inner join sys.default_constraints c on a.default_object_id = c.object_id where b.name='tablename' and a.name = 'columnname' exec('alter table tablename drop constraint ' + @key) // in case you wanted to remove the column alter table tablename drop column columnname [/sourcecode] Foreign Key Constraint [sourcecode language="sql" wraplines="false"] SELECT KCU.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU WHERE KCU.TABLE_NAME = 'Message' AND KCU.COLUMN_NAME = 'MaintenanceID' [/sourcecode]
Read More

Improving your website’s performance

Software Architecture, Web programming
Using Cache One of the best ways to improve your website's performance is by using cache. That way you can save lots of db requests and server processing time. Using Cache for static data Let's start by caching all those reference tables with user roles, categories, error messages, cities, countries, etc. Normally this uses minimal cache and saves thousands of db requests, probably the best improvement possible. Caching often requested dynamic data Imagine you have a real state website for the UK with thousands of possible requests on it (as there are thousands of cities, towns, combinations of filters, etc. But you notice that due to peaks of population requests for London, Manchester, Liverpool and a few more take like 30% of all the overall requests. Of course there are…
Read More

Be care with default values on Foreign Keys!

Web programming
Today I was creating a constraint in my DB using this statement: [sourcecode language="sql" wraplines="false"] ALTER TABLE dbo.[Cars] ADD CONSTRAINT FK_Cars_Users FOREIGN KEY (UserId) REFERENCES dbo.[Users](ID) ON UPDATE NO ACTION ON DELETE NO ACTION [/sourcecode] And got this weird error message: The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Cars_Users". The conflict occurred in database "MyDatabaseName", table "dbo.Users", column 'ID'. The problem came as I didn't realized I had set a default value for FK UserId to 0, and primary key in Users was autoincrmental starting at 1, so there would never be a UserId=0 in User table and SQL complained about it. [sourcecode language="sql" wraplines="false"] ALTER TABLE Cars ADD UserID int NOT NULL DEFAULT 0 [/sourcecode] Good someone helped me finding the problem, I was blind! So…
Read More