First line empty in Razor

First of all, I never thought a problem so simple would give me such a hard time!

My Problem

I’m using Razor views to generate some XML. I know I should probably use some sort of Serializer/Deserializer for that kind of job, but I needed something easier to change and preferably something that doesn’t need to be compiled. The problem is an empty line before my content which off course makes it invalid.

The code looks like:

@{
Response.ContentType = "text/xml";
}
<?xml version="1.0" encoding="UTF-8" ?>
...

and here is how the output is generated:

Empty line before content

First Try

The first thing I tried was to move the <xml> tag to the line above getting rid of the new lines that could possibly have.

@{
Response.ContentType = "text/xml";
}<?xml version="1.1" encoding="UTF-8" ?>
...

I even moved the Razor block to the bottom…

<?xml version="1.1" encoding="UTF-8" ?>
...
@{
Response.ContentType = "text/xml";
}

Nothing!

Second Try

Ok. This first line is not in my code. Something is putting it there. No problem! I can create a Response Filter and change the output removing this empty line.

using System.IO;
using System.Text;
using System.Web.Mvc;

namespace MyWebsite.Helpers
{
    public class RemoveEmptyLineWriter : MemoryStream
    {
        private readonly Stream filter;

        public RemoveEmptyLineWriter(Stream filter)
        {
            this.filter = filter;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            var content = Encoding.UTF8.GetString(buffer);
            content = RemoveFirstEmptyLine(content);
            filter.Write(Encoding.UTF8.GetBytes(content), offset, Encoding.UTF8.GetByteCount(content));
        }

        private static string RemoveFirstEmptyLine(string content)
        {
            var firstLineIsEmpty = content.Substring(0, 2) == "\r\n";
            return firstLineIsEmpty ? content.Substring(2, content.Length - 2) : content;
        }
    }

    public class EmptyLinesRemoverFilter : ActionFilterAttribute
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);
            var response = filterContext.HttpContext.Response;
            response.Filter = new RemoveEmptyLineWriter(response.Filter);
        }
    }
}

 

[EmptyLinesRemoverFilter]
public ActionResult Index()
{
  return View();
}

This code I found here, and then I changed it a little bit.

It simply adds to the Response a Filter which is invoked after the output is generated. So I can get it, modify and write again to the buffer.

I think this would have worked just fine if it wasn’t for my IIS being configured to Gzip the document. With Gzip enabled, after I read the buffer the content is just a bunch of messy characters. Decompressing the content and then compressing again is not a solution as it would cause an unnecessary overhead in my application. I’d rather turn Gzip off for those type of files but only if I really had to.

I also tried changing the order that my filter is added by changing the OnResultExecuted to OnActionExecuting but it doesn’t affect the order that the filter is executed, only the order in which it’s added to the response, which makes no difference.

My next try would be creating an IHttpModule, but I wanted something easier and something that I didn’t have to intercept all my requests.

Solution 1

Maybe you were lucky and the previous solutions worked for you, but in case they don’t, here is what worked for me. I had to go deeper in MVC and change the hierarchy of which the rendering is executed.

I ended up with this:

using System.Web.Mvc;
using System.Web.WebPages;

namespace MyWebsite.Helpers
{
    public class RazorXmlViewPage<T> : WebViewPage<T>
    {
        public override void ExecutePageHierarchy()
        {
            Response.ContentType = "text/xml";
            Layout = null;
            PushContext(new WebPageContext(), Response.Output); // push a new page context to the stack
            base.ExecutePageHierarchy();
        }

        public override void Execute()
        {

        }
    }

    public class RazorXmlViewPage : RazorXmlViewPage<object>
    {

    }
}

and in my Razor view…

@inherits RazorXmlViewPage<IEnumerable<string>>
<?xml version="1.0" encoding="UTF-8"?>

Thanks to this post that provided a source code that helped me get to this one.

The Razor view file inherits the WebViewPage by default. This page tells Razor that it inherits from a different class, in which I can override the execution of its core methods. We also have to override the Execute method because it is abstract.

It turns out I din’t even have to modify the output. Just by pushing a new WebPageContext to the stack the page rendered without the blank line.

But, if wanted, I could do some cools things with the Output. Take this code for instance:

public override void ExecutePageHierarchy()
{
    StringWriter writer = new StringWriter();
    PushContext(PageContext, writer);
    base.ExecutePageHierarchy();
    PopContext();

    Response.Clear();
    string output = writer.ToString();
    output = output.Replace("<body>", "<body><h1>An Example of Filtering Razor Output</h1>");
    Response.Write(output);
    Response.End();
}

If you want to understand better the methods used in the code above, take a look at the WebViewPage source code.

Solution 2

Another solution is to Render your View as a string, using the method bellow, change it and set the Response to your new content.

public string RenderRazorViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (var sw = new StringWriter())
  {
    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
    var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}

You know when you use return View(model);. This method it’s actually an alias to return new ViewResult {}. What the code above is doing is using the same implementation of that class, as you can see in the MVC source, in the method ExecuteResult.

I knew that I could use this code when dealing with this problem, but as I was looking at that class, I felt bad copying that much code from the MVC source and pasting it into my code. What if MVC updates as it does often and change that code? I’ll have to copy and paste it again in case this bug remains not fixed. So, for my use case I used the first solution as is less code copied and rewrote, plus, I didn’t even have to remove the first line from my output since the change skipped the bug. For other use cases the second solution might suit better your need/taste.

Please comment here what worked for you.

ZeroClipboard hosted on CDN

When working with ZeroClipboard, in my local environment it worked perfectly. However, when I uploaded the .swf to Amazon S3 I started receiving an error and the plugin stopped working.

After some googling I found out how to fix this. Here’s the beginning of my code:

var clip = new ZeroClipboard($(".copy"), {
    moviePath: "http://mysite-assets/js/lib/ZeroClipboard.swf",
    trustedDomains: location.host
});

I had to set the trustedDomains with my site url (not the CDN) to enable the Cross-Domain access.

For more info check out the setting options in the ZeroClipboard documentation.

Setting TortoiseGitMerge in msysgit as the Git mergetool

I use git in command-line using msysgit but I use the TortoiseGit’s merge tool to resolve conflicts. After updating TortoiseGit to version 1.8 the “git mergetool” command stopped working. That’s because they’ve changed the name of the .exe file from TortoiseMerge.exe to TortoiseGitMerge.exe. One simple solution is to create a copy of that file with the previous name. I did that at first, but it was bothering me, as if something wasn’t right. Then I figured it out and here’s how I solved it:

git config --global merge.tool tortoisemerge
git config --global mergetool.tortoisemerge.cmd '"C:/Program Files/TortoiseGit/bin/TortoiseGitMerge.exe" -base:"$BASE" -theirs:"$REMOTE" -mine:"$LOCAL" -merged:"$MERGED"'

Redis – Removing items using wildcard

Access your Redis machine and type:

redis-cli KEYS prefix:* | xargs redis-cli DEL

How to transfer files over ssh

This is a handy command I often need to use:

scp <filename> <user>@<address>:<destination>

Ex:

scp ~/Downloads/*.txt root@192.168.2.190:/home/dev

and if you need to specify your private key

scp -i ~/.ssh/myprivatekey.ppk root@192.168.2.190:/home/dev

How to discover the client IP connected to SQL Server

This query gives you details of who is connected to an instance of SQL Server:

SELECT * FROM sys.dm_exec_connections

In my case, this helped me when I was trying to setup the security access to an Amazon RDS with SQL Server and the IP I was getting, no matter which method I used, did not match the one it was being connected to the database.

My IP Address

Did you know you can get your IP on the internet using the following command?

Image

For a list with additional commands you can issue see http://ifconfig.me/

Remember you need CURL installed to do that.

GrooveControl for Grooveshark – Chrome Extension

Image

At work is really hard keep focused without any disturbing or distraction. There are always someone calling your attention, and often you need to stop what your doing to solve other problems.

In an effort to help focusing on my task, I am frequently listening music which not only amuses me as it reduces the noises in the environment. Grooveshark is my cloud music player but the thing is that it needs its window to be opened in order to play, and sometimes, you have so many windows and so many tabs, that it takes some time till you find your opened Grooveshark window, so you can pause and pay attention to who is calling you.

So, I created a Chrome Extension called GrooveControl, that displays a small and useful player that helps me to know what’s being played, pause, rewind or forward. That’s like 98% of what I usually do on Grooveshark’s window.

The good news for you, dear developer, is that it’s open-sourced. I’ve saved it in a public repository on GitHub. If you ever were curios about how to create a Chrome Extension, check it out, it’s very simple! And if you want to contribute to it, feel free to do so.

Enterprise Library 5 with ODP.NET

Enterprise Library 5 with Oracle

Introduction

This tutorial is an update from my previous post Enterprise Library 5 with Oracle Cursor, in which I demonstrated how to use Enterprise Library 5 with Oracle but NOT using ODP.NET, using MS Client instead. That’s because ODP.NET wasn’t compatible with Enterprise Library 5 when I wrote that post.

Well, luckily things have changed and now we can use them together, so, I created this step-by-step tutorial to show you how you can setup your project to use Enterprise Library 5 with ODP.NET. The steps shown here were tested on Oracle 11g, Enterprise Library 5, ODP.NET 11.1.0.7.20, and EntLibContrib 5. Different versions of Oracle and ODP.NET may work as well.

Step 1 – Environment

Oracle

I assume you already have some Oracle installed, but in you case you don’t you can download a Pre-built Virtual Machine that will make your life easier when setting up the environment.

Oracle Data Provider for .NET – ODP.NET

It will install the .NET client which communicates with the database – pretty obvious, I know, sorry for that. You can download it here.

I recommend you to really install it and not just copy the DLLs. I’m saying because I tried it. And it works! I just don’t think it’s worth having to copy DLLs with hundreds MBs into your project. In case you still want opt for that, you will need to copy the DLLs from Oracle Instant Client into your project’s bin folder.

Step 2 – Installing Libraries

I’m going to start by creating a new Project, going to File, New Project…New project window

Give the project a name and now, we install the libraries. I’m going to do that by using NuGet. It’s the easiest and fastest way and if you’ve been avoiding using NuGet all this time, then you should stop doing that!

From the NuGet Package Manager Console, run the following command:
Install-Package EntLibContrib.Data.OdpNetInstalling ODP.NET via NuGet Command

Or, you can right click the project and click on Manage NuGet PackagesInstalling ODP.NET via NuGet Window

For those who prefer manually install everything, download the EntLibContrib and add the necessary assembly references to the project.

Also, add a reference the Oracle.DataAccess.dll (you can find it in your oracle folder), usually c:\oracle\product\11.x.xx.x\odp.net\bin.
Adding Oracle Client library

In the end, regardless the installation type you chose, you should have your references as shown below:
References added to the project

Step 3 – Configuration

In the Web.Config / App.config, we need to tell Enterprise Library not to use its default implementation of Oracle Client and use the EntLibContrib one, which will work with ODP.NET. The code below does that by setting the Provider Mapping:

<configuration>
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </configSections>
  <dataConfiguration defaultDatabase="DefaultConnectionString">
    <providerMappings>
      <add databaseType="EntLibContrib.Data.OdpNet.OracleDatabase, EntLibContrib.Data.OdpNet, Version=5.0.505.0, Culture=neutral, PublicKeyToken=null" name="Oracle.DataAccess.Client"/>
    </providerMappings>
  </dataConfiguration>
</configuration>

After that, also add the Connection String to your database, below is an example:

<connectionStrings>
    <add name="DefaultConnectionString" connectionString="Data Source=127.0.0.1;User ID=scott;Password=tigger;Persist Security Info=True;" providerName="Oracle.DataAccess.Client"/>
</connectionStrings>

If you have problems configuring your connection string, see more different ways of setting it here.

Step 4 – Code

At this point, everything is set up and we can start coding. The code is pretty simple and it’s just to illustrate the concept.

First, I’m going to create a User class that will hold the user’s info.

using System;

namespace EntLib5ODP.NET
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public DateTime? BirthDate { get; set; }
        public string Phone { get; set; }
    }
}

Now, we need to ask Enterprise Library for a Database object. That Database object contains the methods that allows us to talk to the database. The line that does that is this one:

var database = EnterpriseLibraryContainer.Current.GetInstance<Database>();

With that object, we are able to call the method ExecuteReader which queries the database. One of the overloads of that method expect a Stored Procedure name and the arguments of that procedure. It will use the order of the arguments to bind them. My stored procedure has 3 arguments: id, name and result. Notice, we need to supply all parameters, so we set the ones we don’t want as null just to satisfy the parameters count, otherwise we would receive the error “The wrong number of parameters does not match number of values for stored procedure”. Here’s how we call the procedure to return a User by Id.

database.ExecuteReader("pkg_client.sp_list", id, null, null));

This will return an IDataReader, which is a HashTable with some helper methods. Now let’s put all together:

using System;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace EntLib5ODP.NET
{
    public class UserData
    {
        private readonly Database database;

        public UserData()
        {
            database = EnterpriseLibraryContainer.Current.GetInstance<Database>();
        }

        public User GetById(int id)
        {
            User user = null;

            using(var reader = database.ExecuteReader("pkg_client.sp_list", id, null, null))
            {
                if (reader.Read())
                    user = MapUser(reader);
            }
            return user;
        }

        private static User MapUser(IDataReader reader)
        {
            var user = new User
            {
                Id = (int)reader["id"],
                Name = (string)reader["name"],
                Email = reader["email"] as string,
                BirthDate = reader["birthdate"] as DateTime?,
                Phone = reader["phone"] as string
            };
            return user;
        }
    }
}

and the program running…
Program running

Download Sample

The links below contain the sample code with all that I showed you here. If you also want to test it on your machine, you need to download the SQL scripts and execute them in your database. The scripts will create a table with 3 items and a package with one procedure to list the items from that table. In case you’re using an schema, don’t forget to set them as well.

Dropbox => http://dl.dropbox.com/u/6963935/samples/EntLib5_ODP.NET/EntLib5ODP.NET.zip
GitHub => https://github.com/stanleystl/EntLib5ODP.NET
Scripts SQL => http://dl.dropbox.com/u/6963935/samples/EntLib5_ODP.NET/scripts.zip

Other Download Links

NuGet – http://nuget.codeplex.com/
Enterprise Library – http://entlib.codeplex.com/
EntLibContrib – http://entlibcontrib.codeplex.com/
ODP.NET – http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
Oracle – http://www.oracle.com/technetwork/database/express-edition/overview/index.html
Pre-built Oracle Virtual Machine – http://www.oracle.com/technetwork/community/developer-vm/index.html

Pre-built Virtual Machines

VirtualBox emulating Linux and running Oracle

Today I wanted to test a project which connects to an Oracle database but I just didn’t feel like installing Oracle on my machine (I don’t often use it and I formatted my OS recently). Then I remembered have read about the use of Pre-built VMs to test new OS’ and I thought: “Maybe I can find not only a fresh OS installation as well as Oracle already installed and configured”. And… guess what?! I found it!

It’s amazing how fast I had a new Operation System and Oracle up and running on my machine. And the best part is: whenever I think that I don’t need it anymore I can just delete it.

No worries about uninstalls leaving unused files in my machine.

There are many other kinds of pre-build systems around the internet. Don’t waste your time installing everything one by one or installing something in your machine just for testing purposes.

Follow

Get every new post delivered to your Inbox.

Join 79 other followers

%d bloggers like this: