WPF Data Triggers

Today I needed to control the enabled property of a button "Remove Item" on my form depending on weather there was a selected item in a Listbox.

Here's how

[code:c#]
<Button Content="Remove" Click="OnRemoveTranstion">
<Button.Style>
<Style>
    <Style.Triggers>
        <DataTrigger Binding ="{Binding ElementName=listDetails, Path=SelectedIndex}" Value="-1">
            <Setter Property="Button.IsEnabled" Value="false"/>
        </DataTrigger>
    </Style.Triggers>
</Style>
</Button.Style>
</Button>
[/code]

.NET DateTime Webservices UTC

With .NET 1.1 when we receive a UTC DateTime in a SOAP response from a Webservice it used to get converted to Local time.

With .NET 2.0 when we receive a UTC DateTime in a SOAP response it stays in UTC.

If you need it in local time make sure to call .ToLocalTime()

** Edit: P.s. Have a look at this neat class in the framework XmlConvert

Configuring IIS to host WCF services

It's true what they say, to learn new technologies it's simple a matter of ABC (Always be coding), I've watched many the video, read many the book but it's only when I went to try to do something the it sinks in.
Like tonight while trying to host a WCF service on my Windows 7 machine I came across a problem that you'd only find by ABC.

HTTP Error 404.3 - Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

The solution.

Control Panel/Programs and Features/Add or Remove components/Microsoft .NET Framework 3.5.1 section.

I checked the two Windows Communication Foundation checkboxes shown below (the second box enables Windows Activation Service - WAS so that IIS can host WCF services that can be called using non-HTTP bindings such as TCP) (nice!)

 

WPF ErrorList

http://errorlist.codeplex.com/

ErrorList

I recently wrote a control that tries to replicate the error list seen in Visual studio.

The control is dependant on .NET 3.5 SP1. because it uses the WPFToolkit.

I'm hosting a sample here. [Update August 2012 My host has stopped xbap application types, sorry]

Screenshot

BlogEngine and Silverlight

I've had a few people asking me how did I host Silverlight 3 in blog engine.

Silverlight Usercontrol

It was pretty simple really (when you know how)

Basically Silverlight3 needs an <object> tag.

So I created a user control with the object tag and some script handling for client side errors (actually VS2010 did all the hard lifting).

[code:c#]

<%@ Control Language="C#" ClassName="SilverlightControl" %>

<script runat="server">

</script>


<script type="text/javascript" src="~/Silverlight.js"></script>
    <script type="text/javascript">
        function onSilverlightError(sender, args) {
            var appSource = "";
            if (sender != null && sender != 0) {
                appSource = sender.getHost().Source;
            }

            var errorType = args.ErrorType;
            var iErrorCode = args.ErrorCode;

            if (errorType == "ImageError" || errorType == "MediaError") {
                return;
            }

            var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";

            errMsg += "Code: " + iErrorCode + "    \n";
            errMsg += "Category: " + errorType + "       \n";
            errMsg += "Message: " + args.ErrorMessage + "     \n";

            if (errorType == "ParserError") {
                errMsg += "File: " + args.xamlFile + "     \n";
                errMsg += "Line: " + args.lineNumber + "     \n";
                errMsg += "Position: " + args.charPosition + "     \n";
            }
            else if (errorType == "RuntimeError") {
                if (args.lineNumber != 0) {
                    errMsg += "Line: " + args.lineNumber + "     \n";
                    errMsg += "Position: " + args.charPosition + "     \n";
                }
                errMsg += "MethodName: " + args.methodName + "     \n";
            }

            throw new Error(errMsg);
        }
    </script>

  
    <div id="silverlightControlHost">
    <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
    <param name="source" value="<%Silverlight.xbap%>"/>   // where <%Silverlight.xbap%> is location of silverlight xbap
    <param name="onError" value="onSilverlightError" />
    <param name="background" value="white" />
    <param name="minRuntimeVersion" value="3.0.40818.0" />
    <param name="autoUpgrade" value="true" />
    <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40818.0" style="text-decoration:none">
      <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
    </a>
     </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>



[/code]

Windows Forms Validation

One approach for validating child controls on windows froms is to

Validation.

  • Add a Validated event handler to all child controls you're interested in.
  • On a button event handler call this.ValidateChildren();

This will ensure the validation routine on all child controls will be called, if for example you've added an ErrorProvider control extender to your form you can set it up in the validated event handlers.

Inline XML Linq manipulation sample

A quick example of inline xml and Linq

 

Code

[code:c#]

void LinqToXmlSample()
{
  Console.WriteLine("{0} : Start", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

  XDocument xDocument = new XDocument(
    new XElement("people",
      new XElement("person",
        new XAttribute("sex", "male"),
        new XElement("FirstName", "Brian"),
        new XElement("LastName", "Keating")),
      new XElement("person",
        new XAttribute("type", "female"),
        new XElement("FirstName", "Dustin"),
        new XElement("LastName", "Turkey"))));

  IEnumerable<XElement> elements =
    xDocument.Element("people").Descendants("FirstName");

  /*  First, I will display the source elements.*/
  foreach (XElement element in elements)
  {
    Console.WriteLine("Source element: {0} : value = {1}",
      element.Name, element.Value);
  }

  /*  Now, I will display the ancestor elements for each source element.*/
  foreach (XElement element in elements.Ancestors())
  {
    Console.WriteLine("Ancestor element: {0}", element.Name);
  }

  Console.WriteLine("{0} : Finish", new StackTrace(0, true).GetFrame(0).GetMethod().Name);
}

[/code]

 

Output

LinqToXmlSample : Start
Source element: FirstName : value = Brian
Source element: FirstName : value = Dustin
Ancestor element: person
Ancestor element: people
Ancestor element: person
Ancestor element: people
LinqToXmlSample : Finish

 

[Update August 2012: Little did I know when i wrote this post just how much I would use Linq to xml, it saved me from a life of xslt Smile ]

Resource Cleanup and Lambda Expressions

A neat way of always cleaning up resources is to use Lambdas as data.

Take the following

Source

[code:c#]

    internal interface ITryCatchReport
    {
        void Try(Action<IServer> action);
    }

    internal class TryCatchReport : ITryCatchReport
    {
        public TryCatchReport(IServer server)
        {
            _server = server;
        }

        public void Try(Action<IServer> action)
        {
            try
            {
                action(_server);
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.Message);
                // Clean up resources
                // Report errors
            }
        }

        private IServer _server;    
    }

 

[/code]

 

Usage

[code:c#]

TryCatchReport safeInvoker = new TryCatchReport(_data.Server);
safeInvoker.Try(x =>
{
x.MakeInterfaceCall();
});

[/code]

We are now guaranteed that in the case of an exception that the resources will get cleaned up.

 

Usage with code blocks

If you wish to execute many statements in the action look at this sample.

[code:c#]

private List<WFActionDefinition> GetActionDefinitions()
{
    if (_actionDefinitions == null)
    {
        safeInvoker.Try(x =>
            {
                x.Do1();
                x.DoSomething();
                OtherFunc();
            });
    }

    return _actionDefinitions;
}

[/code]