Niraj Bhatt's profileNirajRulesPhotosBlogListsMore Tools Help

NirajRules

.NET, Architecture & Design

Niraj Bhatt

Occupation
Location
There are no photo albums.

Feed

The owner hasn't specified a feed for this module yet.
No list items have been added yet.

Moving to WordPress

Dear All,

        I am moving my blog to Wordpress. http://nirajrules.wordpress.com/. See you there.

Life is so beautiful!!!

Success,

Niraj

Setting two bindings on a single WPF control

       I just published my first article on Code Project. This is a very useful thing to do in WPF & saves lot of time for developers. Actually it was going to be a blog post for me. But the spaces didn't allow me to do that saying I am exceeding the no. of permited lines. Hence I altered my post slightly, converted it to an article & submitted to code project. Spaces loss is CodeProject's gain :).  

ReSharper 4 Beta available!!!

Finally after a long wait Resharper 4 is out but it’s still a beta only. I installed a thirty day evaluation edition & at first run while clicking on ReSharper menu got 5 – 6 exceptions. Just ignored them & after that things seem to be ok.

This has been a long wait & VS.NET is improvising day by day so JetBrains guys really need to speed up. Features like static compilation while editing is provided by VS.NET 2008 SP1. Nevertheless my personal favorites in R# are below:

ALT + Enter – Bulb popup giving various tips (N.B. you need to change keyboard settings by going ReShaper -> Options Menu)

Shift + ALT + SPACE – Type completion (Really scores instead of typing the full type in case sensitive format & using ALT + SHIFT + F10 of VS.NET)

CTRL + SHIFT + R – Refactor this (provides 35 refactorings depending on application context, my favorite being introduce variable)

ALT + INS – Insert code constructs for a given type – class, struct, interface

CTRL + ALT + / - Line Comments (CTRL + K + C in VS.NET), to undo comments press the same key (CTRL + K + U in VS.NET)

CTRL + SHIFT + / - Multiline comments, to undo press the same key

CTRL + SPACE - Used to auto generate a meaningful variable name based on the type just keyed in 

CTRL + D - Copy + Paste the line where the cursor is blinking 

CTRL + MOUSE CLICK - Naviagte to the clicked type / method / language construct

SHIFT + F12 - Find usages of a variable in a file 

Of course there is lot more & you can find a comparision with plain VS.NET 2008 here

Enterprise Library 4.0 Error - ".NET Framework 3.5 not installed"

Oops, again I ran into this. Windows Vista OS is the issue here. Open the command prompt in administrator mode & then run the .msi from console mode. You get a clean install now.

Exploring WF Rules Engine Types

       I was trying to dig into the Rules Framework of .NET WF. Below are the some of the important framework classes.

 

Rule Class

        Condition

               (RuleCondition <- RuleExpressionCondition)

        ThenActions

               IList<RuleAction>

        ElseActions (Optional)

               IList<RuleAction>

        Name

        Priority 

        ReevaluationBehavior

 

RuleAction (Abstract Class)

        RuleStatementAction

        RuleHaltAction

        RuleUpdateAction

 

RuleSet

        Rules (ICollection<Rule>)

        ChainingBehavior

 

RuleReadAttribute

RuleWriteAttribute

RuleInvokeAttribute 

 

A Link worth checking out - http://www.inrule.com/products/InRule_Workflow_Foundation.aspx

Error: Sys.InvalidationOperationException: ManagedRuntimeError error #4002 in control ‘Xaml1’: System.Exception: [AsyncCallbackException]

I was recently stuck up getting started with Silverlight. One of the first applications I tired was to invoke a WCF Service using Silverlight. Although it’s well documented that Silverlight supports only basicHttpBinding due to its sandbox execution, it didn’t seem quite easy to get one sample up & running. The most of samples I came across on sites were adding the .svc file to the same project that was hosting siverlight control. I wanted a complete separate project for WCF Service as that is what would be a normal real word scenario.

And on doing that I got a strange exception:

Line: 377

Char 17:

Error: Sys.InvalidationOperationException: ManagedRuntimeError error #4002 in control ‘Xaml1’: System.Exception: [AsyncCallbackException]

[UnexpectedHttpResponseCode] Arguments:Not Found Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=2.0.30226.2&File=System.ServiceModel.dll&Key=UnexpectedHttpResponseCode

 

And here I was with no clue. After looking over the web I found that Silverlight doesn’t allow to make a call to a service which is located outside its hosting domain. The best explanation is available here & it talks about doing this via 2 files called ClientAccessPolicy.xml & CrossDomain.xml. I created those 2 files but the article wasn’t particularly helpful for me as to where I would place these two xml files.

 

After lot of trial & error (with help of fiddler) I found that you have to place those 2 in your %wwwroot folder (e.g. C:\Inetput\wwwroot). After placing the ClientAccessPolicy.xml file there (listed below) things worked fine for me.  Hope they do for you too.

 

<?xml version="1.0" encoding="utf-8"?>

<access-policy>

  <cross-domain-access>

    <policy>

      <allow-from>

        <domain uri="*"/>

      </allow-from>

      <grant-to>

        <resource path="/" include-subpaths="true"/>

      </grant-to>

    </policy>

  </cross-domain-access>

</access-policy>

 

(P.S. To add, things still didn’t work for me as I guess there was some problem with my Domain Controller. I had changed URL to localhost in the Silverlight project’s config file but somehow that URL was not being used. So finally I altered the proxy code giving the binding & Uri explicitly as below.)

 

            PeopleService.Service1Client proxy = new

                PeopleService.Service1Client(

                new BasicHttpBinding(),

                new EndpointAddress("http://localhost/WCFSilverService/Service.svc")

                );

            proxy.GetDataCompleted += new

                EventHandler<SilverLightWithWCF.PeopleService.

                GetDataCompletedEventArgs>(proxy_GetDataCompleted);

            proxy.GetDataAsync();

Integrating WCF with Windows Cardspace

       Regarding the session I took some time back for user group people have been asking me post the web.config for the WCF Service. Please find the same below along with steps outlined.
 
Steps:
Creating a Service
   Uppercase Service
Testing it
   Wcfsvchost
   Wcftestclient
Configuring bindings
   wsFederationHttpBinding
Certificates
   Adding a certificate to local machine (for service) (ServiceCredentials – ServiceCertificate)
   Setting allowUntrustedRsaIssuers to true (ServiceCredentials)
   Adding the public key of certificate to local machine TrustedPeople Store
 
//Config file of the WCF Service
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="MyService.UpperCaseService" behaviorConfiguration="myBeh">
        <endpoint address="http://localhost:9999/Add"
                  binding="wsFederationHttpBinding"
                  contract="MyService.UpperCaseService"
                  bindingConfiguration="wsFed" />
        <endpoint address="http://localhost:9999/Mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>
    <bindings>
      <wsFederationHttpBinding>
        <binding name="wsFed">
          <security mode="Message">
            <message
 issuedTokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"
 negotiateServiceCredential="false">
              <claimTypeRequirements>
                <add claimType="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier"  isOptional="false"/>
                <add claimType="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"
  isOptional="false"/>
                <add claimType="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth"
  isOptional="false"/>
              </claimTypeRequirements>
              <issuer address=
          "http://schemas.xmlsoap.org/ws/2005/05/identity/issuer/self" />
            </message>
          </security>
        </binding>
      </wsFederationHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="myBeh">
          <serviceMetadata />
          <serviceCredentials>
            <issuedTokenAuthentication allowUntrustedRsaIssuers="true" />
            <serviceCertificate
              storeName="My"
              storeLocation="LocalMachine"
              x509FindType="FindBySubjectName"
              findValue="localhost"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

C# 3.0 Features - A brief writeup

Implicit type variables:

                 var keyword is used for variable, array & collections. There is no '[]', etc., required with var's usage.
                 var a = new int [] {1, 2, 3, 4, 5};

Object Initializers :

                var p = new Point { x = 10, y = 20 }; //Eliminates need of constructors to initialize properties & collections

Auto Implemented Properties:

public int x { get; set; } //same as abstract properties declaration but with no keyword. N.B. the missing private variable in the above code.

Lambda Expressions:

                Simpler syntax then Anonymous methods. Unlike Anonymous methods parameters are not optional though Parameter types are.

button1.Click += (o, e) => MessageBox.Show("Hello World"); //expression lambda

button1.Click += (o, e) => { MessageBox.Show("Hello World"); return; } //statement lambda

delegate int Add(int i, int j); Add a = (int i , int j) => i + j; //return is implicit, parameters type is explicit

=> can be read as “goes to” (i.e. this parameter goes to this expression / statements)

Anonymous Types:

Combination of Implicit Type & Object Initializers.

 E.g. var p = new { x = 10, y = 20 };

Above creates an implicit type which has 2 properties x & y with values set to 10 & 20 respectively. It’s important to note that Anonymous types are immutable & you can’t pass their instances as method parameters or return types (unless you are using type Object in those places).

Extension Methods:

                They allow extending an existing class with additional behavior (method). Looks similar to Visitor pattern. The new method has to be static defined inside a static class with first parameter being the type which you want to extend. The first parameter is suffixed with keyword ‘this’.

E.g. I

static class MyClass

{

        public static int ToInt32(this String s)

        {

            return Convert.ToInt32(s);

        }

}

 

E.g. II

 

List<int> li = new List<int>() { 1, 2, 5, 3, 4 };

 

//OrderByDescending is an extension method defined in Enumberable class (System.Linq namespace)

IOrderedEnumerable<int> results = li.OrderByDescending(x => x);

 

/*

 

//Original API

public static IOrderedSequence<TSource>OrderByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)

 

//TSource is always taken as a collection type (type inference), Key also can be type inferred depending //upon the return of Lambda expression.

li.OrderByDescending<int, Int64>((int x) => x));

 

*/

 

foreach (int num in results)

{

                Console.WriteLine(num);

}

 

Partial Methods:

                Hm... this is a tricky feature. If you think of template method pattern & hooks, their implementation normally carries a bunch of methods, which you can ovverride in deriving classes if you need them.

 

E.g. class BeverageRecipe {

                  public virtual void PourMilk() {} // A step in algo / hook

                  public void Prepare() {

                                        PourMilk(); // Call the hook at this step, the derived class implementation will be called if it's available else it will call the base class's do nothing implementation.

                  }

        }

 

        Drawbacks of the above are it makes a lot of do-nothing calls when derived class comes with no implementation. Another important observation here is the only way to implement the hook is to have a derived class. Of course from pattern's persective we want the algorithm to remain static, hence base class is always justified there. But in cases where the hooks are specific implementation which you want to leave it your team members you can make the method partial.

 

E.g. partial class BeverageRecipe {

                  partial void PourMilk();  // A step in algo / hook with no implementation

                  public void Prepare() {

                                        PourMilk(); // Call the hook at this step. N.B. That this call along with PourMilk declaration will be entirely removed in case there isn't a another partial class implementing PourMilk method.

                  }

 

         Hope this will serve as a starting point.

        }

Custom Path Policy VSTS 2008

I was really annoyed to not have found a single sample on this (at least a search on google/msn didn't help me). Custom Path Policy is installed along with TFS 2008 Power Tools. Like other check-in policies you get to keep a guard on the code that gets into you Version control.

Let's get started,

1)      Create a new team project & corresponding folders in Team System. (Figure 1)

       Figure 1

2)      Now let’s say you don’t want to mandate comments for unit tests but you want to mandate the same for your source. This is where custom path policy comes into play. It’s a policy set for a given path or a given set of files.
(N.B. It’s important to understand that custom path policy doesn’t stand on its own, it requires a child policy to support itself)

3)      Add a child policy in our case it’s a CheckInCommentsPolicy (Team Explorer -> Team Project (Right Click) -> Source Control -> Check-in Policy -> Add)

4)      Add a Custom Path Policy Next. In child policy combo select CheckInCommentsPolicy you added. In Source control Path Filter enter the regular expression - .*/PresentationLayer/.* (the path would different as per your folder names & structure). Figure 2.

     Figure 2
Click Add & Ok.

5)      You will see a message box now.
The selected policy is currently enabled.  It should be disabled or it will end up running twice. (Figure 3)
Figure 3
This indicates that CheckInCommentsPolicy will run twice – once as child policy of Custom Path Policy & other as a standalone policy. It’s important to get rid of this message to make your Custom Path Policy work.

6)      Select the CheckInCommentsPolicy & Disable it. Say ok Close the Source Control Settings dialog box. What you have done by this is effectively disabled CheckInCommentsPolicy from running as a standalone policy. If you open the Source Control Settings dialog box again & go to Custom Path Policy (edit it) & close the dialog box you won’t see the message again. (Figure 4)

     Figure 4

7)      That’s it you are all set. Go ahead check out a file in the PresentationLayer folder. When checking in the file back you see a policy warning that comments are required but the same warning won’t be displayed for a check-in from a unit tests folder. (Figure 5)

           Figure 5

Hope that helps J.

Windows Server 2003 Drivers for Dell / HP

Hello Guys,

     I got a Dell Latitude 360 recently. As always I prefer a dual boot machine one lightweight & second one Heavyweight. By Heavyweight I mean  a server system as all the Microsoft Servers like Sharepoint, Biztalk, Team Foundation run only on it. Windows Server 2008 still being in RC1 version I decided not to risk with it at the moment & went ahead with Windows Server 2003. After installing the machine was definitely looking boring as I couldn’t install any drivers apart from Broadcom Ethernet driver.

     This is very unfortunate as I have seen most of companies don’t support server operating systems (I had the same experience with HP / Compaq). But where there is a will there is a highway. When I tried to install drivers it gave me errors saying OS not supported but after going to Device Manager (My Computer -> Manage) & installing the drive by selecting the path manually there was no complaint. With this trick I could install Audio, Video & Wireless drivers which were my prime requirement. Of course there is no guarantee of this trick & you might damage your devices but if you need a way this could be it.

     All the best!!!

WCF Internals - Class Diagrams

     Lately was trying to understand the underlying framework WCF is built on. Below were some of the important findings which I converted to Class Diagrams. Hope you find them useful. Smile
 

Bindings

ChannelLayer

Message

(P.S. If you are not able to view the Class Diagram clearly leave a comment; I will mail the image files to your id).

 

Hosting WCF on Vista

     I recently installed Vista with VS.NET 2008 & tried hosting a WCF Service on IIS but it turned out quite a difficult task Sad. To give you background I had updated my Windows XP to Vista Ultimate. To start with IIS 7.0 looked very different. And when ever it started it displayed a message box that W3SVC has been locked down. Futher on starting IIS (panel or right side indicating restart, start, stop which I didn't see initially) I was getting error saying Cannot start service W3SVC on computer '.'.
 
     I was luckily able to resolve it after googling for a while. It turned out that World Wide Web Publishing Service (Settings -> Control Panel (Classic View) -> Adminstratrive Tools -> Services) was disabled due to security reasons. I changed the mode to automatic for the service & started the IIS. IIS was up & running now. Next trouble started when I tried creating an ASP.NET web application (just to see whether a simple HW application works or not). To my dismay this also failed saying ASP.NET 2.0 is not installed on machine (On my Windows XP I was running on .NET 1.1). As I use to do always I went to VS.NET 2008 command prompt & fired aspnet_regiis -i but got following error - An error has occurred: 0x800702e4 The requested operation requires elevation.
 
     As you might have guessed I googled again Smile. This time got lucky with this solution. Looked like I was done finally & created a WCF Service (Project -> WebSite -> Http); enabled the knobs, registered endpoints & opened the svc URL in browser but only to be disappointed again. It gave me back plain text with <@ Servicehost ...> directive. After lot of searching & taking a day's break (wasn't this easy in IIS 6.0 Confused) I finally found a solution that worked. And then I was there with my service & client running. Hmm... now I have to agree with some particpants who had started using Vista & had problems with running programs.

Inside DependencyObject & DependencyProperty

     If you have spent some time drilling into WPF you are bound to run into 2 classes - DependencyObject & DependencyProperty. They two together provide the base for underlying Property System of WPF. It's well documented that DependencyObject is nothing but a glorified hashtable, but the same holds true for DependencyProperty too.
 
For e.g. have a look at following code:
 
public class Person :  DependencyObject //CTRL + K + X -> Insert snippet shortcut for inserting Dependency Property
{
     public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof (string), typeof (Person)); 
     public string Name
     {
            get
            {
                return (string) GetValue(NameProperty);
            }
            set
            {
                SetValue(NameProperty, value);
            }
      }
}
 
      The function that caught me in the above code was DependencyProperty.Register - What the heck is that doing? On probing further I discovered that DependencyProperty maintains a Hashtable internally called PropertyFromName. PropertyFromName is where all the dependency properties of WPF are stored. A property is uniquely identified on basis of it's name & owner. For instance if you try to register another property in the above code (may in a different class) with the same name & owner type (that is Person) you will get an ArgumentException. DependencyProperty also stores other attributes like default value of the property (e.g. every Person can have a default name called 'Unknown').
          E.g. Person.NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Person), new PropertyMetadata("Unknown"));
 
       Let's focus on DependencyObject now. DependencyObject itself internally maintains an hashtable. DependencyObject contains 2 important methods called GetValue & SetValue which are used to retrive values from the internal hashtable.  The hashtable comes into play when you try to modify the default value of DependencyProperty. For e.g. the default name of every person is let's say 'Unknown' & you are setting it to your name. So the value you are giving goes & sits inside the DependencyObject's hashtable. Important thing to note here is in many cases the value may not be explicitly set by you but the value may be derived from surroundings. E.g. let's say the creator of class Button has set it's default background to white & you haven't explicitly set the background but when you run the application you see that background color is black. Now this may be due to Operating System's theme you have selected. Hence many developers refer to DependencyObject as a value engine.
 
       So the question that comes to mind is why such complexity was required in first place? Answer is quite simple. If this properties weren't dependency properties then would have been normal .NET properties allocated per instance. Dependency properties are created per type & can be customized if required (like per instance). So if your screen has 20 buttons you storage space for properties occupied is as good as for one button. Of course things can change if all the properties of buttons are modified for all 20 buttons which is a very rare scenario.
 
       How about calling this a sparse storage design pattern Wink?
 
Life is so beautiful!!!
 
Success,
 
Niraj

Scaling up concurrent users

Back after holidays Smile.
 
          Recently I had to scale up the no. of concurrent users for an ASP.NET application (more of a load test). There are 2 tools I came across which can help you do this VSTT & Load Runner. Although I prefer VSTT due to its simplicity Load Runner is equally appealing. But I am not going to talk about either. My focus for this post is on improvising performance.
 
          On starting Load testing surprisingly we were able to find few bugs which were unnoticed during manual testing. After fixing those we saw that application could scale up to 80 users & was failing beyond that. Below are some of the counters which we tuned to enhance performance. You can find them scattered across web but I am going to put them in a single place.
 
Queues:
          There are 2 main queues as far as ASP.NET is concerned. We will get into the details later as to when they come into play, let's understand them first. First queue (ASP.NET / Request Queued) is between IIS & ASP.NET which is actually a named pipe, has maximum default length of 5000. This is queue for all applications (AppDomains). Apart from these ASP.NET also maintains a queue per virtual directory (ASP.NET Applications \ Requests in Application Queue) whose default maximum length is 100. This means that at max by default an ASP.NET application can support 100 max users (although this is not completely true as there are lot of other factors like processor, memory, disk I / O, etc. which might be hurting your performance). You can enhance the AppDomain Queue limit by increasing appRequestQueueLimit attribute of httpRuntime element of web.config file.
E.g. <httpRuntime appRequestQueueLimit="200"/> (machine.config)
 
Threads:
          As you might be aware every AppDomain has 2 types of threads - I / O threads & Worker threads. You can tune their numbers with maxIoThreads, maxWorkerThreads, minIoThreads, minWorkerThreads - attributes of processModel element in machine.config. IO Threads are useful when waiting for an I/O e.g. making a call to remote web service, whereas worker threads are for local execution. Max. Worker threads (default value 20) should be increased if processor utilization is quite low as doing it otherwise would increase context switching & further stress an already stressed processor. Check if processor is idle due to I/O calls, if yes you can increase maxIoThreads. minIoThreads & minWorkerThreads are beneficial in burst load scenarios wherein you want to amortize the cost of thread creation.
E.g. <processModel maxIoThreads="" maxWorkerThreads="" minIoThreads="" minWorkerThreads=""  autoConfig="true"/> (machine.config)
 
          That's not all about threads as there are other 2 interesting attributes of httpRuntime element (web.config) which one needs to be familiar namely - minFreeThreads (def. val 8) and minLocalRequestFreeThreads(def. val 4). minFreeThreads is the number of threads that can't be used to process incoming HTTP requests, hence if threads in thread pool drop below this requests are queued up. But note that threads that are free can be used to make outgoing calls if required. minLocalRequestFreeThreads comes into play when you need to access a local web service. You can decrease this value if you want to speed up local execution of local calls while increasing minFreeThreads or keeping it constant.
E.g. <httpRuntime minFreeThreads="" minLocalRequestFreeThreads="" /> (machine.config)
 
          Performance & Scalability guide contains recommended settings for these attributes, but they are ofcourse starting point for further optimization. Further the client we are serving has an 8 processor box hence I thought of switching to web garden so that all the processors are used. But I was wrong there & guess this is a common misunderstanding among developers. To quote P&S guide from MS - "By default, ASP.NET uses all CPUs available. In Web garden mode, ASP.NET creates one process per CPU. Each process creates an affinity to a single CPU. Web gardens offer an addition layer of reliability and robustness. If a process crashes, there are other processes that still service incoming requests." But turning on Web garden makes the session management difficult hence unless you want that reliability you are better off avoiding web gardens & let a single worker process use all the processors.
 
Life is so beautiful!!!
 
Success,
 
Niraj

Being Proactive with Estimation

        I would like to put across a another story in field of estimation which was conveyed to me by a friend (Kiru) on neccessity of being proactive when it comes to sticking to your estimation, so that it doesn't hurt your customers & in turn profits.
 
        Say you hire a carpenter, asking him to do 2 windows & a door for you. The carpenter says it would take him 15 day each for both tasks, that is 30 days in total for windows & door. After negotiation, you both agree that he will work 8 hours per day & you will pay him Rs. (or what ever currency) 10 per hour. On summation your cost comes to 30 * 8 = 240 hours * 10 = 2400/- Rs. Carpenter says he wants the half of the payment after he finishes windows, that is Rs. 1200/- which sounds quite reasonable to you.
 
        On 15th day you see one window is completely done & other is done only half. Further to your surprise Carpenter says he has actually been working 10 hours per day. He is also expecting payment from you 15 * 10 = 150 hours * 10 = 1500/- Rs. Moreover, Carpenter says it will atleast take him 4 more days to complete the second window. This gets you on your nerves. You fight back saying the work done is only 75% & hence the amount should be Rs. 900/- only. Further, you are quite distrubted as you have already distributed your house opening cermony invitation cards to your friends & relatives. Now the entire plan has gone hay wire due to the delay. Carpenter now wants atleast 1200 from you & you on other hand have taken pledge never to work with him again.
 
        Barring minor issues, the implict reasons for delay were you made carpenter wait for 2 days by due to the late arrival of promised teak wood. You also walked in on 7th day asking that you need a flower design on your window.
 
        Ideal time for carpenter to negotiate was back then, when his estimation was getting tampered due to unforeseen factors. His fighting at the end would only results in a sore customer relationship.
 
        I am able to relate to this story from a carpenter perspective. What about you Smile?
 
Life is so beautiful!!!
 
Success,
 
Niraj

Use Case Driven vs. Domain Driven vs. Architecture Driven

     These are quite random thoughts. So please excuse me this time though I still believe they would be worth reading. I plan to refine them as my understanding improves on these topics.
 
     Recently I had given session on Use Cases & as usual I bragged a lot about them (of course they are deserve that Smile). But at the back of my mind I still had my doubts. Though Use Cases form the base of analysis phase (in OOAD), as I started referring to Class Diagrams, etc. I was wondering whether they part of anlaysis phase or design phase? This confusion came from Domain Model a term I was hearing frequently. At the core of my heart I have believed that it's something that's very important especially when you enjoy being in OO realm (& after all I have spent such a huge time mastering all those patterns).
 
So when does Domain Model come into picture? 
How it's related to use cases?
Do you start with a use case or Domain Model when collecting requirements?
Do you require Use Cases when you have a good domain model or vice versa?
 
     All this left me confused.
 
     Below are my answers & I look forward to hear your comments on the same: 
     
     Use Cases are central to the project execution. They are the spoke with everything else being hub. You use them for planning, risk analysis, sign off, scope management, functional & non functional (non behavioral) requirements. Whereas Domain Model's motive is to capture the underlying world you are addressing. Just understanding the domain won't help you, you have a problem at hand, there are expectations from the user regarding how system should work, etc. which can be captured easily using use cases.
 
    Further there are 2 models to be precise: Analysis Model & Design Model (also called domain model, thanks to M. Fowler PEAA). Analysis model is prepared using the same UML class diagrams used for Design Model. But the latter is a refined version & slightly bent towards implementation. Analysis model complement use cases for requirements elicitation & in my view if the same person refines both the models with help of domain experts it would be better. Eric Evans recommends that (if I have understood him right). Those who are worried about where the architecture fits, I see it being made up of various views primarily addressing non behavioral / functional requirements.
 
Life is so beautiful!!!
 
Success,
 
Niraj 

Creating layered architecture diagrams using Visio

I always had struggled to create layered architecture diagrams when proposing solutions to my clients. I thought Visio was the tool & there would be some stencil available for guidance. But I was both right & wrong. MS guys use Visio for creating these diagrams but there is no separate stencil available for it. Visit this Mai-lan's Visio Blog for more interesting information & I have hooked onto its feed. Happy Drawing
 
Life is so beautiful!!!
 
Success,
 
Niraj

Is RUP Dead?

        
         RUP was no buzzword to me. Infact it was a dead word. Fortunately I had to revise my RUP knowledge to address a team of participants. And boy was I shocked!!!. RUP is real good .
 
         I relooked at the agile maifesto & I found that non of the principles put across are contradicted by RUP. RUP to me is still the best approach when it comes to an average size team with average skills. And if you are using RUP you should be proud of that. To quench my thirst I went on to find more differences between RUP vs. Agile & the best answer I got was from Ivar Jacobson. I agree completely to him, being myself infatuated with words like TDD, Refactoring, Pair programming.
 
         What Say?
 
Life is so beautiful!!!
 
Success,
 
Niraj

Do you want to display the nonsecure items - ASP.NET / HTML

When we create an ASP.NET web site we are normally not sure wether it would be used over HTTP or HTTPS. The problem that normally gets reported by client when he moves to HTTPS is the popup which he gets every now & then -
 
"Do you want to display the nonsecure items?"
 
The solution to this is when ever we refer to any resources (e.g. images) within our pages we should always use relative URL & not the absolute one. That would automaically prefix the required protocol the client is currently using (http or https).
 
Of course I discovered the solution from here  which also talks about - iframes (they contribute to similar problems).
 
Life is so beautfiul!!!
 
Success,
 
Niraj

JavaScript & C#

Dear All,
 
          Unfortunately I had to recently get involved with JavaScript on an ASP.NET project . Though learning a new language amidst so much to learn made me quite skeptical. Nevertheless I am sharing few thoughts for below for anyone who is about to embark the journey. The details below are from C# developer perspective as what he needs to give special attention on & I assume that you know the whats & whys of JavaScript.
 
1) Place where you would normally define your JavaScript is inside the script tag of the html's head tag.
<html>
<head>
          <title> ...
          <script type="text/javascript">
                    //your script goes here
          </script>
 
2) If you have been looking at C# 3.0, var is the only variable type in JS. Although this is an type safe as the former & is basically late binding.
 
3) To define functions in JS, function Keyword is used.
E.g. function Dummy() { alert(window.document.form1.Text1.value); }
 
4) Functions can be invoked by assiging them to events (observer pattern).
E.g. <input type="text" onclick="Dummy()" /> //onClick is the client side event here
VVIMP: Remember the () here
 
5) ASP.NET markup has no facility of directly attaching the JS function to any of the events it exposes. Actually all the events available in the intellisense are only server side events.
<asp:TextBox runat="server" on //Look ma no onClick
 
6) Hence we do this via Attributes property (collection) of every ASP.NET control in code behind file
E.g. Text2.Attributes.Add("onClick", "Dummy");
 
7) Parmeters - When defining a JS function which takes parameters, unlike C# there is no type attached to it.
E.g. function Dummy1(var x) //Wrong
      function Dummy1(x) //Right
 
8) How to pass a control as a parameter? E.g. When you click on  a button you want to check an unchecked checkbox?
In ASP.NET you can use ClientID property of the ASP.NET control.
E.g.
//Script
function Dummy1(x)
{
       document.getElementById(x).checked = true;
}
//Code Behind
Btn1.Attributes.Add("onClick", "Dummy1('" + Check1.ClientID + "')"); //Client ID is the ID generate for HTML markup at runtime
 
Hope this serves as a good begining point.
 
Life is so beautiful!!!
 
Success,
 
Niraj

 

Viso Stencil Repository Download

http://visio.mvps.org/3rdparty.htm - A very useful link for stencil hungry people like me

int value gets converted to zero over the wire- WCF

         This entry is in continuation with previous one. You can attribute this to the Serializers mismatch problem (DataContract vs Xml serializer). You won't run into this problem if the client side generated proxy (Add Service Reference / svcutil) uses DataContracts.
 
          Important thing to note is that despite you using Add Service Reference or svcutil (both use data contracts by default) you will get proxy which uses XmlSerializer. A common scenario of this is explained in my previous blog entry.
 
          To understand it better DataContract is version aware serializer. It has named parameters like IsRequired which can go a long way in resolving version problems.
 
E.g.
 
[DataContract]
class AddParams
{
          [DataMember]
          public int Num1;
          [DataMember]
          public int Num2;
          [DataMember(IsRequired = false)]
          public int Num3; //Recently added hence if older clients don't pass it it's okay.
}
 
           Now this is taken care if the client's proxy is using DataContract but XmlSerializer has got its own way on handling it by creating 'xxxSpecified' property.
 
           E.g. Num3Specified (look at the proxy code by expanding .map file in your solution explorer)
 
           Hence if this property is set to true only then the value of Num3 will be transferred over the wire or else it will null (which in this case equates to zero).
 
           So if you make specified property true & run the program of the previous blog entry the output will as expected 11 .
 
           Of course a better solution could have been to use XmlSerializer on both client & server. This requires you to just add an XmlSerializerFormat attribute on top of Service Contract. This also negates the need of any DataContract attributes on your custom class.
 

           [XmlSerializerFormat]

           [ServiceContract]

           public interface IService

           {

                         [OperationContract]

                         Param Get(Param p);

           }

 
Life is so beautiful!!!
 
Success,
 
Niraj

No Corresponding Start Element Open - WCF

         WCF has Subtle concepts which failing to understand can create nightmare. Take a look at below - an innocent Data Contract.
 

[DataContract]

public class Param

{

              [DataMember]

              public int i;

              [DataMember]

              public DataSet ds;

}

              This is a custom type which client passes on to the service & service increments the i (int) & returns it back. DataSet is present only from error perspective.

public class Service : IService

{

                  public Param Get(Param p)

                  {

                                Param _p = new Param();

                                _p.i = ++p.i;

                               return _p;

                   }

}

          The problem is when you run the application you get an exception message saying - "No Corresponding Start Element" & you can see a XmlTextReader in the trace.

          Now before we venture into cause & solution understand this: WCF has 2 serializers when it comes to serialzing data over the wire - DataContractSerializer  (new) & XmlSerializer (old from ASMX). Although WCF tries to use DataContractSerializer by default but when ever it finds an ADO.NET type it switches to XmlSerializer as they DataSets are best serialized by it. Well this creates lot of chaos.

          The problem over here is that if we don't initialize DataSet, it goes as xsl:nil over the wire which the deserializer on the server is complaining about & hence the exception. To avoid this problem we can ask the XmlSerializer NOT to emit the DataSet's default value (null) by using an named parameter in DataContract attribute.

[DataMember(EmitDefaultValue = false)]  //True is default

public DataSet ds;

          So now if you run the program you won't find the exception but rather something strange happens. If you initalize i (of param class) to 10 & send it to service, the return comes back as 1 & not 11. Strange!!! This calls for another blog entry.                      

Biztalk Overiew

Biztalk is used to connect heterogenous applications which might be spread within or across an enterprise. Following are the components one should be familiar with to leverage on Biztalk server. A pre caution - following is a just a bird eye view of the components involved and the coverage is no where near to be comprehensive.
 
1) Adapters: An adpater abstracts the underlying communication protocol for a developer. A developer can use different adapters in a unified way which in turn can connect to diversified systems like mainframes, SAP, etc.
 
2) Pipelines: Biztalk internally deals with messages (data exchanged between applications) in XML format. The main responsiblity of pipleline is hence converting the those data formats (received from the respective adapters) into XML. Also they are extensible as well for e.g. you want to decrpyt an incoming message before converting it to XML.
 
(N.B. Adapters + Pipelines can be configured for send & receive messages differently).
 
3) MessageBox: After the message is recieved it is stored over here. This is nothing but a persisent store (SQL SERVER 2005).
 
4) Orchestration: This is used the defined the workflow interweaving the applications, i.e. the functionality that is not part of any application per se but that is added when you try to integrate applications. E.g. purchase app might you the invoice app only if the invoice amount has exceeded an agreed limit. There are various orchestration shapes available in Orchestration designer which is integrated with VS.NET.
 
(N.B. Orchestration / Pipeline can subscribe to a message, hence when that type of message enters messagebox it will automatically be delivered to the appropiate subscribers. This is the classic example of GOF's Observer pattern).
 
5) Biztalk Schema Editor: It helps to create xsd (XML Schema) files easily using GUI. It's used to define the message structure of the incoming & outgoing messages.
 
6) Biztalk mapper: There are possiblites that there might be variations in incoming messages (sometimes the field name changes or fields are deleted / added) etc. To create a map between messages you can use biztalk mapper. This mapping files have a .btm extension.
 
7) Functoids: These are functions that can be applied to transform incoming messages as per requirement of outgoing message (a simple e.g. could be converting the a lower case string to upper case).
 
8) Business Rule Engine: To cut short on this one business rules which are frequently changed can be implemented by BR composer. They are easier to change when compared to rules embeded inside Orchestration as the later requires lot of work.
 

Snapshot vs. Read Uncommitted isolation levels

         SQL Server 2005 introduces 2 new isolation levels - Snapshot & Read committed snapshot. It looks to me that Databases like Oracle have support for these already. But it's just a guess considering my current Oracle knowledge .
 
Both of Snapshot Isolation levels & Read Uncomitted don't request for shared locks while reading through a table. So you get the required data that very moment instead of waiting for the other transactions to release the lock.
 
But there is difference over here which is important to understand.
When you use Read Uncommitted isolation level you get the current data, i.e. the data which is temporarily modified by other transactions. Hence your reads may be dirty.
But when you use snapshot isolation levels before a particular row is modified by a transaction it's original copy is saved in tempdb. Hence your select will give you stable data if not current data which might be good for most of scenarios. The only consideration you have here is the use of tempdb which might eat up your resources if transaction is long running one.
 
To turn the snapshot isolation level on execute following commands on your testdb :
ALTER DATABASE testdb SET ALLOW_SNAPSHOT_ISOLATION ON;
ALTER DATABASE testdb SET READ_COMMITTED_SNAPSHOT ON;
Of course there are lot other things to cover up but then inch by inch it's a cinch. So will do it some other time.