SQL Server 2008 is now RTM

7 08 2008

The long wait is over! SQL Server 2008 is now RTM and is also available in MSDN for MSDN Subscribers! Cant wait to download and play with it 8)

sql-server-2008-rtm





Generating WCF Proxy using SvcUtil.exe

7 08 2008

Visual Studio 2008 has made our WCF life a lot easier with the ability to self-host the services and also allow debugging in our service.

What if we were pushed to a situation wherein we need to use the tool svcutil.exe to create our proxy for the client…hmm… 🙂

To do so, we need to have our service running. Once the service is up and running, we could generate the proxy by the following command (replace the tags correspondingly) :

   1: svcutil /t:code http://<service_url> 
   2:       /out:<file_name>.cs /config:<file_name>.config

Here is my example :

   1: C:\Users\Chaks\Documents\Visual Studio 2008\Projects\MyService\MyServiceHost>
   2: svcutil /t:code http://localhost:8731/Design_Time_Addresses/MyService/WcfService/ 
   3: /out:MyServiceProxy.cs /config:MyServiceProxy.config
   4: Microsoft (R) Service Model Metadata Tool
   5: [Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.648]
   6: Copyright (c) Microsoft Corporation.  All rights reserved.
   7:  
   8: Attempting to download metadata from 'http://localhost:8731/Design_Time_Addresse
   9: s/MyService/WcfService/' using WS-Metadata Exchange or DISCO.
  10: Generating files...
  11: C:\Users\Chaks\Documents\Visual Studio 2008\Projects\MyService\MyServiceHost\MyS
  12: erviceProxy.cs
  13: C:\Users\Chaks\Documents\Visual Studio 2008\Projects\MyService\MyServiceHost\MyS
  14: erviceProxy.config

Now we can add this .cs file to the Client project and copy the .config file contents to the Client’s app.config file and execute the client 8)

We can also instruct svcutil to generate the proxy in the preferred language we want :

   1: svcutil /t:code /language=VB 
   2:      http://localhost:8731/Design_Time_Addresses/MyService/WcfService/ 
   3:          /out:MyServiceProxy.vb /config:MyServiceProxy.config

But svcutil already identifies the language with the extension of our output file name 8)





ASP.NET Ajax CalendarExtender and Validation

1 08 2008

ASP.NET Ajax toolkit has a CalendarExtender control which is very cool as you can associate the CalendarExtender to a a TextBox and also to a Button/ImageButton so that you can popup the calendar.

Below is the code to get started with CalendarExtender:

<asp:TextBox 
    ID="TextBox1" 
    runat="server" 
    width="300pt" />
<asp:ImageButton 
    ID="btnCalenderPopup"
    Width="16" Height="16" 
    runat="server" 
    ImageUrl="~/images/calender.bmp" 
    CausesValidation="False" />
<ajaxToolkit:CalendarExtender 
    ID="CalendarExtender1"
    runat="server" 
    TargetControlID="TextBox1" 
    PopupButtonID="btnCalenderPopup" 
    Format="dd/MM/yyyy" />

And here is the output:

calender-extender-1

and,

calender-extender-2

Wait! What’s that grayed text in the textbox that says – Enter the Date of Birth (dd/mm/yyyy)

Certainly that’s not the part of CalendarExtender 🙂 , but part of ASP.NET Ajax Toolkit 8) . We can use the TextBoxWatermarkExtender which can display watermarked (grayed) texts on controls. Below is the code for our CalendarExtender :

<ajaxToolkit:TextBoxWatermarkExtender  
    ID="WatermarkExtender1"
    runat="server" 
   TargetControlID="TextBox1" 
   WatermarkCssClass="watermarked" 
   WatermarkText="Enter the Date of Birth (dd/mm/yyyy)" />

And below is the CSS style that’s used with this watermark extender :

.watermarked
{
    color: #C0C0C0;
    font-style: italic;
}

All looks good now and the user is happy the way Calendar pops up, choosing the date and also the fact that he can type in the date in the textbox in the desired format. Now comes the problem – Date Validation! – How are we going to validate the entered date? – I had to validate that the date entered is not more than today’s date.

There are two ways to do it :

1) Using Javascript (with our CalendarExtender)

2) Using RangeValidators for our textbox

Using Javascript:

The CalendarExtender has a property called OnClientDateSelectionChanged which can be set to a piece of javascript which can do the job for us. Below is the code:

<ajaxToolkit:CalendarExtender
    ID="CalendarExtender1"
     runat="server" 
    TargetControlID="TextBox1"
    PopupButtonID="btnCalenderPopup" 
    OnClientDateSelectionChanged="checkMyDate"
    Format="dd/MM/yyyy" />

and below is the javascript:

<script type="text/javascript">
function checkDate(sender,args)
{
    var dt = new Date();        
    if(sender._selectedDate > dt)
    {
        sender
            ._textbox
            .set_Value(dt.format(sender._format));
    }
}
</script>

Using RangeValidator:

Since we use a TextBox control to display our date once we choose from the calendar or to manually input the date, RangeValidators can be used to check whether the date is within a given range (minimum & maximum). Below is the code for RangeValidator :

<asp:RangeValidator 
    ID="RangeValidator1"
    runat="server" 
    ControlToValidate="TextBox1" 
    ErrorMessage="*Please enter proper date" 
    Type="Date" Display="Dynamic" />

And in your page load event we can set our maximum and minimum date values :

RangeValidator1.MinimumValue 
      = new DateTime(1600, 01, 01).ToString("dd/MM/yyyy");
RangeValidator1.MaximumValue 
     = DateTime.Now.ToString("dd/MM/yyyy");

With these two methods you can easily validate the date. And yes, using both would sometimes lead you to race conditions where choosing a date from the calendar might be an invalid date and the RangeValidators would immediately come to the focus.





Random Post : LINQ to XML

14 07 2008

Thought of refreshing my LINQ to XML skills and here is the outcome – another blog post today! 8)

Here is our sample XML file (never mind where it came from or why it is complex)

<?xml version="1.0" encoding="utf-8" ?>
<Output_Message>
    <Dataset>
        <Row>
            <Persons_Current_Name>
                <Name>
                    <Surname>John</Surname>
                    <GivenName>Samuels</GivenName>
                </Name>
            </Persons_Current_Name>
            <Persons_Name_At_Birth>
                <Name>
                    <Surname></Surname>
                    <GivenName>John</GivenName>
                </Name>
            </Persons_Name_At_Birth>
            <DateOfBirth>1865-07-31</DateOfBirth>
        </Row>
    </Dataset>
    <StatusInformation>
        <Status>OK</Status>
        <Alive>YES</Alive>
    </StatusInformation>
</Output_Message>

I am going to query each element (as listed below) and display their values

  • Persons_Current_Name
  • Persons_Name_At_Birth, and
  • DateOfBirth

Our first step would be to load this XML file. We can make use of XDocument to load the whole XML file.

XDocument mainXMLDoc
         = XDocument.Load("Input.xml");

To start with, let us traverse all the nodes and display their values

//Traversing the whole XML
Console.WriteLine("XML Traverse");
Console.WriteLine();
foreach (XElement xelement in
                   mainXMLDoc.Descendants())
{
    Console.WriteLine("{0} : {0}",
              xelement.Name, xelement.Value);
}

Looks simple, isn’t it 🙂

Next, let us get the value of Persons_Current_Name. I already have a class called Name, which is shown below:

public class Name
{
    public String Surname { get; set; }
    public String GivenName { get; set; }
}

How do we directly query Persons_Current_Name element? Below is the very straight forward (ugly) code 😀

//Persons Current Name
// The Ugly Way
XElement current_name =
    mainXMLDoc.Root
        .Element("Dataset")
        .Element("Row")
        .Element("Persons_Current_Name")
        .Element("Name");
Name persons_current_name = new Name
    {
             Surname =
                  current_name.Element("Surname").Value,
             GivenName =
                   current_name.Element("GivenName").Value
    };

Well, I really don’t like to code this way. Do we have any another option? Yes, we do! 8)

//Persons Current Name
// The Neat Way
Name persons_current_name =
    (from c in mainXMLDoc.Descendants()
     where c.Name == "Persons_Current_Name"
     select new Name
           {
                 Surname =
                      c.Element("Name").Element("Surname").Value,
                 GivenName =
                      c.Element("Name").Element("GivenName").Value
            }).FirstOrDefault();

The above code certainly looks better than our previous code 🙂

Similarly for DateOfBirth,

//Date of Birth
String[] strDob =
    (from c in mainXMLDoc.Descendants()
     where c.Name == "DateOfBirth"
     select c.Value).FirstOrDefault().Split('-');
DateTime dob = new DateTime(Convert.ToInt32(strDob[0]),
    Convert.ToInt32(strDob[1]),
    Convert.ToInt32(strDob[2]));

All looks good, but wait! What to do if I have my XML in string format ? How do I load it? Dont panic, you can use the same XDocument to load the XML in the string format 🙂

XDocument mainXMLDoc =
         XDocument.Parse(strXML);




Team System Unit Test and Output Directories

14 07 2008

I always use NUnit to write my unit tests but now at Intergen I also use Microsoft Visual Studio Team System Unit Tests. Today I was stuck by a very basic problem and here it is.

I have a XML file in my project which is added to the output directory when compiled.

When I was running my unit tests against this, Visual Studio threw me this error saying that it couldn’t find the file!

(click to enlarge)

I was really surprised as my XML file is said to copy to output directory and the test fails saying that there is no such file. Checked my Test Solution’s output directory and found that there is indeed the Templates folder and the XML file.

So, whats the problem? Why is my test failing?

Well, the VSTE has a separate directory where it stores all its test results. The directory can be found in your root directory of your solution under the name TestResults. The TestResults also have various folders for each test run you do. If you refer back to the error image that is attached above, you could get the exact directory name. So, the VSTE did not copy the Templates directory to this ‘dynamic’ (for each test run there will be a directory created : correct me if am wrong here) directory. How do we do this then?

The answer is with the Local Test Run Config’s Deployment settings. You can find the local test run config in your solution browser.

Double click the file to open the properties dialog and go to the Deployment section.

Specifying a file or directory here would be included along with the test results 🙂

My test doesnt fail now 8)

Another way to do this (if its a single file : if you know how to add for a directory, please do leave your comment 🙂 ) is to specify along with your test method,

[TestMethod, DeploymentItem(@”Templates\BirthInputTemplate.xml”)]

public void Test_BuildInputXML()
{
}





How I Got Started in Software Development

13 07 2008

babyandcomputer_thumb1

I have been memed! Thanks James 🙂

How old were you when you started programming?

19

How did you get started in programming?

I got introduced to programming and computer languages in my high school. It got into me from then and when I joined my University, I was fully ready to rock myself in programming 🙂

What was your first language?

C/C++

What was the first real program you wrote?

A DirectX game in Visual Basic 6.0

What languages have you used since you started programming?

C/C++, Visual C++ 6.0, Visual Basic 6.0, HTML, Javascript, ASP 2.0, Python, PyGTK, PyQt, Qt (C++), ASP 3.0, C#

What was your first professional programming gig?

A tool for Telecommunication and Telemedicine for one of the projects at ISRO

If you knew then what you know now, would you have started programming?

YES!

If there is one thing you learned along the way that you would tell new developers, what would it be?

1) Blog, Communicate

1) Analyse whatever you are doing

2) Dont hurry – Relax, Think and Code

3) Test whatever you code (Unit Testing)

What’s the most fun you’ve ever had… programming?

Testing what I write. Its always a challenge to break up your mind to test what you write and find mistakes/problems 😉

I Choose

1) Daniel Moth

2) Nigel Parker

3) Kirupa

4) Jeremy Boyd





NDepend

13 07 2008

Its really hard to summarize what is NDepend in few words as this tool does a lot and its really useful when you have a big project and had to do code analysis, code usage, code metrics etc., etc., So, to make things simpler, lets take what their website says 🙂

NDepend is a tool that simplifies managing a complex .NET code base. Architects and developers can analyze code structure, specify design rules, plan massive refactoring, do effective code reviews and master evolution by comparing different versions of the code.

With NDepend you can analyse a set of .NET assemblies and that was the first step for me in using NDepend. Another highlight of NDepend is that you can use Code Queries to query to analyse and get results. More on Code Query Language here.

Here is a small screencast on NDepend introduction from me. Its in .swf format and just open it in your browser 🙂





Silverlight and WCF

31 05 2008

With the release of Silverlight 2 beta 1, now developers can use .Net to create Silverlight applications To be more precise, developers can use XAML and VB.NET or C# as the back-end code language. To know more about Silverlight and what tools you need to start developing Silverlight applications, visit my post here.

This post focuses on how to make your Silverlight applications interact with Windows Communication Foundation(WCF) services. Visual Studio 2008 introduced several new WCF features. We will create a small calculator service which is going to add two numbers and return the result to the user.

First, let us create a Silverlight Web Application project.

silverlight-project

Visual Studio creates the necessary files needed for your solution. Let us straight away start with adding our WCF service. Visual Studio creates two projects, one being the actual Silverlight control project and the other being the web application project where the Silverlight control is hosted. So, we would be able to add a WCF service to our web application project and then reference the service in our Silverlight control project. Right click the web application project and add a WCF service to the project.

add-new-item

Name the service as CalculatorService. Visual Studio adds the necessary files such as the SVC and code-behind files and also the service configuration to the web.config file.

wcf-service-added

I have modified the service to hold only function as shown below:

[ServiceContract]
public interface ICalculatorService
{
    [OperationContract]
    int AddTwoNumbers(int num1,int num2);
}

And here is the implementation:

#region ICalculatorService Members

public int AddTwoNumbers(int num1, int num2)
{
    return (num1 + num2);
}

#endregion

Nothing complex, just simple addition and return the result 😉

Now comes the most important thing, at least for this beta 1 release – Silverlight supports only basicHttpBinding and thus our WCF service can only use basicHttpBinding if we are to interact with a Silverlight client. Let us check our CalcultorService’s binding in the web.config file under the system.servicemodel section.

default-binding

Yes, you are right. WCF by default uses wsHttpBinding and thus we need to change the binding to basicHttpBinding. Below is the modified version:

modified-binding

How do we use this service in our Silverlight application? Below is a screenshot of our Silverlight application.

screenshot-control

The interface is pretty simple accepting two numbers from the user and when Add is clicked, our service’s AddTwoNumbers is invoked to get the result.

How do we reference our WCF service now? We do the same way as we do in normal WPF or WinForms applications 😀

Right click on the Reference and select Add Service Reference

silverlight-add-service-reference

We will be presented with a dialog box to add a service reference.

service-discover

We can use the Discover option to discover any WCF services in our solution. As our CalculatorService is hosted in the same solution, the Discover would be able to find our service.

calculator-service-discovered

Let us give a name to our service reference – CalculatorServiceProxy 🙂

Once we add our service, we can see that the Silverlight project now has the necessary files to interact with our WCF service.

silverlight-added-wcf-reference-files

Now we are ready to add our code to the button Click event handler. Below is the code snippet.

private void Button_Click(object sender, RoutedEventArgs e)
{
    int num1 = Convert.ToInt32(TxtNum1.Text);
    int num2 = Convert.ToInt32(TxtNum2.Text);

    CalculatorServiceClient calculator_proxy =
        new CalculatorServiceClient();

    calculator_proxy.AddTwoNumbersCompleted +=
        new EventHandler<AddTwoNumbersCompletedEventArgs>
            (calculator_proxy_AddTwoNumbersCompleted);

    calculator_proxy.AddTwoNumbersAsync(num1, num2);

}

void calculator_proxy_AddTwoNumbersCompleted(object sender,
    AddTwoNumbersCompletedEventArgs e)
{
    HtmlPage.Window.Alert(Convert.ToString(e.Result));
}

You guessed it right – WCF reference adds the asynchronous operations to our Silverlight project and it does makes more sense to use asynchronous operations in a Silverlight environment as we cant block the browser and make the user wait.

Let us build and execute our project 🙂

And here is the screenshot:

output

That’s it! Now we have a Silverlight application interacting with a WCF service 😉

Wasn’t it easy 8)

The sample can be downloaded here:





Resharper 4.0 – Lambda Support

26 05 2008

Resharper 4.0 beta was out few days back. I found an excellent feature which I think should be blogged 🙂

Here is small test code snippet which uses RhinoMocks unit testing framework

You can see that Resharper has issued a warning against

Call(delegate { mockSubject.Remove(subject); });

And the warning message is as follows,

You can see that it is intelligent enough to deduce that lambda expressions can be used in the place of anonymous delegates! 8)

And once you allow Resharper to convert to lambda, you get this:

How cool is that 8)





ReSharper 4.0 Beta is out now!

23 05 2008

Resharper 4.0 Beta which supports C# 3.0, LINQ and Visual Studio 2008 is ready for download now! This is THE best addin for Visual Studio and I would recommend it to everyone who uses Visual Studio 8)

Here is an article which compares Plain Visual Studio 2008 Vs Resharper 4.0 Visual Studio 2008

You can download the beta here

Enjoy! 🙂