in

mscommunity.net

Interactive mscommunity.net online activities

DamirDobric

ožujak 2009 - Posts

  • Creating of Proxies inside of Singleton Service

    Problem description

    Sometimes you will have to connect to some other service while executing of some service method in your service. Following example shows the method “TestMethod”, which performs this action. When the consumer invokes the operation Operation1(), the operation creates the new proxy instance on each call. For the sake of simplicity this code does not perform any action on created channel instance.

    When you do this the service code will do leaking as Steve has noticed in this post. Not that leaking happens only if instance context mode is set on Single.

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public void Operation1()
    {

                BasicHttpBinding b2 = new BasicHttpBinding();

                ChannelFactory<ISomeOtherService> fx = new ChannelFactory<ISomeOtherService>(b2, "http://localhost:51234/Test2");

                ISomeOtherService proxy = fx.CreateChannel();

                ((IChannel)proxy).Close();

                ((IDisposable)proxy).Dispose();

    }

     

    Here is the related host sample.

     

      ServiceHost host = new ServiceHost(typeof(MyService), new Uri("http://localhost:51234/Test"));
    host.AddServiceEndpoint(typeof(IMyService), new BasicHttpBinding(), "");

                host.Open();

     

    Workaround:

    First it is important to know that leaking-issue will happen in all bindings. That means it is not a WCF-bug in some specific binding. Note also, that the trivial code in Operation1 does not produce leak at all. You can prove this if you copy the code in some other none-WCF method and execute it in endless loop. You will notice that there is no leak.

    So, if all works fine, how it is possible that the code above produce leaks? The answer is deep down in WCF part called OperationContext.
    The code shown above will produce leaks only if the operation context exists. When this is case and when not is out of scope of this post (For example if security is totally disabled operation context is null).

    When the channel is created and the operation context exists, then each new channel instance is appended in the list of WmiChannels (see property InstanceContext.WmiChannels in code below). This list causes the leak. However if the InstanceContext is recreated on each invoke of operation (that is when InstanceContextMode is set on PerCall), the list will be recreated and no leak will be caused.

    Here is s short snapshoot of WCF factory CreateChannel code:

    public object CreateChannel()
    {
             serviceChannel = …

              . . .


              OperationContext current = OperationContext.Current;
              if ((current != null) && (current.InstanceContext != null))
              {
                  current.InstanceContext.WmiChannels.Add((IChannel)serviceChannel.Proxy);
                  serviceChannel.WmiInstanceContext = current.InstanceContext;
              }

              return serviceChannel.Proxy;
    }

    So, we could now discuss about this behavior trying to declare it as design issue of WCF or even let it as it is. Please let me know what you think.

    However, solution for this issue could be and is to create proxy instances for one destination only once and store them internally in some member. Assuming that the InstanceContext is set on “Single” means that the service instance is singleton. If this holds, then also proxy instances can be singletons too. If not, then one could ask, “why the service should be singleton at all”?

     

    Damir

  • Code which outputs to WCF trace

    The code snippet below has explicitly nothing to do with WCF. But, it can be used to output trace messages to the WCF-log file, which can be read by WCF Trace Tool.
    In other words, this example answers two questions:

    1. How to trace messages to WCF trace? Messages are mixed with service model messages and/or traces
    2. How to trace messages which can be graphically presented by WCF Trace Tool? So, this tool can be used for reading of traces of any kind of .NET application.

    After executing the code below follow instructions shown in this post.

     [TestMethod]

    public void TestTrace()

    {

    TraceSource wcfTrace  = new TraceSource("System.ServiceModel");
    Guid currentActivity = Trace.CorrelationManager.ActivityId;
    Guid newActivity = Guid.NewGuid();
    Guid newActivity2 = Guid.NewGuid();

          Guid newActivity3 = Guid.NewGuid();


    wcfTrace.TraceEvent(TraceEventType.Start, 100, "[+] Method entered");


    wcfTrace.TraceEvent(TraceEventType.Information, 101, "[+] In current activity");

    wcfTrace.TraceEvent(TraceEventType.Start, 100, "[+] Still in current activity");


    wcfTrace.TraceEvent(TraceEventType.Information, 102, "[+] Still in current activity");

    wcfTrace.TraceTransfer(0, "[+] Start Level 1 activity", newActivity);

         

    Trace
    .CorrelationManager.ActivityId = newActivity;

    wcfTrace.TraceEvent(TraceEventType.Information, 103, "[+] Hello from Level 1");

    wcfTrace.TraceEvent(TraceEventType.Warning, 104, "[+] Level 1");
    wcfTrace.TraceEvent(TraceEventType.Error, 103, "[+] Level 1");
    wcfTrace.TraceEvent(TraceEventType.Critical, 105, "[+] Level 1");
    wcfTrace.TraceTransfer(0, "[+] Start Level 2 activity",newActivity2);



    Trace.CorrelationManager.ActivityId = newActivity2;


    wcfTrace.TraceEvent(TraceEventType.Information, 102, "[+] Hello from Level 2");

    wcfTrace.TraceEvent(TraceEventType.Information, 103, "[+] Level 2");

    wcfTrace.TraceTransfer(0, "[+] Jump back to level 1", newActivity);

    Trace.CorrelationManager.ActivityId = newActivity;

    wcfTrace.TraceEvent(TraceEventType.Transfer, 101, "[+] Hello from Level 1");

    wcfTrace.TraceEvent(TraceEventType.Information, 102, "[+] Level 1");

    wcfTrace.TraceTransfer(0, "[+] Jump back to current",

    currentActivity);


    Trace
    .CorrelationManager.ActivityId = currentActivity;

    wcfTrace.TraceEvent(TraceEventType.Information, 103, "[+] Again in current activity");

    wcfTrace.TraceEvent(TraceEventType.Stop, 101, "[+] Method exited");

     }

  • Happy T-Mobile UMTS Express Card user Part II

    Few month ago I described briefly in this post how happy I was after successful installation of my UMTS card. Usually, everything was working fine two or three hours per day. After that I always had to restart machine, because huawei driver has been hanging. This cause all networking applications like browser etc. to hang too. After this happens, there is no possibility to use such applications until the machine is restarted. :( :(

    Imagine now, you are developer working with 10 instances of Visual Studio connected (via network) to Team Foundation Server.

    Sometimes I cannot believe that this still happen in year 2009.

    Now as part two, I installed Windows 7 BETA. I didn’t want, but I had to install some service pack for Vista. So I install Win7. Imagine now, you have to install the story from this post on Windows 7 BETA version. Everybody will tall you that you are crazy. But probably not because of Windows 7.

    Here is how to do it:

    1. Insert the card. (First start the machine)

    2. Wait on USB driver to be installed. After that new usb drive will be discovered.

    3. Choose automatic installation.

    4. After a while you will get some error message. You will not be able to understand it totally. it is some kind of strange technical English. Don’t wary just press “Next” and try to forget that something goes wrong. The message means that the software cannot be installed on this unknown version of operative system.

    5. After installation you will be notified that everything is installed correctly. This is not true. It is just some transaction problem of installer. I assume that 50% of package was not installed. The good thing is that UMTS and GPRS modems have been installed.

    6. Forget what happened now and restart machine.

    7. Open network sharing center and perform configuration as shown at the picture below.

    image

    image

    That’s all.

    PS. Hi T-Mobile and Huawei guys. Could you please, please try to document all these issues on some page which has good search ranking. I have a feeling that I can find everything in internet, but nothing about your drivers.

    Here is a pretty simple deal.

    Open google and look for “download driver {cordnuameandnumber}”

    If you find something at the first page community will give you score of 100.

  • Using of WCF Trace

    Tracing in WCF is could be very powerful feature helping to diagnostic activities behind the scene. Unfortunately it is not well documented and not often used at all. In this post I will describe how to use WCF tracing.

    Trace in WCF is is build on top of .NET Trace features. It means internally WCF use TraceSource-s. The WCF trace source behind the scene is implemented in the class System.Diagnostics.XmlWriterTraceListener in System assembly. That means it does not have anything to do with WCF. If this is true, then it should be possible to use Microsoft Service Trace Viewer tool without WCF too.

    Additionally, it is important to know that WCF use two different sources System.ServiceModel and  System.ServiceModelMessageLogging. Both sources are based on XmlWriterListener. That means that even the format of messages in both sources is the same. First one is used for tracing purposes and second one for tracking of messages.

    I use usually second one for tracking. If some bad error occurs I usually switch to the first one. Here is the configuration for both. Note that switchValue "Information" is highlighted and no propagateActivity attribute is set (if used this attribute could cause some issues. If you use Service Config Editor this attribute is by default set on true).

    <system.diagnostics>
        <sources>
          <source name="System.ServiceModel" switchValue="Information, ActivityTracing">
            <listeners>
              <add type="System.Diagnostics.DefaultTraceListener" name="Default">
                <filter type="" />
              </add>
              <add name="ServiceModelTraceListener">
                <filter type="" />
              </add>
            </listeners>
          </source>
          <source name="System.ServiceModel.MessageLogging"
               switchValue="Information, ActivityTracing">
            <listeners>
              <add type="System.Diagnostics.DefaultTraceListener" name="Default">
                <filter type="" />
              </add>
              <add name="ServiceModelMessageLoggingListener">
                <filter type="" />
              </add>
            </listeners>
          </source>
        </sources>
        <sharedListeners>
          <add initializeData="c:\\temp\\Web_tracelog.svclog"
           type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0,
                 Culture=neutral, PublicKeyToken=b77a5c561934e089
    "

           name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
            <filter type="" />
          </add>
          <add initializeData="c:\\temp\\Web_messages.svclog"
           type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0,
                 Culture=neutral, PublicKeyToken=b77a5c561934e089
    "
           name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
            <filter type="" />
          </add>
        </sharedListeners>
        <trace autoflush="true" />
      </system.diagnostics>

    If you want to use a trace you do not need any service. Just execute the code below and open c:\\temp\\Web_tracelog.svclog. with WCF Trace Viewer. Picture below shows the result.

    [System.ServiceModel.ServiceContract]
        public interface IService
        {
            [OperationContract]
            BusinessObjectBase GetProcess(string businessObject);

            [OperationContract]
            BusinessObject1 GetProcess1(string businessObject);
        }

     

    image

  • About "KnownTypeAttribute" example

    When working with Web Services it is often the case that service utility "svcutil" generates classes which contains attribute KnownTypeAttribute. Because people very often asking about meaning of this attribute, I will give very short example which briefly describes its purpose. Assume there is a service IService, which has two operations as shown below:

    [System.ServiceModel.ServiceContract]
        public interface IService
        {
            [OperationContract]
            BusinessObjectBase GetProcess(string businessObject);

            [OperationContract]
            BusinessObject1 GetProcess1(string businessObject);
        }

     

    [DataContract(Namespace = HcmService.cNamespace)]
        public class BusinessObjectBase
        {
            [DataMember]
            public Guid Id { get; set; }

            [DataMember]
            public string Key { get; set; }
        }

     

    [DataContract(Namespace = HcmService.cNamespace)]
        public class BusinessObject1
        {
            [DataMember]
            public string Key1 { get; set; }
        }

    Note that BusinesObjectBase represents a bas class and BusinesObject1 derives from the base class. Also note, that it is not important what these two methods will do with business objects. Important is, that there is at least one operation which use both business objects. In other words, as long there is no operation which uses one object, the object will NOT BE a part of service contracts. For example, if operation GetProcess1 wouldn't exists, the contract would include BusinessObjectBase type only.

    If you start svcutil against this service as shown above, the imported contract will import both types. Now, let's take a look on imported types.
     

    [SerializableAttribute()]
    [KnownTypeAttribute(typeof(BusinessObject1))]
    public partial class BusinessObjectBase : object, IExtensibleDataObject, INotifyPropertyChanged
    { . . .}

     

    [SerializableAttribute()]
    public partial class BusinessObject1 :
    object, IExtensibleDataObject,
    { . . .}

    As you see svcutil has disovered that BusinessObject1 is derived from BusinessObjectBase. It means BusinessObjectBase has attribute KnownType helps serializer to deserialize BusinessObject1 if service returned it instead of BusinessObjectBase. Now it is interesting, that this is not a service setting. It is all about intelligence of svcutil. So, svcutil will alwas try to discover right types and append them as KnownAttribute. This allows serializer at the client side to work properly.

    Unfortunately this is one part of the story only, because the example shown above will not work. Imagine the service implementation of GetProcess looks like:

    public BusinessObjectBase GetProcess(string businessObject)
    {

        return new BusinessObject2();
    }

    You may not believe, but this code will fail at the service side with following exception, shic can only be seen in the WCF trace viewer.

    There was an error while trying to serialize parameter http://tempuri.org/:GetProcessResult. The InnerException message was 'Type BusinessObject2' with data contract name 'BusinessObject2:' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'.  Please see InnerException for more details.

    When trying to invoke the service you will get following exception at the client side:


    {"The underlying connection was closed: The connection was closed unexpectedly."}


    To solve the problem you have to decorate the BusineObjectBase class at the service side as shown:
     

    [KnownType(typeof(BusinessObject1))]
    [KnownType(typeof(BusinessObject2))]
    [DataContract(Namespace = HcmService.cNamespace)]
    public class BusinessObjectBase
    {
            [DataMember]
            public Guid Id { get; set; }

            [DataMember]
            public string Key { get; set; }
    }

    This instructs serializer at the service side that when serializing return values or deserializing requests instead of BusinessObjectBase two more types can be used. Now you can return in GetProcess both types BusinessObjec1 and BusinessObjec2.

    One more thing. In examples above without of last decoration at service side, svcutil has knowledge about BusinessObject11, because it is used as part of contract of operation GetProcess2. This is a reason why svcutil has decorated BusinessObjectBase with KnownType=BusinessObject1. Because BusinessObject2 is not part of contract in any of operations, the client will not known anything about it. If client doesn't know about type, but service knows (this happens when client has imported reference to service and service has implemented new type later.) following exception will be thrown at the client side, when service returns a new type:

     

    The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:GetProcessResult. The InnerException message was 'Error in line 1 position 471. Element 'http://tempuri.org/:GetProcessResult' contains data of the 'BusinessObject2' data contract. The deserializer has no knowledge of any type that maps to this contract. Add the type corresponding to 'BusinessObject2' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.'.  Please see InnerException for more details.

    Sometimes it is useful to have a method which dynamically creates known types. That is when your types are possibly dynamically created. In such cases it is not possible to declare known types if types are not know at design time. Follwong example shows how to do this by using of ServiceKnownType instead of KnownType.

    ServiceKnownType("GetAllMyKnownTypes", typeof(KnownTypeContainer))]
    [ServiceContract()]
    public interface ITableService
    {
        // Table could contain any type
    [OperationContract] Hashtable GetTableItems(); } static class KnownTypeContainer { public static IEnumerable<Type> GetAllMyKnownTypes(ICustomAttributeProvider p) { System.Collections.Generic.List<System.Type> dynamicyTypes = new System.Collections.Generic.List<System.Type>();
            // Here I'm adding my static types.
    // Usually I could generate the type on the fly and append it here.
    knownTypes.Add(typeof(MyType1)); knownTypes.Add(typeof(ByType2)); return knownTypes; } }

     

    :)

     

    Posted ožu 24 2009, 10:26 by anonymous
    Filed under:
  • Issue while installing Silverlight 3 BETA 1

    After installing Silverlight 3 BETA, I run into some series issues which will also not make your day funny. So, I decide to post the workaround.

    Problem description:

    If your application uses WCF, after installation you can send your development team home, because they will not be able to work. The installation works more or less fine, if you don’t mind that VS is restarting a twice only (also interesting Silverlight-Only experience). More over if you use TFS, the VS will hangs waiting to enter credentials (I was running installation in VPN).

    But, much more interesting (please read: "funny") is following:

    After installation you will not be able to compile, because something with service references are damaged. After you try to update them following error appears:

    Error “Object reference not set to an instance of an object” when adding a WCF service.

    No problem you may say. Just delete existing and try to add the new one. Uupps, now following error will smile to you:

    Error “Unable to find ‘DynamicTypeService’” 

    By the way one more thing. VS is crashing after exit. This one you can solve by just closing you eyes and awaiting for few minutes. We, software people have enough time anyhow. :)

    The solution:

    1. Uninstall Silverlight 3.0 and VS tools. (two uninstalls not one)

    2. Find the assembly Microsoft.VisualStudio.ServicesProxy.dll in folder c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE and rename it.

    3. Install Silverlight 3 again.

    4. You will have to restart the machine now. Before you do that, go into named folder and be sure that the ServicesProxy.Dll is in folder. The new version is from March 12. 2009. If not so do not restart, it will not help.

     

    Hope this helps.

  • Hot developer downloads March 09

    Microsoft Silverlight 3 Software Development Kit Beta 1 - March 2009

    http://www.microsoft.com/downloads/details.aspx?familyid=11DC7151-DBD6-4E39-878F-5081863CBB5D&displaylang=en

    This software development kit provides libraries and tools for developing Silverlight applications.

    Windows Azure Software Development Kit - March 2009 Community Technology Preview

    This software development kit provides developers with the APIs, tools, documentation, and samples needed to develop Internet-scale applications that run on Windows Azure.

    Windows Azure Tools for Microsoft Visual Studio - March 2009 Community Technology Preview

    Windows Azure Tools for Microsoft Visual Studio extend Visual Studio to enable the creation, building, debugging, running, and packaging of scalable services on Windows Azure. Installation includes the Windows Azure Software Development Kit.

    Microsoft .NET RIA Services - March 2009 Preview

    The .NET RIA Services is an framework that provides a pattern to write application logic that runs on the mid-tier and controls access to data for queries, changes, and custom operations.

    Microsoft Code Analysis Tool .NET v1 Community Technology Preview - 32 bit

    The Microsoft Code Analysis Tool .NET is a binary code analysis tool that helps identify common variants of certain prevailing vulnerabilities that can give rise to common attack vectors such as Cross-Site Scripting, SQL Injection, and XPath Injection.

  • Internet Explorer 8 (IE8) top features

    Top new features in Internet Explorer 8 are:

    · Accelerators. Accelerators give people easy access to the online services they care about most from any page they visit and allow users to browse faster by eliminating most of the clicks required to access desired content and services.

    · Web Slices. With Web Slices, people can see the information they want to see most often without going away from the page they are on. Appearing in the Favorite bar, users can identify Web Slices with updates when in bold and they can see a rich Web Slice visualization of their content with access back to the source Web page.

    · Instant Search Box. The enhanced Instant Search Box in Internet Explorer 8 is more helpful, making it easier for people to find content of interest and increasing the relevancy of search results. As users type a search term, they can see real-time search suggestions, including images and rich text, from their chosen search provider.

    · Smart Address Bar. Provides matches as the user types across History and Favorites searching against all parts of the URL string (and the page title) instead of just the beginning. Allows mistyped entries to be removed from the Address Bar.

    · Enhanced Tabbed Browsing.  Tabs are grouped and color-coded so people can quickly discern which are related. It is easy to group or ungroup tabs or reopen closed tabs.

    · Performance improvements. We’ve reduced the time that people must wait when starting the browser, opening a “new tab” and loading a page.

    · SmartScreen Filter. Built upon the Microsoft Phishing Filter, the SmartScreen Filter helps protect against a broader set of phishing threats and helps protect from sites that attempt to download malicious software. The SmartScreen Filter is now easier to use with enhanced user interface and warning messages to reduce users’ click-through to confirmed sites.

    · Domain Highlighting. Internet Explorer 8 highlights the domain name of the URL string in the Address Bar in bold text, making it easier for people to tell which site they are on and aid them in identifying phishing sites and other deceptive sites. The domain name is in black, standing out from other characters in the URL, which are gray.

    · Cross-Site Scripting filter. Helps protect users and systems from attacks that can lead to information disclosure, cookie stealing, account/identity theft or otherwise masquerading as the user without permission.

    • InPrivate. InPrivate helps to protect people’s data and privacy from being retained locally on the PC they are using. This protects against third parties who might be in a position to track their online activities.  The consumer has the ability to use either of the features (InPrivate Browsing or InPrivate Filtering) independently.
      • InPrivate Browsing. When activated, InPrivate Browsing helps ensure that History, temporary Internet files and cookies are not recorded on a PC after browsing. When in InPrivate Browsing, toolbars and extensions are automatically disabled and browsing History is automatically deleted when the browser is closed.
      • InPrivate Filtering. InPrivate Filtering helps protect privacy by enabling the consumer to block content coming from third parties that are in a position to track and aggregate their online behavior. Users are provided with notice, choice and control of which third parties to allow and which ones to block.
    For a comprehensive look at the features in Internet Explorer 8, please see the fact sheet available here.
  • Future of BizTalk Server

    BizTalks has always been Microsoft's major integration product. Although Microsoft is extending the Server platform with "Dublin", BizTalk Server will definitely remain major integration product for long, long time. Currently BizTalk-Team is designing future versions which will come after BTS2009. They are known under names BizTalk V. Next(V7) and V.Next +1(V8).

    More about this by Sudhir.

  • Improving Web Services Security: Scenarios and Implementation Guidance for WCF

    For all WCF (Windows Communication Foundation) developers and those who think to adopt this technology in the future, Patterns and Practices has released few days ago the ultimate WCF Security Guide for WCF.

    The guide covers following topics:

    1. Security Fundamentals fro Web Services

    2. Fundamentals of WCF security

    3. Intranet Application Scenarios

    4. Internet Application Scenarios

    5. Checklists

    6. Guidelines

    7. Practices

    8. Q&A-s

    9. Many, many How-To-s

    Posted ožu 04 2009, 01:50 by anonymous
    Filed under:
  • Designer Issue in Silverlight

    I found a very "funny" issue in Silverlight, which cause designer to stop working. Because, such things make me crazy, hope this post will help you save you time.
    If you have a page with some custom user control, which works properly, but designed doesn't want to show it in preview mode, try to llo for following error:

    Error    2    Unknown namespace clr-namespace:Daenet.Xy.Controls;assembly=MyNamespace.MyControl;assembly=MyAssembly. [Line: 170 Position: 63]    X:\\FieldDetailViewControl.xaml    39    17    MyAssembly

    Note, that this error doesn't appear in output window, which is not another silvering problem (out of scope).
    So, the bad on this error is that it doesn't say anything useful. Moreover it point to the line of code which from your point of view doesn't exist in whole universe for sure.

     

    image

    However, there is a little entropy of information in the error described above.

    The error is caused by declaration of the namespace (not shown above): xmlns:controls="clr-namespace:Daenet.Xy.Controls"

    Because designed for same reason doesn't parse this correctly you can help a bit.
    Change namespace as following and all will work fine:
    xmlns:controls="clr-namespace:Daenet.Xy.Controls;assembly=MyAssembly"

    Where MyAssembly is the name of assembly which implements controls with namespace Daenet.Xy.

    If you want to do all right way, use always assembly attribute in the namespace declaration.

    This is all.

Powered by Community Server (Commercial Edition), by Telligent Systems