Skip to main content

What is the difference between Reference Types and Value Types?

Here is where you will understand the difference between a Class and a Struct. Also the difference between Stack Memory and Heap Memory.

Posted in C#, Back to basics, .NET Framework

Before we talk about the differences between Reference Type and Value Type we need to understand some basic things.

What is a data type?

A data type is a format which can contain some specific type or range of values. Basically, whenever you are declaring your variables you must assign some specific data type, as described here. On .NET Framework we have 2 data types: Reference Type and Value Type.

Stack Memory and Heap Memory

There are 2 different types of memory we will talk about: Stack Memory and Heap Memory. While the Stack Memory receives the values using FILO (First In, Last Out) the Heap Memory is much more like an unorganized set of boxes in a room. This means that the access to the Stack Memory will be much faster than the Heap Memory. And here is the catch: The Stack Memory is where the Value Type stays. And the Heap Memory is where the Reference Type stays.

One thing to keep in mind: The Heap Memory is cleaned by the Garbage Collector, which means that Reference Types will be disposed automatically.

What is Reference Type?

Reference Type is the type of data which makes a reference to where the value is placed.

A class is an example of reference type. If we copy a class into another class of the same type and change the values of the latter we will end up changing the values of the first one. This happens because the 2 classes are pointing to exactly the same place.

What is Value Type?

Value Type is the type of data which holds the actual value of the object.

A struct is a good example of value type. If we follow the logic used above (copy a struct into another struct and change the values of the latter) we will realize that we didn’t change the value of the first struct. This happens because we literally copied the values from one object to another.

If you want to see it working make sure to go to my GitHub repository and download the code: https://github.com/davidsonsousa/Back-To-Basics/tree/master/ValueAndReferenceType

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 are and how to use variables in C#

A short text explaining the basics of this every day necessity

Posted in C#, Back to basics

Every program you decide to write will use data at some point. I am not talking about databases nor web services. I am talking about plain simple variables.

To put it simple: Variables are nothing more than a named place in the memory where you store something to use later. Think of a box with a name in it and which accepts only certain kind of objects. For example: A box named "balls" which accepts only spherical objects.

In C# we have the following types:

  • Integral: sbyte, byte, short, ushort, int, uint, long, ulong, and char
  • Floating point: float and double
  • Decimal: decimal
  • Boolean: true or false values, as assigned
  • Nullable: Nullable data types

Define your variables

You can define your variables in 2 ways:

  1. [type] [variable_name], [variable_name]; (eg.: string name, surname;)
  2. [type] [variable_name] = [variable_value]; (eg.: string name = "Joe";)

The first one is used when you want to define one or many variables at once, without setting a value. The second alternative can be used when you want to initialize the variable already during its declaration.

Default values

As mentioned above, we can define our variables without initializing it (setting a value). In case we do it, however, we need to pay attention to the default values which each object has. See below:

  • bool: false
  • byte: 0
  • char: '\0'
  • decimal: 0.0M
  • double: 0.0D
  • float: 0.0F
  • int: 0
  • long: 0L
  • sbyte: 0
  • short: 0
  • uint: 0
  • ulong: 0
  • ushort: 0

Notice the letters beside some of those default values. Normally the compiler will require you to specify what kind of value you are assigning to a type. And in order to tell it to the compiler that you want to assign a, for example, double instead of a float you need to add the D in the end of the number.

Sources: MSDN, Tutorials point

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

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

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

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

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: