Skip to main content

Could not load file or assembly ‘Antlr3.Runtime’ or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))

How to fix this weird project error with in a very simple way?

Posted in Tutorials, IIS, ASP.NET

I just had a weird issue with my project: I’ve hit Ctrl+F5 to run and the browser opens. So far, everything ok. When I was going to attach the process I got a BSOD.

As if that wasn’t weird enough I got the error below after restarting everything and running my project again:

Could not load file or assembly ‘Antlr3.Runtime’ or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG)) Antlr3.Runtime

Luckily someone had this issue before (thanks Cloud Developer!) and I was able to solve it easily. What is the solution? Just empty your %TEMP% folder. Here is how:

  1. Click the Start button and then Run (or press Win+R)
  2. Type: %TEMP% in the box
  3. Click the OK button (The directory for temporary files opens)
  4. Select all files (press CTRL+A)
  5. Press the DELETE key on your keyboard

You don’t need to delete all files, but just the right ones. In case it doesn’t work and you need to delete all files it’s recommended to close all programs (even those on the system tray – beside the clock) and repeat the steps above.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

The best way to use DropDownListFor with ASP.NET MVC

Things don't need to be difficult and, of course, do everything you can to reuse your code

Posted in Tutorials, C#, Code snippets, ASP.NET

One of the most annoying things on ASP.NET MVC is to create a decent dropdown list, and Scott Allen already covered it here nicely. While I like his explanation I often see people facing different scenarios. What I will describe here is the way I use to create the dropdown lists for all my projects.

The problems

  1. Create a common place dropdowns will be placed, so we can maintain it easily;
  2. Get the data from somewhere;
  3. Put the minimum necessary logic into the Controller;
  4. Show it in the View.

The solution

First of all, we need a class. I will use a Model, as example, since this data can also come from the database.

This class has only 2 properties since it’s all you need to use with a DropDownListFor. But keep in mind that your class can have other properties.

Now, we need the code to generate the items for the DropDownListFor.

I have this code in a helper specially build for dropdown lists. In this way, as mentioned before, I can ease the maintenance of the project. And if you didn't notice, this code is concatenating with the DefaultItem property, which I show below.

This property will add the standard "-SELECT-" item at the first position in our dropdown list.

Also, you will see once you download the code that I am hard coding the items in the DropDownListHelper's constructor. In the real world I would load the data directly in the property.

Now that we have the class (Model) and the helper, we will go for the ViewModel. This is a pretty standard situation: I personally like to keep my Model exclusively for database while my ViewModel is the one going to create the forms. The reason is that I can customize the ViewModel for my needs, not needing to have a Model with a lot of properties using [NotMapped] on the top.

Here is what we need in the ActionMethod.

And here is the View.

Some might say it’s an unnecessary effort, and I would agree if we would use only one dropdown list. However, when we start building bigger systems which are going to use multiple dropdown lists, this approach comes in handy.

You can check the full code in my GitHub repository: https://github.com/davidsonsousa/DropDownList

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

Create a video gallery with modal using ASP.NET and Bootstrap

Learn how to create a video gallery using the Youtube API with ASP.NET and Bootstrap modal

Posted in Tutorials, API, Youtube, Code snippets, ASP.NET, JavaScript

We are in the 3rd article of the series about Youtube API. The articles are:

  1. Load a single predefined video
  2. Load a custom video with the Youtube API in ASP.NET
  3. Create a video gallery with modal using ASP.NET and Bootstrap (this article)

We saw in the previous how to load a custom video from the backend using ASP.NET. For this one we will use the same approach to create our gallery, plus Bootstrap for the modal.

The player

We will need to put the player we saw on the first article in the Bootstrap modal, as it’s shown below.

The Javascript

There are 2 scripts to be used. The first one is the general script, which I've shown in the previous articles and it didn't change. The second one is the script below, which will handle the video gallery.

The View

As you saw in the javascript above we are using only one modal. The magic happens in the code below, where I am passing all parameters via data-* attribute. I am using the same Model from the previous article.

As you can see there is no mystery on working with Youtube API and ASP.NET. And the next article will show how you can detect the state of the videos, which is very important for tagging and user interaction.

Check the full code here: https://github.com/davidsonsousa/YoutubeAPI

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

Load a custom video with the Youtube API using ASP.NET

Learn how to load a video from the backend (ASP.NET) using the Youtube API

Posted in Tutorials, API, Youtube, Code snippets, ASP.NET, JavaScript

Let’s continue with this very simple series of articles about the Youtube API. The articles are:

  1. Load a single predefined video
  2. Load a custom video with the Youtube API in ASP.NET (this article)
  3. Create a video gallery with modal using ASP.NET and Bootstrap

On the previous article, we saw how to load a predefined video using the API. It was simple and clean, while we could load only that specific video. In the real world that would be a bit different since we would have to load the video from diferent sources, by using the backend. In this article we will see how we load the from the backend using ASP.NET

The player

We will use a div tag as player, which should be handled by the javascript later.

<div id="player"><div>

The Javascript

We will split this script in 2 parts: The general script, which makes the API calls and the Video script, which actually calls the video.

