Alik Levin's

Clarity, Technology, and Solving Problems | PracticeThis.com 

February, 2008

  • Alik Levin's

    Securing IIS7 - Windows Server 2008 Security Guide

    • 1 Comments

    Windows Server 2008 Security Guide is out.

    It covers many crucial aspects but my favorite of course is IIS7 chapter:

    Chapter 6: Hardening Web Services

    This chapter provides prescriptive guidance for hardening the Web Server role. The chapter discusses how the Web server role installs Microsoft® Internet Information Services (IIS) 7.0, which has been redesigned into forty modular components that you can choose to install as needed.

    It points to the following resources:

  • Alik Levin's

    How To Consume WCF Using AJAX Without ASP.NET

    • 11 Comments

    RESTful .NET - Build and Consume RESTful Web Services

    How to consume WCF services directly from Html client? How to add AJAX-like functionally to application that does not natively support ASP.NET AJAX like classic ASP, ASP.NET 1.1, or PHP?

    WCF that ships with .Net 3.5 provides capability to consume it from any JavaScript enabled client via XML or JSON encoding. There is new built in webHttpBinding that supports either JSON or XML encoded messages to be sent to WCF services.The functionality can dramatically improve performance and user experience.

    This post summarizes the steps to create and consume basic WCF service using webHttpBinding binding.

    Summary of Steps

    • Step 1 – Create WCF service.
    • Step 2 – Configure WCF end point.
    • Step 3 – Create JavaScript to invoke WCF service.
    • Step 4 – Test the solution.

    Next section describes each and every step in details

    Step 1 – Create WCF service

    Open Visual Studio and create new WCF service project by choosing "WCF Service Application" template under "Web" project type. Name it Wcf2Ajax. Open IService1.cs file and create OperationContract as follows:

       1: [ServiceContract]
       2:  public interface IService1
       3:  {
       4:  
       5:      [OperationContract]
       6:      string Sum2Integers(int n1, int n2);

    Open Service1.svc.cs file and add public method that accepts to integers and returns the sum of it. This is the functionality that will be exposed by the WCF service and consumed by JavaScript enabled client:

       1: public class Service1 : IService1
       2: {
       3:     public string Sum2Integers(int n1, int n2)
       4:     {
       5:         int result = num1 + num2;
       6:  
       7:         return result.ToString();
       8:     }

    Step 2 – Configure WCF end point

    Open web.config file and add <binding> section to <system.serviceModel section. Add <webHttpBinding> to binding section:

    <system.serviceModel>
      <bindings>
        <webHttpBinding>
          <binding name="AjaxBinding"/>
        </webHttpBinding>
      </bindings

    Add AjaxBehavior to <behaviors> section to support WCF invocation via AJAX:

    <behaviors>
      <endpointBehaviors>
        <behavior name="AjaxBehavior">
          <enableWebScript/>
        </behavior>

    Configure WCF service's endpoint to use newly created binding:

    <endpoint address="ajaxEndpoint" 
              behaviorConfiguration="AjaxBehavior" 
              binding="webHttpBinding" 
              bindingConfiguration="AjaxBinding" 
              contract="Wcf2Ajax.IService1">

    Step 3 – Create JavaScript to invoke WCF service

    Add Html file to the solution by right clicking on the solution node in solution explorer and choosing "New Item..." and then "HTML Page" template. Name it WCFConsumer.htm. Add few HTML controls - two text boxes to accept two integers, one pure HTML button to trigger WCF call, and <span> element to present the result:

    <input type="text" id="num1" />
    <input type="text" id="num2" />
    <br>
    <input type="button" onclick="CallWcfAjax()" value="Call WCF via AJAX" />
    Result <span id="result"></span>
    

    Add <script> block to <header> section and add JavaSctip that builds HTTP request and wires invocation function to some event, say button click:

        <script type="text/javascript">
        function CallWcfAjax()
        {
            var xmlHttp = new ActiveXObject("Microsoft.XmlHttp");
    
            var url = "Service1.svc/ajaxEndpoint/";
            url = url + "Sum2Integers";
    
            var body = '{"n1":';
            body = body + document.getElementById("num1").value + ',"n2":';
            body = body + document.getElementById("num2").value + '}';
              
            // Send the HTTP request
            xmlHttp.open("POST", url, true);
            xmlHttp.setRequestHeader("Content-type", "application/json");
            xmlHttp.send(body);
    
            // Create result handler 
            xmlHttp.onreadystatechange= function X()
            {
            
                 if(xmlHttp.readyState == 4)
                 {
                      result.innerText = xmlHttp.responseText;
                 }
            }
        }
        </script>
    

    Step 4 – Test the solution

    Build the solution and navigate to WCFConsumer.htm. Provide two integers to both text boxes and hit "Call WCF via Ajax" button. You should expect for result similar as depicted below:

    image

    Parse the result to your needs.

     

    My related post

     

    Related resources

    Download Visual Studio 2008 project with the sample from my SkyDrive

     

  • Alik Levin's

    Performance Sin - Using Exceptions To Control Flow

    • 4 Comments

    Want to spot coding anti-patterns from performance perspective without actually looking in the code?

    One of the common performance coding anti-patterns I’ve noticed lately is using Exception Handling to control program flow.

    The anti-patterns

    Most common anti-pattern is just using exception handling to control flow, in some cases it was even nested exception handling – that means the exception is thrown anyway.

    In other cases there were empty “catch” exception statements. That means that precious cycles .Net consumes to handle the exception spent for nothing.

    The last case was where exception handling was done to catch simple types parsing. That was done on each request.

    How to identify Exception Handling anti-pattern

    To identify exception handling anti-pattern set “.NET CLR Exceptions/# of Excepts Thrown” perf counter. If you see the graph constantly climbs on each request chance are Exception Handling is used to control the flow which is performance anti-pattern:

    clip_image002

    Look at the relevant source code to spot try/catch blocks. If the source code is not available use Reflector to reverse engineer the compiled assemblies into C# sources – I used it very successfully during my latest performance review.

    Best practices

    Do not use exception handling to control the flow. Try to reduce catching exceptions to only most upper component/class. Catching exceptions is expensive from both CPU and memory perspective.

    Use TryParse method instead Parse method to avoid throwing exceptions .

    Use simple "if" statement to check for nulls.

    Tools

    Use perfmon to spot the anti-pattern with Exception handling. Run perfmon in command line and add “.NET CLR Exceptions/# of Excepts Thrown” counter. Then run few scenarios to see the graph.

    Use Practice Checker for static code analysis. The tool scans the code and reveals excessive usage of exception handling.

    My related posts

Page 1 of 1 (3 items)