Monday, March 29, 2010

Quiz #2: Goto statement in C#

@YaronNaveh

I have written a very simple C# method. This method did not contain any goto statements (they're bad, right?). I have then opened my method in the reflector and found this:


private void NoGoto()
{
     int i = 0;
     if (i == 0)
     {
         switch (i)
         {
             case 0:
             case 1:
             goto Label_002C; //WTF?!
         }
         i--;
     }
    Label_002C:
         i++;
}


The quiz question is: What is going on here? What was my original code?

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Tuesday, March 23, 2010

Customizing ClearUsernameBinding

@YaronNaveh

ClearUsernameBinding has became very popular recently and many people ask how to modify it for their needs. Most people want to increase message size quotas but there are definitely other required customizations.

Suresh has written a nice post on how to increase some of the message quotas. Also the comments to the original post contain more useful information.

Generally speaking, most customizations can just imitate the way messageVersion is handled, so just search for wherever this string appears (5 places) and add you equivalnet code for what you are customizing. Hopefully soon I'll publish a concrete example.

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Monday, March 22, 2010

Wcf: "The security capabilities do not match the generated runtime object"

@YaronNaveh

The below Wcf error message is quite rare. You would encounter it only when developing some specific kinds of Wcf custom channels and transports.


The security capabilities of binding
'System.ServiceModel.Channels.CustomBinding' do not match those of the generated runtime object. Most likely this means the binding contains a StreamSecurityBindingElement, but lacks a TransportBindingElement that supports Stream Security (such as TCP or Named Pipes). Either remove the unused StreamSecurityBindingElement or use a transport that supports this element.

at

System.ServiceModel.Channels.Binding.
ValidateSecurityCapabilities(ISecurityCapabilities runtimeSecurityCapabilities,
BindingParameterCollection parameters)


When you develop a custom channel you usually develop one class which derives from BindingElement and another which implements IChannelFactory. Both classes have this method:


public virtual T GetProperty()


In many cases you override this method to return a specific set of ISecurityCapabilities. One example use case is ClearUsernameBinding:


public override T GetProperty(BindingContext context)
{
   if (typeof(T) == typeof(ISecurityCapabilities))
     return (T) (ISecurityCapabilities) new AutoSecuredHttpSecurityCapabilities();

   return base.GetProperty(context);
}


In runtime, Wcf verifies that the capabilities the factory claims it can support are also supported by the actual channel. In other words this must be true:

channel.GetProperty()==factory.GetProperty()

If you have override the GetProperty() method of the channel but not of the factory then you will get the error above.

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Saturday, March 20, 2010

Wcf Binding Box: Security usage patterns

@YaronNaveh

WCF Binding Box is on air for over six months now. Hopefully it will stay there for a while, at least until Azure will close the free trial period. For those of you who forgot, the binding box allows to convert any WCF binding (e.g. WSHttpBinding) to a CustomBinding.

Around 1500 users have converted their bindings already. This seems like a good time to analyze some WCF security usage patterns.


Message Security Type

The first aspect I analyzed is the security type people use. Results show that over 60% of users apply some message level security (possibly together with ssl). One possible explanation to this result is that message level security is the default with Wcf (in contrary to most legacy soap stacks). Another explanation is this: People who work with message level security have much more available configurations, so they seek the binding box in order to get a custom binding. This means the measurement here may be a little biased.

(click image to enlarge)




Client Credential Type (Message)

The second question I tested is which message credentials are most popular. The results show that username authentication is by far the most popular authentication mechanism. This is expected considering that usernames are the easiest to work with and offer the best interoperability. We can tie this together with the huge interest in ClearUsernameBinding. Windows authentication gets a relatively low share which may indicate that most binding box users wrote internet and not intranet applications.

(click image to enlarge)




Client Credential Type (Transport)

Finally I have tested which are the most popular client authentication types with transport security. Here domain based authentication (windows, ntlm) is used by almost 40% of the users. Basic authentication is only 15% which is surprising taking into consideration that the most popular message level authentication mechanism is a UserName token. A quarter of the users chose the Certificate authentication type. We can add to this the fact that client certificates have a similar message level share, and that server side certificates are used in all of the transport modes and in most message level modes. This shows that most organizations deal with X.509 certificates this way or the other.

(click image to enlarge)

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Saturday, March 13, 2010

My favorite online programming utilities

@YaronNaveh

Every blogger has his own list of favorite programming utilities.
Here are some utilities I love - all are online. You are welcome to share your favorites in the comments.

Binary translator
(Or whatever its name is) converts between base64, hex, binary, text, decimal... you got it.

Xml Pretty Print
If you think this:


<some>
  <dummy xmlns="xml">
    <to>
      <test p:attr="the">pretty xml utility</test>
    </to>
  </dummy>
</some>


is better than this:


<some><dummy xmlns="xml"><to><test p:attr="the">pretty xml utility</test></to></dummy></some>


then this utility is for you.

Color Picker
Hey they have some nice colors there!

What are your favorite online programming utilities?

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Programatically install SSL for WCF self hosting

@YaronNaveh

When we use SSL with IIS deployed services we can configure SSL in the IIS console. But what to do when we self host our service?

Here's one way to do it (vista / windows 7 / windows 2008 server only).

Run this command line:


netsh http add sslcert ipport=0.0.0.0:8732 certhash=4f35f9386692f45b6cc35b7e786c9f06625b9567 appid={00112233-4455-6677-8899-AABBCCDDEEFF}


Where:


ipport - The port on which you want to install SSL. The zeros stand for the local machine and 8732 is the port.

appid - any unique GUID should do it here.

certhash - The thumbprint of our certificate. See below how to get it.


How to get the certificate hash / thumbrpint?

1. Run mmc and add the certificates snap-in.
2. Double click your certificate and see its thumbprint (hash):



3. Convert the base64 representation to Hex - this is the value you need.

From code...

Now in many cases you will want to do the installation dynamically at run time. This is as easy as:


using System.Diagnostics;

...

void RunCommandLine(string filePath, string arguments)
{
     var p = new Process();
     p.StartInfo = new ProcessStartInfo(filePath, arguments);
     p.StartInfo.UseShellExecute = false;
     p.Start();
     p.WaitForExit(10000);
}

...

RunCommandLine(
   "netsh",
   "http add sslcert ipport=0.0.0.0:8732   certhash=4f35f9386692f45b6cc35b7e786c9f06625b9567 appid={00112233-4455-  6677-8899-AABBCCDDEEFF}");

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Saturday, March 6, 2010

"Google forms" is useless

@YaronNaveh

Google has a nice forms feature for their spreadsheet: You can build a form and send it to your audience. They answer the form and you get to see the summarized results. One useful idea is to use it for online surveys. This is exactly what I did.

At the beginning, life was good. I went to see the results sometime after I published the post and already a few people have answered it:



After some more time I came back and saw that a lot of people answered it:



I was exited to see so many responses. Until I saw the responses that is... When I opened the spreadsheet I saw that most if not all of the new responses were spam. Some robot filled in the default values every few seconds. My next thoughts were:

1. Let's add some captcha so only humans can submit from now on.
2. Let's manually delete the spam answers already in.

I was surprised to find out that none of these options are available! While you can delete answers from the spreadsheet, the aggregated data used to generate the survey report does not seem to change. This data sits somewhere on Google servers and I have nothing to do about it.

This makes Google forms useless.

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Friday, March 5, 2010

DataSets Considered Harmful (part 2): Performance

@YaronNaveh

The first part in this series discussed various interoperability issues with DataSets. This time I want to discuss the performance implications.

Let us sent the simplest DataSet to some server:

var ds = new System.Data.DataSet();
DataTable t = new DataTable();
t.Columns.Add("col1");
t.Columns.Add("col2");
t.Rows.Add("row1col1", "row1col1");
t.Rows.Add("row2col1", "row2col1");
ds.Tables.Add(t);
localhost.Service s = new Service();
s.GetData(ds);

Here is the generated Soap:

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <GetData xmlns="http://tempuri.org/">
            <value>
                <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
                    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
                        <xs:complexType>
                            <xs:choice minOccurs="0" maxOccurs="unbounded">
                                <xs:element name="Table1">
                                    <xs:complexType>
                                        <xs:sequence>
                                            <xs:element name="col1" type="xs:string" minOccurs="0" />
                                            <xs:element name="col2" type="xs:string" minOccurs="0" />
                                        </xs:sequence>
                                    </xs:complexType>
                                </xs:element>
                            </xs:choice>
                        </xs:complexType>
                    </xs:element>
                </xs:schema>
                <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
                    <NewDataSet xmlns="">
                        <Table1 diffgr:id="Table11" msdata:rowOrder="0" diffgr:hasChanges="inserted">
                            <col1>row1col1</col1>
                            <col2>row1col1</col2>
                        </Table1>
                        <Table1 diffgr:id="Table12" msdata:rowOrder="1" diffgr:hasChanges="inserted">
                            <col1>row2col1</col1>
                            <col2>row2col1</col2>
                        </Table1>
                    </NewDataSet>
                </diffgr:diffgram>
            </value>
        </GetData>
    </soap:Body>
</soap:Envelope>

This Soap commits two “crimes”. The first one is the embedded schema. Since the wsdl is not typed, .Net must serialize the schema inside the soap. This can have serios performance implications with large schemas.

The second issue is the rowOrder and hasChanges attributes over each data row. In most cases when you just want to pass a snapshot of data to a client so these are simply not required.

The overall result is a bloated Soap without any meaningful benefit.

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

DataSets Considered Harmful (part 1): Interoperability

@YaronNaveh

There are various reasons why you do not want to expose System.DataSet in your web service contract. One reason is interoperability: Non-.Net clients will have hard time consuming such services. Let’s see how the schema of a service with DataSet looks like.

Service

public interface MyService
{
    public void MyOperation(DataSet value);
}

Wsdl

<xs:element minOccurs="0" name="value" nillable="true">
          <xs:complexType>
            <xs:annotation>
              <xs:appinfo>
                <ActualType Name="DataSet" Namespace="
http://schemas.datacontract.org/2004/07/System.Data" xmlns="http://schemas.microsoft.com/2003/10/Serialization/" />
              </xs:appinfo>
            </xs:annotation>
            <xs:sequence>
              <xs:element ref="xs:schema" />
              <xs:any />
            </xs:sequence>
          </xs:complexType>
</xs:element>

The “DataSet-ness” of the element is expressed inside an “appinfo” element. Also it is under a Microsoft specific namespace. This means only .Net clients can understand the semantic of this type.

To be specific, the actual content of the schema type is an “any” element. This is an xml “wildcard” that allows to put any arbitrary xml inside it. This has very bad interoperability and usability implications. To begin with, a client application cannot know the on-the-wire format of xml instances from this wsdl as it is not typed. The format is dependent in the implementation (DataSet). This breaks one of the SOA main tenets “Service API should rely on Contract.”

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Monday, March 1, 2010

.Net Reflector not free anymore?

@YaronNaveh

We all love our .Net reflector. And we had all repressed some dangerous feeling that day when Red Gate bought it from Lutz Roeder. Well, not any more. Starting today there is a commercial edition of the Reflector alongside with the free one. The main benefit of this version is the ability to debug third party assemblies. Let us all hope that the free edition will not stay in a "maintenance" mode only...

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!