Connecting your LDAP to ClicData

With the February update (17/02) of ClicData comes the ability for our DataLoader to connect to your LDAP directory.

DataLoader can connect from any machine that is in the LDAP domain or outside of it as long as it can connect to the LDAP server.

Connect to any LDAP server using any credentials
Connect to any LDAP server using any credentials
You can also leave all the fields blank ; DataLoader will connect to the domain server as the current user
You can also leave all the fields blank ; DataLoader will connect to the domain server as the current user

Once the connection is established, you can use any standard LDAP filter to fetch anything you like.

That’s all there is to it – get data from your LDAP domain in ClicData in a matter of minutes!

LDAP Users imported into ClicData
LDAP Users imported into ClicData

Happy Dashboarding with ClicData!

Could not establish connection to IIS Server. Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)). (or Invalid namespace)

You are setting up a new server with IIS and you have another server doing remote stopping/starting of the websites, and you’re getting the following error:

Could not establish connection to IIS Server. Access is denied.

or

Could not establish connection to IIS Server. Invalid namespace.

In my case, our FinalBuilder server was throwing this error trying to stop a remote IIS website.

What you need to do is enable the IIS Management Scripts and Tools role of your IIS server:

iismanagementscriptandtools

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable.

I’ve been struggling (a little) with this one yesterday and the solution to this turns out to be pretty dumb so here’s why you may be getting this error.

In a .NET project, you are using Entity Framework / Linq to Entity and you are trying to delete an object from a related collection:

myOrderEntity.OrderDetails.Remove(myOrderDetailsEntity)

You’d think removing the object from the collection should remove it from the database (too much MVVM thinking huh?). Unfortunately, calling the context SaveChanges method throws the following exception:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

The reason: the above line of code only tries to break the relationship between the 2 objects. But because the foreign key is NOT NULL, you’re getting this exception.

The fix: to actually delete the object from the database, you need to do the following:

myContext.OrderDetails.DeleteObject(myOrderDetailsEntity)

Javascript – How to pass a function parameters in setTimeout (when the number of parameters is variable)

Let’s assume the simple following problem:

function DoIt(/* any number of parameters is accepted */) {
    var args = Array.prototype.slice.call(arguments, 0);
    if (ready) {
        DoStuff(args);
    } else {
        // how to repeat the current call to DoIt, with given parameters?
    }
}

The DoIt function takes a variable number of parameters, and passes them to the DoStuff function only when ready, a global variable, is set to true. The question is, how to replay the call, i.e. call DoIt with the same parameters? The answer is the following:

setInterval(function () { DoIt.apply(this, args); }, 1000);

This will replay the same call to DoIt one second later, with the same parameters.

Of course, if the number of parameters of the DoIt function was not variable, we’d get away with the following simple solution:

function DoIt(param1, param2) {
    if (ready) {
        DoStuff(param1, param2);
    } else {
        setInterval(function () { DoIt.apply(param1, param2); }, 1000);
    }
}

Using WebSockets in .NET 4.5 and HTML5

HTML5 introduced WebSockets, a TCP full duplex channel between a browser and a server. Modern browsers now largely support WebSockets (see support table) and you can always use one of the numerous polyfills to ensure compatibility with older browsers.

WebSockets have been around for a long time but it took a lot of plumbing to have a .NET server up and running before .NET 4.5. Thanksfully, .NET 4.5 introduced the WebSocket class, making it really easy to create a server. Here’s what you need to do to run a WebSocket server.

On the server

First make sure that your WCF web.config has the following:

<system.web>
	<httpRuntime targetFramework="4.5" />
</system.web>

Then creating a socket server is as easy as adding a Generic Handler (.ashx) to your project. The full code for a simple server that tracks who is connected to the server is the following:

Public Class WebSocketHandler
    Implements System.Web.IHttpHandler

    ' List of all connected sockets
    Private Shared users As New List(Of WebSocket)

    ' Function called when a client sends a request (connects) to the socket
    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        If context.IsWebSocketRequest Then
            context.AcceptWebSocketRequest(AddressOf OnConnection)
        Else
            context.Response.StatusCode = 400
        End If
    End Sub

    Private Async Function OnConnection(ByVal context As AspNetWebSocketContext) As Task
        Dim socket As WebSocket = context.WebSocket
        ' Store the socket
        users.Add(socket)

        Try
            While socket.State = WebSocketState.Open
                ' Read message incoming from the client (here 1024 is the max size of the message)
                Dim buffer As New ArraySegment(Of Byte)(New Byte(1023) {})
                Dim result As WebSocketReceiveResult = Await socket.ReceiveAsync(buffer, CancellationToken.None)
                ' If the client explictely closed the socket
                If result.MessageType = WebSocketMessageType.Close Then
                    users.Remove(socket)
                    Await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, CancellationToken.None)
                End If
                ' If the socket is open, read the message sent by the client
                If socket.State = WebSocketState.Open Then
                    Dim userMessage As String = Encoding.UTF8.GetString(buffer.Array, 0, result.Count)
                    ' Do something with userMessage
                    ' ...

                    ' Send a message to all connected users
                    userMessage = "The server received: " & userMessage & " at " & DateTime.Now.ToLongTimeString & " - There are " & users.Count & " connected users."
                    buffer = New ArraySegment(Of Byte)(Encoding.UTF8.GetBytes(userMessage))
                    For Each s In users
                        Await s.SendAsync(buffer, WebSocketMessageType.Text, True, CancellationToken.None)
                    Next
                End If
            End While
        Catch ex As Exception
            ' An exception will be thrown if the channel is closed (for example if the client closes the browser)
            users.Remove(socket)
        End Try
    End Function

    Public ReadOnly Property IsReusable As Boolean Implements IHttpHandler.IsReusable
        Get
            Return True
        End Get
    End Property

End Class

The OnConnection function, called when a client connects to the server, loops indefinitely while the socket is open and waits for messages. When a message is received, it can process it and do whatever is needed. In our example, the server simply sends the message back to all connected users and also tell them how many users are connected.

On the client

Writing the client side is even easier.

Have the browser open the socket:

var socket = new WebSocket("wss://myserver.com/WebSocketHandler.ashx", ['soap']);

Notice the protocol is wss, can be ws for non-secured connections.

Then make sure you know when the socket is open and simply send messages:

socket.onopen = function () {
    socket.send("hello");
}

Finally, do something when the client receives a message from the server:

socket.onmessage = function (e) {
    alert(e.data);
}

And this is it! You established a WebSocket connection between a browser and your .NET WCF web service and you did not even use any 3rd-party library. Yay!

Public Member ‘Last’ on type ‘String()’ not found. LinqToEntities extension method not recognized?

Consider the following code:

Capture

This throws the following exception on last line:

Public Member ‘Last’ on type ‘String()’ not found.

This is how to fix this:

Capture

Why? One would think the FullName member is a String anyway, and that Split(” “) returns a String array in all cases. So why do we need to declare the object with the entity type for the .Last extension method to work?

Please leave a comment if you have any idea 😉

Split the Solution Explorer view in Visual Studio 2012

Visual Studio gives us the option to create views of the Solution Explorer. This is quick and easy, and it can be a great time saver when you have a solution with a number of projects and you regularly switch between 2 or more (for example when working on a web project and its associated web services project).

Simply right-click on a project or a folder and choose “New Solution Explorer View” to create a new Solution Explorer window with the selected folder as the root folder.

Untitled

You can then easily your windows to have several projects always visible at the same time.

Untitled

[SQL Server, Entity Framework] Entity Framework does not generate GUIDs for uniqueidentifier columns

I had a table with a uniqueidentifier column (GUID datatype). Objects inserted in that table through Entity Framework always had a GUID all zeros.

The problem (and solution) is nicely described in this blog post from Lee Dumond: http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/

The short answer is to add StoreGeneratedPattern=”Identity” in the column definition of the edmx file (see Listing 3 in post linked above).

Developping with Chrome – Disabling cache

Chrome has no simple option to disable cache, which is an annoyance to both SSD owners and developpers.

Unfortunately, there is no simple way to disable cache and most of the solutions I could find online did not work or only partly. Shortcuts to force reload of a page seems to not work 100% as well.

I only know of 2 safe ways of working with no cache:

1/ Open your page in Incognito mode (CTRL+SHIFT+N), because this mode does not use cache at all. The problem is that because it disables cookies, it may not be suited for everyone.

2/ Open the developper tools (CTRL+SHIFT+J or F12), open the Settings (button at bottom right of screen), and check the “Disable cache” checkbox. It seems though that you have to keep the developper tools open for this to work, but you can easily make it not that intrusive if you don’t use it and in the end you’ll work with no cache.

Also worth knowing, Chrome’s CTRL+SHIFT+DEL shortcut will allow you to clear the cache in one click.

Keep the value of an input field after a postback

You have an html form with an input field and you want to keep the value of this field even after the page postbacks. Here’s an easy way to do that:

<input name="field_DataSiloName" id="field_DataSiloName" type="text" value="<%= Request.Form("field_DataSiloName") %>" />

By setting the attributes name and value like in the above example, you can then get the value of the field in the page load or document ready function of your javascript:

$("#field_DataSiloName").val()