Anonymous delegates and Lambdas

Just a sample that may catch you eye as unusual..

 

[code:c#]

 class WorkItem
{
    public WaitCallback Callback;
    public object State;
    public ExecutionContext Context;

    private static ContextCallback _contextCallback = s =>
    {
        var item = s as WorkItem;
        item.Callback(item.State);
    };

    public void Execute()
    {
        if (Context != null)
            ExecutionContext.Run(Context, _contextCallback, this);
        else
            Callback(State);

    }
}

[/code]

 but here's the same code using anon delegates

[code:c#]

class WorkItem
{
    public WaitCallback Callback;
    public object State;
    public ExecutionContext Context;

    private static ContextCallback _contextCallback = delegate(object s)
    {
        var item = s as WorkItem;
        item.Callback(item.State);
    };

    public void Execute()
    {
        if (Context != null)
            ExecutionContext.Run(Context, _contextCallback, this);
        else
            Callback(State);

    }
}

[/code]

The threee A's of Silverlight Security.. (Part I)

·      Authentication

·      Access control

·      Auditing

Authentication.

One of the critical requirements of any LOB application ia authentication; before the user can use any function he will authenticate by giving a user id and password.

 

In ASP.NET web application, thi can easily be done by taking advantage of the membership provider and the server-side ASP.NET login controls. In Silverlight, there are two ways to enforce authentication: authentication outside and authentication inside.

Authentication outside is very straightforward and is similar to ASP.NET applications, with this approach, authentication happens in anASP.NET based web page before the Silverlight application is displayed. The authentication context can be transferred into the Silverlight application through the InitParams parameter before a Silverlight application is loaded. The other approach is to use a webservice.

 

 

Silverlight Multithreading and the UI

 

When you wish to know if you are on the UI thread and you've no access to any UIElement how do you do it?

[code:c#]

static bool IsUiThread()
{
    return Deployment.Current.Dispatcher.CheckAssess();
}

[/code]

Checked GroupBox

Here's a bit of code that i'm using in an application to give this result (Checked GroupBox)

 

[code:c#]

<GroupBox Grid.Row="3" Grid.Column="1" BorderBrush="Black" Margin="0,0,116,0">
<GroupBox.Header>
    <CheckBox x:Name="cbValidity" IsChecked="{Binding Path=HasValidity}" >Validity</CheckBox>
</GroupBox.Header>

<StackPanel>
    <StackPanel.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding ="{Binding ElementName=cbValidity, Path=IsChecked}" Value="false">
                    <Setter Property="Button.IsEnabled" Value="false"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>
    <TextBlock Margin="10,10,0,0" Text="This job is valid from" />
    <wfi:WindowsFormsHost x:Name="propertiesCtrlHost" SnapsToDevicePixels="True" Background="Transparent" Height="22" Margin="10" Width="200" HorizontalAlignment="Left">
        <wf:DateTimePicker x:Name="dtpFrom" Format="Custom" CustomFormat="dd MMMM yyyy  HH:mm" ValueChanged="dtpFrom_ValueChanged" />
    </wfi:WindowsFormsHost>

    <TextBlock Margin="10,10,0,0" Text="This job is valid to" />
    <wfi:WindowsFormsHost SnapsToDevicePixels="True" Background="Transparent" Height="22" Margin="10" Width="200" HorizontalAlignment="Left">
        <wf:DateTimePicker x:Name="dtpTo" Format="Custom" CustomFormat="dd MMMM yyyy  HH:mm" ValueChanged="dtpTo_ValueChanged" />
    </wfi:WindowsFormsHost>
</StackPanel>
</GroupBox>

 

[/code]

Data Validation in Silverlight (Method 1)

Here's one way to do validation in silverlight.

This is a pretty straight method using exceptions (if you're from the camp that allows exceptions in your Data objects Cool)

 

[code:c#]

public string Name

 get 
 {
     return _name; 
 } 
 set 
 {   
  if ( value.Length >= 10 )
    throw new ArgumentException( "Name is too long" );   
  _name = value;
 }
}


<TextBox x:Name="name"
  <TextBox.Text>
   <Binding Path="name"
     NotifyOnValidationError="True"
      ValidatesOnExceptions="True" />  
 </TextBox.Text>
</TextBox>

[/code]

Linq to SQL

Requirment:

Nothwind Sql Database

Advantages of Linq to SQL

While everything with Linq to Sql ca be done with Ado.Net, there are a few advantages

  • Less code: you don't need to write ADO.NET code for querying the database. You can use a tool to generate the data classes you need.
  • Flexible querying capabilities: Rather than struggle with SQL, you can use the LINQ querying model. Ultimately, you'llbe able to use one consistent model (LINQ expressions) to access many different types of data, from databases to XML.
  • Change tracking and batch updates: This is the most important one for me, (because I already have ado.net tools and i don't mindwriting sql) You can change multiple details about the data yo've queried and commit a batch update. 

Add a new linq to sql item to your project 

 

 

 Sample usage

 

[code:c#]

class Program
{
    static void Main(string[] args)
    {
        Program prog = new Program();
        prog.ListAllOrderProducts();
        prog.ListAllOrderProductsForCustomer();
        Console.ReadLine();
    }


    private void ListAllOrderProducts()
    {
        CustomerOrdersDataContext dc = new CustomerOrdersDataContext();
        Table<Order> table = dc.GetTable<Order>();
        foreach (var order in table)
        {
            Console.WriteLine(order.Order_Details[0].Product.ProductName);
        }           
    }

    private void ListAllOrderProductsForCustomer(string custId = "ALFKI")
    {
        CustomerOrdersDataContext dc = new CustomerOrdersDataContext();
        var result =
            from order in dc.GetTable<Order>()
            where order.CustomerID == custId
            select order;
                   
        foreach (var x in result)
        {
            Console.WriteLine(x.Order_Details[0].Product.ProductName);
        }
    }
}

[/code]

Anonymous delegates and event execution

A nice little trick to save you always checking for null when firing custom events
Initialize to anonymous delegate.
Ok.. we've an extra call in the invocation list so use judiciously

[code:c#]

public event CompleteTaskExecutionHandler CompleteExecution = delegate { };

//or a sample using Lambdas

public event PropertyChangedEventHandler PropertyChanged = (s,p) => { };

 

 

private void Fire()
{
   this.CompleteExecution(...);
}

 

[/code]

Extension Method for Wpf Window with Froms Owner

 

Extension Method

[code:c#]

internal static class InteropExtensions
{
    public static bool? ShowDialog(this System.Windows.Window win, IntPtr handle)
    {
        WindowInteropHelper helper = new WindowInteropHelper(win);
        helper.Owner = handle;
        return win.ShowDialog();
    }
}

[/code]

 

Usage

[code:c#]

var win = new WpfWindow();
win.ShowDalog(windowsFormOwnerHandle);

[/code]