Friday, November 5, 2010

WPF ContentControl and ItemsControl concepts

ContentControl is used to display a control and data from a single object.
ContentControl extends Control and has three main properties (of which 'Template' property is inherited from the parent Control class):

        // Summary:
        //     Gets or sets the value of the System.Windows.Controls.ContentControl dependency
        //     property.
        //
        // Returns:
        //     An object that contains the control's content. The default is null.
        public object Content { getset; }
        //
        // Summary:
        //     Gets or sets the data template that is used to display the content of the
        //     System.Windows.Controls.ContentControl.
        //
        // Returns:
        //     The data template that is used to display the content of the System.Windows.Controls.ContentControl.
        public DataTemplate ContentTemplate { getset; }
        //(Note: Inherited from parent 'Control' class
        // Summary:
        //     Gets or sets a control template.
        //
        // Returns:
        //     The template that defines the appearance of the System.Windows.Controls.Control.
        public ControlTemplate Template { getset; }
ControlTemplate is used for display of the control. All ContentControl objects come with default values for their ControlTemplate property. 
The control author can define the default ControlTemplate and the application author can override the ControlTemplate to reconstruct the visual structure of the control.
The default ControlTemplate contains a ContentPresenter that is defined by the control author.  If the application author chooses to redefine the Template property, he HAS to include the ContentPresenter in the ControlTemplate otherwise, the ContentControl will not display.
The DataTemplate is used to display the data contained in the control.This should be defined in XAML only and cannot be done in code.
The XAML usage that defines the content for creating a data template is not exposed as a settable property. It is special behavior built into the XAML processing of a DataTemplate object element.
Here is how they all work together (click here for more details):
You typically use the ContentPresenter in the ControlTemplate of a ContentControl to specify where the content is to be added. Every ContentControl type has a ContentPresenter in its default ControlTemplate.
When a ContentPresenter object is in a ControlTemplate of a ContentControl, the ContentContentTemplate, and ContentTemplateSelector properties get their values from the properties of the same names of theContentControl. You can have the ContentPresenter property get the values of these properties from other properties of the templated parent by setting the ContentSource property or binding to them.
The ContentPresenter uses the following logic to display the Content:
Similarly, The ItemsControl is used for collections. The equivalent of ContentTemplate here is ItemTemplate (hence the type is the same: DataTemplate). In an items control, when bound to a collection, each element of the collection is displayed using the ItemTemplate.
        //
        // Summary:
        //     Gets or sets the System.Windows.DataTemplate used to display each item.
        //
        // Returns:
        //     The template that specifies the visualization of the data objects. The default
        //     is null.
        public DataTemplate ItemTemplate { getset; }

Wednesday, March 3, 2010

Windows Server 2008 and IIS 7.0 problems with WCF execution

First error set:
Error Summary:
The requested page cannot be accessed because the related configuration data for the page is invalid

Detailed Error Information:
This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

Config Source: <handler>
Solution:
Go to C:\Windows\System32\inetsrv\config and edit the applicationHost.config file.
Find the node
under
 and change it to 

You may have to do the same thing for the
node (change Deny to Allow) if the message persists in the browser, but this time the Config Source being


Second error set:
HTTP 500 --- Handler svc-Integrated has a bad module "ManagedPipelineHandler" in its module list

Basically it means your IIS has not been configured to allow http activations.
Start-&gt;Control Panel-&gt;Programs-&gt;Programs and Features.
Click on "Turn on Windows features on or off" on the left. This opens the "Server Manager" window. Click on the "Features" node on the left and click on "Add features" on the right.
You will see a list of features listed, one of them being .NET Framework 3.x features (installed). Expand it and check the "WCF Activation" node or all nodes under it (HTTP Activation and Non-Http Activation). Click on install.
This will now allow http activations such as svc support.

Friday, February 26, 2010

WCF Exception Handling

You can create a high level exception interceptor of WCF exceptions. This should be coded to convert any exception, including unhandled exceptions into FaultExceptions since this is the only type of exception that should be legally passed across the wire to the client.
NOTE: This may not work properly if the exception is happening in the constructor itself.

The code for the IErrorHandler is below.
Note: The FaultAction value is very important. Read comments in the code.

/// <summary>
/// This intercepts exceptions before throwing them to the client from the service
/// </summary>
public class CalculatorErrorHandler : IErrorHandler
{
// Provide a fault. The Message fault parameter can be replaced, or set to
// null to suppress reporting a fault.
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
   Console.WriteLine("Error=" + error.Message);
   var fe = new FaultException<CalculatorFault>(new CalculatorFault { Message = error.Message }, new FaultReason(error.Message));
   //The FaultAction value should match exactly with the Action value set in the attribute of the OperationContract that throws this Fault
   fault = Message.CreateMessage(version, fe.CreateMessageFault(), CalculatorFault.FaultAction);
   //Console.WriteLine("provideFault=" + error.StackTrace);
}

// HandleError. Log an error, then allow the error to be handled as usual.
// Return true if the error is considered as already handled
public bool HandleError(Exception error)
{
if (error != null)
{
//Use log4net here if you want
Console.WriteLine("In ErrorHandler: " + error.GetType().Name + " - " + error.Message);
}
return false;
}
}

Here is the custom Fault datacontract:

namespace MyDataContracts
{
public class CalculatorFault
{
public const string FaultAction = "FaultAction";
public string Message { get; set; }
}
}


Then wire it up using a service behavior as an attribute:




// This attribute can be used to install a custom error handler for a service.
public class ErrorBehaviorAttribute : Attribute, IServiceBehavior
{
Type errorHandlerType;

public ErrorBehaviorAttribute(Type errorHandlerType)
{
this.errorHandlerType = errorHandlerType;
}

void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
}

void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
{
}

void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
IErrorHandler errorHandler;

try
{
errorHandler = (IErrorHandler) Activator.CreateInstance(errorHandlerType);
}
catch (MissingMethodException e)
{
throw new ArgumentException("The errorHandlerType specified in the ErrorBehaviorAttribute constructor must have a public empty constructor.", e);
}
catch (InvalidCastException e)
{
throw new ArgumentException("The errorHandlerType specified in the ErrorBehaviorAttribute constructor must implement System.ServiceModel.Dispatcher.IErrorHandler.", e);
}

foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
{
ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;
channelDispatcher.ErrorHandlers.Add(errorHandler);
}
}
}



Now you can add the service behavior as an attribute. Note: The IServiceBehavior attribute has to go in the service implementation and NOT in the interface. Otherwise, the attribute is not properly invoked.


[ErrorBehavior(typeof(CalculatorErrorHandler))]
public class CFService1: ICalculator, IForecaster
{
#region ICalculator Members
//...
#endregion
}


The interface will have the fault contract decorated on each method of interest:

namespace MyServiceContracts
{
public interface ICalculator
{

[OperationContract]
[FaultContract(typeof(CalculatorFault), Action = CalculatorFault.FaultAction)]
int SquareIt(int input);

}
}

And finally, in the client, you catch your FaultException of expected type:

try
{
wcfClient.DoubleIt(32);
}
catch (FaultException<CalculatorFault> fecf)
{
Console.WriteLine("Client: Got expected Fault Exception of type CalculatorFault: " + fecf.Message);
}


test:
try
{
wcfClient.DoubleIt(32);
}

test2:
for (int i = 0; i < 4; i++)
{
    //do something
}


test3:
for in()
    sfadaf
endfor

Hello World

A "Hello World" to you all !
This is my first post on blogspot.

I use http://www.manoli.net/csharpformat to insert code snippets

I added the css file contents in the layout html. Refer: