Sunday 7 June 2015


Introduction

While I was working with WCF service application, I came across a situation where I am hosting my WCF service in a console application and I don't want the console application to show up when my service is up. I fixed it this by Pinvoke a call to FindWindow() to get a handle to your window and then call ShowWindow() to hide the window. I have created a sample code to show how I did this. It is as given below.

using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace TestShowHideConsole
{
    internal class Program
    {
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private static void Main(string[] args)
        {
            string consoleWindowTitle = Console.Title;
            IntPtr hWnd = FindWindow(null, consoleWindowTitle);
            if (hWnd != IntPtr.Zero)
            {
                ShowWindow(hWnd, 0); /* 0 = SW_HIDE */
            }
            Thread.Sleep(1000*10);/* will show your console after 10 second */
            if (hWnd != IntPtr.Zero)
            {
                ShowWindow(hWnd, 1); /*1 = SW_SHOWNORMA */
            }
            ConsoleKeyInfo consoleKeyInfo = Console.ReadKey();/* this will make the window wait till some key is pressed.*/
        }
    }
}

Here in this example, this will open up a console and it will be hidden for 10 seconds and will come up after that.

How to hide a console application If it is running from another application.

If you are running the console application from another application and you want to hide the console window, then you can do like this. This will start your console application but the window will be hidden. You can see your application still running from the task manager. If you cant find your application running in the task manager, then some error is there in your application and you may need to debug it

Process p = new Process
        {
          StartInfo =  {
                       FileName = YourConsoleaApplicationFileHere,
                       Arguments = "Argument to console application if                     any.",
                       WindowStyle = ProcessWindowStyle.Hidden
/*Or you can use CreateNoWindow = true instead of WindowStyle*/
                       }
         };
p.Start();




Introduction

This error can happen when you use Microsoft Team Foundation Server(TFS) and if you don’t have proper binding files. This can happen if the solution is new in TFS and there are no binding files associated with it. You can easily fix this. To fix it, you have to go to

File -> Sourcecontrol-> change source control.


Click on the project which don’t have binding and say bind. This will automatically bind your solution with the source control. Do the same for the entire project which don’t have proper binding.

ContractFilter mismatch at the EndpointDispatcher

A "ContractFilter mismatch at the EndpointDispatcher" can happen because the client could not process the message because no contract claimed it. This can happen because of the following reasons:

  1. Your client and the service have different contracts in between.
  2. Your client and service is using a different binding in between.
  3. Your client's and service's message security settings are not consistent in between.

Most of ContractFilter mismatch at the EndpointDispatcher bugs are because you use custom binding and your binding has extra tag which is missing either at client or service side. Have a close look at your binding, verify that it is same at both client and server side. The tags has to be same at client and server side, attribute value such as timeouts can vary at client and server. This is common and will not create issue. But if you have a tag say <ReliableSession /> at client side and is missing at server side, 'http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequence' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher can happen.



Introduction

This post is for those who are working with WCF and at times sulking because of errors which does not show up and who spends lots of time debugging what is going wrong with their service and client.

I was working with a WCF service and I came across a situation where my client application is trying to connect to service via proxy and client is waiting for the call to return and it never returns finally it times out. I was not having any clue what was happening. I had application level tracing which was not able to track anything. Finally I decided to  enable WCF built in tracing!.

How to enable WCF Trace listener

By default Windows Communication Foundation (WCF) does not log messages. To enable message logging, you must add a trace listener to the System.ServiceModel.MessageLogging trace source and set attributes for the <messagelogging> element in the configuration file. Lets see how to enable WCF logging.  You can use WCF provided Configuration Editor Tool (SvcConfigEditor.exe) to configure these settings..

Basic Setting

<system.diagnostics>
  <sources>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
                 <add name="messages"
                 type="System.Diagnostics.XmlWriterTraceListener"
                 initializeData="c:\logs\messages.svclog" />
          </listeners>
      </source>
    </sources>
</system.diagnostics>

<system.serviceModel>
  <diagnostics>
    <messageLogging 
         logEntireMessage="true" 
         logMalformedMessages="false"
         logMessagesAtServiceLevel="true" 
         logMessagesAtTransportLevel="false"
         maxMessagesToLog="3000"
         maxSizeOfMessageToLog="2000"/>
  </diagnostics>
</system.serviceModel>


  1. maxSizeOfMessageToLog is the message size in memory . This size can differ from the actual length of the message string that is being logged, and in many occasions is bigger than the actual size. As a result, messages may not be logged. So consider this situation and set the value of maxSizeOfMessageToLog appropriately.
  2. logMessagesAtServiceLevel This boolean value is for logging messages at service level. Messages logged at this layer are about to enter (on receiving) or leave (on sending) user code. By default all messages at the service level are logged. Infrastructure messages (transactions, peer channel, and security) are also logged at this level, except for Reliable Messaging messages. On streamed messages, only the headers are logged. In addition, secure messages are logged decrypted at this level.
  3. logMessagesAtTransportLevel This boolean value is for logging messages at transport level. Messages logged at this layer are ready to be encoded or decoded for or after transportation on the wire. By default all messages at the transport layer are logged. All infrastructure messages are logged at this layer, including reliable messaging messages. On streamed messages, only the headers are logged. In addition, secure messages are logged as encrypted at this level, except if a secure transport such as HTTPS is used.


Where to apply the log

You can apply the configuration on both service side and client side configuration file. You can analyse the log file which will be created after you run the service. Here if you are using the trace listener as-is then it will create a log file at "c:\logs\messages.svclog". you can change the file location as you like.

Recommended Setting for debugging 


When you are using logging in  debugging environment , and you are using WCF trace sources, set the switchValue to Information or Verbose, along with ActivityTracing. To enhance debugging, you should also add an additional trace source (System.ServiceModel.MessageLogging) to the configuration to enable message logging. Notice that the switchValue attribute has no impact on this trace source.
You can set the switchValue attribute to Information in all the previously mentioned cases, When you set the switchValue attribute to Information, it will log all messages. A recommended configuration is as shown below.

 <configuration>
 <system.diagnostics>
  <sources>
    <source name="System.ServiceModel" switchValue="Information,
 ActivityTracing"
            propagateActivity="true" >
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
    <source name="System.ServiceModel.MessageLogging">
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
    <source name="myUserTraceSource" switchValue="Information, ActivityTracing">
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="xml"
         type="System.Diagnostics.XmlWriterTraceListener"
               initializeData="C:\logs\Traces.svclog" />
  </sharedListeners>
 </system.diagnostics>

 <system.serviceModel>
  <diagnostics wmiProviderEnabled="true">
      <messageLogging 
           logEntireMessage="true" 
           logMalformedMessages="true"
           logMessagesAtServiceLevel="true" 
           logMessagesAtTransportLevel="true"
           maxMessagesToLog="3000" 
       />
  </diagnostics>
 </system.serviceModel>
</configuration>

Recommended setting for Production environment 


When you are using logging in production environment, and you are using WCF trace sources, set the switchValue to Warning. If you are using the WCF System.ServiceModel trace source, set the switchValue attribute to Warning and the propagateActivity attribute to true. If you are using a user-defined trace source, set the switchValue attribute to Warning, ActivityTracing. If you do not fell like there will be any performance hit, you can set the switchValue attribute to Information in all the previously mentioned cases, When you set the switchValue attribute to Information, it will log all messages which will be a fairly large amount of data and this is why it should be avoided if you feel it will cause you performance hit. A recommended configuration is as shown below.

<configuration>
 <system.diagnostics>
  <sources>
    <source name="System.ServiceModel" switchValue="Warning"
            propagateActivity="true" >
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
    <source name="myUserTraceSource"
            switchValue="Warning, ActivityTracing">
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="xml"
         type="System.Diagnostics.XmlWriterTraceListener"
               initializeData="C:\logs\Traces.svclog" />
  </sharedListeners>
 </system.diagnostics>

<system.serviceModel>
  <diagnostics wmiProviderEnabled="true">
  </diagnostics>
 </system.serviceModel>
</configuration>

After enabling WCF level logging you will come to know what is wrong in your system. When you have the type of exception that you have, its much simpler to fix it. :)



Introduction

  This fix explained here is helpful if you are using WCF and when you try to access the service, the client throws an exception like "An endpoint configuration section for contract ‘YourContract' could not be loaded because more than one endpoint configuration for that contract was found. Please indicate the preferred endpoint configuration section by name".

How to fix this exception 

  WCF service can expose more than one endpoint and client can use any of this endpoint but not more than one at a time. This type of exception occurs when you have more than one endpoint configured at your configuration file (app.config) file while adding service reference or while configuring service at client side manually. You can have only one and only endpoint for the client. If you are getting this exception then check your client side configuration file and make sure the client tag under system.serviceModel has only one endpoint configured.

<system.serviceModel>
   <client>
      <endpoint [...]>
     </endpoint>
   </client>
</system.serviceModel>


Introduction

WPF applications support rich media and graphics, this require styles and styles can be reusable across different window or element in WPF. Here we need a mechanism by which we can share this style across different window or say application. By adding the style in application resource file, we can share it across windows in application but not across application. Here reusable styles need to be utilized and in a managed way. Here WPF provide an easy way to manage these styles and other reusable resources which can be used across WPF windows and across application. This is called Resources Dictionary. We can define the styles in WPF XAML files and can manage all our useful styles for a particular application in a resource dictionary file. This resources dictionary can then be referred from other WPF projects and can use the styles in this resources dictionary in that project.

Using the code

Adding a resource dictionary is pretty simple. We have to select the project or folder in Solution Explorer and then right click and select “Add”. We will get a menu item called “Resource Dictionary”. Selecting that menu item will pop up the Add New Item wizard with the Resource Dictionary Item template selected. Rename the item as you wish. In a Resource Dictionary, we can keep our custom styles, Templates, custom definitions for Brush, Color, Background and a lot of other stuff. Most important thing is that we have to assign a key to each of them since it is a Dictionary and it stores the values besed on the key. Or perhaps, we can give names to the styles.

How to refer to Resource Dictionary and use it in WPF xaml.

In this section, we are going to see how we can import a resource file to a XAML file for a WPF Window, user control or a page.  We can refer to the resource dictionary that we created for our window resources section. Since we can have a resource dictionary for each control, we are going to merge the other resource files to the existing resource dictionary.

<Window […] >
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary 
                  Source="ResourceDictionaryReferencePath/ResourceDictionaryName.xaml">
                </ResourceDictionary>
                <ResourceDictionary 
                  Source=" ResourceDictionaryReferencePath/ResourceDictionaryName.xaml ">
                </ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    </Window>

How to refer to resource dictionary from another project.

If your resource dictionary is in a different project, then make sure that the project can be referred from the project that you need the resource. If not then WPF will throw an exception at runtime. Either add reference to that project or drop that project dll to your applications folder so that your application can refer to it. Here the source path depends on where you have added your dictionary. If you have added resource file to the root of your application, then you can refer to this file as

Source="ResourceDictionaryName.xaml"

If you have added this file to a directory in your project then you can refer to it as

Source= "ResourcesDirectoryReferencePath/MyResourceDictionary.xaml"

If you your resources dictionary is in another project then you can refer to it as

Source= "pack://application:,,,/ApplicationNameWhereResourceDictionaryResides; component/ResourceDictionaryName.xaml"


Introduction

 This post will help you in binding a command to a button, where the button is defined in a template say a data template. With normal command binding it won’t work. We need some sort of workaround to achieve this.

How to fix this.

 Here the requirement is to bind a command to an element which is defined in a template. When we do a normal command binding, it is not aware of the data context and will not resolve. We need to provide the binding with the data context. This can be achieved in many ways say you can do
<Button Content="{Binding}" Command="{Binding RelativeSource={RelativeSource Window}, Path=DataContext.ClickHandlerCommand }" />

<Button Content="{Binding}" Command="{Binding Path= ClickHandlerCommand, Source={StaticResource MainWindow}}" />

<Button Content="{Binding}" Command="{Binding Path= ClickHandlerCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

But these won’t work with all scenarios. But one solution will work with all scenarios. Define your data context as a static resource and refer it as the source of the binding. As shown below.

<Window […]
        xmlns:this="clr-namespace:Your.Namespace.For.The.ViewModel"
        […]>

    <Window.Resources>
        <this:MainWindowViewModel x:Key="Model" />

        <DataTemplate x:Key="ItemsDataTemplate">
          <Button Content="{Binding }" Command="{Binding Command, Source=                            {StaticResource Model}}" />
        </DataTemplate>

    </Window.Resources>

    <Window.DataContext>
        <this:MainWindowViewModel></this:MainWindowViewModel>
    </Window.DataContext>

        <Grid>
        <ItemsControl ItemTemplate="{DynamicResource ItemsDataTemplate"  ItemsSource="{Binding Collections, Mode=OneTime}" >
            
        </ItemsControl>
    </Grid>
</Window>

Introduction

In this post we will see how to fix the exception due to mixed mode assembly while working with version 4.0 of runtime.

Background

I was working with a project which uses an older mixed mode assembly and I got an exception like mixed mode assembly is built against another version of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information. When I was able to fix this, I felt like this should be shared with all so that people can save their time.

Using the code

Mixed mode assembly is built against another version of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
If you are using .net version 4.0 there can be a chance of getting an error like this.
Additional information: Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
This error happens because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode.

How did I fixed it

To fix this, You have to add the below settings to your App.config file under configuration tag.
<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0"/>
    <requiredRuntime version="v4.0.20506"/>
</startup>


Introduction

In this post we will see how to fix the exceptions like this which hapens even after adding proper dll(s). Here in this post we will see how to fix exception, "The type or namespace name Data does not exist in the namespace Microsoft.Practices.EnterpriseLibrary (are you missing an assembly reference?)"

Background

I was working on a project when I encountered one exception which was The type or namespace name 'Data' does not exist in the namespace 'Microsoft.Practices.EnterpriseLibrary' (are you missing an assembly reference?)
I added the proper dll reference but still I was getting this compilation error. I was wondering what is going wrong. I tried to browse the class inside this dll using object browser. I was able to find classes inside this dll. I tried to create an object of the class which was inside the dll; I was able to create the object while I was writing the code. When i build it, it again failed.

1. Added Proper dll reference but compilation fails.
2. Exception the type or namespace name 'Data' does not exist in the namespace even after adding proper dll references.
Using the code

How did I fix this exception

Finally when I check the project configuration, I was running .Net Framework 4.0 Client Profile. I made it to .Net Framework 4.0 and everything worked perfectly.

The .NET Framework 4 Client Profile is a subset of the .NET Framework 4 which is optimized for client applications. It provides functionality for most client applications, including Windows Presentation Foundation (WPF), Windows Forms, Windows Communication Foundation (WCF), and ClickOnce features. This enables faster deployment and a smaller install package for applications that target the .NET Framework 4 Client Profile. If you are targeting the .NET Framework 4 Client Profile, you cannot reference an assembly that is not in the .NET Framework 4 Client Profile. Instead you must target the .NET Framework 4. This is what happening in my case. :)

To change the Target Framework, Go to your project in the solution and right click on the project and select properties. In the window that comes up, select the Application tab. There you can see the Target Framework section. Select the .Net Framework 4 instead of .Net Framework Client Profile. :)