Skip to main content

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 Code snippets, C#, Tutorials, 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 Code snippets, API, Youtube, Tutorials, 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 Code snippets, API, Youtube, Tutorials, 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 Code snippets, API, Youtube, Tutorials, 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 Code snippets, Web Deploy, Tutorials, 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:

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 Code snippets, Tutorials, 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 Code snippets, C#, Tutorials, 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 Code snippets, C#, Tutorials

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:

Horizontal scrolling with jQuery

Learn how to easily make horizontal anchors with jQuery

Posted in Code snippets, Tutorials, 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 Code snippets, Tutorials, 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 Code snippets, Tutorials, 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 Code snippets, C#, Tutorials, 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:

Resize images keeping the aspect ratio in C#

A very useful code snippet which will help you to resize images programmatically in your projects!

Posted in Code snippets, C#

There are some moments while developing an application that we have to stop playing with the usual (CRUD) in order to do something that we aren't used to do. One of these things (in my case) is image editing.

The code below is plain simple and the few comments in it might give you an insight of what is happening. Apart from that, the only hard work you will have is to copy the code and paste into your app. Then you only need to make the proper call and, voilà! Resized image without changing the ratio!!

 

public static void ResizeImage(string originalFile, string newFile, int newWidth, int maxHeight, bool onlyResizeIfWider)
{
	Image fullsizeImage = Image.FromFile(originalFile);
 
	// Prevent using images internal thumbnail
	fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
	fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
 
	if (onlyResizeIfWider)
	{
		if (fullsizeImage.Width <= newWidth)
		{
			newWidth = fullsizeImage.Width;
		}
	}
 
	int newHeight = fullsizeImage.Height * newWidth / fullsizeImage.Width;
	if (newHeight > maxHeight)
	{
		// Resize with height instead
		newWidth = fullsizeImage.Width * maxHeight / fullsizeImage.Height;
		newHeight = maxHeight;
	}
 
	Image newImage = fullsizeImage.GetThumbnailImage(newWidth, newHeight, nullIntPtr.Zero);
 
	// Clear handle to original file so that we can overwrite it if necessary
	fullsizeImage.Dispose();
 
	// Save resized picture
	newImage.Save(newFile);
}

Only remember to save the images in a folder with the proper permissions (read/write) in order to avoid errors.

via DZone snippets

		public static void ResizeImage(string originalFile, string newFile, int newWidth, int maxHeight, bool onlyResizeIfWider)
		{
			Image fullsizeImage = Image.FromFile(originalFile);
 
			// Prevent using images internal thumbnail
			fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
			fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
 
			if (onlyResizeIfWider)
			{
				if (fullsizeImage.Width <= newWidth)
				{
					newWidth = fullsizeImage.Width;
				}
			}
 
			int newHeight = fullsizeImage.Height * newWidth / fullsizeImage.Width;
			if (newHeight > maxHeight)
			{
				// Resize with height instead
				newWidth = fullsizeImage.Width * maxHeight / fullsizeImage.Height;
				newHeight = maxHeight;
			}
 
			Image newImage = fullsizeImage.GetThumbnailImage(newWidth, newHeight, nullIntPtr.Zero);
 
			// Clear handle to original file so that we can overwrite it if necessary
			fullsizeImage.Dispose();
 
			// Save resized picture
			newImage.Save(newFile);
		}

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 Code snippets, Tutorials, 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:

How to create a list of time zones programmatically

It's very easy to create a list of timezones! And that is very useful too!!

Posted in Code snippets, C#

Imagine that you are developing an application which requires the user to choose in which time zone he is located. Now picture yourself adding 40 time zones into a dropdownlist manually.

Unless you need to have the list of time zones in the database you can just use the following code snippet:

public static IEnumerable<SelectListItem> TimeZoneCollection
{
	get
	{
		return new SelectList(TimeZoneInfo.GetSystemTimeZones()
			.Select(q => new SelectListItem
						{
							Text = q.DisplayName,
							Value = (q.DisplayName.Substring(0, 5) != "(UTC)") ? q.DisplayName.Substring(4, 3) : "0"
						}
 
				    ), "Value""Text");
	}
}

Now just bind it into a dropdownlist and voilà.

P.S.: Let me know in case you have improved the code. :)

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: