Tuesday, January 26, 2016

Getting the client name and IP address from WCF

One of the concerns we have where I work is that users keep sharing logons and passwords. Then later we get support calls such as "The change history says I did this but I wasn't even here that day". So I decided to see what it would take to track IP Addresses.

Obviously the client knows its own IP Address and can send it to the WCF endpoints that actually do all the work. However we have a lot of endpoints and I didn't want to have to change all the contracts so I looked for a way for the end point to know the IP Address of the client that it is talking to. I turns out to be quite easy if you are targeting framework 3.5 or later.

Imports System.ServiceModel
Dim context As OperationContext
Dim prop As Channels.MessageProperties
Dim endpoint As Channels.RemoteEndpointMessageProperty

context = OperationContext.Current
prop = context.IncomingMessageProperties
endpoint = CType(prop(Channels.RemoteEndpointMessageProperty.Name), Channels.RemoteEndpointMessageProperty)

Return endpoint.Address

So this works great, but IP Addresses can change over time as they are released and renewed. Even better would be the client name, but that requires a reverse DNS lookup from the IP Address. Here is the completed code to get the IP Address from the conversation and perform a reverse DNS lookup. If the lookup fails the IP Address is returned instead.

Note that when the client and the WCF endpoint are on the same computer as is the case when you are debugging, the conversation doesn't even use TCP/IP so this all fails and returns "n/a".

Imports System.ServiceModel
Public Shared Function GetClientName() As String

    Dim context As OperationContext
    Dim prop As Channels.MessageProperties
    Dim endpoint As Channels.RemoteEndpointMessageProperty
    Dim addr As Net.IPAddress
    Dim entry As Net.IPHostEntry

    Try
        context = OperationContext.Current
        prop = context.IncomingMessageProperties
        endpoint = CType(prop(Channels.RemoteEndpointMessageProperty.Name), Channels.RemoteEndpointMessageProperty)

        Try
            addr = Net.IPAddress.Parse(endpoint.Address)
            entry = Net.Dns.GetHostEntry(addr)
            Return entry.HostName
        Catch ex As Exception
            Return endpoint.Address
        End Try
    Catch ex As Exception
        Return "n/a"
    End Try
End Function

Wednesday, January 13, 2016

DataGrid SelectedItems collection

I discovered something unexpected while researching a user's complaint today. It make sense, which may explain why it was unexpected.

The user was complaining that when they select several rows in a grid, I wasn't processing them in document number sequence, even though the grid was sorted in document number sequence. Of course, being a typical user, they omitted to mention that they weren't selecting the first row to be processed and then shift-clicking the last row. If you do that (which I always do because I think LOGICALLY) everything works as they expected.

Instead, they were selecting rows randomly. It turns out the the datagrid's selecteditems collection lists the rows in the sequence they were selected, not in the sequence they were displayed. This makes perfect sense now that I think about it.

It actually means that an intelligent user could specify the sequence they want stuff processed in. However, I doubt many developers have the luxury of a user group that is intelligent enough to use such a feature. I know I don't.

I emailed the user back saying they are using the grid selection feature incorrectly and they have to select the first row and shift-click the last row. That shut them up for a while.

One more thing, for the Microsoft people (I'm sure Bill reads my blog religiously). We seriously need a datagrid footer feature. It would be just like the header feature but at the bottom. The hacks I'm seeing online to fake up this feature are ugly.

TTFN

Wednesday, December 16, 2015

SQL Server ALTER COLUMN calculates table width incorrectly

SQL Server 2012

I recently discovered a bug/feature of SQL Server that drove me crazy until a colleague found an article that explained everything. Before I reference the article, read through the following...

Consider this table create statement...
CREATE TABLE WideTable (Col1 int, Col2 char(3000), Col3 char(3000));

Now change the width of Col2 to char(4000) to make the total width = 7004 bytes ...
ALTER TABLE WideTable ALTER COLUMN Col2 char(4000)

You get the error
Msg 1701, Level 16, State 1, Line 2
Creating or altering table 'WideTable' failed because the minimum row size would be 10011, including 7 bytes of internal overhead. This exceeds the maximum allowable table row size of 8060 bytes.

Where does SQL Server get 10011 bytes from? This is a perfectly legal change isn't it? Let's prove it...
CREATE TABLE WideTable2 (Col1 int, Col2 char(4000), Col3 char(3000));

Apparently SQL Server can't do math. That's a little scary. Here's the story...

Let's start off by running a handy query - you might want to save this one.

SELECT  c.name AS column_name, column_id, max_inrow_length,
      pc.system_type_id, leaf_offset
 FROM sys.system_internals_partition_columns pc
    JOIN sys.partitions p
        ON p.partition_id = pc.partition_id
    JOIN sys.columns c
         ON column_id = partition_column_id
            AND c.object_id = p.object_id
WHERE p.object_id=object_id('WideTable');
GO

This query shows the results below.
column_name column_id   max_inrow_length system_type_id leaf_offset
----------- ----------- ---------------- -------------- -----------
Col1        1           4                56             4
Col2        2           3000             175            8
Col3        3           3000             175            3008

Now you can see that there is a four byte overhead before Col1, Col2 starts at offset 8, and Col3 starts at offset 3008. So if we added another column it would have an offset of 6008. A new column with a width of more than about 2050 bytes would exceed the 8060 maximum allowable table row size. Let's try reducing the width of Col2 to 2500 bytes and see what happens.

ALTER TABLE WideTable ALTER COLUMN Col2 char(2500) 

This works. Let's run that query again...
column_name column_id   max_inrow_length system_type_id leaf_offset
----------- ----------- ---------------- -------------- -----------
Col1        1           4                56             4
Col3        3           3000             175            3008
Col2        2           2500             175            8

Look at the column sequence. It changed. It looks as though SQL Server is adding the altered column to the end of the column list and then removing it from the middle. In between those events it looks like there is code that says something like "If the column width is increasing then check that the sum of the columns does not exceed 8060." But it's including the old AND the new widths of the altered column. This check is not performed if the column width is not increasing.

Looks like a bug, smells like a bug, walks like a bug.

The article that helped me on this issue is http://sqlblog.com/blogs/kalen_delaney/archive/2006/10/13/alter-table-will-not-reclaim-space.aspx. It talks about a slightly different issue but is very relevant to this problem.

The solution is obviously to make a structure change that forces the table to be rebuilt. There's a discussion of this at the end of the referenced blog entry.

Monday, October 19, 2015

Binding to a user control property

This is for Framework 4.0.

I have a page with a user control on it. The user control contains a list and I want to display the count of items in the list in a text block on the main page. It was obvious I would need to create a dependency property in the user control, so...

Public Shared ReadOnly CountProperty As Windows.DependencyProperty = Windows.DependencyProperty.Register("AttachmentCount", GetType(Integer), GetType(Attachments), Nothing)

Public Property AttachmentCount As Integer
Get
    Return CInt(GetValue(CountProperty))
End Get
Set(value As Integer)
    SetValue(CountProperty, value) 
End Set
End Property

Now it's a simple matter of binding the textblock to the user control's property, right?

<TextBlock Name="AddAttachmentsCount" Text="{Binding ElementName=AddAttachmentsUserControl, Path=AttachmentCount"/>

Oops, now I'm seeing an error in the output window at run-time...


System.Windows.Data Error: 40 : BindingExpression path error: '(AttachmentCount)' property not found on 'object' ''UserControl' (Name='AddAttachmentsUserControl')'. BindingExpression:Path=AttachmentCount; DataItem='UserControl' (Name='AddAttachmentsUserControl'); target element is 'TextBlock' (Name='AddAttachmentsCount'); target property is 'Text' (type 'String')

Well maybe I can bind the AttachmentCount property to the text property of my textblock as I define the instance of my user control...


<local:Attachments x:Key="AddAttachments" AttachmentCount="{Binding ElementName=AddAttachmentsCount, Path=Text, Mode=TwoWay}"/>

Yay!


Tuesday, October 13, 2015

Installing Reporting Services

The second time I've had to install Reporting Services I have decided to create a blog. If I were smarter I would have done it the first time.

We have a curious situation where we have Reporting Services partially installed. Perhaps it was installed for an earlier version of SQL Server but not upgraded so now when I run SQL Server xxxx Reporting Services Configuration Manager it cannot find an instance and the screen looks like this...


Follow these steps.

  1. Insert your SQL Server installation DVD and when SQL Server Installation Center pops up click on "Installation" on the left and then "New SQL Server stand-alone installation or add features to an existing installation" on the right.
  2. Click [Next >] in the wizard until you get to Installation Type.
  3. Select the "Add features to an existing instance" radio button and select the instance. Click [Next >]
  4. Check the "Reporting Services - Native" checkbox (unless you wanted sharepoint). Click [Next >] until you get to the [Install] option
  5. Click [Install]. Have a cup of tea and read the newspaper. Click [Close]
Configure your new Reporting Service

  1. Run Reporting Services Configuration Manager. The Report Server Instance should now be populated
  2. Click [Connect]
  3. Click Service Account on the left. The default service account is ReportServer. This is good.
  4. Click Web Service URL on the left. The default Virtual Directory is ReportServer. This is good. Click [Apply]
  5. Click Database on the left. There is no default database so click [Change Database]
     - You will probably want to create a new report server database. Click [Next]
     - Enter the server name and authentication used to create the new databases. I default to Current User - integrated security. Click [Next] and [Finish]
  6. Click Report Manager URL on the left. The default virtual directory is "Reports". This is good. Click [Apply]
  7. That's all you have to do. You can exit the application now.
Now go to my previous blog on enabling non-administrator access to a new instance of reporting services at http://wpfthoughts.blogspot.com/2015/05/running-report-manager-on-newly.html

Friday, October 9, 2015

Flicker and fail with Clickonce and Citrix

We deployed our first widespread WPF application recently and our Citrix users were experiencing a weird problem with the ClickOnce process. When they attempted to perform the install their mouse cursor started flickering and they got a black screen. The Citrix server was still running Server 2003 which is obsolete so tech support blamed the version of IE (8). I installed the Citrix receiver app on my computer and I was able to install the WPF application without a problem. What gives?

Some sleuthing revealed a hot fix http://support.microsoft.com/en-us/kb/955692 which describes our environment and the symptoms reported. It also mentions that the problem only affects non-administrators on the Citrix server (I am an administrator) which explains why I had no problems.

Maybe someone will find this useful.

Tuesday, October 6, 2015

ICO files in WPF applications

Well the last blog entry was a bit lengthy so here's a nice short one. Is has to do with assigning a ico file to a WPF project. The ico file contains a set of graphics at different resolutions in a single file and is used by WPF for the taskbar, the alt-tab, and window graphics like this...




Setting the ico file is simple. You add it to your project and reference it in the project properties under the application tab like this.

Setting the ico file for a WPF project
The problem is that when you are debugging in visual studio the ico file is not used because you are actually running against a proxy exe called vshost.exe. If this is a problem for you there are two solutions.


  1. Disable the visual studio hosting process in the debug tab of the project properties. This causes you to debug against the actual executable that has the ico file. I don't know why the proxy doesn't have it.
  2. Explicitly specify the ico file in the main page XAML like this.
    <Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Icon="Images\pur.ico" .../>
  Take your pick.