Saturday, February 19, 2011

To Box or not to box?

 

So recently I started refreshing my knowledge in .net basics since I'm starting to seek for a new job, and I ran into a subject that Shani Raba once told  me about.

I am talking about boxing and unboxing of value types.

let's starts from the really basics.. I'm sure most of you know that in .net Framework we have two types, value types and reference types. value types are the type we mostly use, these are the common types like int32, bool, decimal and so on, these types are located in the thread stack(in the process we use) and we don't need to initialize them(with the new keyword). on the other hand we have the reference types, these types are located on the managed heap, they are heavier since they have a overhead of additional members and they are garbage collected.

I must also point that value types derive from System.ValueType which derives from System.Object.

watch this code sample:

array

So what actually happens here? The ArrayList.Add method takes and Object as a parameter, so for each integer we want to insert to the list it has to cast to Object. however the integer is stored on the stack and the list expects a Object from the managed heap. In that case the CLR is using a mechanism called Boxing.

what is Boxing:

1) Memory is allocated on the managed heap, according to the size of the value type pluse some extra overhead.

2) fields from the value types are copied to the new object on the managed heap.

3) the CLR returns the address of the value which is now it's reference.

So in our example we actually created 20 new objects on the managed heap, and as we stated in the begining of the post it's a big overhead. Now what will happen if we will write the following code?

unb

Now we try to convert the Object to int. That action is called UnBoxing, and that's what actually happens is that the CLR generates a pointer to the data in the Object, the one on the heap. As you can understand the UnBox action is much more "cheap" than the box action.

So what can we do to avoid this overhead:

1) use proper methods and overloads, for example the Console.WriteLine method has about 12 overloads, so if you have an integer you can send it as a parameter to the writeline method (by that using the overload which takes int as a parameter), and you should not use the ToString method for this.

2) Box your value type in a single place, and use that boxed type for all the places you need.

3) use Generics and Interfaces when possible.

 

BRIUT

Saturday, February 5, 2011

Working with threads in silverlight

Lets say that we have a silverlight application that gets updates from an outer service every X seconds. the application calls the service every X seconds and waits for the answer(async-way of course).

The most trivial way is to use a timer that every X seconds the Tick event will raise and call our service.

In order to do so we have got the System.Threading.Timer to use. the code will look like that:

       public MainPage()
       {
           InitializeComponent();

           var timer = new Timer(TimerTick, null, new TimeSpan(0, 0, 0, 1), new TimeSpan(0, 0, 0, 5));
       }

       private void TimerTick(object state)
       {
           var client = GetClient();
           client.GetUpdatesComplete += GetUpdate_OnComplete;

           client.GetUpdates();
       }

       private void GetUpdate_OnComplete(object sender, GetUpdatesCompleteEventArgs e)
       {
           if (e.Error == null)
           {
               MyTextBox.Text = "Hello world! the time is " + DateTime.Now;
           }
           else
           {
               MyTextBox.Text = "Error!";
           }

       }

But when we will run the code we will get an error:

"Cross-thread operation not valid: Control 'MyTextBox' accessed from a thread other than the thread it was created on."

The meaning of this error is that we are trying the access the UI from other thread rather than the UI thread. and in silverlight, this is not possible.

So what we do?? we use the method Dispatcher.BeginInvoke() that will change the property via the UI thread. the code will look like this:

        private void GetUpdate_OnComplete(object sender, GetUpdatesCompleteEventArgs e)
        {
            if (e.Error == null)
            {
                Dispatcher.BeginInvoke(() => MyTextBox.Text = "Hello world! the time is " + DateTime.Now);
            }
            else
            {
                ispatcher.BeginInvoke(() => MyTextBox.Text = "Error!");
            }

        }

This is all nice and pretty but there might be a problem. this thread will run no matter what is the state of the UI. even if the UI is stuck, because it runs from another thread….

If we want to use timer that will run on the UI thread we can use DispatcherTimer , and we won't have to call the Dispatcher.BeginInvoke().

Did you got confused?? lets summarize:

1) If you need to use threads that should run each X seconds, no matter what the UI state is, and don't want it to effect the UI – use Timer and Dispatcher.BeginInvoke().

2) If you want that your timer will not run while the UI is stuck or have al long processing to do – use DispatcherTimer.

WCF service with multiple http-hosts

Introduction:

In the IIS configurations there is a section to configure which address are allowed to access the web-site in term of host-names.

For example, we can access our application in several ways:

http://IP/MyApp/My.aspx

http://server-name/MyApp/My.aspx

http://MyLoadBalancerName/MyApp/My.aspx

We can configure this in the IIS for our web-site:

On IIS 6:

right click on the web-site->properties-> web-site tab –> advanced

On IIS 7 and up:

right click on the web-site –> Edit bindings

image

*on IIS 7 on windows 7, as you can see the configuration is for all kinds of bindings, not just http.

The default is an empty host name => you can access any way you want. but you can set all kinds of host-names for all kind of ports. this way you are limiting the access to your site, and of course this is the best-practice for securing your site. usually we will configure our server-name and our load balancer server if we have one.

So what does WCF has to do with all of that??

Well, when you configure more that one host-name to a specific binding(let's say http) on your IIS and try to access a service on the site via that binding you'll get not-so-nice error that says that you have too many http-address but you only allowed to have one:

"This collection already contains an address with scheme http. There can be at most one address per scheme in this collection."

The solution is quiet simple – you can set an address filter in the server config that tells him to access the server with a specific address only. you can do this with baseAddressPrefixFilter:

<system.serviceModel>   
<serviceHostingEnvironment>
<baseAddressPrefixFilters>
<add prefix="http://MyHostName"/>
<add prefix="net.tcp://MyHostName"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
........
</system.serviceModel>
In this case the wcf will try to access the specific address for the binding and will ignore all the other headers.
Some notes:
*If you want, there are other solutions that includes creating a serviceFactory to solve the problem.
*This is relevant for .net 3/3.5. in .net 4 there is a property called MultipleSiteBindingsEnabled that handles this issue, and by setting it to true you can freely use wcf with several http-hosts.

Saturday, January 29, 2011

"Access denied" in accessing arcgis server from remote

A couple of weeks ago we upgraded our gis server(esri) from 9.3 to 9.3.1. nothing too much exciting about that except for the following problem:

After we uninstall the ags 9.3 from the server we restart it. than, we installed 9.3.1 and all good(allegedly). than we wanted to manage the gis server from another server. when doing the configuration we got:

"Access Denied: Either the SOM service on machine is not started or the user attempting this connection is not a member of the agsuser or agsadmin group and cannot be granted access to the SOM."

Of course everything was started and we could manage the gis server from local ArcCatalog.

After hours of searching and google-ing we found that our Dcom was disabled(remember the restart? that's what probably cause the Dcom settings to change).

The fix:

On the server, go to Start > Run and type dcomcnfg
Component Services > Computers and right click on My Computer-> Choose Properties.
In the Default Properties tab => ensure that "Enable Distributed COM on the computer" is checked.

That what solved our problem, but here's a link to 1000 solutions for this same problem:

http://forums.esri.com/thread.asp?c=158&f=1702&t=220661&mc=21#668317

Good luck.

Friday, January 21, 2011

Silverlight control template–Part II

As I promised in my last post I will show you how to change the visual appearance of controls that are not content control.

For this explanation I will create round text box.

I will start from the end and show you the complete result:

image

And the style code:

<Style x:Key="TextBoxStyle" TargetType="TextBox">
          <Setter Property="Template">
              <Setter.Value>
                  <ControlTemplate TargetType="TextBox">
                      <Grid x:Name="RootElement">
                          <Border x:Name="Border" BorderThickness="{TemplateBinding BorderThickness}" 
                                  CornerRadius="15" BorderBrush="Black" >
                              <ScrollViewer Height="Auto" 
                                                    x:Name="ContentElement" Width="100"
                                                    BorderThickness="0" 
                                                    IsTabStop="False" 
                                                    Padding="{TemplateBinding Padding}" 
                                                    Margin="5"/>
                          </Border>
                      </Grid>
                  </ControlTemplate>
              </Setter.Value>
          </Setter>
</Style>

At first, it's look exactly the same as the example of the round button. but the big difference is in the bolded text. because text box does not have a content we cannot use content presenter to holds it's content. but every textbox has the place where you can write things, and you need some way to present it in your template!

In my case, The ScrollViewer comes to help. and why? because in the textbox defenition it defines "place holder" for the text area, in order for us to be able replace it with another control. so I defined a ScrollViewer and gave it the name of the part "ContentElement".

What? Where? How?

From msdn:

[TemplatePartAttribute(Name = "ContentElement", Type = typeof(FrameworkElement))]
[TemplateVisualStateAttribute(Name = "InvalidUnfocused", GroupName = "ValidationStates")]
[TemplateVisualStateAttribute(Name = "InvalidFocused", GroupName = "ValidationStates")]
[TemplateVisualStateAttribute(Name = "ReadOnly", GroupName = "CommonStates")]
[TemplateVisualStateAttribute(Name = "Normal", GroupName = "CommonStates")]
[TemplateVisualStateAttribute(Name = "Disabled", GroupName = "CommonStates")]
[TemplateVisualStateAttribute(Name = "Unfocused", GroupName = "FocusStates")]
[TemplateVisualStateAttribute(Name = "Valid", GroupName = "ValidationStates")]
[TemplateVisualStateAttribute(Name = "MouseOver", GroupName = "CommonStates")]
[TemplateVisualStateAttribute(Name = "Focused", GroupName = "FocusStates")]
public class TextBox : Control

The control defines TemplatePart that can be any FrameworkElement and by defining this part it will behave as text holder for the text box. (p.s the state the you see are the visual state that you can define to the control)

Here is the same code with button as ContentElement part of the textbox:

(The text is not the content of the button! you can write whatever you like in runtime)

image

All silverlight controls defines parts that helps you change the control's appearance without loosing it's behivor! all you need to do is go to the control definition is msdn – and start desigining your controls!

Silverlight rocks!!

Saturday, December 18, 2010

Silverlight Control template for content controls

One of the strongest things about silverlight is that it gives you the complete control over your application visual appearance.

Unlike win-forms controls or asp.net controls, the look of the control and it's behavior are two different things.

For example, a button is Clickable but it doesn't have to look like a button, it can be a bunch of circles or whatever you like.

So how you change the control appearance?

It depends on what you want to do… let's say we want to create a round Button.

We can try to create a Border element around it, like this:

 <Border BorderThickness="5" CornerRadius="15" BorderBrush="Black">
            <Button Content="Click me!" />
 </Border>

Now we have a round border around our button, but it's still a regular button:

image

So we have to get into the actual control and change it's complete appearance , and how? by changing the control's template.

The control template defines the visual-tree of the control.

In order to create our round button I created a style that defines the visual tree of the button as an ellipse.

 <Style TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Grid Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
                        <Ellipse  Opacity="0.8">
                            <Ellipse.Fill>
                                <SolidColorBrush x:Name="Brush" Color="LightGreen"/>
                            </Ellipse.Fill>
                        </Ellipse>
                        <ContentPresenter Margin="{TemplateBinding Padding}" VerticalAlignment="Center"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
</Style>

So what did I do here?

I've changes the button to be a grid that has an ellipse and something to holds it's content (Content presenter) on top of the ellipse.

When someone that use's this template define a content for the button(it can be some text,another control etc..), the content will be presented on the ellipse.

The button with text content:

image

The button with 2 ellipses as a content:

image

Note: this is still a button! when you click on it, it fires the "Click" event!

Another important thing to mention is that when you create your own template for the control, you actually run-over the default template, and by doing so, loses some things like the management of visual states of the control, which means you need to create them yourself (like I did in this post).

The code with the visual states(simple mouse-over) will look like this:

<Style TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Grid Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal">
                                    <Storyboard>
                                        <ColorAnimation Storyboard.TargetName="Brush"    
                                                        Storyboard.TargetProperty="Color" Duration="0:0:0"/>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="MouseOver">
                                    <Storyboard>
                                        <ColorAnimation Storyboard.TargetName="Brush" 
                                                                    Storyboard.TargetProperty="Color"
                                                                    To="Pink"  Duration="0:0:0"/>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Ellipse  Opacity="0.8">
                            <Ellipse.Fill>
                                <SolidColorBrush x:Name="Brush" Color="LightGreen"/>
                            </Ellipse.Fill>
                        </Ellipse>
                        <ContentPresenter Margin="{TemplateBinding Padding}" VerticalAlignment="Center"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
</Style>

Last thing, this post is for content controls, and why is that? because we use Content Presenter as a placeholder for the content.

But what if it's a TextBox that does not have content? well,this is for the next post… סמיילי

Friday, December 3, 2010

Comparing Lambda expression in unit tests

A couple of days ago i had an interesting debug session at work.

Some guy try to test a method that gets a lambda expression as a parameter. he tried to create a stub for the method but had some difficulties.

The code looked like this:

public class MyClass
{
    public int MyMethod(Expression<Func<int,bool>> expression)
    {
      //Do something
    }
}

....

[Test]
public void MyMethodTest()
{
    var myStub = MockRepository.GenerateStub<MyClass>();
    myStub.Stub(x=> x.MyMethod(y=>y==3)).Return(10);
    myStub.MyMethod(y=>y==3);
}

The problem was that when the code tried to run MyMethod he didn't recognized the stub because the lambda expressions was not equal… why? because the default "Equals" compare references.

To solve the problem we started by searching for something that will help us identify in a unique way lambda expressions.

If you have read my post about expression trees you will know that an Expression object has the following properties:

1)Body - the expression
2)Parameters
3)NodeType - LambdaExpression
4)Type - Func<int, bool>

The only thing that identify the expression is the body, which is an expression itself. so the solution was not here.

The Only solution we thought of is to implement the Equals ourselves(as we let re-sharper do it for us in our  own entities), but we didn't know how. we searched for some Constraints and we found the following solution which was exactly what we needed:

myStub.Stub(x=>x.MyMethod(Arg<Expression<Func<in,bool>>>.Matches(Property.AllPropertiesMatch(y=>y==3))).Return(10);

The constraint Property.AllPropertiesMatch does the trick and compare the expression by it's properties.

Note: the expression y=>y==3 does not equals to x=>x==3!

*This post is dedicated to Jones,that gave me an interesting afternoon of debugging and coding.

Saturday, November 13, 2010

"Selected button" with visual state in silverlight

Lately, I start using silverlight to create some pages in my asp application.

I needed to create a toolbar that had some buttons for different operations for users to use, and to make their experience better I wanted to mark the selected tool in some way.

My first thought was to create "click" events to all my tools buttons and write something like this:

private void MyToolAButton_Click(object sender, RoutedEventArgs e)
{
       UnClickedTool(ToolB);
       UnClickedTool(ToolC);
       ClickedTool(ToolA)
}
……
private void UnClickedTool(Button tool)
{
       //Set unclicked visual appearance
}

private void ClickedTool(Button tool)
{
       //Set clicked visual appearance
}

This solution will work but it felt a bit outdated for silverlight.

Then I remembered hearing stuff about silverlight VisualStateManager that helps you define the visualization for each of the states in your control(such as mouseOver,Focused etc..), and all in simple xaml code!

For example, here is some code to change the color of the button(from red to orange) when mouseOver:

<Button x:Name="ButtonA">
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <Grid>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="MouseOver">
                                    <Storyboard>
                                        <ColorAnimation Storyboard.TargetName="ButtonSolidBrush"
                                                        Storyboard.TargetProperty="Color"
                                                        To="Orange" Duration="0" />
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Normal"/>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name="ButtonBorder" >
                            <Border.Background>
                                <SolidColorBrush x:Name="ButtonSolidBrush" Color="Red"/>
                            </Border.Background>
                        </Border>
                    </Grid>
                </ControlTemplate>
            </Button.Template>
</Button>

But I wanted to change the color when the button is selected! so at first, I configured the "Pressed" state of the button. but the problem is that when your mouse leaves the button, the state is changed back to "normal" (and return to the old color) because "Pressed" state is when you actually press the button.

The solution for this is simple – use ToggleButton.

What is ToggleButton?

ToggleButton is the base class of checkbox and radiobutton, which means that it's a button with checked and unchecked states.

The state of the control is determined by the IsChecked property.

By replacing my Button control with ToggleButton I was able to achieve my goal!

I've created a control template with "checked" and "unchecked" visual configuration:

 <ControlTemplate TargetType="ToggleButton" x:Name="ToggleTemplate">
            <Grid>
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup x:Name="CommonStates">
                        <VisualState x:Name="Checked">
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetName="ButtonSolidBrush"
                                                        Storyboard.TargetProperty="Color"
                                                        To="Orange" Duration="0" />
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="Unchecked">
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetName="ButtonSolidBrush"
                                                        Storyboard.TargetProperty="Color"
                                                        To="Blue" Duration="0" />
                            </Storyboard>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
                <Border x:Name="ButtonBorder" BorderBrush="Coral">
                    <Border.Background>
                        <SolidColorBrush x:Name="ButtonSolidBrush" Color="Red"/>
                    </Border.Background>
                </Border>
           </Grid>
</ControlTemplate>

Created 2 togglebuttons with this template:

<ToggleButton x:Name="MyButton" Grid.Row="1" Content="Click me.." Checked="MyButton_Checked"  Template="{StaticResource ToggleTemplate}" IsThreeState="False"/>
<ToggleButton x:Name="MyButton2" Grid.Row="2" Content="Click me2.." Checked="MyButton2_Checked"  Template="{StaticResource ToggleTemplate}" IsThreeState="False"/>

*The "IsThreeState" property determine if we had "indeterminate" state or just "checked" and "unchecked" states.

And implemented the events(when checking one button,the other is unchecked):

private void MyButton_Checked(object sender, RoutedEventArgs e)
{
     MyButton2.IsChecked = false;
}

private void MyButton2_Checked(object sender, RoutedEventArgs e)
{
     MyButton.IsChecked = false;
}

You can see that I still had to implement sort of "ClickedTool" and "UnClickedTool" in my events. so what's the difference??

Well, the big difference is that I don't use any visual definition in my code behind! I've just changed the states of the controls and that's it! all the visual definitions is in the xaml,so I can change them without changing any code! so if tomorrow I get new control template I just need to change the "Template" properties of my buttons and that's it!

Saturday, October 16, 2010

Problems with Wcf RIA services installation(or uninstallation)

Yesterday i installed the full version of vs2010 on my laptop(i had vs2010 express so far) and remove the vs2008.

All well, till i tried to create a silverlight application with Ria service.

First,when creating the Silverlight Application project i didn't have the "enable WCF Ria services" checkbox. that turned a red light, but i kept going… then i tried to add a Domain service to the web application but i couldn't! it wasn't in the list of items to add..

So i tried to uninstall and install the silverlight tools,toolkit and sdk about a 1000 times – didn't help! there was a time that i did get the "enable WCF Ria services" checkbox but it was disabled.

Then,i found a post somewhere that talked about old vs2008 installation of Ria services that should be uninstalled,so i looked in the control panel and searched for the installation of WCF Ria services, but trying to uninstall it led to nothing. it was still there no matter what i tried to do…

At the end, after heavy search on google i found the solution! removing some keys from the registry and the problem solved! (i had to install all silverlight stuff again and that's it).

The solution is described in here:

http://forums.silverlight.net/forums/t/149912.aspx

Good luck…

Saturday, September 18, 2010

Moving up! to visual studio 2010

After to holidays season(in Israel), we are planning to start working with visual studio 2010!
Except the nice IDE features,we will start working with silverlight 4 and hopefully .Net 4 (there are some problems with our maps engine, so we might stay on 3.5 for awhile).
To get ready, i found some good tips to improve our vs2010 experience.

Search and navigation – tip & tricks:
http://weblogs.asp.net/scottgu/archive/2010/08/24/search-and-navigation-tips-tricks-with-visual-studio.aspx

Debugging tips:
http://weblogs.asp.net/scottgu/archive/2010/08/18/debugging-tips-with-visual-studio-2010.aspx

And the shortcuts poster:
http://weblogs.asp.net/scottgu/archive/2010/07/29/visual-studio-2010-keyboard-shortcuts.aspx

Shana toova.

Saturday, March 6, 2010

Unit Tests and Integration tests, are they so different?

Hi there,

in my team we have lots of service side code, which connects to other services.

of course we need to write unit tests for this code, and we need integration tests also – so we will know if it actually works with the other side.

and we use Rihno mocks to test only what we want while writing UT.

our unit tests looks something like this:

[TestMethod]
public void DoAction_SendingTrueValue_MessageReturning()
{
            ILogWriter mockLogWriter =

                      (ILogWriter)mocks.CreateMock( typeof(ILogWriter));
            mockLogWriter.LogAction("");
            LastCall.Constraints(Text.Like("MyError"));
            mocks.ReplayAll();
            MyService.LogWriter = mockLogWriter;

            string message = MyService.DoAction(true);
            Assert.AreEqual("bla", message); 
}

and on the other hand, this is our integration test:

[TestMethod]
public void DoAction_SendingTrueValue_MessageReturning()
{
            string message = MyService.DoAction(true);
            Assert.AreEqual("bla", message);

}

Of course this example is extreme but the fact is that the integration tests and the unit test very often looks almost the same, the only difference is the use of a mock.

I was thinking, how can we merge the tests and  perhaps use the same code. so I read a great idea in one of the .net blogs, we can use a simple conditional compilation symbol.

we can take the first test method, and change it a little bit:

[TestMethod]
public void DoAction_SendingTrueValue_MessageReturning()
{

            #if MOCK
            ILogWriter mockLogWriter =

                      (ILogWriter)mocks.CreateMock( typeof(ILogWriter));
            mockLogWriter.LogAction("");
            LastCall.Constraints(Text.Like("MyError"));
            mocks.ReplayAll();
            MyService.LogWriter = mockLogWriter;

           #endif

            string message = MyService.DoAction(true);
            Assert.AreEqual("bla", message); 
}

than all we need is to change one definition in the project settings and change our method to be integration test,

in the project settings you can find this:

settings

if the “MOCK” word will be written there, the if in the test will return true, and the it will create a mock and work as a unit test. but if we remove the “MOCK” word, the if will return false, skip the creation of the mock and work as an integration test.

simple..

by the way, in case you didn’t understand, “MOCK” is only an example, you can write any word and write these #if symbols where ever you like.

Hope I helped – bye for now.

Friday, February 5, 2010

Linq – Different between "join" syntax

As I recently discovered, Linq is a very powerful query language that can help us query our objects in a very beautiful way (yes,beautiful).

Lately I had to write some join queries between lists and I found-out that linq let you do that in all kinds of ways.

So what kind of joins can we do,and what is the difference between them?

In order to explain this we need an object model,a simple one.

Lets say we are running a store. we have products and each product is created by a company.

   public class Company
   {
       public string Name { get; set; }
       public int Id { get; set; }
   }

   public class Product
   {
       public string Name { get; set; }
       public int CompanyId { get; set; }
   }
We will run our queries on these lists:
var companies = new List<Company>
                            {
                                new Company() {Name = "Candy's", Id = 1},
                                new Company() {Name = "Cow's",  Id = 2},
                                new Company() {Name = "Stuff",  Id = 3},
                            };

           var products = new List<Product>
                           {
                               new Product() {CompanyId = 1, Name = "Bamba"},
                               new Product() {CompanyId = 1, Name = "Bisli"},
                               new Product() {CompanyId = 2, Name = "Milk"},
                           };

Inner-join

The first join is a simple inner-join. we want to print each product from the list and it's company's name:

from product in products
join company in companies on product.CompanyId equals company.Id
select new {Product = product.Name, Company = company.Name};

If we print the result it will be:

Bamba - Candy's
Bisli - Candy's
Milk – Cow's

The query run on the products list and search the matching company.

another option to get these same result is with this "sql" syntax:

from product in products
from company in companies 
where product.CompanyId == company.Id
select new { Product = product.Name, Company = company.Name };
So what's the difference? when to use what? in a second…

Group-join

Now we would like to print a company and all of it's products.

we could use the inner-join syntax as follows:

from company in companies
join product in products on company.Id equals product.CompanyId
select new { Product = product.Name, Company = company.Name };
And get this result:

Candy's - Bamba
Candy's - Bisli
Cow's – Milk

But what if we want to print the company's name only once? or we want to keep the company's products in a list? that why we have the group join.

from company in companies
join product in products on company.Id equals product.CompanyId into companysProducts
select new { Company = company.Name,Products = companysProducts };
As you can see we added the "into" key-word and now,for each company we select it's name and a list of it's products.

The result will look like that:

Candy's
    Bamba
    Bisli
Cow's
    Milk
Stuff

Another interesting thing we can see in the query result is that the "Stuff" company appears although it has no products. that didn't happened before. this is because now we group for each company it's products. if it has no products the list will be empty. this query also called "outer-join".

Outer-join

Except for the query we saw above we have one more option to perform an outer-join. what if we wanted to print lines of type "company-product" but wanted "Stuff" (that has no products) to be in that list with empty product?

For this, we have "DefaultIfEmpty" method:

from company in companies
join product in products on company.Id equals product.CompanyId into companysProducts
from item in companysProducts.DefaultIfEmpty(new Product{Name = "No products"})
select new {Company = company.Name, Product = item.Name };
What we do is creating a "default product" that will be inserted if the companysProducts list of the current company is empty.

The result of this will be:

Candy's Bamba
Candy's Bisli
Cow's Milk
Stuff No products

Custom-join

As you noticed, all our joins so far used the "equals" comparison. but what if we want to select for each company all the products that it didn't make?? we need to use not-equal.

The "join" syntax we saw so far wont be good here. so we need to use the "from" statements to perform what we want:

from company in companies
from product in products 
where company.Id != product.CompanyId
select new { Company = company.Name,Product= product.Name };

The result will be:

Candy's Milk
Cow's Bamba
Cow's Bisli
Stuff Bamba
Stuff Bisli
Stuff Milk

(we could obviously do this with a group-join and the results would be more readable)

So now it's the time to explain "When to user what":

The "join" syntax is designed to perform equals joins in the best way,that's why when you want to use "==" operator you better use the "join" syntax – it has best performance.

When you want to use other operators than "equals" Or you want to use more than one condition (where company.id == product.CompanyId and company.state = product.state) you need to use the "from … from.. where.." syntax.

This was just the tip of the iceberg about linq queries, hope i made things a beat more understandable, and now you are able to refactor your 10 lines of "foreach" loop to one query statement(really, that what happens).

Saturday, January 23, 2010

Windows live writer

A small tip to all the bloogers –

There is a very good tool the can be download from http://download.live.com/ that gives you a very powerful editor to write your blog posts.

All you have to do, is download the program and (easily) configure your blog(s) and it gives you full support in writing posts,adding pictures,videos etc…

It can even show you "quick preview" with your blog layout!

The tool also save drafts, and all you have to do is just press "Publish" and the post will be published on your blog.

It's very comfortable, especially if you have more than one blog…

highly recommended.

Friday, January 22, 2010

5 Tips on How to work in a huge team

Okay, so our company is very successful, we have lots of clients, and we have a very strict dead-line to deliver. the next thing that happened – our team grew to something like 20 programmers!! and all sitting in the same huge open space.

So there are plenty of people to write code, but there are lots of unfortunate side effects: 

  • first of all – lots of stuff to do, lots of people to do it, however – things falls between the chairs, things get done twice, the code is duplicated, and so on
  • there is lack of coordination between all the programmers.
  • a lot of code is written and therefore – build is breaking.
  • noise in the room.
  • tons of questions to the experienced programmers.
  • and more…

So after a lot of talks in the team we made some adjustments to our daily work so we could actually get some work done, so thanks to my team I selected 5 tips that I think will help a huge team get something done:

  1. split the team – we took the team leader and added 3 more lower level managers, so each of them has 5 programmers, and each connects between the team-leader and his team. we also made sure that in each team there will be at least one experienced programmer.
  2. rearrange the workspace – first of all, make sure each and every one has his privacy, it’s very important, you can do so by adding something that physically separates between the work stations. you should also arrange the workstations by the teams, so the team meeting won’t interrupt each other’s.
  3. continuous integration – The best way to make sure nobody breaks the build, we use TeamCity but every other tool will do just fine.
  4. Make Morning standup meetings – We use agile as our development methodology, but even if you don’t, make morning meetings – a separate meeting for each team for 10 minutes so you would understand what you accomplished yesterday and will be done today. after this we make a meeting between all the leaders and the Team leader, that is how we make sure we are coordinated.
  5. Get to know all the team-mates of the team – I believe it’s very important to know all the programmers in the big team personally, so there won’t be a situation when someone don’t want to approach you because he is shy and is embarrassed to talk to you! you want people to talk to each other between the teams, that’s how things gets done best.

So that’s it, that’s what I learned by working in a huge team, I hope you could use these insights for your team.

Health!!

Tuesday, January 19, 2010

Expression trees

first post - yay! :)

A while ago i was debugging a method that generates a Linq query and returns IQueryable  .
I had a problem with it's results and i wanted to check-out the IQueryable object that was generated,
so I set an "Add watch" to the return value and was trying to find my generated linq. that wasn't so simple as i though.
In fact, the IQueryable dose not keeps the Linq statement as is, but saves it in an Expression object(also known as Expression tree).
You can see this in the IQueryable  interface definition:
public interface IQueryable : IEnumerable
{
   Type ElementType { get; }
   Expression Expression { get; }
   IQueryProvider Provider { get; }
}

What is an expression tree?
“Expression trees represent language-level code in the form of data”
msdn.microsoft.com
-This means that an expression tree gives us some kind of meta-data for our code.

To explain the concept of the Expression trees we need to start from the very beginning....
Lets say we have this method:
public void PrintNumbers(Func<int,bool> filter)
{
   for(int i=0;i<=10;++I)
  {
      if (filter(i))
         Console.writeline(i);
  }
}

The method takes a filter function and prints all the numbers from 1 to 10 that match the filter.

Until now we had 3 ways to do this:
1) Declare a method that match the parameter,something like this:
private bool MyFilter(int x)
{
  return (x%2) == 1;
}

And call our method like this:
PrintNumbers(MyFilter);

2) we could call it with anonymous delegates:
PrintNumbers(delegate(int x)
{
   return (x%2) == 1;
}

3) Lambdas expression:
PrintNumbers(x => (x % 2) == 1);

And Now we have a new way - Expressions:
Expression<Func<int, bool>> myExpression = x => (x % 2) == 1;

This expression is of type Func<int, bool> and assigned with lambdas expression.
when doing this assignment the expression object's properties are filled  as follows:
1)Body - the expression: (x % 2) == 1
2)Parameters - x
3)NodeType - LambdaExpression
4)Type - Func<int, bool>

Becasue expressions are nested types(that's why they are called trees) we would like to view them in a tree format.
you can download the visualizer from Visual studio 2008 sampels.

For exmple, if we run the visualizer on our current expression, we will get the following result:



Our Expression is an : ExpressionEqual which equals between (marked in pink underline) ExpressionModulo(left) and ExpressionConstant(righ).

The Expression modulo represent a modulo operation between ExpressionParamter "x" and a ConstantParameter "2' ,and the ExpressionConstant represent the const "1".

Expression trees and Linq
As I said in the begining of the post,the linq statement is saved in the Expression property of the IQueryable object. when the query is "executed" the expression is translated into sql statment.

for example, if we run the expression tree visualizer on the query:
var query = from c in db.Customers
where c.City == “London"
select new { c.City, c.CompanyName };

We will get the:

and now that we can read this, it is simpler to debug Linq queries.

There are some more usages to the Expression trees such as generating code and reflection, but thats for a diffrent post....

Barko(aka Tal)

Saturday, January 9, 2010

Welcome!!

hello everybody We are Matan and Barko, and We have been .net developers for almost 5 years We both work in a big Software company in Israel. In this blog we will post some interesting stuff , mostly about .net, WCF, TFS, unit testing, ESRI technologies, Agile and more.. we hope you will enjoy what we have to say, Have fun Pair (of) Programmers