General script

We use this one just once, as we did before.

Video script

Here is the trick. Since I am using ASP.NET MVC here and I need to have some flexibility since we are using the back end to bring the video, I will need to put the script in a partial view. Also, I am passing the Video model, which should bring all the parameters needed for the video.

Video model

Here is the model I am using. Keep in mind that such model could bring the video data from a database, for example. Or some web service.

That's it.

Next article will be about a video gallery opening a video in a modal window. All of it using videos loaded from the backend in ASP.NET MVC and bootstrap.

Check the full code here: https://github.com/davidsonsousa/YoutubeAPI

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

How to use the Youtube API to load a single video

Learn how to use the Youtube API and javascript to load only one video

Posted in Tutorials, API, Youtube, Code snippets, JavaScript

The most common way to embed any video on Youtube is: Click in Share, Embed, copy the code and place in the website. I guess everybody used this at least once but let’s be realistic: This is not the best approach when you are working with clients as you never know what the client is going to ask in the future. It might happen the client will not request anything extra. Or he might ask to record the time the user paused the video.

My idea here is to make a very simple series of 4 articles which should cover the most basic usage of Youtube API. And they are:

  1. Load a single predefined video (this article)
  2. Load a custom video with the Youtube API in ASP.NET
  3. Create a video gallery with modal using ASP.NET and Bootstrap

For this series I am going to use the Youtube API for iframe embeds which forces the HTML5 player and it’s better for compatibility with mobile. You will find the code to download in the end of the article.

The player

When embedding a video we normally get a code like this:

<iframe width="560" height="315" src="https://www.youtube.com/embed/XdlmoLAbbiQ" frameborder="0" allowfullscreen><iframe>

However, since we are going to use the Youtube API, we will need a very simple code:

<div id="player"><div>

The Javascript

Here is where the magic happens. The javascript code will load the video we want and replace that div with the proper embed code. However, I will split this script in 2 parts.

General script

This script is used only to make the API calls. Note that we are using this approach since we still don’t have full support for async javascript calls straight from the script tag, so this script should take care of this for us. We need to call it just once.

Video Script

After setting the API call we need to load the video and the way we will do that is also through javascript. So far, in this example, all we will need is the video dimensions (height and width) and also the ID. We will set this up in the function onYouTubeIframeAPIReady(), which is executed once the API is ready to be used.

That’s it for now. In the next article I will show a very simple way to load a custom video. And for that I will use ASP.NET to simulate some database retrieval. But you can use your language/framework of choice.

Check the full code here: https://github.com/davidsonsousa/YoutubeAPI

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

Setting folder permissions using Web Deploy

Learn how to set folder permissions to your ASP.NET projects when using Web Deploy

Posted in Tutorials, Web Deploy, Code snippets, ASP.NET, Configuration

I was running into a very odd problem recently: I couldn't upload files to my website because of an error saying that I didn’t have permission to write files into the App_Data folder. I’ve decided to look into it and I realized that it began since I started using Web Deploy.

For those unfamiliar with Web Deploy I will tell you something: This is the best deployment tool for ASP.NET websites so far. It checks the files before you send to the server so it will send only those which had some change, publish entire databases and even pre-populate the tables.

The problem is that Web Deploy resets all folder permissions, which basically broke my file upload. And since ELMAH couldn't log the errors I spent some time thinking that my website was running flawlessly perfect. Silly me...

The solution I found was to create a .targets file in order to set the permissions during the deployment time. Let’s see how to do it:

  1. Create a .wpp.targets file in the root of your web project. You may not find this file in your File -> New window. In that case just create a normal Text File, change the extension and add XML content in it, as you can see in the gist below:
  2. Set the permissions to the folders you want. In my case, the App_Data was just enough but you can add other folders as well (lines 15 to 29).
  3. Deploy through Web Deploy. A very simple explanation of this step: When you deploy the MSBuild will run, pass through the .targets file you’ve created and set the permissions to the folders you’ve defined.

You might keep some things in mind:

  • Visual Studio caches the .targets files, which means that you will have to restart Visual Studio every time you want to make changes and see the effects when you are building the deployment package.
  • The package will not be rebuild unless you actually make changes in the .targets file.
  • Remember to always use Clean Solution in case you want to rebuild the deployment package.

For more information visit the Sayed Ibrahim Hashimi’s website.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

Leave the office! See what you need to work anywhere you want

Do you know those days you don't want to be in the office? Here is what you need to work anywhere you want!

Posted in Tutorials, Workplace, Misc, Career, Personal life

When I started my career as software developer all I could have was a big desktop computer. It was an Intel Celeron 300 MHz with 32 MB of RAM and a HDD of 4 GB. Such beauty would never let me to have the mobility I am able to have today, although I am still far from being as mobile as I want.

But what do you need to become a “work anywhere professional”?

The basic checklist is this:

  • A nice place
  • Good devices
  • Internet connection
  • Tools
  • Concentration

Now, let’s talk about each item.

Place

The place must be nice, preferably with a table where it's possible to place all your devices (more on that later), and calm unless you have a good concentration level (more on that later). Most of people think of places like Starbucks or McDonalds but, actually, it would depend on the kind of work you do and how connected you must be. For a writer, who doesn’t need to be online all the time, work in the woods would be a nice thing. But for a software developer, who depends on internet connection, it would be a bit more complicated.

Good devices

The very basic is a notebook and a mobile phone with a good data plan. In my particular case I have a 17” Lenovo as main computer and a 10” ASUS Transformer as side computer. If I am traveling or going to a place where I know I will need a computer, I take the ASUS. The keyboard is comfortable enough to write and the touchscreen replaces in a very nice way. In addition, I have Visual Studio Express here and it works fine for me.

Another thing to keep in mind is battery time. My Lenovo can work up to 3h with Wi-Fi turned on while my ASUS works up to 10h in the same conditions. Given that I assume I will not find sockets anywhere I go a good battery time is very important. Not to mention that I can it also to recharge my phone, at least to keep alive for longer time (if necessary).

Internet connection

You have 3 possibilities here: Connect over Wi-Fi, use your mobile data plan and share the internet with your notebook or work offline.

It’s clear that Wi-Fi is the best alternative here. However, you can’t expect to find free Wi-Fi with a good speed anywhere. And I am not even talking about how unsafe that would be. Connect over mobile and sharing the internet to your notebook is to be the best option if you have a good (big and fast) data plan, except if you are on roaming.

Tools

The idea here is to have everything to make the transition from your portable machine to your stationary machine as seamless as possible. Except, of course, for some software you can’t install on both due hardware limitations.

Assuming that you have internet connection, you can make use of tools like a private VPN, online file services (OneDrive, DropBox, Google Drive), online repository (TFS Online, GitHub) and others. As a developer, I consider all of them important, although I don’t have a private VPN. Yet.

Concentration

The best here is to be self-aware: If you know how much concentration you are able to have in the moment you decide to leave the office, you will pick the perfect place for you. For those who can work only in a silent environment a Starbucks would not be the best place.

Conclusion

My case is a very specific one. I love what I do but I am far from being workaholic. But sometimes I need to work on something small or go somewhere where I could use a computer. Today, for example, I started this article watching children play indoor soccer in the morning. It was noisy, messy and I was using my ASUS on my laps. Luckily, that place had a good internet connection and I could save this text in my OneDrive in order to finish on my notebook later.

Keep something in mind: Find balance. It doesn’t matter if you have an outstanding data plan if you are abroad most of the time as you will need to use roaming. Or even, you have the best of everything but you can’t concentrate in a café.

And remember: The best alternative is always the alternative that suits you.

 

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

Adding an external link message to all links with jQuery

Learn how to show a message to the user whenever he clicks in a link pointing to a different website

Posted in Tutorials, Code snippets, jQuery, JavaScript

Sometimes we face some situations where we have to tell the user he is leaving our website. This can be achieved with CSS selector without so much problem. But what if the external link is in a button? For that situation we should use JavaScript.

Let's see how to do it in this very short tutorial.

Objective

We need to create a script where a message will be shown whenever the user clicks in some link which will lead him outside of the website. And this must be done unobtrusively.

The foundation

First we need to prepare the foundation of our code. Given the objective we will need to:

  1. Loop through all "a" elements
  2. Get the href value
  3. Compare if the host matches with the href host
  4. Assign the click button

1. Loop through all "a" elements

Since we are using jQuery we can make use of the jQuery.each(), as seen below, to loop through all "a" elements:

$('a').each(function () {
// something
});

2. Get the href value

This is a bit trickier but, to make it easier, we will create a function to do the job:

var getLocation = function (href) {
	var l = document.createElement("a");
	l.href = href;
	return l;
};

And we will call it like this:

var a = getLocation($(this).attr('href'));

3. Compare if the host matches with the href host

var retValue = a.href && a.hostname !== window.location.hostname && a.href.indexOf('mailto') == -1;

Here you have to use a set of rules which will make the code work properly. For the sake of the example I’ve decided to keep it simple, but you can (and should) extend according to your project. 

4. Assign the click button

For those who are already aware of jQuery this is an easy piece. But I will leave it here anyway.

if (retValue === true) {
	$(this).on('click'function () {
		// something
	});
}

Now that we have the foundation ready you can see it working in this JSFiddle. When you click the links you will see that one of them shows an alert() message. Now the things will get more interesting, by implementing our confirmation message. 

Showing the message

Now that we have everything in place we can start to work with the message. For this example I will keep it simple and use a simple confirm(), as seen below:

return confirm('Do you really want to leave this website and go to ' + a.href + '?');

Conclusion

Here is the whole code:

var getLocation = function (href) {
	var l = document.createElement("a");
	l.href = href;
	return l;
};
$(function () {
 
	$('a').each(function () {
		var a = getLocation($(this).attr('href'));
 
		// IE fix
		a = getLocation(a.href);
 
		var retValue = a.href && a.hostname !== window.location.hostname && a.href.indexOf('mailto') == -1;
 
		if (retValue === true) {
			$(this).on('click'function () {
				return confirm('Do you really want to leave this website and go to ' + a.href + '?');
			});
		}
	});
 
});

As you can see it is very simple to make and even simpler to use. Once you call it in all pages it will scan all your links and check if they should have this extra event or not. Also, for most of the projects we don’t need more than this. And when you have the need of more customization (Bootstrap Modal or jQuery UI Dialog) you can just replace the confirm() by something else.

I will show how to do it in the future articles.

EDIT: I've made a small change on the script (bold, see above) as IE11 had some problems to get the a.hostname.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

Write and read XML files by serializing and deserializing objects with C#

This is a very useful approach when you don't want to create the XML files using XmlWriter

Posted in Tutorials, C#, Code snippets, XML

Have you ever wondered how to write an XML file easily? And what about reading the XML file and mapping into an object? There are cases we need to generate XML in order to send information here and there. Or even to use as a kind of database. And the most used approach (by my friends, at least) is to create the XML manually, defining every single node. Pro: More control of the output. Con: Time consuming.

And that brings us to the situation we had in the office.

We have access to a SQL database. But due the amount of security layers we end up taking a huge amount of time to develop against the database. Besides, we wanted to make something flexible and easy to be edited by anyone with more than 2 brain cells. That's why we decided that it would be much more flexible if we would use XML files for the data.

All we need is a well structured class, which could be a Model for those using MVC:

public class DummyClass
{
    public string Id { getset; }
    public string Name { getset; }
}

And the following code:

public class XmlSerializerHelper where T : class
{
	public static string Serialize(T obj)
	{
		var stringBuilder = new StringBuilder();
		try
		{
			var xmlWriterSettings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true };
			var ns = new XmlSerializerNamespaces();
			ns.Add("""");
			var xs = new XmlSerializer(typeof(T), "");
 
			using (var writer = XmlWriter.Create(stringBuilder, xmlWriterSettings))
			{
				xs.Serialize(writer, obj, ns);
			}
		}
		catch
		{
			throw;
		}
		return stringBuilder.ToString();
	}
 
	public static T Deserialize(string xmlString)
	{
		var reader = new StringReader(xmlString);
		var serializer = new XmlSerializer(typeof(T));
		var instance = (T)serializer.Deserialize(reader);
 
		return instance;
	}
}

If you want to serialize a class to XML:

xDoc.Add(XElement.Parse(XmlSerializerHelper<DummyClass>.Serialize(dummy)));

And if you want to deserialize:

var dummyObj = XmlSerializerHelper<DummyClass>.Deserialize(xDoc.ToString());

Please note a couple of things:

  1. This code will generate a very simple XML file, without namespaces or declarations;
  2. The "type of T" is there to give you flexibility when using the serialization/deserialization methods;
  3. The way the XML will be generated depends entirely on the way the class is created.

I know this code is not perfect (no try/catch on Deserialize, etc) it should give you a good head start. ;-)

If you start to implement this code you might have noticed one thing: Everything what is in the class will be serialized into the XML with the names you defined there. We can solve this and I will show you how.

Renaming the XML elements

It might happen that you have a class with a name which wouldn't make sense after generating a XML file. In that case it would be much better if we would have the XML elements in a way that anyone can understand. After all, it's much better to read than , right?

One easy way to do it is using Annotations over the name of the class and its properties. Here some that might be very useful:

XmlRoot

[XmlRoot("Person")]

XmlRoot will work in 2 ways: First by defining the root of your XML file; Second by defining its name. Recommended to be used to rename the class itself.

XmlAttribute

[XmlAttribute("Id")]

By default every property is serialized as XML element. By XmlAttribute you will tell the serializer that your property should be used as an attribute in the root element.

XmlElement

[XmlElement("Name")]

Use XmlElement in case you have a property you wish to rename. Very useful in the case you have a property called PersonName and you want to serialize it as Name.

XmlIgnore

[XmlIgnore]

You can use XmlIgnore when you don't want a property to be serialized.

XmlArrayItem

[XmlArrayItem("Children")]

XmlArrayItem is used to create sub elements. You can also use it to rename your properties which contains List, for example.

Of course there are more. But create a kind of ultimate xml serialization guide was never my idea. Maybe one day I will write a book about it. But while it doesn't happen I hope this article will be able to help some people around the interwebs.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

Replacing all non numeric characters from a string using Regex

Use this simple snipet to remove all dashes and dots from document numbers, license plates and so on

Posted in Tutorials, C#, Code snippets

Everybody who works coding something must use Regular Expressions (RegEx) at least once in a lifetime. They can be used for a lot of things but my favorite will be always matching and removing characters from a string.

One of the problems I always have developing softwares was with number formatting. While in the user interface we should allow dots and dashes as the user will never really care if he should or should not use it. In Brazil, for example, the postal code has the following format: 00000-000. Some people might put it without the dash. And that, my friend, will hurt the database.

One way to solve this is forcing the backend to keep only the numbers. Let's take a look on how to do it using Regex.Replace:

  1. Add the reference
    using System.Text.RegularExpressions;
  2. Use this line of code
    string onlyNumbers = Regex.Replace(str, "[^0-9]""");
    

And that's it!

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

Using web.config to make your ASP.NET project accept LESS CSS

Learn how to solve the 404 error you get when you try to run an ASP.NET project with .less files

Posted in Tutorials, IIS, ASP.NET, Configuration

Every ASP.NET developer must love the web.config file. Seriously, I will write about it some day. :-)

Some time ago, we have faced a very interesting problem in one of our ASP.NET projects. We have decided to use LESS CSS in order to optimize the front-end development and speed up the things a bit. While we knew that we should compile the LESS files before throw it to production we were facing an error during the development phase:

HTTP Error 404.3 - Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

The reason: IIS doesn’t support .less files by default.

By this time we have 2 solutions: The first one is to call the responsible for the webserver and ask him to add a new MIME type into the IIS. But thanks to the .NET architecture we don't need to do that. All we need to do is to add some extra lines to your web.config, inside , as seen bellow:

<system.webServer>
  <staticContent>
    <remove fileExtension=".less" />
    <mimeMap fileExtension=".less" mimeType="text/css" />
  staticContent>
system.webServer>

As you saw it’s simple, clear and useful. Keep in mind that you can use the same method to solve the problem with other non-supported files such as webfonts (.eot, .woof), videos (.mp4, .ogg, .m4v), images (.svg, .svgx) and so on (as Mads Kristensen wrote).

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

How to upload a file using ASP.NET MVC and AJAX

A very simple file uploader using the progress bar component from Bootstrap

Posted in Tutorials, C#, ASP.NET, MVC, AJAX

I've decided to get my old upload post and upgrade the components I am using. For example: Before it was an MVC3 project made on Visual Studio 2010 using the old version of everything. Now it's a Visual Studio 2012 project, ASP.NET MVC4, using bootstrap and the newest version of each plugin I've used before.

First step

First of all we need to create a Model just like Scott Hanselman made in his article. Then we will have the name, length and type of our file:

public class UploadFilesResult
{
	public string Name { getset; }
	public int Length { getset; }
	public string Type { getset; }
}

Second step

We will need to create an Action Method which will take care of the upload. It will be called by using the http POST method, get the list of selected files and save into App_Data. This Action Method should return a json informing the name, length and type of the files:

[HttpPost]
public ContentResult UploadFiles()
{
	var r = new List<ViewDataUploadFilesResult>();
 
	foreach (string file in Request.Files)
	{
		HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
		if (hpf.ContentLength == 0)
			continue;
 
		string savedFileName = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(hpf.FileName));
		hpf.SaveAs(savedFileName); // Save the file
 
		r.Add(new ViewDataUploadFilesResult()
		{
			Name = hpf.FileName,
			Length = hpf.ContentLength,
			Type = hpf.ContentType
		});
	}
	// Returns json
	return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}""application/json");
}

Third step

After that we only need to download a jQuery plugin called jQuery File Upload. It brings us lots of cool stuff but, for the sake of simplicity, we are gonna use only 2 files (apart from the others I am already using): jquery.fileupload.css and jquery.fileupload.js:

Fourth step

We need now a way to send these files. This is what I've created - just for the upload - but you can adapt into your page:

<div class="container">
	<span class="btn btn-success fileinput-button">
		<i class="glyphicon glyphicon-plus">i>
		<span>Add files...span>
		<input id="fileupload" type="file" name="files[]" multiple>
	span>
	<br />
	<div class="progress">
		<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width0%;">
			<span class="sr-only">0% completespan>
		div>
	div>
	<br />
	<div class="file_name">div>
	<br />
	<div class="file_type">div>
	<br />
	<div class="file_size">div>
div>

Notice 4 things:

  1. I didn't use HtmlHelper to create the form. The reason is the ease to create the form without it. Also, we don't need to use HtmlHelpers all the time;
  2. I am not using a form tag. The plugin takes care of everything;
  3. The progress bar, thanks to bootstrap;
  4. The divs at the end, which will only receive the json data.

Last step

Now we need to make the javascript in order to make this work. I am using the jQuery File Upload plugin calling the Action Method UploadFiles created in the HomeController. In addition I have also attached an event which shows the upload status to the user by using the bootstrap progressbar component:

<script type="text/javascript">
	$(document).ready(function () {
		$('#fileupload').fileupload({
			dataType: 'json',
			url: '/Home/UploadFiles',
			autoUpload: true,
			done: function (e, data) {
				$('.file_name').html(data.result.name);
				$('.file_type').html(data.result.type);
				$('.file_size').html(data.result.size);
			}
		}).on('fileuploadprogressall'function (e, data) {
			var progress = parseInt(data.loaded / data.total * 100, 10);
			$('.progress .progress-bar').css('width', progress + '%');
		});
	});
script>

That's it. Now you are ready to add this feature to your website, without any postback.

Download the code here: jQueryFileUploadMVC4.zip (5.84 MB). Yes, almost 6MB thanks to the packages.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

How to reduce the size of a word document by optimizing the images in 5 easy steps

Very useful in case you get a huge .doc / .docx full of images

Posted in Tutorials, Misc

Some time ago, I got a word document with around 36 MB and a request to resize this file in order to be lighter as it be sent via e-mail. The first thing I thought was the obvious: Why not compact the file? I use 7-zip, which is the best compression utility I have ever used. It did not work as expected since the file went down to 30 MB.

The problem 

When I’ve opened the document I could see that it had only 10 pages, each with 2 images. So it could be possible the images were way too heavy, meaning, not optimized for internet or text documents. Do you know those people who take a picture using all megapixels of the digital camera and start to send those 4 MB files to everybody? This was more or less the case.

The solution

It’s simple: All we need is to reduce the dimensions of the images in the word document. But I am not saying about simply resizing, but editing. By editing we will be able to reduce every of those heavy images into something more acceptable. For that, I will use my favorite image visualizer, the XnView.

So, with the word document open:

  1. Right click on the image, select “Save as picture…”, define a name and save itd

  2. Open the saved image in the XnView

  3. Click on the menu “Image” and then “Resize” (or Shift + S)

  4. Choose the appropriated size and press Ok. Here is a bit tricky since it depends on the width/height the image actually should have according to your word document

  5. Save the image (File -> Save or Ctrl + S)

I’ve used 800 x 400 with this image and its size decreased from 7 MB to 65 KB. Now it is only about deleting the huge picture from the word document and add the new resized one. The result is a document with 78 KB, which is much better to send around the internet.

Note: This problem is going to happen if you insert the images by drag & drop. If you use the menu (Insert -> Pictures) the image will go through a process of optimization and the document will not be so heavy.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

Horizontal scrolling with jQuery

Learn how to easily make horizontal anchors with jQuery

Posted in Tutorials, Code snippets, jQuery, JavaScript

I've got a freelance job from a Brazilian company few days ago. The project is fine, nothing so different than the usual. Except for one thing: They want the page to scroll horizontally.

The clients are getting creative these days...

My biggest problem is the main menu: If the page would be normal I could use anchor. But I can't since anchors don't work on the horizontal.

Fortunatelly the solution is easy: .scrollLeft()

What .scrollLeft() does is simple: It returns the position of the horizontal scroll bar. And if we pass a parameter it will set the scroll bar where we want.

I have an example on how it's done. Let's walk through it:

HTML

Very simple, no problem at all. Only one navigation and a couple of divs just to give something to work with:

<header>
    <nav>
        <ul>
            <li><a class="nav-item1" href="#">Item 1a>li>
            <li><a class="nav-item2" href="#">Item 2a>li>
            <li><a class="nav-item3" href="#">Item 3a>li>
        ul>
    nav>
header>
<section>
    <div class="item item1">Item 1div>
    <div class="item item2">Item 2div>
    <div class="item item3">Item 3div>
section>

CSS

The CSS is very basic, just to give some formatting:

<style type="text/css">
    nav { position: fixed; z-index: 1030; }
    section { width: 3600px; top: 100px; position: relative; overflow: auto; }
    .item{ float: left; position: relative; width: 900px; height: 500px; font-size: 200px; }
    .item1 { background: #f00; }
    .item2 { background: #0f0; }
    .item3 { background: #00f; }
style>

Javascript

Since we have 3 items I've created a function which groups everything. In that way I am able to keep the code clean, without repeating important parts:

function horizontalNavigation(position, event) {
    $('html').scrollLeft(position);
    event.preventDefault();
}

And here is where the magic happens:

$('.nav-item1').click(function (event) {
    horizontalNavigation(0, event);
});
$('.nav-item2').click(function (event) {
    horizontalNavigation(900, event);
});
$('.nav-item3').click(function (event) {
    horizontalNavigation(1800, event);
});

See the working example.

There is only one problem with this code: What if I want to have a smoothly horizontal scrolling? For that we can use .animate(). Solution in bold bellow:

function horizontalNavigation(position, event) {
    $('html').animate({scrollLeft: position}, 800);
event.preventDefault(); }

See the working example.

As you can see it is not so complicated as it looks. Just a bit of work, but quite easy.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

How to uncheck all radio buttons and checkboxes using jQuery

Learn how to use jQuery to reset all radio buttons and checkboxes AT ONCE in a page

Posted in Tutorials, Code snippets, jQuery, JavaScript

- UPDATE -

My friend Wellington sent me this code right after I've published this post:

$('input:checked').removeAttr('checked');

This should get all the checked items and remove the "checked" attribute.

- Original post -

Recently I have come across a very interesting problem in a project I am working on. I had to uncheck all checkboxes at once. It was fine by using a simple .each on jQuery. After that the requirements changed and I had to add radio buttons and they weren't working with the code I already had. That was fixed with one more line. Let's see how it was done.

Suppose I have 3 checkboxes and I want to clear all of them at once. Normally I would do something like this:

$('#clear-all').click(function () {
	$(':checkbox').each(function () {
		$(this).removeAttr('checked');
	})
});

Very simple, very generic and it works like a charm. However, suppose that I have to add some radio buttons. The code above will not work with radio buttons, as mentioned before. If you want to uncheck all the radio buttons and checkboxes you will need to add one single line (in bold):

$('#clear-all').click(function () {
	$(':checkbox').each(function () {
		$(this).removeAttr('checked');
		$('input[type="radio"]').prop('checked'false);
	})
});

According to jQuery website the .prop is gets the value of a property for the first element in the set of matched elements or set one or more properties for every matched element. In another words it will look for the "checked" property and, if you want, it can change its value as well.

Easy, simple and clean.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

How to insert many records into the database using Entity Framework (bulk insert)

It's using SqlBulkCopy but as both Entity Framework and SqlBulkCopy belong to ADO.NET...

Posted in Tutorials, Code snippets, Entity Framework

Entity Framework (EF) is a Microsoft ORM which allows programmers to develop against a conceptual data model instead of developing anything inside the database. In this way any change done in this conceptual data model must be persisted as this is not done automatically. For EF we have to use SaveChanges.

To understand EF is simple: A SQL script is generated for every action done against the conceptual model. For example: In case we want to add some record into the User table. For that we would have to use the AddObject method and pass the properties of the User (name, surname, etc) along. Behind the scenes the EF will generate an INSERT and will execute it in the database with the properties of User.

And what about inserting 3.000 records at once?

In this case we have 2 options:

  1. We do a loop and use AddObject for every one of the 3.000 records (not recommended)
  2. We use a class called SqlBulkCopy (deeply recommended)

But why?

The EF doesn't have a native method in case we want to make a bulk insert but, as it was built on top of ADO.NET, there is no problem to use SqlBulkCopy. Not to mention the performance gain if we compare with the multiple INSERTs.

An example of SqlBulkCopy:

Let's just hope Microsoft will add a similar feature into the Entity Framework in the future.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

How to fix "Error in processing. The server response was: Greylisted, please try again in X seconds"

Yes! A solution for this strange error! How many times have you seen this one while trying to send an e-mail?

Posted in Tutorials, C#, Code snippets, ASP.NET

I had a quite interesting Friday. It was the last day of a class in which I had to replace the trainer. They had some problems with him and I was the choosen one for the replacement. Everything went well so far. After that I went to check the error log of my blog (I use Elmah, by the way) and I found an issue I've never seen before:

System.Net.Mail.SmtpException
Error in processing. The server response was: Greylisted, please try again in 240 seconds

The time may vary. But after google it for a while I found it! My server was implementing Greylisting which, according to Wikipedia, is a method of defending e-mail users against spam. So, the non-recognized e-mails are automatically rejected for a while.

And how to fix that?

All I needed to do was to create a mail account on my server and add it to my web.config in the following way:

<system.net>
	<mailSettings>
		<smtp>
			<network defaultCredentials="false" host="Mail@DomainName.com" port="25" userName="username@DomainName.com" password="ThisIsAPassword"/>
		smtp>
	mailSettings>
system.net>

Needless to say, you need to put your own host, username and password. :-)

And that's it.

In time: The answer I found here.

	<system.net>
		<mailSettings>
			<smtp>
				<network defaultCredentials="false" host="mail.davidsonsousa.net" port="25" userName="contact@davidsonsousa.net" password="D#sousa12"/>
			smtp>
		mailSettings>
	system.net>

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

Getting started with Windows Azure

Learn how to get started building applications for Windows Azure with the Windows Azure SDK & Tools

Posted in Tutorials, Windows Azure, Videos

Some time ago a friend of mine recommended me a project which consisted in an iPhone application which would receive the news from a webservice. And, behind the webservice, should exist a Windows Azure app. I had very little time to learn the details of Windows Azure and, after a while, the project was released. The experience was very interesting and satisfying but, since Windows Azure was a very recent technology, there weren't so many material or bug reports where I could look at that time.

And why am I saying that?

Because now, after Microsoft have re-organized itself and moved some people around, Scott Guthrie became the head of Windows Azure team and gave a keynote about Microsoft's newest technology:

The keynote is very interesting and have clarified many points about Windows Azure I didn't know or I have ignored. It's a good start for everyone who would like to dive into cloud computing using the Microsoft stack.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

How to resize images for any resolution (or fluid layout) using CSS

Learn how to resize images for any resolution by simply using CSS

Posted in Tutorials, Code snippets, CSS

When I was creating this layout I wasn't really thinking of mobile devices. Actually I was only thinking about throwing something online as I wanted to start to write. As the days passed by I started to make some tests with Opera Mobile Emulator and I could see that my blog looked horrible in it. Few adjustments later and everything seemed fine.

Until I wrote this post.

The problem was: The images had naturally a fixed size which was bigger than their container. To solve this problem I could simply apply to the images the width of the container. But what about the mobile devices or different resolutions? [more]

The solution for that is very simple: Set the max-width as 90%.

#content article img { max-width:90%; }

In this case, the div #content and the element article (HTML5, anyone?) can have any width as the image will automatically resize until 90% of their size. It means that if the image would have less than 90% of the width it wouldn't be resized. The most important: The ratio doesn't change, as you can see on the print from the emulator bellow.

So, this is the perfect solution for my blog and also for websites where we can't have control of the images which will be uploaded.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

What is NuGet and how to install its packages into Visual Studio 2010

It's very easy to install the Newtonsoft.Json into the project with NuGet!

Posted in Tutorials, Visual Studio

Today I'm gonna talk about a Visual Studio extension which makes things very easy for us developers: NuGet.

What is Nuget?

NuGet (don't mistake with nugget) is a Visual Studio extension which helps the library management and on Visual Studio. It helps a lot to add references to a project and also to keep them up to date.

Example: You are working on a project which needs to use Json and just found an amazing library (Json.NET) which can help you to serialize all List<> as you want to return them in json format. You have 2 choices: 1) Add and update the reference manually always when there is a new version available; 2) Install via Nuget and let it take care of the updates.

Where do I download?

Nuget is normally installed when you download and install ASP.NET MVC 3 but, in case you don't have Nuget yet or it had some problems, you can download it directly from the Visual Studio Galery.

How do I install a library via NuGet?

  1. Using Visual Studio go to the Solution Explorer, right click in References and select Manage NuGet Packages



  2. When the window open you can notice 4 items on the left side:
    1. Installed packages: List of libraries (packages) already installed;
    2. Online: Packages available for download;
    3. Updates: Updates available for your installed packages;
    4. Recent packages: List of packages which you recently used.



  3. Select the Online item (normally pre selected) and use the search field at the right side (Search Online) to look for the desired package. In our case, type Json.NET and wait. The results will appear after few seconds (according to your connection)



  4. Click in Install at the first item. Nuget will download the package automatically and also install it in your project



  5. After finished you can close the Nuget window. Notice that, besides the reference to Json.NET (Newtonsoft.Json) have been added, a file named packages.config was created in the root of the project



  6. This files has the names and versions of all Nuget packages which were added to your project. I would recommend you to not touch it. :)



