Example for extension methods in C#

Today I found one real world example for using extension methods in C#.

Maybe you know this code snippet from your own code:
If(object != null)
{
MessageBox.Show(„Value:“ + object.ToString().Trim());
}

I think it looks way to complex, for this stupid task.
Now lets write a extension method which checks for us

=> if the object is null return an empty string

=> if the object is a whitespace string return an empty string too

=> if the object is a normal string, returns it but with a automated trim() to remove annoying white spaces.

How to achieve that:

1. Create a public static class called „StringOptimizer“ and then create the function ToStringIntelligent.

public static class StringOptimizer
{
public static string ToStringIntelligent(this object _object)
{
if (_object == null)
{
return string.Empty;
}
else
{
return _object.ToString().Trim();
}
}
}

See the extension in the parameter _object. You use this before parameter declaration, that’s all.

Now to call this function your just do this:
Console.WriteLine("Value:" + item.ToStringIntelligent());
Note, no validation have to happen here, cause we do it in the extension method already. Extra plus is, that this method actually works with all types that derives from object, so you can use it with your string variables as well. Of course, we could use string.IsNullOrEmpty() function from the .NET framework, but I like to do the validation in just one method, instead of writing validation code for all string objects manually.

Another example is here on codeproject

Software architecture in .NET Entity Framework app.

First I was a little bit confused how to structure my applications when I use .NET EF.

Here’s a good video where you’ll extract your Entity Framework Model to a separate class library, which makes it easier to update clients or reuse your model in other projects like WPF Service, WEB, etc.

If you need further Business Logic you can follow this articles.

Cheers!

Start with prototyping Today!

I couldn’t believe that there is no complete free mockup app out there. And I was right. After wasting a lot of time with searching I found one, which fulfilled all my dreams <3: Pencil

Why I love it:
– Easy to use
– All relevant shapes for Desktop GUI, Web, IPhone, etc
– Open source

Check it out:

http://pencil.evolus.vn/

Introduction to Microsoft’s Entity Framework (Database First)

Great Video and Description about the Database First Approach with the Entity Framework. I used it already in my last project about a little web reporting tool in MVC 4 and I was really impressed how easy and powerful it is.

Check it out:
http://msdn.microsoft.com/en-us/data/jj206878

Cheers!

Make a .NET Assembly run as COM-Server

Because it’s the second project about COM i decided to write a short article about it. Com is great for extending old projects with great and creative .NET code 😉

How to achieve that:

1. Write a normal Class Library with Visual Studio

2. Mark your class with this attributes

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IUserHelper))]
[Guid("9602F34A-3E49-4A84-A408-5B8C67B3CE4D")]
public class UserHelper : IUserHelper
{

//Your Class Code

}

3. Implement an interface for your class with all your methods and properties that should be accessible via COM

[Guid("YOURGUID")]
[ComVisible(true)]
public interface IUserHelper
{
void SomeMethod(int param1, string param2);
}

4. Build your library

5. Use regasm.exe to register the dll. I use

regasm.exe "PathToDll.dll" /codebase /regfile

5. Execute the generated .reg file for creating all needed registry keys

6. Test your COM Server via a little vbScript

SET obj = CreateObject("NAMESPACE.CLASSNAME")
obj.METHODNAME Param1,"Param2"
MsgBox "Well done!"

 
Notes: Never ever use the VS tools like  „Make Assembly Com-Visible“ or „Register for COM interop“. It drives me crazy and is a waste of time at all. Keep in mind that this example is for platform target „Any CPU“. You should register it with reagsm.exe 32 bit wich is located in C:\Windows\Microsoft.NET\Framework\v4.0.30319. 64 bit version of regasm.exe is here: C:\Windows\Microsoft.NET\Framework64\v4.0.30319

Great article in .NET Pro (German):

http://www.dotnetpro.de/articles/onlinearticle4266.aspx

Regasm.exe reference:

http://msdn.microsoft.com/de-de/library/tzat5yw6(v=vs.80).aspx

Switchable desktop and mobile view in MVC projects

Scott made an awesome article about implementing a switchable desktop and mobile view in your MVC projects.

Additional hints:

The solution above provided doesn’t work for android phones. Add this code in your Global.asax to get it done.

DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("Mobile")
{
ContextCondition = ctx => ctx.GetOverriddenUserAgent().Contains("iPhone") || ctx.GetOverriddenUserAgent().Contains("Windows Phone OS") || ctx.GetOverriddenUserAgent().Contains("Android")
});

How to use AJAX in .NET MVC projects

When developing Web Projects one point you should always keep in mind is this: A great web project makes the user feel, that there is no web. You created a good user-experience when they just forget that they are working in a browser.

One way to achive that, is using AJAX as often as possible

Why? Because Page Load is a user experience killer. The complete page refreshes which is awful in UI and even worse for us programmers, cause we have to store user selections in our viewdata and so on. Very bad. Using ajax and refreshing only parts of your site makes the user feel comfortable and is actually easier for us programmers.

Code in your javascript file (I recommend to generate extra javascript files, to keep your views clean)

function drawChart(month, year) {
$.ajax({
url: '/YOURCONTROLLER/YOURMETHOD',
type: 'POST',
data: { param1: month, param2: year },
dataType: 'json',
success: function (data) {
//Make something with your data
}
})
};

Then in your Controller your functions should look like this

public JsonResult GetChartData(int month = 0, int year = 0)
{
//Generate or get your data from db
return Json(data);
}

Thats all. Easy and powerful.

Now, one last thing is your UI behavior. When you gather your data from a database you should display a loading panel or something like that, so your users know what’s going on. A great way to do this, is using the BlockUI Plugin for jQuery

Here you can see some demo cases:

http://www.malsup.com/jquery/block/#demos

And here is some example code (As mentioned above I recommend to extract all javascript and jquery code in separate files to keep your views clean!)

http://www.malsup.com/jquery/block/#page

Easy to use and looks very great. We’re in developers heaven 😉

Start with .NET MVC 4

.NET MVC is the first Microsoft technology which is really well documented and with practical samples. Beside that i like the architecture which is really simple but powerful. I never want to write a .NET ASP Project again.

Here you find all what you need to start:

http://www.asp.net/mvc

I highly recommend the Music Store Tutorial: http://www.asp.net/mvc/tutorials/mvc-music-store

Well done, Microsoft! (I don’t‘ say that, that much :))

Just another dev blog

BAM! I made it! I’m a fucking dev. Blogger. This is awesome! And i do it in english. Not only to be cooler, its just solidarity you know^^. There are so many awesome dev Bloggers out there and they saved my ass a dozen times. Well….time to give something back! Hope you’ll enjoy it! Special thanks goes to Scott Hanselman. He inspired me to this.

PS: Don’t care about the million spelling and grammer mistakes. Communication is fault tolerant. Hopefully. I’m still improving!

 

Keep the faith fuckers!