Home Contact

Jeroen Bourdeaud'hui

web application developer

News

Twitter












Archives

Post Categories

Image Galleries

.NET url

Friends/Other developers

Syndication:

TechDays Belgium 2012


Next month, the TechDays edition 2012 (14-15-16 february)
will take place in Belgium. The last three years, the event passed in Antwerp, but now they are moving to a new location. Kinepolis Imagibraine in Braine l'Alleud (Eigenbrakel).
The location isn't that important.

The hard thing will be, to pick out the most interesting sessions, because there any many sessions in the same time-blocks.
Here is a list of some sessions, i'll certainly attend:

Introducing Windows Runtime in Windows 8
What's new in Visual Studio 11 for Application Lifecycle Management

The Future of C# and Visual Basic

The Developer Story: Platform Futures

Project Roslyn: Exposing the C# and VB compiler’s code analysis

Real world example: integration in the cloud
Windows Phone 7 by Rob Miles









SignalR: example chat application

I remember myself a tweet from Scott Hanselman a couple of months ago, where he asked us to check out a small application he wrote. As one of  the first testers of his new "thing", I was interested but there were no documentation or libs available yet.































A couple of days a go, I read a blogpost from Maarten Balliauw about SignalR. (Maarten's blog). Because I allready heard about SignalR a couple of months ago, I had to develop a very small application to test how it really works.


1. Install SignalR package

You also have to update the jquery package to 1.6.2 or higher

2. Create a chat class

We only want 1 chat instance so use the Singleton pattern, lazy creation because that's thread safe.

    public class Chat
    {
        private readonly static Lazy _instance = new Lazy(() => new Chat());
                public static Chat Instance
        {
            get
            {
                return _instance.Value;
            }
        }
    }

 

3. Create a (chat)hub

Create a class ChatHub which will inherit from Hub


Have a look at the HubName attribute. That's the name you will use in javascript to define the connection.

    [HubName("chatHub")]
    public class ChatHub : Hub
    {
        private readonly int TimeoutInSeconds = 30;
        private readonly Chat _chat;

        public ChatHub() : this(Chat.Instance) { }

        public ChatHub(Chat chat)
        {            
            _chat = chat;
        }
    }

4. Javascript connection

Create a connection between the client and the server. When the connection has been started, we want to call the join method on the server.
var chatHubClient = $.connection.chatHub;
// Start the connection
$.connection.hub.start(function () {
chatHubClient.join('@Model.Name');
});

5. Model

Define a callback method on the server in the Chathub class

        public void Join(string myName)
        {
            if (Chat.Clients.Where(x => x.Name.Equals(myName)).Count().Equals(0))
            {
                Chat.Clients.Add(new Client() { Name = myName, LastResponse=DateTime.Now });
                SendMessageServer(string.Format("{0} entered the chat", myName));
                GetClients();
                Caller.Naam = myName;
            }
            else
                throw new Exception("This login is allready in use");
        } 

Download the Chat Application Example

Get more information on GitHub
Listen to a podcast about SignalR on DotNetRocks

ASP.Net Web Application Administration Website showing error.aspx on startup

To add a new role into my aspnet database, I tried to use the asp.net Web Application Administration Website. But it was showing the following error message:
An error was encountered. Please return to the previous page and try again.

Strange, because I was sure, that my connectionstring was correct.

After a while, after reading about the asp.net Web Application Administration Website, I found that it can't handle spaces or special character in the project path.
My project was located in C:\Users\JEROEN\Documents\Visual Studio 2010\Projects\




Trouble with WCF and X 509 certificates


I played a bit with WCF and security, but I had some trouble to create certificates between the server and the client.

This article helped me out:
9 simple steps to enable X.509 certificates on WCF



How to prevent the user to post page twice, by using refresh

When a user post's data to the server, the page will be reloaded. When the user hits the F5/refresh button, a message appears, which tells us, that we´ve allready sended the data to the server. And asks us if we want to sent it again.
If the user clicks "yes", we have to catch that, we don´t want this in our application


- check that the user can only post something every 2 minutes.
- save the posted data in viewstate and check if something changed
- ...


Or we can check if the user hit the refresh button. I haven't found a way to check this in Javascript, which will work in all browser.

Or our solution is to check it in code. Add the following code, for example in a basepage.

    

     Private _refreshState As Boolean
    Private _isRefresh As Boolean
    Private _terminateRaisePostback As Boolean

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Page.IsPostBack AndAlso _isRefresh Then
            Response.Redirect(HttpContext.Current.Request.Url.ToString(), False)
            HttpContext.Current.ApplicationInstance.CompleteRequest()
            _terminateRaisePostback = True
        End If
    End Sub

    Protected Overrides Sub LoadViewState(ByVal savedState As Object)
        Dim AllStates As Object() = CType(savedState, Object())
        MyBase.LoadViewState(AllStates(0))
        _refreshState = Boolean.Parse(CStr(AllStates(1)))
        _isRefresh = _refreshState.Equals(CBool(Session("__ISREFRESH")))
    End Sub

    Protected Overrides Function SaveViewState() As Object
        Session("__ISREFRESH") = _refreshState
        Dim AllStates() As Object = New Object(2) {}
        AllStates(0) = MyBase.SaveViewState
        AllStates(1) = Not (_refreshState)
        Return AllStates
    End Function

    Protected Overrides Sub RaisePostBackEvent(ByVal sourceControl As System.Web.UI.IPostBackEventHandler, ByVal eventArgument As String)
        If Not _terminateRaisePostback Then
            MyBase.RaisePostBackEvent(sourceControl, eventArgument)
        End If
    End Sub


How to Encrypt connection string in web.config

A couple of years ago, I used 'something' to encrypt the connectionstring on a production server. But I never wrote anything down about it. And in the other projects I did later, I never had deploy to the production server. 

Yesterday, I had to use it again but I couldn't find it. Why? Because I never wrote about it. This blogpost is copy of Chirag Darji post about the encryption of the connectionstring in web.config. All credits to him!

 

The most sensitive information stored in web.config file can be the connection string. You do not want to disclose the information related to your database to all the users where the application is deployed. Every time it is not possible to have a private machine for your sites, you may need to deploy the site in shared host environment. To encrypt the connection string in above situation is advisable.

ASP.NET 2.0 provides in built functionality to encrypt few sections of web.config file. The task can be completed using Aspnet_regiis.exe. Below is the web.config file and <connectionStrings> section.   


<connectionstrings>		
	<add name="cn1" connectionstring="Server=DB SERVER;
	database=TestDatabase;
	uid=UID;
	pwd=PWD;">
</connectionstrings>		

Fig – (1) Connection string section of web.config file

     To encrypt the connection string section follow the steps,

1. Go to Start - Programm Files -> Microsoft Visual Studio 2005 -> Visual Tools
    -> Microsoft Visual Studio 2005 Command Prompt

2. Type following command,

    aspnet_regiis.exe -pef “connectionStrings” C:\Projects\DemoApplication

    -pef indicates that the application is built as File System website.  The second argument is the name of configuration section needs to be encrypted. Third argument is the physical path where the web.config file is located.

   If you are using IIS base web site the command will be,

   aspnet_regiis.exe -pe “connectionStrings” -app “/DemoApplication”

 -pe indicates that the application is built as IIS based site. The second argument is the name of configuration section needs to be encrypted. Third argument “-app” indicates virtual directory and last argument is the name of virtual directory where application is deployed.   

   If everything goes well you will receive a message “Encrypting configuration section…Succeeded!”

  Open your web.config file and you can see that connection string is encrypted,


<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
	<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
   	xmlns="http://www.w3.org/2001/04/xmlenc#">
   		<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />		
		<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"> 
			<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
				<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
				<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
					<KeyName>Rsa Key</KeyName>		
				</KeyInfo>
  				<CipherData>
 					<CipherValue>Ik+l105qm6WIIQgS9LsnF8RRxQtj2ChEwq7DbHapb440GynFEoGF6Y3EM3Iw/lyDV8+P8bIsketi5Ofy9gpZlCBir7n315Q6RPbdclUo79o/LKadhX4jHFpnSIQNIF/LhwjwkLFC0=</CipherValue>
	 			</CipherData>
 			</EncryptedKey>
  		</KeyInfo>
  		<CipherData>
  			<CipherValue>JsLrQ5S8Pq3U72nQzmSl/XlLX72GM0O3EbPLaHRNvjTDgG9seDflGMjTfO10M1s7/mPh//3MhA7pr0dNHUJ143Svhu5YXODRC6z9CkR0uyE4H7uDvTKJ8eR3m9APhXoo1sT1K3tCLHD6a2BM+gqSk9d8PzCfbM8Gmzmpjz1ElIaxu62b4cg9SNxp8o86O9N3fBl2mq</CipherValue>
  		</CipherData>
  	</EncryptedData>
</connectionStrings>

Fig – (2) Encrypted connection string section

 

       You do not have to write any code to decrypt this connection string in your application, dotnet automatically decrypts it. So if you write following code you can see plaintext connection string.

Response.Write(ConfigurationManager.ConnectionStrings["cn1"].ConnectionString);

 

    Now to decrypt the configuration section in web.config file use following command,

For File System Application,

aspnet_regiis.exe -pdf “connectionStrings” C:\Projects\DemoApplication

For IIS based Application

aspnet_regiis.exe -pd “connectionStrings” -app “/DemoApplication”

 

    If you want to encrypt any nested section in web.config file like <pages> element within <system.web> you need to write full section name as shown below,

aspnet_regiis.exe -pef “system.web/Pages” C:\Projects\DemoApplication

     You can encrypt all the sections of web.config file except following using the method I displayed in this article,

<processModel>
<runtime>
<mscorlib>
<startup>
<system.runtime.remoting>
<configProtectedData>
<satelliteassemblies>
<cryptographySettings>
<cryptoNameMapping>
<cryptoClasses>

   To encrypt these section you needed to use Aspnet_setreg.exe tool.  For more detail about Aspnet_setreg.exe tool search Microsoft Knowledge Base article 329290, How to use the ASP.NET utility to encrypt credentials and session state connection strings.

 

Source



Just to remember: new Guid() != Guid.NewGuid()

Just to remember:


 

when you want a new guid:

Dim g As New Guid()

--> the value of g is empty

Just call:

Dim g As Guid = Guid.NewGuid()

and everything works fine!



Paging using Linq

Last, I needed a function to add paging. The first problem I had, was how to this.
A couple of seconds later, I allready had a solution to this problem: Linq

Skip and take will do the trick.

list<t>.Skip(_howManyRecordsDoYouWantToSkip).Take(_howManyRecordsDoYouWantToTake)

This won't crash if you pass one of both statements. It will just return the result.

source.Skip(startRowIndex).Take(pageSize)

I've created an extension method to use this function.

 VB


     Module LinqHelpers
        <System.Runtime.CompilerServices.Extension()> _
        Public Function Page(Of TSource)(ByVal source As IEnumerable(Of TSource), ByVal startRowIndex As Integer, ByVal pageSize As Integer) As IEnumerable(Of TSource)
            Return source.Skip(startRowIndex).Take(pageSize)
        End Function
    End Module


 C#


public static class LinqHelpers
{
    public static IEnumerable Page(this IEnumerable source, int startRowIndex, int pageSize)
    {
            return source.Skip(startRowIndex).Take(pageSize);
    }
}

 

Change IEnumerable to IQueryable if you want to use Linq to SQL.

Take care about the traffic, if you use large lists and add paging at runtime. You'd better select the rows you want to show! (IQueryable)

 



Code Retreat Belgium

Last saturday I participated the Code Retreat organised by Agileminds.be
There were 6 code retreats at the same moment arround the world. In Belgium, UK, Spain, USA and  2 in Romania.

We all had the same challenge, to implement the Conway's Game of Life. By writing beautiful code, using TDD .

For me, TDD is a new thing. I allready read about it, but thinking in a TDD way is really different and difficult. 
I met interesting people, and it was great to skype with the other Code Retreat around the world. We had people working the .Net framework (C# and vb.net), Java, Python, Ruby and it was great to work/test in other frameworks.

In the future I will try to apply some of the best practices defined by TDD, but it will be hard.

Thanks to Adrian Bolboaca, Erik Talboom and the other participants to introduce me in TDD.
Hope to see you again at one of the following Code Retreat.


You can check Code Retreat on twitter:  #coderetreat
Or on http://coderetreat.ning.com

Some pictures of the event in Belgium:

 yfrog.com/user/talboomerik/photos



Community Day 2011

The next community day event will be on 23rd of June. I will attend this event.
Spread the word about this free event and subscribe!

For more information: www.communityday.be
www.snowball.be/2011/04/21/Community+Day+2011+Is+Coming+Closer+Save+The+Date.aspx