Archive for the “C#” Category

Something not many people know: when you need to compare 2 strings in C#.NET you can use the == operator overload:

if(firstString == secondString)
{
    //...
}

This is case sensitive. But when you need to ignore the case please don’t use this:

if(firstString.ToLower() == secondString.ToLower())
{
    //...
}

or this:

if(firstString.ToLower().Equals(secondString.ToLower()))
{
    //...
}

A Framework provides you with utilities, please use them. They are usually better than your implementation!

Use this:

if (firstString.Equals(secondString, StringComparison.OrdinalIgnoreCase))
{
    //...
}

StringComparison is an enum. So please look at the options :)

Comments 1 Comment »

(scroll down for an in depth explanation)

I’m writing this post since I had a lot of problems finding out how Model binding works in ASP.NET MVC.

This behavior has changed in the beta and the final. This causes that some blog posts on the internet are inaccurate.

But let’s set things straight.

Create a MVC Project, leave everything default and add Product in your Models folders with the following (very simple) code:

namespace BlogPost.Models
{
    public class Product
    {
        public string Name { get; set; }
    }
}

Then add a ProductsController (in the Controllers folder) with the following code:

using System.Collections.Generic;
using System.Web.Mvc;
using BlogPost.Models;

namespace BlogPost.Controllers
{
    public class ProductsController : Controller
    {
        public ActionResult Add()
        {
            return this.View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Add(IList<Product> products)
        {
            return this.View();
        }
    }
}

And add the following view for the Add function:

image

With the following markup:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Add up to 10 products to the database
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        Add up to 10 products to the database</h2>
    <%
        using (Html.BeginForm())
        {
            for(int x = 0;x <= 9;x++)
            {
                %>
                <fieldset>
                    <legend>Product <%=x %>:</legend>
                    <input type="text" name="products[<%=x %>].Name" />
                </fieldset>
                <%
            }

            %><input type="submit" name="submitForm" value="Save products" /><%
        }
    %>
</asp:Content>

Now put a breakpoint in the Add function in your ProductsController that handles the Http Post.

image

Hit f5 and go to <your url>/Products/Add:

image

Enter 10 names, and hit the submit button at the bottom.

Visual Studio will break on your this.View(). Hover over your products parameter and you’ll see something in the lines of this:

image

Not too hard is it?

A little bit more in depth:

ASP.NET MVC binds your HTML input to your parameter through the default model binder. I recommend you read the source code available on http://aspnet.codeplex.com/SourceControl/changeset/view/23011

image

If you want to step through the source code using your application I refer you to Steve Sanderson’s excellent blog post.

If you take a look at the generated HTML source code you’ll notice this:

<fieldset>
    <legend>Product number 0:</legend>
    <input type="text" name="products[0].Name" />
</fieldset>
<fieldset>
    <legend>Product number 1:</legend>
    <input type="text" name="products[1].Name" />
</fieldset>

The name ‘products’ is VERY important, since this specifies that it your input should be bound to the ‘products’ parameter in your controller action.

Then the index between brackets: IT MUST START FROM 0 AND BE CONTINUES!

Then the .Name, which specifies that your input should be placed in the Name property (not just a public variable, but a property with a get/set) (see code above).

You can repeat this for multiple properties, and group them by product.

That’s it for simple model binding.

Hope it helps.

Comments 2 Comments »

What’s the difference?

object dinner = new Dinner();
Dinner myDinner2 = (Dinner) dinner;
Dinner myDinner = dinner as Dinner;

Well, the first cast (which is really a cast) throws an error if dinner is null.

The second one doesn’t, so you have to check that by yourself.

Also see the MSDN reference on the ‘as’ keyword.

Comments No Comments »

Today I bumped into this problem at work. I had a label on a form and I had to display an employee’s department.

Quite easy, but the department sometimes contains an ampersand. And that ampersand was not displayed. I went looking for this problem and I bumped into this property (in System.Windows.Forms.Label): Label.UseMnemonic Property

Setting this property true means: an ampersand that precedents a character underlines that character, so that it can be used in conjunction with the alt key.

The problem arises when you for example pull a department from the database with an ampersand (for example: shipping & hauling). Putting this into the label causes the & not to be displayed since the label assumes that the ampersand means ‘underline the character after the ampersand’.

To display the ampersand you’ve got two choices:

  1. set UseMnemonic to false so that it doesn’t parse the ampersand.
  2. if you need the mnemonic: replace the & with &&, that displays 1 ampersand in the label.

Comments No Comments »

When creating one to many relationships one might bump into the following problem:

Consider the following database design:

Tables:

Customers
-Id
-FirstName
-LastName
-…snip…
-City

Cities
-Id
-Name
-Zip

With a many to one relation from Customers.City to Cities.Id

While this is easy to do in SQL, the LINQ to Entities syntax might seem a bit different.

Consider the following piece of code:

City c = (from city in ctx.CitySet
where city.Name == cityName && city.Zip == cityZip
select city).FirstOrDefault();

This selects the city (if it exists) or null.

Now the problem is: IF the city exists, how do I point the current customer’s city to that particular city.

I tried this:

//customer is a customer object
customer.City = c;

But that resulted in duplicate cities in the database.

The solution was actually quite easy, I browsed through all the properties (Intellisense!) and found this:

customer.CityReference.EntityKey = c.EntityKey;

This resulted in the one to many relationship I had in mind. No duplicate cities in my database.

I love database normalization!

Comments No Comments »

Rick Brewster made this comment on my previous post about the Inconsistent FileDialogs.

So I decided to fire up his solution:

I’ve created an empty WPF project, with a Window called ‘Main’ with the following code:

using System.Windows;
using Microsoft.Win32;

namespace OpenFileDialogNewStyle
{
	///

	/// Interaction logic for Main.xaml
	/// 

	public partial class Main : Window
	{
		///

		/// Constructor
		/// 

		public Main()
		{
			this.InitializeComponent();

			OpenFileDialog myOpenFileDialog = new OpenFileDialog();

			myOpenFileDialog.ShowDialog();
		}
	}
}

This opens the ‘old’ style FileDialog, with the outdated icons.

old-filedialog

To resolve this you can add a manifest in your project:

add-manifest

The manifest should be named NameOfYourStartUpProject.exe.manifest (as pointed out above), it should be a text file containing the following code:



	
	Description
	
		
			
		
	

Change the name on the 5th line to the name of your project!

Now go to properties and point to the manifest.

select-manifest

Now compile, and test if you see the new type icons :)

new-filedialog

Comments No Comments »

(My friend Peter pointed me to this so I am writing this on his behalf)

Basic setup:

A simple application, an SDF (Microsoft SQL Server Compact file) and the Entity Framework.

So I created the project, added the files, created the tables, made a model, and wrote this class:

namespace LinqToEntities
{
	class Program
	{
		static void Main(string[] args)
		{
			using (Database1Entities ctx = new Database1Entities())
			{
				Test myTest = new Test() { Value1 = "Blah", Value2 = "Blah2" };

				ctx.AddToTestSet(myTest);

				ctx.SaveChanges();
			}
		}
	}
}

And this gives me a nice error on ctx.SaveChanges();sqlserver-ce

(Big image!!!)

The problem is not the database, like the error says. But the problem is that the EF just doesn’t understand it.

Here are some ‘workaround’, I quote it because I don’t really consider them a workaround.:

  • Disable autoincrement, and manually fetch the highest id, and then insert. This could lead to corruption if you are in a multi threaded  environment.
  • Use a SqlCeCommand

But it’s a breaking issue I think, and I hope they fix it in the next version.

Comments 1 Comment »

You might run into this problem:

When you try to make an Open/SaveFileDialog on in a WPF program, you might see that the dialog is displayed with the old graphics:

savefiledialog

*yuk*

This seems to be caused by a detection inconsistency somewhere inside the Microsoft.Win32.

To solve the problem you could manually add a Reference to System.Windows.Forms, and use the System.Windows.Forms.OpenFileDialog or the System.Windows.Forms.SaveFileDialog.

This will display the beautiful Open/SaveFileDialog on Vista 64-bit.

Good luck :)

Comments 3 Comments »

struct MyStruct
{
	public int X { get; set; }
	public int Y { get; set; }

	public MyStruct(int x, int y)
	{
		this.X = x;
		this.Y = y;
	}
}

Will trigger an error on line 8:

The ‘this’ object cannot be used before all of its fields are assigned to

So I thought I might fix it by assigning a value to the fields. Since we have automatic properties, let’s convert them to normal properties:

struct MyStruct
{
	private int _x = 0;
	public int X
	{
		get
		{
			return _x;
		}
		set
		{
			_x = value;
		}
	}
	private int _y = 0;
	public int Y
	{
		get
		{
			return _y;
		}
		set
		{
			_y = value;
		}
	}

	public MyStruct(int x, int y)
	{
		this.X = x;
		this.Y = y;
	}
}

Let’s press F5. Oeh noes, another error:

‘MyStruct._x’ cannot have its instance field initializers in structs

So you can’t do field initialization in a struct (apart from in a function / constructor / getter / setter).

Let’s go back to the first piece of code and make it work by adding 7 characters:

struct MyStruct
{
	public int X { get; set; }
	public int Y { get; set; }

	public MyStruct(int x, int y) : this()
	{
		this.X = x;
		this.Y = y;
	}
}

The this() initializes the struct, and in the constructor itself the struct’s vars & properties are set to their default values. It’s weird though that an int needs initialization…

Comments 1 Comment »

Does not work.

Outlook.Application and Outlook._Application are both interfaces. And I want to use them as a class in my program (I don’t know how they made that work).

I wanted to extend Outlook.Application and add a simple method to create a new email. But that does not work since you have to implement a bunch of methods which I hardly understand.

Thank Microsoft for creating extension methods, so here is my solution:

using System;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace SendToExtended
{
	static class OutlookExtensions
	{
		///

		/// Creates and returns an Microsoft Outlook MailItem
		/// 

		///
an instantiated Outlook application
		/// A new MailItem object
		public static Outlook.MailItem CreateMailItem(this Outlook.Application outlook)
		{
			if (outlook == null)
				throw new ArgumentException("outlook parameter cannot be null");

			return (Outlook.MailItem)outlook.CreateItem(Outlook.OlItemType.olMailItem);
		}
	}
}

Comments No Comments »

And shepherds we shall be, for thee my Lord for thee, power hath descended forth from thy hand, that our feet may swiftly carry out thy command. We shall flow a river forth to thee, and teeming with souls shall it ever be. In nomine Patris, et Filii, et Spiritus Sancti.

headless horseman worksheets

letters requesting endorsements

multiplication printable worksheets

form letters template

hope center for youth texas

mass ufo sightings

letter holder decorative

sample acceptance job letter

examples of written warning letters

ufo news sceptical enquierer

words used for letters of alphabet

old missing goverment plane ufo

mission statement worksheet

four seasons maui day of hope

astronaught aliens

memorial letter sent after death

scooby doo worksheets for children

payson utah ufo wierd happenings

reading worksheets grade 1

stop forclosure hardship letter

fraction worksheets grade5

berkley wellness letter

fasfa worksheets

beginning worksheets for high school readers

language arts worksheet

without hope

ertes letter a print

beef o brady's hope mills nc

letter g sign

vowel print letter practice sheets

letter de scrambler

sample letter to credit reporting agencies

hope cestrone

fables arnold lobel worksheet

ghetto bubble letters

hope dream wish

paranoid personality disorder hopes

annual lease value worksheet

fourth of july independence day worksheets

physics themed movies worksheet

ufo contact from pleiades

alphabet soup wall letters

legal resident aliens

scale drawings worksheets furniture

dressage movements ten letters

cognitive behavioral depression worksheet

funny letter from boy scout

city of hope uae

september hope

ufo clode encounters diamond

phoenics printables

atom printable

printable brackets 2009 basketball

stand-ins printable

printable marriage certificates

free printable travel games for kids

printable english garden

free printable coupons for cesar canine

reading printables for halloween

printable divine office bookmarks

printable applebees coupon

printable english skill sheets

printable taget

printable map pacific islands

star printable

geoboard printable

printable volleyball line up sheets

free printable coloring pages sport

printable diego button

free printable online maths crossword puzzles

printable humorous fiction stories eighth grade

printable blank bracket forms

new years printable

printable novelitys

printable computer monitor calendars

thomas printable

asia printables

printable gothic stationary

printable summer memory game

digital audio cd-r injet printable hub

free printable last will and testament

clip art printable business check

printable timeline

printable millimeter scales

free printable christmas letterheads

free printable quizes

caterpillar printables

tornado photos printable

printable question mark sign

estimation printables

printable offer

printable pet vaccine record

earthweek printable

printable frame

tj maxx printable coupon

free printable dollhouse miniatures

autozone printable

kenken printable

third grade printable worksheets

printable daytime sequencing worksheet

printable callanders

printable elevation maps

winnie the pooh printables page

picasso printable

anime printable

barn printables

printable calenda

hpc mmal card printable version

olympia sports store printable coupons

printables money for kids

printable teen devotional

kinder printable

kids math problems printables

punctuation printables

free printable worksheets for books

employment printables

printable ohio state buckeye logo

free printable activities about chi

printable coloring pages of fish

free printable colorful calenders

printable julian date calendar

printable walmart application

printable country songs

printable cardboard

printable picture of car racing flags

printable story groundhogs day

free printable dragon pictures to color

proctor gamble printable coupons

printable frames for scrapbooking

target 10 off printable in-store coupon

free printable first then

free printable 5-day planner

soup and hand printable coupon

printable facts mardi gras

printable radiation signs

printable map pikeville ky

chinese new year printables for kids

printable manuscript writing sheets for abcs

printable coupon for atkins morning bar

printable pattern of a rose

a printable redneck diploma

kindgergarten printables

naming objects printables

printable alphabet dot to dot

printable tanglewords

lowes printable coupon wow

printable coloring mandalas pages

printable picture of niagara falls

starbucks frappuccino 4 pk printable coupon

printable soduku

michael jacksons printable photos

domino printables

printable ant activities

conservation printables

kohler printable coupons

printables art

printable ncaa

brown bear brown bear printables

pharmacy coupons retail printable

disney printable pumpkin patterns

printable cooking border writing paper

printable invitations

printable t-shirt

printable fruit

printable fantasy football draft sheet

printable ab workout

nebraska printables

free printable graduation cards

printable advanced english grammar exercises

printable list sms and text lingo

printable good manners pictures for kids

bible character word search printable

printable address albels

printable golf gift certificate template

print custom printable coupons

free printable pre-algebra worksheets

printable label

printable coloring pages of water

religious easter printables for kids

printable preschool biting activities

printable piano worksheets

printable do not enter signs

printable coupons gander mountain

printable superbowl square pool grids

jonathan mccoy n-word printable

party city printable coupon april

printable notepaper

fchristian printables

free printable business card templates

taco johns printable coupons

colorwheel printables

hidden picture printables

printable layouts

printable travel checklist

printable coloring pages of spongebob

printable brain

ups printable logo

printable camo

printable sign in sheet

pentominoes printables