Jack @ ASP.NET

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries for the ‘Programming’ Category

List(T).BinarySearch in C#

I think most of us are quite familiar with binary search. Binary search is an algorithm for locating the position of an element in a sorted list by checking the middle, eliminating half of the list from consideration, and then performing the search on the remaining half.If the middle element is equal to the sought value, then the position has been found; otherwise, the upper half or lower half is chosen for search based on whether the element is greater than or less than the middle element. The method reduces the number of elements needed to be checked by a factor of two each time, and finds the target value, if it exists in logarithmic time. A binary search is a dichotomy divide and conquer search algorithm.

In C#, .Net provide a List<T>.BinarySearch Method (T) which can be used easily. here is a demo:

   1: // Init a long type list

   2: var myList = new List<long>();

   3: foreach (var item in "269, 361, 347, 355, 352, 346, 351, 354".Split(','))

   4: {

   5:     myList.Add(long.Parse(item.Trim()));

   6: }

   7:  

   8: // sort

   9: myList.Sort();

  10: var ret = myList.BinarySearch(347);

  11: Console.WriteLine(ret);

Note, I have a ‘myList.Sort();’ before call the BinarySearch, why? It is because BinarySearch will Search the entire sorted System.Collections.Generic.List<T> for an element using the default comparer and returns the zero-based index of the element.

Yes, it is sorted list that binary search will operate on! So remember make your list sorted before call binary search function

.NET Development for the iPhone

Until recently your only choice for developing applications for Apple’s iPhone was to jump into the Apple development ecosystem. This means being willing to write Objective-C code in the XCode IDE. For many developers, learning Objective-C was seen as a huge barrier-to-entry. This is especially true for many .NET developers whom have never had to worry about memory management, pointers, and other C language responsibilities that they are unfamiliar with.

All this has changed with the introduction the MonoTouch framework, a part of Novell’s Mono Project. The Mono Project is an open-source implementation of Microsoft .NET Platform. It allows you to run .NET applications on nearly any platform, including Apple, FreeBSD, Linux, Unix, and others. MonoTouch, which is a new part of the Mono Project, allows you to write applications using C# with .NET platform that run on the iPhone.

The intent of this article is to provide a solid introduction to the MonoTouch platform, where to find all the necessary pieces, the limitations of it, and how to build a basic application.

How does it Work?

When building MonoTouch applications, most of the non-UI .NET 3.5 stack is either already available, or is in the roadmap to be included. This allows you to write applications using many of the .NET Framework Technologies that you’re already familiar with, including Windows Communication Framework (WCF), Workflow Foundation (WF), etc. It also includes nearly all of the Base Class Library (BCL) including things like Garbage Collection, Threading, Math Functions, System.Net, Cryptography, etc. For a list of available standard .NET assemblies see http://monotouch.net/Documentation/Assemblies. This is accomplished through a MonoTouch-specific set of base .NET libraries, similarly to how Silverlight and Moonlight work.

This means that you can compile standard .NET 3.5 code libraries using the MonoTouch core assemblies and use them in your application. So if, for example, you have a specialized library that does advanced math functions for engineering problems that you use for other applications, you can simply include the code library in your MonoTouch solution, and reference it. When you build your solution, it will compile it using the MonoTouch libraries, and it will then be available in your application.

MonoTouch also includes wrappers to the native iPhone APIs such as Location (GPS), the accelerometer, address book, etc. It also gives you the ability to bind to native Objective-C libraries that are not wrapped, so you can interop directly with existing Objective-C code.

How do I Distribute My Apps?

MonoTouch applications are distributed the exact same way that traditional iPhone applications are distributed, either via the Apple App Store, or Enterprise deployment.

The App Store is an online repository that allows users to pay for applications (if they’re not free), and download them. It is available from within iTunes, or directly from the iPhone itself. In order to get a license to distribute via the App Store, you must register with Apple, and pay $99/year.

Enterprise deployment is for those wishing to develop internal applications for a company, and distribute them to employees, etc., without listing them with the App Store.

What is the Licensing Model?

Unlike Mono, MonoTouch is not open source and is a commercial product. That means if you want to do anything useful with it you have to purchase a license. MonoTouch comes in three flavors and prices:

  • Professional ($399) – A single personal developer license that allows you to develop applications and distribute them via the Apple App-Store.
  • Enterprise ($999) – A single corporate developer license that allows you to develop applications and distribute via the App-store, or enterprise deployment.
  • Enterprise, 5 Seat ($3,999) – The same as the Enterprise license, but includes 5 seats.

All three options include a year of free updates.

There is also an evaluation edition that allows you deploy to the simulator only. For the purposes of this introduction, that is all we’ll need.

Effective C#, What Content got dropped

It should be clear from the additional content what’s new: I added coverage of the significant C#4.0 features like dynamic invocation and named / optional parameters. New library additions like PLINQ are also covered.

It’s much harder to see how I decided which items to drop. There are 15 completely new items in the 2nd edition, so that meant finding 15 items to drop. (Several other items have the same title, but were significantly rewritten – that will be the subject of another blog post.) Here’s how I decided which items to remove:

Items that are less important now. A number of the items in the first edition discussed techniques that were much more important before generics were available. Some of these items were those that discussed boxing and unboxing, the collection classes, and the data set class. All of those techniques and libraries were far more useful in C# 1.x than in the current .NET universe.

Items that have become common practice. C# has been around for almost a decade, and the community is much more mature than it was in 2004, when Effective C# was published. Some of the items are part of the conventional wisdom now

Items that assumed your last language was C++ or Java. The early adopters of C# were developers that came from C++ (on the Windows platform) along with some developers that came from Java. That’s no longer true.  College grads (since 2002 or so) are using C# for their first professional programming experience. Others are coming from VB, Ruby, Python, or PHP. (I’m not claiming that C# is grabbing market share from all those languages; the migration happens in all directions.) It just wasn’t right to assume that every C# developer has C++ or Java experience anymore.

The poster child for dropping items is the original Item 41, where I advocated using DataSets rather than implementing IBindingList yourself. I didn’t rewrite this item because the obvious answer now is to use BindingList<T> when you need the IBindingList capability. If you were using DataSets for some other reason, pick some other generic collection type. There are many, and the options grew again in .NET 4.0. Those generic collections have better APIs (the type parameter means the compiler ensures type correctness), and better performance (boxing / unboxing doesn’t apply. It’s not often that it’s trivial to get better performance and better chances at correctness. Even in the 1.x days, I didn’t advocate using DataSets are part of a service API. That was and still is a painful choice.

There’s also been many enhancements in the .NET framework that mean there are better data solutions. LINQ, along with the query syntax pattern (See Item 36 in More Effective C#), means there are much better ways to work with data in .NET 4.0.  Chapters 4 and 5 of More Effective C# discuss these important techniques. The entity framework has matured, and is a better way to handle data transfer between layers and machine boundaries. (I still need to look more closely at the latest EF, I know some of the changes, but not all).

How to Enable the ASP.NET Ajax script loader

An important feature of the script loader is the separation of the script meta-data from the script code itself. The meta-data can include the name of the script, its dependencies, instructions on how to figure out if it’s already loaded, its debug and release URL patterns and a declaration of the lazy components and plug-ins it introduces. The script loader can also handle composite scripts but I won’t cover that in this post.

  • The name of the script is what will be used to reference it from other scripts and to generate the URL from a pattern. It shouldn’t include the “.js” extension.
  • The dependencies and executionDependencies are each a simple array of script names that the script depends on. I’ll explain the difference in a minute.
  • The is loaded criterion is a JavaScript expression that returns true if the script is already loaded. This is usually a test on an object that the script file defines. For example, the “templates” script uses !!(Sys.UI && Sys.UI.Templates). It can assume Sys because it’s defined by start.js.
  • Debug and release patterns are expressions that enable the framework to map script names into debug and release URLs. The ASP.NET Library uses “%/MicrosoftAjax{0}.debug.js” and “%/MicrosoftAjax{0}.js” where % gets replaced with the path where the script loader was downloaded from (this can be CDN or local) and {0} gets replaced with the script name. You can create your own pattern or just provide fixed URLs if you have only one script file. The debug pattern is optional.
  • Lazy components and plug-ins are helpers that the script loader can create for you and that enable developers to start using your components before they are even loaded and hide the script loading aspects as much as possible. For example, it’s that feature that enables you to write this while still having only start.js loaded:
    Sys.create.dataView("#myDataView", {
        data: myData
    });

    The code that needed to be written for this helper to be created was this:

    behaviors: ["Sys.UI.DataView"]

    This gets automatically transformed by the script loader into the Sys.create.dataView method, before it even tries to load the actual script that defines Sys.UI.DataView. And if you have jQuery loaded as well, you’ll also get a jQuery plug-in out of it for free, which means that you can do:

    $(".data").dataView({data: myData});

    and instantiate DataView controls over the results of a selector query in one operation. Groovy. Of course, you can do the same with the behaviors and controls that you write in your own scripts, with lots of options to customize names, add parameters, etc.

In the case of the class library code, here’s the meta-data declaration code that I had to write:

Sys.loader.defineScript({
  name: "classBrowserTree",
  releaseUrl: "%/TreejQuery.js",
  executionDependencies:    ["jQuery", "Templates", "ComponentModel"],
  isLoaded: !!(window.jQuery &&    window.jQuery.fn.classBrowserTreeView)
});

This declares that my script, named “classBrowserTree”, can be found at the URL TreejQuery.js relative to the base URL of the script loader, that it depends on jQuery, Templates and ComponentModel (which themselves have their own dependencies) and that the loader can determine whether it’s already loaded by evaluating the classBrowserTreeView jQuery plug-in.

Now, loading that script and all its dependencies is as simple as writing this:

Sys.require(Sys.scripts.classBrowserTree);

Notice that as you’re typing this, you actually get full IntelliSense in Visual Studio on the name of the script, which is great for speed and to avoid typos:ScriptLoaderIntelliSense

One of the things that enable the script loader to do its job is a special way to write your script that makes it possible to separate the loading and parsing of the code from its execution.

Don’t freak out (yet) though as the code you have to introduce is very lightweight and it doesn’t prevent your script from being loaded without the script loader (with a plain old script tag for example).

Reversely, a script that doesn’t have the special script loader code can be handled by the script loader but its dependencies must be declared using “dependencies” instead of “executionDependencies” in the meta-data declaration code, which will in effect disable the more advanced features of the script loader such as parallel loading.

The special code in question is the following:

(function() {
  function execute() {
    // Your code goes here.
  }
  if (window.Sys && Sys.loader) {
    Sys.loader.registerScript(      "classBrowserTree", null, execute);
  }
  else {
    execute();
  }
})();

What you see here is a (function() {…})(); wrapper, which is standard practice to isolate code from the global namespace (essentially, it’s a local scope); we also have another named scope in there that we arbitrarily call “execute” (but the name doesn’t matter). This is where you’ll typically put your actual code. Then we have the bootstrapping code that looks for the script loader. If it isn’t found, the code in the execute function is immediately run. If it is found, the execute function is registered with the script loader but is not immediately executed.

This wrapper code is what enables the script loader to do its magic. Thanks to this little bit of code, it doesn’t care at all in what order the scripts are being loaded, because it can delay the time when any script actually gets executed until all its dependencies have been successfully loaded.

This also allows the script loader to load scripts in parallel, even if one depends on another. Normally a script loader would have to download a dependent script first and wait for it to completely load before loading the next script. This ‘serializes’ the loading process and is not good for performance. Modern browsers can download 6 to 8 scripts simultaneously. Separating the loading of a script from its execution allows the loader to take advantage of that, and in most cases, even complex dependency trees can be downloaded completely in parallel, meaning the total time is not the sum of each script, but only the longest one.

Activate items in visual studio toolbox

You might meet these questions in visual studio toolbox, and the items are not shown properly:

  • My code works if Visual Studio is already opened when my code executes.
  • My code works fine when executed outside of an installation project. 
  • If my code is executed from an installation project and Visual Studio is not opened, then ToolBox item is not added. I’ve added a "MessageBox" during the process and I can confirm that devenv.exe *is* executed. 

 

If you have any trouble using the toolbox items in visual studio, just delete the hidden files:

toolbox.tbd, toolbox_reset.tbd, toolboxIndex.tbd, toolboxIndex_reset.tbd

in

<drive>:\Documents and Settings\<user>\Local Settings\Application Data\Microsoft\VisualStudio\<VS version>

Ex:

C:\Documents and Settings\JAVIER.VILLARREAL\Local Settings\Application Data\Microsoft\VisualStudio\8.0

Start Visual Studio, and it will reset the toolbox items in the correct form. following this, you can active items in visual studio toolbox immediately.

VS 2010 and .NET Improvements

VS 2010 and .NET 4 bring a huge number of improvements and additions. They include big advances for ASP.NET web development, WPF and WinForms client development, SharePoint development, Silverlight development, data development, parallel computing development, and cloud computing development.  VS 2010 also delivers a ton of improvements in the core IDE, code editors, programming languages, and enterprise design, architect, and testing tools. 

TFS 2010 is now easy to install (only 20 minutes to setup source control, bug and work item tracking, build automation, and continuous integration), can be installed on both servers as well as client OS and domain controller machines, and is now included with all MSDN subscriptions of Visual Studio.

VS 2010 Product Line SKU Simplifications

With VS 2010 we are simplifying the product lineup and pricing options of Visual Studio, as well as adding new benefits for MSDN subscribers.  With VS 2010 we will now ship a simpler set of SKU options:

  • Visual Studio Express: Free Express SKUs for Web, VB, C#, and C++
  • Visual Studio 2010 Professional with MSDN: Professional development tools as you are used to today with the addition of source control integration, bug tracking, build automation, and more. It also includes 50 hours/month of Azure cloud computing.
  • Visual Studio 2010 Premium with MSDN: Premium has everything in Professional plus advanced development tools (including richer profiling and debugging, code coverage, code analysis and testing prioritization), advanced database support, UI testing, and more.  Rather than buying multiple “Team” SKUs like you would with VS 2008, you can now get this combination of features in one box with VS 2010. It also includes 100 hours/month of Azure cloud computing.
  • Visual Studio 2010 Ultimate with MSDN: Ultimate has everything in Premium plus additional advanced features for developers, testers, and architects including features like Intellitrace (formerly Historical Debugging), the new architecture tools (UML, discovery), test lab management, etc.  It also includes 250 hours/month of Azure cloud computing.
Side by Side Support with VS 2008

VS 2010 and .NET 4.0 can be installed side-by-side on the same machine as VS 2008 and .NET 3.5.  You can install the Beta 2 version on a machine and it will not impact your existing VS 2008 / .NET 3.5 development.

Go-Live License Available

.NET 4 and VS 2010 Beta 2 include a “go-live” license which means you can start using the products for production projects.