blog.a.lish syndication : .NET http://www.noamwolf.com en-us Sat, 22 Nov 2008 03:24:55 GMT Sat, 15 Nov 2008 03:24:55 GMT http://www.noamwolf.com/rssfeeds Noam Wolf postmaster@noamwolf.com (noam wolf) <![CDATA[ Search blog.a.lish ]]>http://noamwolf.com/blogItem/search-blog.a.lish/104 As of today you can search blog.a.lish! You can click the magnifying glass on the main navigation (i guess it would be awkward if I changed design and I no longer used a magnifying glass... oh well...) and start searching the content of this blog!

This was an exciting project for me because of many reasons. Technically speaking I did the following:

  • Set up full-text indexing on my database (Sql Server 2005).
  • Create a store procedure that searched the columns I'm willing to let people search on.
  • Writing the service that makes the backend call and gets the response (JSON).
  • Write the Javascript that deals with the response and formats it into HTML objects. (kind of a TODO)
  • Style the html.

Step 1: Full Text Indexing

You should watch this video if you have no idea what I'm even talking about. Then after you've watched it you need to enable full text indexing on your database:
exec sp_fulltext_database 'enable'

Then you need to enable indexing on a per-table base:
exec sp_fulltext_table 'table_name', 'create', 'catalog_name', 'unique_key_name'

Then you need to specify which columns you want to "full-text" index:
exec sp_fulltext_column 'table_name', 'column_name', 'add'

Then you need to activate the full-text index:
exec sp_fulltext_table 'table_name', 'activate'

Then you probably want to fill the index when a change occurs to the table:
exec sp_fulltext_table 'table_name', 'start_change_tracking'
exec sp_fulltext_table 'table_name','start_background_updateindex'

NOTE: if you're using Sql Server 2005 Express you have to install the advanced services edition with SP1.

Step 2: Writing your SQL

Now that you have set and activated full-text indexing you can start using the new sql predicates to search on these columns. The new predicates include FREETEXT, CONTAINS and other very powerful key words you can use to refine your searches. These predicates are more powerful than the LIKE predicate and the index is optimized for large amounts of textual data so by default it will be faster. Another cool thing you can do is tweak the noice terms like "the", "and", etc. You can read more about it at MSFT's Full-Text Search Developer InfoCenter.

Step 3: Writing your WebService

There really isn't much to this step. I created a webmethod that accepted the search phrase and the output (XML or JSON), if it's XML you can simply use the FOR XML AUTO in your stored procedure, if it's JSON then it becomes a little trickier. I wrote a simple XMLtoJSON converter that just works (disclaimer: it works great for my needs).

Step 4: Javascript and JSON

If you want to write a JSON parser in Javascript feel free to. I didn't feel like it so I used YUI's JSON parser and I was ready to spit out HTML. YUI has a data table structure that can make XHR calls for you but there is a lot of wiring to get it going so I just decided to work with a for loop....

That's pretty much it. I'm working in parallel on a silverlight search widget. Both "widgets" work off of the same back end (database, stored procedure, and webservice) the only difference is that the Javascript one parses JSON and the silverlight one uses LINQ to objectify the XML. I'm having some debugging issues with the silverlight version but I hope to release it soon. So now that I have Ubuntu installed I have to try to respect my potential Linux readers that won't have silverlight available to them.... hmmm... silverlight for mono... 20% time???


]]>
Sun, 30 Mar 2008 14:39:25 GMThttp://noamwolf.com/blogItem/search-blog.a.lish/104Noam Wolf1
<![CDATA[ MIX 08 - Reviewed ]]>http://noamwolf.com/blogItem/mix-08---reviewed/84 MIX 08 was my first MIX conference but not my first Microsoft (MSFT) event. So my expectations were not that high. My experience with MSFT type events over the past years has given a whole new meaning to the phrase "nothing is free." I'm used to getting excited over product releases and tech talks hoping to get a glimpse of what matters most to me... code. SHOW ME THE CODE, while that might be lame at best and geeky at worst that's how I roll so deal with it. MSFT events are usually (almost always) a sales and marketing driven show that very seldom produces real value to me as a developer. MIX is not. I was very happy to find demo driven sessions, great speakers (in Scott Guthrie, Scott Hanselman, and Guy Kawasaki), and most importantly a LOT of CODE. I am definitely happy I got to go to this event and I hope I will be as fortunate next year! Here are some of my observations and gripes divided into highs and lows of MIX 2008.

Highs

V-E-G-A-S
That says it all, this city is great, non stop action 24-7, and the casinos aren't bad either. I enjoyed my 3rd visit to Vegas as an adult and I must say it just seems to get better. You would really have to go out of your way to have a bad time there. I stayed at the very fancy and colossal Venetian at a humongous suite and I gotta say... life is good. This is truly a temptation packed city that keeps you on the edge of your toes all day and all night.

Silverlight 2.0
I must admit that I didn't like Silverlight 1.0 and actually pretty much thought it was a MSFT version of a crappy product known as Flash. At the risk of sounding snobbish I think actionscript and flash are counter intuitive and in a large part greatly separated from classical OO languages like Java and C# and therefore I find it really annoying to use them. That said, I do see the merit of such a browser plugin in today's Web 2.0 world of "give me data now" and up until MIX 08 I didn't realize the potential of Silverlight. With the power of C#, WCF webservices, and a little design skillz you can really do some damage (in the best sense of that word) with Silverlight. I have some gripes with Silverlight 2.0 which I will present in the Lows section later. Look for a blog search tool utilizing Silverlight on blog.a.lish at stores near you very soon.

Keynote #2
The second keynote was absolutely great. I was prepared to hear Steve Ballmer talk about MSFT from a birds eye view and basically cover everything in 2 hours of a boring marketing speech... to my surprise the keynote was actually an interview conducted by Guy Kawasaki (formerly of Apple). Guy came out swinging and really didn't hold anything back... "what's the deal with Yahoo!?" he asks of the bat... followed by "what's the deal with Vista?" The part I enjoyed the most was when he pulled out the now famous inter-office envelope with a macbook book air and handed it to Steve who proceeded to place it on the floor and almost stomp on it. Good times. What Impressed me most about Mr. Ballmer was that no questions caught him off guard. You can read more about this on Jason's blog and you can watch the actual interview here.

ballmer is bradshaw
Is it just me or does Ballmer remind you of Terry Bradshaw?

In a cramped room filled with overweight, balding, goat t sporting, terribly dressed, coughing, sniffling, worst humor t-shirt wearing software engineers I was eagerly waiting to hear a session titled "Building Great AJAX Applications from Scratch Using ASP.NET 3.5 and Visual Studio 2008" (link) by Brad Abrams from big ol' MSFT. The big screen in front of the room read "no slides, demo only", my kind of session! Turns out 90% of the session was a review of .net 2.0, Brad even mentioned the "new" placeHolder control in 3.5 (really? are you kidding me?)... it was quite a waste of time IMO.

Lows

Silverlight 2.0 (beta)
Sure it's beta but really? There are a couple of issues that I just can't ignore even though I realize Silverlight 2.0 is in beta.

  • Debugging - none, well you can put breakpoints but if you miss spell anything, forget to close a tag your entire Silverlight app will not load.
  • Brevity - nope, you have to style and animate every control seperately, there is no concept of skinning or really of style sheets (I know silverlight doesn't render to html but still...)
  • WinForms on the web - WTF, MSFT is bringing winForms to the web... there's a reason it's reserved for the desktop. When will MSFT learn from it's mistakes?

Keynote #1
Ray Ozzie is probably one of the smartest people at MSFT but he can really put a crowd to sleep. His keynote address was just boring and it felt like he went on forever.

Geeka-paloozza
MSFT really took geek to a whole new level at MIX... while they had free massage sessions (which were sweet) they basically tailored the other "free time" events for the geek in you. A rock band stage equipt with top of the line plazma TV's, lights and a really cool mic stand invited people to show off their rock band skills (Jason captured it here). Halo 3 campaigns for groups of 12 people around 3 huge flat screens were also a setting for showing off xbox skills. The sandbox area was actually a little cool, then again I am kind of a geek... they had partitioned a couple of zones for different .net labs, I didn't spend much time there but it looked cool.


]]>
Mon, 10 Mar 2008 07:52:26 GMThttp://noamwolf.com/blogItem/mix-08---reviewed/84Noam Wolf0
<![CDATA[ My Favorite C# Features - Part 1: Generics ]]>http://noamwolf.com/blogItem/my-favorite-c-sharp-features-part-1-generics/83 I've been working on this article for what seems to be forever now, so instead of just listing all the things I like and/or dislike I decided to take it piecemeal. So without further ado I give you part 1 (of an undecided total) of my favorite c# features.

Introduction

C# is the language of choice for me when it comes to writing software. I spend most of my time writing code in C# and ASP.NET with a lot of JavaScript, I also write in Java (when I absolutely have to), php (if the client is cheap), and I've even had to resort to C++ lately (pointers are stars in my mind). I find each language to have it's set of great features and, of course, it's problems. Since I am hardly an expert on Java, php, or C++, I would like to attempt to point out some of my favorite C# and ASP.NET features.

Side Note

I like to ask interviewees to point out their favorite C# and/or ASP.NET feature simply to get the interview going and to see what excites that person about a language they are and will be coding with a LOT. To my surprise I quite frequently hear that the gridview control is a favorite feature of an entire framework put together to write software and not just display lists of tabular data. Even though the gridview is miles ahead of it's 1.1 predecessor I don't really think it's great and I don't really think it should be considered in the top 10 best features in ASP.NET, let alone C# (or VB.NET for this matter).

Favorite #1 - Generics

Without a doubt, and years ahead of any other feature in C# (2.0 and above...), my favorite feature is Generics. For those of you who are not familiar with Generics (known as generics in Java 1.5+ and very similar to templates in C++) click on the link above to get the basics... this article will not cover those.

Type parameters that defer type specification until runtime. That's pretty much what Generics provide. The first example I read, and tested out, was of a generic collection (of course). Using generic collections (like List) over untyped or regular collections gives you a "hat trick" advantage:

  • Design time type checking, instead of an argument that accepts an ArrayList (a list of type Object) you now restrict the type to be a list of integers or List. You no longer have to worry about bad arguments (to an extent...)
  • No more casting! Casting is great, but it's also expensive. If you add a "Car" object to a collection you shouldn't need to cast it to a Car when you retrieve it.
  • No more boxing and unboxing! Boxing is also expensive and a waste of precious CPU cycles...
While all of those things are really really great the world of generics does not stop at collections. Do NOT be fooled into thinking generics are only good for collections!

What impressed me most about C#’s implementation of Generics (as opposed to Java’s implementation) was the fact that in the IL code (intermediate language) at runtime a “specialized” version of the generic type is created and then reused. So under the covers you are getting IL typed collections (for collections) that are reused (instead of adding more code for each subsequent duplicate type declaration). This is a huge advantage on Java’s generic implementation. In Java Generics is [almost] completely a design time feature. There still exists boxing/unboxing and casting, only Java handles it for you, so basically you’re still paying for it. To summarize the last paragraph, the C# implementation of generics greatly reduces the amount of code by reducing to one the number of specialized classes created by the compiler for generic classes of reference types.

Moreover, when a generic C# class is instantiated by using a value type or reference type parameter, reflection can query it at runtime and both its actual type and its type parameter can be ascertained.

Generics can be used on a very wide variety of CLR elements: Collections, Classes, Interfaces, Methods, Delegates and more! This gives you the power to strongly type elements of your design that weren't "bullet proof" in the past. A Class, Interface, or Delegate can define a type parameter that is limited to the scope of that object. So if you want to create a super collection (or a Google collection) you can implement it by passing in type parameters to your object.

A key feature of Generics are constraints. You can apply restrictions to the type argument (or generic type… either way works for me) making your code even more “bullet proof.” You can restrict each type argument separately with the where keyword. For code examples and to read more about this click here.

Another “cute” feature, and I use the word “cute” because it’s nothing more than that but still worth mentioning is the default keyword. Sometimes when you write a generic class you really don’t know if the type parameter will be a reference type or a value type, and if it’s a value type whether it’s numeric or a struct. So how do you instantiate “it”? You use the default keyword.

   /// A node class to be used with many different 
   /// types of collections
   Public class Node {  
	private T data;  
	public Data { 
           get {  
                  T tmp = default(T);
                  if ( null != data ) tmp = data;
                  return tmp;
           }
	}
   }

Short Comings

Like a lot of things that we love there are some short comings. Here are few that I've run into:

  • No support of "jokers" or "wild cards", in Java 1.5+ you can use the or "question mark" to tell the compiler that you can take any generic subtype that you don't even know exists at design time. I've run into situations where this could have been a sweet option to have but instead had to come up with workarounds.
  • Polymorphism does not apply to the Generic type! You heard me. If you don't believe me consider the following, a Garage class that internally stores it's cars in a generic List of Car collection (makes sense, why would the Garage class care which subtype the car is). Now imagine you could park a collection of cars, defined by a ParkCars method on the Garage class which takes a List of Car as a parameter. Doesn't it make sense to pass in a List of a subtype of Car?

    public class Car {} public class SportsCar : Car {} public class Garage { private List<Car> cars; public void ParkCars(List<Car> cars) { cars.AddRange(cars); } } List sportsCars = new List(); sportsCars.Add(new SportsCar()); Garage g = new Garage(); g.ParkCars(sportsCars); <--- design time ERROR!!!!

Anyway, this article is getting really long and I've only covered one favorite... I'll try to keep it short so that it's still enjoyable and not too short so that it's worth keeping around as a reference. What's next? The next topic/feature I intend to cover are anonymous types, Predicates and Delegates.... what a wonderful duo.


]]>
Mon, 03 Mar 2008 17:28:01 GMThttp://noamwolf.com/blogItem/my-favorite-c-sharp-features-part-1-generics/83Noam Wolf2
<![CDATA[ Boxing, Shadowing, Overriding and Overloading ]]>http://noamwolf.com/blogItem/boxing,-shadowing,-overriding-and-overloading/54 This is more of a reference post. I really like to ask object oriented programming questions when I do technical interviews mainly because I believe that the most basic, and probably the most important, concept of computer science is object oriented design and programming. I frequently like to ask the interviewee to model a league of their favorite sport (as a side note the most popular sports that have been modeled during this interview question are Cricket, Soccer, and Basketball...) and then take the model and refer to it (classes, interfaces, delegates etc.) in following questions.

You can easily take this question and expand it to fit almost anything you want to focus on. I like to work it into an exercise where the interviewee is building a game for EA Sports where they have to consume an EA webservice for online gaming. From there I go into serialization, soap, WSE and other fun stuff.

What I've found from doing this exercise for a couple of months now is that many engineers with over 2 years of experience have problems with collections (more specifically the System.Collections and System.Collections.Generic libraries). Most interviewees will choose an ArrayList to model a list of Players in a Team (this obviously applies to most sports, yes even tennis, think Davis Cup). The natural question that follows a design choice of an ArrayList is what happens when a consumer of your class decides to add a Referee or a Coach into your list of Players? How can you protect access to and from this collection? These questions either lead to an interesting discussion or to the following question: What is the underlying type of an ArrayList anyway? You'd be surprised how many 2+ year engineers have said String... yeah, sad.

Boxing

When you use an ArrayList (that is a collection of Object types, if you didn't already know that) you are using an Object (or reference type). So when you add a primitive (or value type) to your ArrayList like:

ArrayList players = new ArrayList();
int p1 = 12;
players.add(p1);

What actually happens behind the scenes? Since p1 is a primitive how is it stored on the heap? boxing, which means the primitive gets converted to an object. That's all it is. The opposite of boxing would be unboxing or the process of taking an object and converting it into a primitive (reference type to value type conversion).

Shadowing

Shadowing is an interesting concept in .NET because, unlike Java, C# methods aren't implicitly virtual. So if you create a base class (which isn't abstract) and you want to override methods in sub classes (child classes) you need to use the virtual keyword, but what happens when you don't have access to the base/super class? what happens when you MUST override a method that's not marked virtual? You can use the new keyword and use shadowing.
Override redefines an inherited method which is marked as virtual or abstract, and its access level must be the same as the method it overrides. New allows you to completely hide an inherited member and create a different implementation of it with whatever attributes you chooses. Shadowing is another name for disabling an inherited method and redefining it.

public class A  {
    public virtual string doStuff() {
         return "doing stuff in A";
    }

    public string doSomeOtherStuff() {
         return "doing some other stuff in A";
    }
}

public class B : A {
     // overriding
     public override string doStuff() {
         return "doing stuff in B";
    }

    // shadowing
     new public string doSomeOtherStuff() {
         return "doing some other stuff in B";
    }
}

public class test {
    public static void Main(string[] args) {
         A myA = new A();
         Console.WriteLine(myA.doStuff());  // will output "doing stuff in A"
         Console.WriteLine(myA.doSomeOtherStuff());  // will output "doing some other stuff in A"

         B myB = new B();
         Console.WriteLine(myB.doStuff());   // will output "doing stuff in B"
         Console.WriteLine(myB.doSomeOtherStuff());  // will output "doing some other stuff in B"

         A myAB = new B();
         Console.WriteLine(myAB.doSomeOtherStuff());  // will output "doing some other stuff in A"
    }
}

Overriding vs. Overloading

Overridng vs. Overloading seems to be a little problematic for some people, and it can get a little confusing when you're not in front of your IDE. So in general:

Overriding

Any time you have a class that inherits a method from a superclass, you have the opportunity to override the method (unless the method is marked sealed). The key benefit of overriding is the ability to define behavior that's specific to a particular subclass type.

Overloading

Overloaded methods let you reuse the same method name in a class, but with different arguments (and optionally, a different return type). Overloading a method often means you're being a little nicer to those who call your methods, because your code takes on the burden of coping with different argument types rather than forcing the caller to do conversions prior to invoking your method.

Since Java is virtual be default overloading vs. overriding can play tricks on you if you don't notice what's going on, but in C# it's a little simpler because you can easily tell overloading from overriding because of the virtual and override keywords:

public class Test {
 public static void Main(string[] args){
    Human h = new Noam();
    h.eat();  //this will print Noam class enjoying breakfast at cafe Hillel.
    h.eat("lunch");  //this is a call to an overload and is NOT legal
                     //you get a compile error:
                     //Test.cs(9,5): error CS1501: No overload for method 'eat' 
	             //takes '1' arguments
 }
}


class Human{
   public virtual void eat(){
        Console.WriteLine("Generic human eating");
   }
}
 
class Noam : Human{
   public override void eat(){               //notice the signature is identical to the super class
        Console.WriteLine("Noam class enjoying breakfast at cafe Hillel.");
  }

  //overload no keyword needed
  public void eat(string meal){
  	Console.WriteLine("Noam class enjoying " + meal + " at cafe Hillel.");
  }
}


]]>
Thu, 10 Jan 2008 11:56:13 GMThttp://noamwolf.com/blogItem/boxing,-shadowing,-overriding-and-overloading/54Noam Wolf0
<![CDATA[ Array.ForEach on Primitives ]]>http://noamwolf.com/blogItem/array.foreach-on-primitives/22 java.util.Arrays class called fill. As you might imagine it takes two parameters, namely the array that you want to fill, and the value you want to fill it with.

C# (2.0) does NOT have a fill method in it's static System.Array class, but the nifty world of generics provides us with an System.Array.ForEach method that, as described by MSDN:
Performs the specified action on each element of the specified array.


Well, I was wondering at first why I would use Array.ForEach (on either Arrays or generic Lists) at all. It turns out that using Array.ForEach (which is apparently always generic) is much faster that using a regular foreach statement.

From diditwith.net

while the ForEach method is much faster at iterating a List, this is not the case with arrays. An Array.ForEach method does exist for single-dimension arrays (or vectors) and it is actually slower than using foreach. The reason is that the compiler doesn't generate code that uses IEnumerator for foreach-loops over vectors. Instead, it generates special IL instructions that are designed for working with vectors. Thus, using foreach on a vector results in no method calls while Array.ForEach still requires one call to the supplied delegate per iteration.


Anyway, the reason I looked at using Array.ForEach was simply to set the value of a single dimensional boolean array to true (preset the values to true rather than false) without a for-loop or a standard foreach. The reason was not to optimize the speed of my application but simply to type less... Armed with anonymous delegates and the need for speed I wrote the following code:

bool[] array = new bool[10]; // will default all values to true
Array.ForEach(array, delegate( bool val ){ val = true; }); // should set all values to true


According to MSFT the action specified by the delegate should be applied to each element in the array. Can you guess what the outcome was?

It seems to me (and I might be wrong) that the Array.ForEach method actually creates a brand new array "under the sheets" and assigns it the values produced by performing the action. Since bool is a primitive and a struct (which happens to be immutable) it looks like the values of the newly created array (which should be a copy of the array passed to the ForEach method including the changes performed by the action delegate) are reset to the default value of the primitive type, namely false.

So, what does all this mean? It means that you can't use primitive arrays with the Array.ForEach method (which turns out to be slower than a regular foreach anyway...) which sucks.

One interesting discovery I had was that if you have a member in a reference type (class) that is a value type (struct, bool for example) and you use the Array.ForEach on that specific value type member, the changes do get applied and the newly created array stores actually shows the actions performed. Consider the following code:

class SomeClass
{
private bool _someMember;

public bool SomeProperty
{
get { return _someMember; }
set { _someMember = value; }
}

public SomeClass() { }
}

SomeClass[] sArray = new SomeClass[3]; sArray[0] = new SomeClass();
sArray[1] = new SomeClass();
sArray[2] = new SomeClass();

Array.ForEach(sArray, delegate(SomeClass s) { s.SomeProperty = true; });



The value of sArray[0].SomeProperty will be true after the Array.ForEach operates.
Maybe it's because it's too late or maybe it's because value type members get auto boxed in the context of a reference type... either way this is interesting stuff.


]]>
Tue, 11 Dec 2007 22:38:47 GMThttp://noamwolf.com/blogItem/array.foreach-on-primitives/22Noam Wolf0
<![CDATA[ Syndication .NET 3.5 Style ]]>http://noamwolf.com/blogItem/syndication-.net-3.5-style/17

I have a tendency to reinvent the wheel when it comes to my pet projects. A great example is this blog, why didn't I use WordPress or Blogger? Good question, one my boss likes to ask me daily.

The latest thing I've engineered, almost from scratch, is syndication. As you can see this blog is syndicated. I am actually using FeedBurner but that was the easy part.

So after spending a good portion of my trip to Orlando futzing around with syndication for my blog I get a "fun" link from my buddy Yuval about how the new .NET Framework has built in syndication classes... Maybe I'll upgrade to 3.5... maybe not.


System.ServiceModel.Syndication
The System.ServiceModel.Syndication namespace contains all of the classes that make up the Syndication Object Model.

XmlWriter rssWriter = XmlWriter.Create("rss.xml");
Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(feed);
rssFormatter.WriteTo(rssWriter);
rssWriter.Close();
Sweet.
]]>
Sat, 08 Dec 2007 12:02:43 GMThttp://noamwolf.com/blogItem/syndication-.net-3.5-style/17Noam Wolf0