vs2010 parallelism

Take some time to explore the new vs2010 debugger.

Those of you to have experience with multithreading know that it can be a right old PIA (and i'm not talking Primary interop assembly here!).

Try the parallel tasks/stacks in vs2010 and see just how valuable a friend they become :-)

 

In recent times, CPU clock speeds have stagnated and manufacturers have shifted their focus to increasing core counts.
This is problematic for us as programmers because our standard single-threaded code will not automatically run faster as a result of those extra cores.

Spend some time investigating the new Tasks in .net 4.0

Linq in asp.net

A quick sample of how to use linq in your webpages

 

[code:c#]

<% Model.ToList().ForEach(item =>
{ %>
  <tr>
      <td>
          <%: Html.ActionLink("Edit", "Edit", new { id = item.AlbumId })%> |
          <%: Html.ActionLink("Delete", "Delete", new { id = item.AlbumId })%>
      </td>
      <td><%: Html.Truncate(item.Title, 25)%></td>
      <td><%: Html.Truncate(item.Artist.Name, 25)%></td>
      <td><%: item.Genre.Name%></td>
  </tr>
<% }); %>

[/code]

 

I said quick ey!  :-)

Workflow Arguments how to

So you've started up your very first 4.0 Workflow application.
You've added some arguments and want to know how to pass some information..
You can either use the Dictionary approach that exists since 3.0 or you can use the properites you've just created.

 

Thes scrren shots show a simple workflow with an input string UserName and an output string Greeting.

 

 

 

I added an assignment activity and set the "To" to be the output Arguement "Greeting"

 

And set the Value as follows.

 

 

To prove this works I've added a test fixture and implemented it as follows

 

 

 

So there you go. The quickie for today Smile

Syncronization Context

A sample of using SyncronizationContext to post a message back to the UX thread

 

[code:c#]

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    SynchronizationContext ctx = SynchronizationContext.Current;

    ThreadPool.QueueUserWorkItem(_ =>
    {

        WebClient client = new WebClient();

        string html = client.DownloadString("https://www.briankeating.net");
        ctx.Post(state =>
        {
            tbDetails.Text = (string)state;

        }, html);

    });

}

[/code]

MVC Stories

Hi All,

Been a while since I've writen some posts, been pretty hectic hours at work and weekends building a house so my chances to blog have been limited.

I intend over the coming few days to give a few tips and tricks on MCV2.

Here's on gottya..

Be carefull how you name your formal arguements in your controller functions.

You can see from the screenshot below that I created two args, "Name" and "name"

By default the first matching case insensitive value will be applied to both variables by MVC...

Usually this will be avoided by good naming conventions but be carefull nonetheless :-)

 

 

WCF 4.0 File-less Activation (.svc less)


http://url/abc.svc  .svc at the end of url makes it user unfriendly. It also makes it Low REST service as it donot follow the REST URI principle.

Till date developers have to overcome this limitation by implementing URLReWrite module in IIS.
Writing custom code to implement this is error prone and needs maintenance over a period. WCF 4.0 has introduced
a feature to access WCF services using attribute called as relativeAddress.
Following .config setting depicts how a Calculat

orService can be accessed using relative URL.

<system.serviceModel>

    <serviceHostingEnvironment>

      <serviceActivations>

        <add relativeAddress="/Payment" service=“CalculatorService.svc"/>

      </serviceActivations>

    </serviceHostingEnvironment>

  </system.serviceModel>

 

**UPDATE

I've just tried to do this in an application I was working on, don't know where I got my origional information from but this Fileless activation was not what was advertised at the time, it requires a .svc extension on the url without the need for for a .svc physical file.

I've accomplished my restful approach with routing.

 

Output and Encoding in ASP.net 4.0

Pre .NET 4.O

Prior to  ASP.NET 4.0 (and especially with MVC) when a user outputted information to a webpage they used <%= Server.HtmlEncode(modelViewStore.Content) %>

The reason for the Encoding is primiarily to prevent XSS (cross site script injection) whereby someone may try to inject some client side script or HTML Markup to vandalize a site or to steal valuable information.

This approach has a few shortcommings; like,

* Users may forget the encoding
* bit verbose

 


.NET 4.0

A new nugged has arrived:

<%: modelViewStore.Content %>

WaitCursor and MVVM

Ever wondered how to display the correct cursor in an application that is databinded to async methods?

Pretty easy solution, just databind the cursor on the window itself.

Here's how:

  • Add an IsBusy property on the DataContext (and implement INotifyPropertyChanged on it)
  • Add the following to your window xaml

[code:c#]

xmlns:valueConverters="clr-namespace:XXX.ValueConverters"
Cursor="{Binding IsBusy, Converter={valueConverters:CursorExtensionConverter}}" 

[/code]

 

  • Create the following ValueConverter

[code:c#]

public class CursorExtensionConverter : MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && ((bool)value))
            return Cursors.Wait;           
        else
            return Cursors.Arrow;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return instance;
    }

    private static CursorExtensionConverter instance = new CursorExtensionConverter();
}

[/code]

 

Note: Use of MarkupExtension

 

INotifyPropertyChanged diagnostics

Those of you that use INotifyPropertyChanged may have noticed it's easy to break the code if you choose to refactor/rename as the property name string does not get refactored.

Here is a mechanism to catch this problem at the implementation stage.

 

[code:c#]

#region Debugging Aides

/// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
    // Verify that the property name matches a real, 
    // public, instance property on this object.
    if (TypeDescriptor.GetProperties(this)[propertyName] == null)
    {
        string msg = "Invalid property name: " + propertyName;

        if (this.ThrowOnInvalidPropertyName)
            throw new Exception(msg);
        else
            Debug.Fail(msg);
    }
}

/// <summary>
/// Returns whether an exception is thrown, or if a Debug.Fail() is used
/// when an invalid property name is passed to the VerifyPropertyName method.
/// The default value is false, but subclasses used by unit tests might
/// override this property's getter to return true.
/// </summary>
protected virtual bool ThrowOnInvalidPropertyName { get; private set; }

#endregion // Debugging Aides

#region INotifyPropertyChanged Members

/// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged = (s, e) => { };

/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
    this.VerifyPropertyName(propertyName);
    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));           
}

#endregion // INotifyPropertyChanged Members

[/code]

WPF ListViewItem Commands with MVVM pattern

If you're interested to see how to attach commands to listview items for use with an implementation of the MVVM pattern, have a look at this.

 

[code:c#]

<Style x:Key="Local_OpenEntityStyle"
           TargetType="{x:Type ListViewItem}">
        <Setter Property="acb:CommandBehavior.Event"
                        Value="MouseDoubleClick" />
        <Setter Property="acb:CommandBehavior.Command"
                        Value="{Binding ElementName=uiEntityListDisplay, Path=DataContext.OpenEntityCommand}" />
        <Setter Property="acb:CommandBehavior.CommandParameter"
                        Value="{Binding}" />
</Style>

[/code]

 

Here the command to be fired on the MouseDoubleClick event is set, the CommandParameter, will be the data object that we click on.