DCSIMG
December 2008 - Posts - Ariel's Remote Data Center

December 2008 - Posts

My biggest Vista problem solved.

Posted Dec 24 2008, 01:08 PM by Ariel Ben Horesh  

No. I didn't go downgrade to XP, nor did I install LINUX.

Lot's of bad blood exists around Vista, I know, Everyone's favorite punch doll. I dare say not without reasons.

I kinda got used to it, I've been working with it since it got out, most of time I was happy, not thrilled but content.

Regardless of that there was one thing that completely drove me crazy with Vista: Explorer folder settings.

I like to view my folders in the same way, I want "details", I want to see file sizes and dates, if for some reasons I am viewing pictures, I will know where to go in order to change it to Large Icons, no need to do that for me or persist that. Also there is no reason on earth to change my last c# project folder settings to "music" view where there is not a single hint to indicate that there is need to that.

There were times that I wish I could just get a hold of that vista code and see this genius piece of code that decides what setting to apply to what folder, what rules does it use, I just couldn't figure it, is it Random based algorithm?

Anyway it took me a while to actively looking for a cure, and I found it, that why I thought I would share it with you in case you were suffering as much as I did.

Follow Method 2 in this guide, and may there be world peace. (especially for the innocent people that really suffers even while I write this post, in the south).

Ariel

MIX 10K challenge, Learn How I did my Silverlight App. Part 2

Posted Dec 23 2008, 01:24 AM by Ariel Ben Horesh  

In Part 1, we’ve discussed how the Layout was done, and we finished designing our XAML.

Now let’s see what is going on beyond the scenes.

We will define two helper classes that will help us manage the data in our App.

Function class got:

  • Name : Will be shown inside the ComboBox.
  • Params: List of Param class, will be used to persist data into the function.
  • Run: a Func<double, double> type property, contains a lambda expression representing the mathematical function to be used.

Param class got:

  • Name : Will be shown inside the listbox like “a” or “b”.
  • Val: The Value that was entered by the user.

image

In code they look like this.

  public class Function

  {

    public string Name { get; set; }

    public List<Param> Params { get; set; }

    public Func<double, double> Run { get; set; }

  }

  public class Param

  {

    public string Name { get; set; }

    public string Val { get; set;}

  }

OK let’s get some meat.

  1. We will define our private members of class Page. We will need a Polyline object and PointCollection for it.

      public partial class Page : UserControl

      {

        PointCollection polyPoints = new PointCollection();

        Polyline yellowPolyline = new Polyline();

  2. Now we will create the data source of the mathematical functions a list of Function objects as a private member (note that the Run property is unassigned we will assign it later) :

        List<Function> funcs = new List<Function>

        { new Function { Name = "aX",

                         Params = new List<Param> { new Param {Name="a"}}},

     

          new Function { Name = "aX + b",

                         Params = new List<Param> { new Param {Name="a"},

                                                    new Param {Name="b"}}},

          new Function { Name = "aX^2 + bx + c",

                         Params = new List<Param> { new Param {Name="a"},

                                                    new Param {Name="b"},

                                                    new Param {Name="c"}}},

     

          new Function { Name = "aX^d + bx + c",

                         Params = new List<Param> { new Param {Name="a"},

                                                    new Param {Name="b"},

                                                    new Param {Name="c"},

                                                    new Param {Name="d"}}},

          new Function { Name = "Sin(X)"},

          new Function { Name = "Cos(X)"},

          new Function { Name = "Tag(X)"},

          new Function { Name = "Floor(X)"},

          new Function { Name = "Abs(X)"}};

     

  3. We will define a method called SeedFunc inside Page class, this method will run for each X pixel we have on the X axis of our drawing area we will calculate it’s Y part. In our case we have 400 pixels. We could iterate over them from –200 to 200 for example but you will notice that a method like Sin(x) is giving back Y in the range of –1 to 1. so it will look very very small with that ratios. The trick is to use smaller X numbers from –10 to 10 and translating them to X,Y in pixels. Furthermore if we have a point that the Y value is outside our plotting area we disregard it.

        private List<Point> SeedFunc(Func<double, double> func)

        {

          List<Point> funcPoint = new List<Point>();

          for (double i = 10; i >= -10; i -= 0.05)

          {

            try

            {

              double y = func(i) * 20;

     

              if (Math.Abs(y) < (Canvas.ActualHeight / 2))

              {

                funcPoint.Add(new Point(i * 20, y));

              }

            }

            catch (DivideByZeroException ex)

            {

              continue;

            }

          }

          return funcPoint;

        }

  4. We will define an helper method, a quick and dirty way to retrieve a  parameter value from a given Function.

        private double Ex(int f, int c)

        {

          return Convert.ToDouble(funcs[f].Params[c].Val);

        }

  5. Move to the Page constructor just after InitializeComponent(); we will start assigning values to our private members. First we will assign the lambda expressions for each of our Function.

          funcs[0].Run = x => x * Ex(0, 0);

          funcs[1].Run = x => x * Ex(1, 0) + Ex(1, 1);

          funcs[2].Run = x => x * x * Ex(2, 0) + x * Ex(2, 1) + Ex(2,2);

          funcs[3].Run = x => Math.Pow(x, Ex(3,3)) * Ex(3, 0) + x * Ex(3, 1) + Ex(3, 2);

          funcs[4].Run = x => Math.Sin(x);

          funcs[5].Run = x => Math.Cos(x);

          funcs[6].Run = x => Math.Tan(x);

          funcs[7].Run = x => Math.Floor(x);

          funcs[8].Run = x => Math.Abs(x);

  6. Also inside the constructor, we will assign the ComboBox with this list. And create a few defaults for our Polyline.

          fChs.ItemsSource = funcs;

          SolidColorBrush yellowBrush = new SolidColorBrush();

          yellowBrush.Color = Colors.Yellow;

          SolidColorBrush blackBrush = new SolidColorBrush();

          blackBrush.Color = Colors.Black;

     

          yellowPolyline.Stroke = blackBrush;

          yellowPolyline.Fill = yellowBrush;

          yellowPolyline.StrokeThickness = 2;

  7. Now that we are familiar with Param class we can define a DataTemplate for it. Go back to Page.xaml, locate the listbox and define this template. Notice that the Textbox binding is marked with TwoWay, which mean every change is automatically relayed to the parameter underneath.

            <ListBox x:Name="ParamList" Width="200" Height="200">

              <ListBox.ItemTemplate>

              <DataTemplate>

                <StackPanel Orientation="Horizontal">

                  <TextBlock Text="{Binding Name}"/>

                  <TextBlock Margin="5,0,5,0" Text="="/>

                  <TextBox Width="50" Text="{Binding Val, Mode=TwoWay}"/>

                </StackPanel>

              </DataTemplate>

            </ListBox.ItemTemplate>

            </ListBox>

  8. Switch back to the cs file, let’s handle the Selection change of the combo box. we get the function from the combobox and we set the source of the list with its’ params list.

        private void fChs_SelectionChanged(object sender, SelectionChangedEventArgs e)

        {

          selectedFunc = e.AddedItems[0] as Function;

          ParamList.ItemsSource = selectedFunc.Params;

        }

  9. Move on to implement the clear button, we will remove the current ployline and clear the pointlist making it ready for new plotting. if there was an error, we eliminate the error message.

        private void Clear_Click(object sender, RoutedEventArgs e)

        {

          Canvas.Children.Clear();

          polyPoints.Clear();

          ErrorLabel.Visibility = Visibility.Collapsed; }

     

  10. Last piece of the puzzle. The plot button event implementation.
    1. Before we plot we clear again.
    2. we position our polyline in the middle of the canvas.
    3. We call the SeedFunc method to generate a list of points.
    4. We just add them to Polyline list collection.
    5. And last we add the polyline to the canvas.
    6. If something bad happened, we warn the user and clear everything.

      private void Plot_Click(object sender, RoutedEventArgs e)

        {

          ErrorLabel.Visibility = Visibility.Collapsed;

          if (selectedFunc != null)

          {

            try

            {

              Canvas.Children.Clear();

              polyPoints.Clear();

     

              Canvas.SetLeft(yellowPolyline, Canvas.ActualWidth / 2);

              Canvas.SetTop(yellowPolyline, Canvas.ActualHeight / 2);

     

              List<Point> funcPoint = SeedFunc(selectedFunc.Run);

     

              foreach (Point p in funcPoint)

              {

                polyPoints.Add(p);

              }

              yellowPolyline.Points = polyPoints;

              Canvas.Children.Add(yellowPolyline);

            }

            catch (Exception ex)

            {

              Canvas.Children.Clear();

              polyPoints.Clear();

              ErrorLabel.Visibility = Visibility.Visible;

            }

          }

        }

     

    It should look like this:

    image

     

We can now conclude this 2 part tutorial, of how I built my Silverlight app to the MIX 10K competition. I hope I will see you apps beside mine their and If I don’t win, at least you will, so it will have a little piece of me inside :).

I urge you to visit my app at MIX and share your support with me.

Thanks

Ariel

MIX 10K challenge, Learn How I did my Silverlight App. Part 1

Posted Dec 23 2008, 01:22 AM by Ariel Ben Horesh  

My esteemed colleague Alex Golesh  sent me a request to rate his app on the MIX 10k competition, I wasn’t aware of this competition, but I immediately decided that I want in.

The rules are simple, do anything you want on Silverlight or XBAP but you mustn’t exceed 10kb of code and resources.

After some thinking I’ve decided I want to create a mathematical function plotter, you can find such on sites like www.Mathway.com.

So Now before you continue reading and learning how I put it together, play with my app, discover all the features, try out all the functions. It will make you life easier understanding what I’m doing because we will get very soon to XAML.

http://2009.visitmix.com/MIXtify/TenKDisplay.aspx?SubmissionID=0031

(And if you liked it, rate it, please).

Thread.Join();

You have returned. Good. Hope you took your time. Now let’s us continue.

I will begin dissecting the final solution but it took me a while to grasp how everything will fit in, and what UI to use.

Just to describe chronologically, I’ve started with manipulating a simple object Line  inside a Silverlight application. When I mastered it I hardcoded some functions such as X^2 and Sin(x) to see how the line is behaving with different sets of points.

Then I put my mind on the UI of how the user will create his function.

At first I fantasized on Mathway.com style ability to parse a function from a string, I realized quickly that building such a parsing engine will most definitely bring me over the 10k limit.

So I inclined to be building a much simpler way to describe what function is to be plotted: The user chooses the function to plot, if there is a need for extra parameters, a listbox is used to enable editing.

One last comment: In order to remain under 10k limit, comments, nice separation to functions (or files), extensive error handling is a luxury one can not afford. You have been warned.

 

So enough talking let’s start seeing some code.

Everything we need is inside Page.xaml and Page.xaml.cs.

Beside that we have the app.xaml and app.xaml.cs that were created with some code generated from the visual studio template. I left them almost untouched except of deleting comments (Which by the way if you didn’t know saved me precious k-s!).

  1. Open Page.xaml and notice we have a Grid object called LayoutRoot with background.

    <UserControl x:Class="Plotlight.Page"

     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

       Width="400" Height="300">

        <Grid x:Name="LayoutRoot" Background="White">

     

        </Grid>

    </UserControl>

  2. A cool tip I learned from Guy Burstein, change the Width and Height of your app to MinWidth and MinHeight. I choose 600, you can have whatever u like.
  3. Because we want our app to win and we are no designers the easiest thing we can do to make our app more pretty is use gradient brush, everybody loves them and you don’t need to really have a talent. right? Remove the background = “White”.

      <Grid x:Name="LayoutRoot">

          <Grid.Background>

            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

              <GradientStop Color="#C4008DFA"/>

              <GradientStop Color="#FFFFFFFF" Offset="1"/>

              <GradientStop Color="#FDF9FCFE" Offset="1"/>

            </LinearGradientBrush>

          </Grid.Background>

  4. We will create a basic layout for our app, I decided to create 2 columns, one for the function retrieval and second for the plotting area.

        <Grid.ColumnDefinitions>

          <ColumnDefinition Width="30*"/>

          <ColumnDefinition Width="70*"/>

        </Grid.ColumnDefinitions>

  5. Create a StackPanel, this will arrange all children control in a way that each will be on top of the other one.

    <StackPanel Margin="10" Orientation="Vertical" Grid.Column="0">

  6. Add a pair of TextBlock and Combobox, the ComboBox will contain the functions that are offered to be plotted.

            <TextBlock FontSize="14" Text="Choose a Function:" Margin="0,0,5,0"/>

            <ComboBox x:Name="fChs" Width="200" DisplayMemberPath="Name" SelectionChanged="fChs_SelectionChanged"/>

  7. Add another pair, now it will be a TextBlock and a listbox. The listbox will contain a mean to edit parameters to the functions.

            <TextBlock FontSize="14" Text="Enter coefficients:" Margin="0,0,5,0"/>

            <ListBox x:Name="ParamList" Width="200" Height="200">

            </ListBox>

  8. Inside the listbox we will define a DataTemplate, we will do that later on. The DataTemplate will define how a certain class is to be shown in the UI so each entry will receive it’s own line inside the listbox.
  9. Add another StackPanel this time it will align the controls Horizontally, and fill it with 2 buttons and TextBlock: One button will Plot, the second will clear and the label we will use to notify an error, if needed that why it is not visible.

            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,8,0,0">

              <Button Margin="0,0,5,0" Content="Plot!" Click="Plot_Click"/>

              <Button Content="Clear" Click="Clear_Click"/>

              <TextBlock x:Name="ErrorLabel" Foreground="Red" Text="Error" Visibility="Collapsed"/>

            </StackPanel>

     

     

OK we finished creating the first column of our Layout.

The second column contains a part with a lot of boring text and it is not very interesting, but the second part is our drawing area.

  1. We will create a Border for our drawing Area. So it will be very clear where the function will be plotted. Actually the Width and Height are very important. it is 400 and 3 for each side of the border. Is is very important for us that the plotting area would be 400 exactly, in the code behind we will see that we will plot a point for each pixel (400 points total).

    <Border BorderThickness="3" BorderBrush="Black" Grid.Column="1" Width="406" Height="406">

  2. Now we will create another Grid, this will serve as the background for our drawing area. I choose Azure for some reason :) and the Grid lines are shown because they will be our Axis. Yep, remember less is code in our app.

    <Grid Background="Azure" ShowGridLines="True" >

  3. So now it shouldn’t surprise you that we are separating the Grid into 4 equal quarters

          <Grid.ColumnDefinitions>

            <ColumnDefinition Width="50*"/>

            <ColumnDefinition Width="50*"/>

          </Grid.ColumnDefinitions>

          <Grid.RowDefinitions>

            <RowDefinition Height="50*"/>

            <RowDefinition Height="50*"/>

          </Grid.RowDefinitions>

  4. The last part is inserting a Canvas object on top of the Grid. On this objet we will draw our beloved function. Notice that I’m using a transformation to flip the content of the Canvas. The reason that while Y axis behaves the opposite from the Y axis of the screen meaning when values increases Graph Y Axis is going up and Screen Y axis is going down, this small manipulation saves some trouble.

            <Canvas x:Name="Canvas" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Grid.RowSpan="2" RenderTransformOrigin="0.5,0.5">

              <Canvas.RenderTransform>

                <TransformGroup>

                  <ScaleTransform ScaleY="-1"/>

                </TransformGroup>

              </Canvas.RenderTransform>

            </Canvas>

Now we are ready for Part 2. Which we will discuss the interesting part, the code behind.

Stay Tuned.

Ariel

Cool LINQ trick

Posted Dec 22 2008, 07:31 PM by Ariel Ben Horesh  

Today I was approached with a nice question.

Suppose we have a simple class with a few properties.

image

We want to do a linq query over it with a where clause. (it doesn’t matter what is the data source, in this case it will be plain CLR objects).

Let’s say that we want to construct our Where clause in such a matter that if a variable is null we ignore it and use another condition, but if it is not null we will use this one; did I confuse you?

let’s try to look on an example:

First we will create our “DataSource”. For our example just a list of Margols.

List<Margol> list = new List<Margol> 
{   new Margol { Name="x", Address="y", Val=0}, 
    new Margol { Name = "a", Address="b", Val=1}
};

Let’s mock some variables we want to filter our list with them:

string nameCheck = null;
int valueCheck = 0;

and now let’s create a simple query:

var d = (from m in list
         where m.Name == nameCheck
         select m);

The problem is that if nameCheck is null we will get an exception, furthermore we would like that if it is the case make fallback condition with valueCheck based that fact. (Thus a simple check is not enough).

Anyway it is a cool excuse to check out a different approach.

First we will not use the syntactic shortcuts and we will use the extensions methods.

We will exchange that query with that one:

var d = list.Where(myMethod).Select(m => m);

Only thing now for us is to declare myMethod.

myMethod will be a function that gets a Margol as a parameter and will return a bool, meaning whether it will be filtered or not, and now we have all the power of the world! to do whatever we want.

 

Func<Margol, bool> myMethod =
               m =>
               {
                   if (nameCheck != null)
                   {
                       return (m.Name == nameCheck);
                   }
                   else
                   {
                       return (m.Val == valueCheck);
                   }
               };

 

Cheers,

Ariel

תגים:, , ,

#devacademy3 : Summary, observations, and a few recommendations

Posted Dec 16 2008, 01:10 PM by Ariel Ben Horesh  

So the dust cloud behind #devacademy3 has scattered, and what did we get?

DevAcademy3 is based on a proven concept, you can feel that it was made with the same template as the previous events. Based on past experience I knew what to expect, I wasn't surprised, I wasn't disappointment as well, because I knew perfectly well how this event is going to be.

On the other hand, event in that magnitude should have a clean message to it, and if you can, plan a surprise, anything, let people have something to discuss on for the next few days, create a buzz over it, let people expect something new each time you raise such an event.

Also it lacked a clear roadmap of what is ahead and how those sessions are supposed to fit in on a much larger scale. We got mostly unrelated sessions to each other, even on the same track, some even overlapped.

Generally speaking I am not fond of keynotes, but maybe you just need to have at least one space allocated for something surprising and turn the heads of every attendee to the direction of your message.

As in past events, Microsoft continues to strengthen their relationship with Bloggers. From invitations, the famous blogger corner to screens that show off the latest blogs. As a blogger I can just try to think of more ideas that can enhance and harness the power of the blogsphere and such conferences in the future, a glimpse of that could be seen on Guy Burstien session which involved twittpeople (most of them are bloggers as it appear) to create an interaction between them and the session. I hope in future sessions, such interaction could be used as well.

About the feedbacks - There must be a way to give feedbacks online. At least give every attendee a pen. I hope they will have enough feedbacks because most people I've seen didn't bother to evaluate and it is highly important.

About the Food. It was plentiful but such were the lines/queues. Perhaps a few more lines to balance the load? or maybe different time for each track?

SWAGs : Clearly not enough, especially when people on the first time paid money to for this kind of event. I think anything could have been suffice, a CD with the latest bits, a shirt, a book, it was done before why not here as well.

I would be happy to hear your feedbacks as well!

Ariel

Twitter Craziness

Posted Dec 16 2008, 08:58 AM by Ariel Ben Horesh  

twitter

I most admit I’m fairly new to Twitter. I’ve observed this phenomena from outside for many days. Again I need to be honest I thought it is just plain stupid, why do I need to tell anybody what do I do now, why share every stupid thing with the rest. Furthermore I thought that people will get tired from it, and as quickly as it came into our lives and became a trend, it will be equal like forgotten.

Rarely, I am wrong, and as the days past by I ignored twitter until I read this post which describe 7 ways to self promotion. I qoute:

I mentioned Twitter a few times already in this post, but it deserves its own section. Talking about yourself on Twitter is INVALUABLE. In the simplest definition, Twitter is meant for people to answer one simple question: What Are You Doing Right Now? But it has become a networking tool on a much larger scale. Start following some of the big names in your industry. If you're into .NET development, start listening to Scott Hanselman (@shanselman), Joe Stagner (@misfitgeek), Sara Ford (@saraford), and your local evangelists (that's me - @jblankenburg), Jennifer Marsman (@jennifermarsman), Brian Prince (@brianhprince), and Bill Steele (@wjsteele).

While I reading it I remember thinking maybe there is something I miss around here, and soon enough I opened up my own twitter account : www.twitter.com\arielbh

In a platform which you can follow a cat or weirder Shaquille O'Neill, and be followed by political parties?! (btw did you notice that they shamelessly copied Obama “Yes we can”), it do raises a lot of questions on  my mind whether cooperate with this, do I let a political party follow my twits? Should I block them? what do they look for anyway.

The highlight of course was during Guy Burstein session at DevAcademy3 which fast enough became the fastest(or spammest…) twitter around competition.

But nevertheless it was fun, the feeling of being interactivity engaged with the presenter and the presentation itself was unique.

So be sure to follow me! whatever your reasons :)

Ariel

#devacademy3. Live blogging : Building Azure app

Posted Dec 15 2008, 08:03 AM by Ariel Ben Horesh  

I can separate this session into 2 distinct parts.

While talking about the theory Manu managed to do a great job, he was very clear, his points were sharpened and well understood, I think anybody on the crowd understood what is the purpose of Azure, What it will do for them and why do they need it, even if it was only for a very specific usage such as a web application hosting.

When Manu is speaking it feels like a religious zealot speaking, Manu really put all of his heart into the talk.

The problem arises when we switched into the demo.

The demo was too long in a way that it wasn't grained enough to be shown to the audience. In a matter of fact he couldn't run or compile it until the very end after 9 long code snippets (At Least he used snippets!), and in the during of it I am afraid some of the audience lost him through the object model of Azure.

A pity.

Ariel

#devacademy3. Live blogging : Building Twitter Silverlight App

Posted Dec 15 2008, 05:01 AM by Ariel Ben Horesh  

Guy have produced a well structured lecture. Managed it with high precision and very well timing, never slowing on it's own, just the proxy slowed his pace, and in those times it felt like he didn't have really nothing more to say out of his well practiced script. Furthermore, I felt a little bit like watching a screencast, but it is a very minor rant

For his benefit He managed both to introduce the technology for newbies and delivering a worthy app.

That for really the content, the rest for me was Twitter madness. Watching our twitts on the big screen, and getting feedbacks from fellow bloggers was an enormous fun.

My big moment was to seeing that I twitted the most on a cool Silverlight chart but later discovered to be cheated of that title (and the prize) by a sneaky twitter spam, originated solely to get the prize.

Well I got the applause.

Now need to decide what to do now :)

Ariel

#devacademy3. Live blogging : Ajax Internal

Posted Dec 15 2008, 03:49 AM by Ariel Ben Horesh  

Dan's lecture promised a lot, I carefully reviewed the slides prior of the event, and decided to go to this lecture, first it promised the most advanced issues and second I so far scratched the surface of Ajax and it is good opportunity to learn more on this.

Dan stated the lecture with good pace, moving swiftly into the architecture of the Web model.

I think he should have elaborated more on this subject, it would be a very critical point of the lecture to keep the audience well understood what he is going to do and especially where. Because of the pace I don't think all understood how the pipeline is structured and what is the role of each piece in it. It is very important to explain in more than a sentence what is an HttpHandler, especially when you are about to build one.

Dan is a very good developer and he has a developer instincts one can tell, his typing abilities are very good, but if I need to know that, something is wrong. Dan allocated more than 50% of his time to type and debug his typos, and that is just wrong, I don't need to really count "{" with him, it is not important, I can see his code later. More than that when Dan is concentrating on finding assemblies full names, I lose my patience and disconnect from the main objective of his code.

A good point was to show undocumented stuff, and code with reflector. This is what makes me interested, show me stuff I don't already know, or didn't have the time to dig in into internal code of Microsoft.

Anyway I really recommend you to watch this session on video, with that way you can skip the boring typing moments and concentrate on pure code and concepts. Past exprience from Teched is guratentee that those recorsing will be really high quality.

Now heading to Guy's lecture on Silverlight.

Got to see my Tweets there http://twitter.com/ArielBH

:)

Happy live blogging!

Ariel