There is another way to install the packages, which is via command line. If you want to do so just go to  menu View -> Other Windows -> Package Manager Console. When the window open you can just type the command which is written at the page of the project you want to install. For Json.NET the command is Install-Package Newtonsoft.Json.

I honestly prefer to install the packages using the Nuget Manager. It's more centralized and just few clicks far away. Besides, I don't need to open the Nuget website for that. ;)

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

A quick reference for the ASP.NET inline server tags. Great for beginners!

Here is a complete guide of the ASP.NET inline tags. I am sure you will find it useful!

Posted in Tutorials, ASP.NET

I have to tell you: Sometimes I get confused on which server-side tag I should use to make my codes. Normal since I never use all of them so oftem. If you suffer from the same issue this text might be useful as a quick reference.

<% ... %>

The most common of the inline tags. It's used when you need to make some small code on the aspx page or render some expression there. For example:

<% if(isAdmin) { %>
Hello Admin!
<% } %>

<%= ... %>

This is the simplest way to display some information in an ASP.NET page. The equal sign acts as Response.Write rendering the object directly on the page. For example:

Today is <%= DateTime.Now %>

<%: %>

This was implemented in ASP.NET 4 and it's basically the same as above but with one small thing: This server tag automatically does the HTML Encoding for you. So, instead of using Server.HtmlEncode(htmlText) on your code you can simply use as the example:

Here is some html <%: htmlText %>

<%-- ... --%>

This tag is a server-side comment. Since this code is not rendered on the browser you can use it in case you don't want anyone to see the comments you leave on the system. Example:

<%-- Nobody is gonna see this --%>

<%# ... %>

If you want to do some data binding, you have to use this tag. It can be used with DataBinder.Eval(), DataBinder.Bind() or any member which you have in the page (public or protected). The only "problem" is that you have to use these tags only in server-side elements (with runat="server"). You will find this tag being used in some controls such as GridView, DetailsView and Repeater. Example:


    
         <%# Eval("LastName") %>, <%# Eval("FirstName") %>
    

 

<%$ %>

This one is used to evaluate expressions in a configuration file. For example:

    SelectCommand="SELECT * FROM [Employees]"
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString1 %>">

<%@ %>

This tag is used to specify the settings used by the page and user controls. Example:

<%@ Page Language="VB" ContentType="text/xml" %>

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network:

Fixing the annoying IIS error: Cannot open database requested by the login

Cannot open database _Database Name_ requested by the login. The login failed. Login failed for user _User_

Posted in Tutorials, IIS

While I was developing this blog I got a very nice error right after setup the IIS 7 on my machine:

Cannot open database requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\davidsonsousa.net'.

Why does it happens?

It happens because once you create an Application Pool (in my case davidsonsousa.net), the IIS will create a virtual account with its name (IIS APPPOOL/davidsonsousa.net) and run the Application Pool's worker processes under this account. And, I suppose, as the database doesn't have this account setup you will get this error. [more]

How to fix it?

Before you run to your SQL Server and create this account there I would advice you to do the following:

  1. Open IIS Manager
  2. Go to the Application Pools node
  3. Right click on the Application Pool you would like to change and select "Advanced settings..."
  4. Select the "Identity" list item and click the button with the three dots
  5. In the new window, select the Identity Type "LocalSystem" from the combo box
  6. Confirm everything and restart the website.

Now you will be able to run your website without any problems.

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network: