Archive for the ‘.Net’ Category

Comparing Owner Drawn in Winforms vs Swing

Monday, May 12th, 2008

I was having a play with custom renderers in Java Swing, and comparing them with the effort required in .NET. I find that in this case, the Swing approaches the problem at a higher level of abstraction (less effort), at the expense of a lot of new objects being created, while .NET goes for a straightforward custom paint.

Here’s an example in Swing, custom rendering JListbox control. Notice that we return a JLabel control here. This is what Swing does by default. We can also choose to return any controls, like combobox, et. c. There’s no additional painting required. In this sense, JListbox resembles a repeater control we see in WPF. The downside is a JLabel control is returned for every visible item in the listbox. Custom drawing can be done by creating an Anonymous inner class with an overridden onPaint handler.

                    jList1.setCellRenderer(new ListCellRenderer() {

                        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                                // By default, listbox renders using a label
                                JLabel display = new JLabel(value.toString());
                                display.setOpaque(true);
                                display.setBackground(isSelected ? Color.GRAY : Color.WHITE);
                                return display;
                        }
                    });

Contrast this with the J# implementation of custom painting in .NET (sourcecode nicked from MSDN), lots of low level painting, but no new objects being created or garbage collected. However, it’s not clear if you can reuse the paint() routine from an existing control.

private void listBox1_DrawItem(Object sender,
    System.Windows.Forms.DrawItemEventArgs e)
{
    // Set the DrawMode property to draw fixed sized items.
    listBox1.set_DrawMode(DrawMode.OwnerDrawFixed);
    // Draw the background of the ListBox control for each item.
    e.DrawBackground();
    // Create a new Brush and initialize to a Black colored brush
    // by default.
    Brush myBrush = Brushes.get_Black();
    // Determine the color of the brush to draw each item based on the
    // index of the item to draw.
    switch (e.get_Index()) {
        case 0 :
            myBrush = Brushes.get_Red();
            break;
        case 1 :
            myBrush = Brushes.get_Orange();
            break;
        case 2 :
            myBrush = Brushes.get_Purple();
            break;
    }

    // Draw the current item text based on the current Font and the custom
    // brush settings.
    e.get_Graphics().DrawString(System.Convert.ToString(listBox1.
        get_Items().get_Item(e.get_Index())), e.get_Font(), myBrush,
        RectangleF.op_Implicit(e.get_Bounds()), StringFormat.
        get_GenericDefault());
    // If the ListBox has focus, draw a focus rectangle around the selected
    // item.
    e.DrawFocusRectangle();
} //listBox1_DrawItem

C# 3.0 and 3.5 for experienced developers.

Sunday, April 20th, 2008

Python developers are probably already familiar with List Comprehensions, and lambda expressions. The interesting twist with LINQ is these expressions are translated into SQL and executed on the RDBMS instead of being done on the client side. There was a pretty clever Python project that achieved this in Python through dissassembly of python bytecodes, but I can’t recall it’s name [Update 23 Apr 2008: see http://svn.aminus.net/dejavu/branches/ldap/logic.py ] . There are some interesting ideas raised in LINQ that even Python developers ought to explore and consider adopting in a future Python. [Edit: 23 Apr 2008: Meaning I'd prefer to see this in Python core through AST transformation rather than bytecode hacks, C# has just got macros.]

  1. Setting up a Linq DataContext

    MyDatabaseContext db = new MyDatabaseContext(MyConnectionString); // or MyDatabaseContext db = new MyDatabaseContext();
     
  2. Basic LINQ Expression

    var AnIQueryable = from Customer in db.Customers
    where Customer.FirstName.StartsWith("m")
    select Customer; 
  3. Logging the generated queries

    db.Log = Console.out

    The previous example translates into a LIKE operator:

    SELECT [t0].[CustomerID], [t0].[FirstName] AS [FirstName]
    FROM [dbo].[Customer] AS [t0]
    WHERE [t0].[FirstName] LIKE @p0

  4. LINQ with Aggregates

    var AverageRuns =(from Master in this.db.Masters select Master.Runs).Average()
    

    The SQL generated isn’t too shabby either:

    SELECT AVG([t0].[Runs]) AS [value]
    FROM [dbo].[Master] AS [t0]
  5. LINQ grouped aggregates

    
       var categories =
          from p in products
          group p by p.Category into g
          select new
                  {Category = g.Key,
                   AveragePrice = g.Group.Average(p => p.UnitPrice)
                   };
    
  6. Lambda Expressions

    • Map

      db.Customers.Select(customer => master.Customer.LastName.length)
    • Filter

      db.Customers.Where(customer => customer.LastName.StartsWith("M")
    • Reduce / Fold


      double[] doubles = { 1.7, 2.4, 3.5, 8.9 };
      double result = doubles.Aggregate(0.0, (d1, d2) => d1+d2);

      Note: You can’t use Aggregate directly on IQueryable from database contexts. Instead,

      var arr_masters = this.db.Masters.ToArray();
      var totalRuns = arr_masters.Aggregate
      (0, // seed
      (int accum, MyDB.Master master) => accum + master.Runs
      );

  7. Updating Database

    
    this.Validate();
    this.masterBindingSource.EndEdit();
    db.SubmitChanges();
    
  8. How to cheat

    Use Microsoft’s 101 LINQ samples

 

Mobile Technology

Wednesday, April 2nd, 2008

I’ve been listening to MIX’08 talking about new uses for mobile phones and I came across this piece of news:

Man divorces two wives in three minutes (via SMS) link (includes photos of two disappointed women)

Interestingly, it appears that the women initiated the proceedings.

[Justice] Wan Abdul Malik said this was the first time in the court’s history that two wives had sought a divorce at the same time.

.Net Scripting / Hosting / Embedding

Friday, November 2nd, 2007

Add VB.NET Scripting to .NET Apps

The .NET Framework contains classes (such as those in the Microsoft.VisualBasic.Vsa namespace) that allow you to host a scripting engine in your application so that users can script your application. This article will show you how to host the VB.NET engine in your application, compile and run VB.NET code, and deal with syntax errors.

[Ed: vsa has been deprecated, look at VSTA SDK]

Using .NET Languages to make your Application Scriptable

You can go a long way to make a large application customisable. You can include a comprehensive options and preferences system or even use configuration files to allow access to advanced settings, but there’s nothing like being able to write code within an application to fully control it or simply hook in to it.

VSTA SDK is a new component that has to be licensed through summsoft.com for it to be legally distributable.

CLRs tail opcode

Friday, November 2nd, 2007

Jomo Fisher demonstrates how tail call works in CLR using mutual recursion in F# as an example:


let rec f1 n =
    f2 (n+1)
and f2 n =
    f1 (n+1)

f1 1

.method public static !!T f1(int32 n) cil managed
{
    .maxstack 4
    L_0000: ldarg.0
    L_0001: ldc.i4.1
    L_0002: add
    L_0003: tail
    L_0005: call !!0 Test::f2< !!T>(int32)
    L_000a: ret
}

F# to be productized

Sunday, October 21st, 2007

(Via Secret Geek)

Now, I don’t really know what this means. Does it mean that MS is going to guarantee some kind of backwards compatibility and offer official stable/supported releases?

Somasegar offers scant details on the productization of F# itself, but indicates

We will be partnering with Don Syme and others in Microsoft Research to fully integrate the F# language into Visual Studio and continue innovating and evolving F#.

It is said that having too large an adoption base for a new programming language/platform can actually stifle further evolution, as considerations about preserving backward compatibility (even bugs) become far more important than improving the language. I would have been happier to see that Microsoft cultivate the F# community over time organically, rather than go for the big product push.

Exactly how hard is it to encode and decode RFC2396 in ASP.net?

Monday, July 9th, 2007

Yang Xing reports:

Developer [sic] should avoid encoding Space into “+” or double encoded into “%2b”. It is recommended that when encode [sic] URL use “System.Uri.EscapeDataString”, when decode URL use “HttpUtility.UrlDecode”

Sigh. There are days when one just wishes one’s back in Python-land.

Contrast with the following Python-equivalent:

>>> urllib.quote('255 m')
'255%20m'
>>> urllib.quote_plus('255 m')
'255+m'
>>> urllib.unquote('255%20m')
'255 m'
>>> urllib.unquote_plus('255%20m')
'255 m'
>>> urllib.unquote_plus('255+m')
'255 m'

What Rich Client Applications Can Learn from the Web

Wednesday, June 20th, 2007

Zef writes in Ajax Reality Check that

Does anybody realize where we came from and that these “web 2.0 technologies” aren’t great at all, but just the best we could do — in the browser?

However, I assert that do have something to learn from the browser1, and it’s not ajax.

Here is my list:

1. Bookmarkable applications. I can send you the URL of a particular screen, or a particular record.

2. This opens up applications to easily implement Most Recently Used Feature, or Most Recently Accessed Data

3. It makes it easy to add annotation-like features to an app (through mashups).2

4. You can create mashups easily, e.g. treat an application as a component for free3

5. Back button and Breadcrumbs (MSMoney-style UI), although the caching of application screens on browser make this somewhat broken, but desktop apps will be able to address this.

6. Ease of deployment - no need for Administrator rights to install applications, modify registry, centralized profiles. Notably, a lot of apps today are still written in the style that network availability and bandwidth is poor, rather than the other way round - ubiquitious network availability. (Sidenote: things get interesting in the mobile space, because bandwidth is expensive, while storage gets cheaper, you might see a resurgence of the older style of programming again)

Footnotes

1Check out AJAX is not a mobile paradigm

2I had mentioned here:

In Scribbling in the Margins, Jon Udell’s thesis is that extensibility was the mark of enduring design. Jon likened the extension of DNS records for use in SPF to how people scribble in the margins of a document.

3There are versioning and security issues with mash ups though. Spoofing, CSRF. Any guidance on doing this properly with a critical app?

REST-compatible Ajax Patterns

Wednesday, June 6th, 2007

Can AJAX be used to strengthen REST-style programming? Yes! Here are some common scenarios where AJAX is better than standard HTML.

User authentication

Display authentication dialog on the URL where access is attempted, instead of redirecting to a logon screen, and then redirecting back.

Dialogs

Present dialogs using DHTML instead of popping up windows. URLs should be permanent if they are meant to be bookmarkable. Dialogs are temporal, and have no need for URLs.

ASP.net or JSF backbutton

The curse of the backbutton goes away when ajax is used with ASP.net or JSF applications. Instead of building up a history list of POSTs to the same page, back button works again, and brings user to the previous screen. (Note: 10 June 2007 - Turning on SmartNavigation in ASP.net has the same effect, through using an IFrame to postback.)

Wizards (Guided User Interaction)

Since wizards encapsulate actions within a single dialog, an Ajax implementation can progressively gather data until user finally commits the transaction.

Refreshing Value-Observer Pattern

This is part of the pop-up window problem. When a pop-up window mutates state, the parent window may need to refresh. Although this is possible via javascript, there is an element of cooperation that is required between the pop-up window and the originating window. This can limit reuse. This leads to an interesting question: what I like about simple URLs is that you can reuse and bookmark resources. What I don’t like about URLs is they pretty much suck for modal interaction, or where gosub style navigation is involved. How do you approach these in your web apps?

I’m keen to hear from you if there are more cases when you think Ajax is appropriate. Let me know!

ASP.net 2.0 Data Binding Internals

Tuesday, May 29th, 2007

Alexander Jung has a post outlining how ASP.net 2.0 data binding is implemented using code generation. A more detailed look at ASP.net 2.0 databinding internals is available at DotNetDan. Looking at the generated code, it surprised me that the Bind() method doesn’t even appear in the final generated code. Makes one wish that the ASP.net team had talked to the WinForms team, and used TypeConverters instead.


public IOrderedDictionary @__ExtractValues__control12(Control @__container) {

    OrderedDictionary @__table;

    TextBox TextBox2;

    TextBox2 = ((TextBox)(@__container.FindControl("TextBox2")));

    […] // other controls ommited

@__table = new OrderedDictionary();

    if ((TextBox2 != null)) {

        @__table["id"] = TextBox2.Text;

    }

    […] // other values ommited

    return @__table;

}

Useful references on Asp.net Controls:

  1. Custom asp.net control with CSS and Postbacks
  2. Custom asp.net templated databound control
  3. MSDN - building databound controls (example doesn’t support the Bind or Eval syntax)

Why Silverlight May Yet Displace HTML

Tuesday, May 29th, 2007

There’s a live discussion over at sogrady’s blog whether RIA’s will ever gain a foothold on the web. Stephen points out that HTML had been adequate for most online tasks people wish to do today - webmail, search, banking, and that AJAX is useful in filling in the gaps.

On the other hand, David (who works at Adobe) rightly points out that people [will] gravitiate inexorably to better experiences.

I would like to point out some technical reasons why I believe of all the RIAs that are going to be deployed, Silverlight stands in a good position to start carving off browser realestate  from HTML.

  1. Microsoft has learned to embrace the existing ecosystem. Silverlight, being text based, can be served by Apache and PHP
  2. In addition, Silverlight can be embedded in existing HTML markup. This makes it extremely attractive for web designers and developers to incrementally deploy Silverlight applications. Look out for a Silverlight version of SIFR soon.
  3. There is no separate compiler. Taking cues from the web browser, the absense of a separate compilation step means users are free to tinker, view source, and learn from other users. There’s going to be a lot of plagiarisation, copying and adaptation of published Silverlight markup, and the ecosystem will flourish.
  4. Silverlight content, being text-based, is indexable. For instance, this may mean that video streams can include subtitles based on Silverlight markup. Anything that helps search engines find your content is always welcome.
  5. Silverlight offers a sane model of embedding and integrating Silverlight content (read “Widgets”) from other websites. Current approaches, such as using embedded javascript and iframes are really hacks, and lack a sane unified component model. Being vector based, these widgets will be able to fit into different page layouts. (Question: Is Silverlight still restricted by the outdated cross site remote access rules?)
  6. The runtime is small enough that Microsoft is in a position to “push” out it’s plugin widely and by default. (Although I believe there’s a dependency on the .Net runtime, which is HUGE).

 

Technorati tags: ,

ASP.net Special Tags

Tuesday, May 22nd, 2007

Anyone exposed to ASP.net syntax will come to realize

ASP.net is not XML

Here is a page example that contains typical tags (sorry about the space between < and tag names, :


<%@ Page Language="VB" %>
<html>
  <body>

    <!-- #Include virtual="/include/header.inc" -->

    <%-- Server Side Comment --%>
    <script runat="server" 
      language="VB">
      
       Dim m_UserName As String = "Chui"
       
       Function MyFunction() As String
         return "Hello"
       End Function
       
       Sub called_when_page_is_rendered()
         ' Inside Private Sub __RenderContent1
       End Sub
       
    </script>

    <asp:Label id="Label1" 
         Text='<%# MyFunction() %>'
         runat="server" />

    <%-- Also try Custom Expression Builders
  %$ ConnectionStrings:LocalSqlServer
  %$ Resources:NameOfResxFile, LBL_HELLO
    --%>
    <asp:Label id="Label4" 
         Text="<%$ AppSettings:Foo %>"
         runat="server" />

    <% called_when_page_is_rendered() %>

    <%= m_UserName %>
             
    </form>
  </body>
</html>


For further reference, consult the Microsoft ASP.net Page Syntax for Special Tags. 

OdeToCode's shows how databinding expressions are translated into VB or C# code.

Public Sub __DataBindingLabel1(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim dataBindingExpressionBuilderTarget As System.Web.UI.WebControls.Label
    Dim Container As System.Web.UI.Control
    dataBindingExpressionBuilderTarget = CType(sender,System.Web.UI.WebControls.Label)
    Container = CType(dataBindingExpressionBuilderTarget.BindingContainer,System.Web.UI.Control)

    #ExternalSource("C:\Doc...\Chui\My Documents\Visual Studio 2005\WebSites\WebSite1\Default.aspx

    dataBindingExpressionBuilderTarget.Text = _
       System.Convert.ToString( MyFunction() , _
       System.Globalization.CultureInfo.CurrentCulture)

    #End ExternalSource
End Sub

References:

Undiscovered Features of ASP.net

Returning Identity Column of Autoincrement Fields

Wednesday, March 28th, 2007

Issuing an Insert command on an ObjectDataSource typically requires two database calls:

1) INSERT INTO mytable ….
2) SELECT @@IDENTITY

If you are prototyping against Access databases, one problem that becomes quickly apparent is that OleDb providers do not support multiple SQL statements. So you can’t do set the following commandtext in a DataTableAdapter method:

INSERT INTO mytable ….;
SELECT @@IDENTITY

However, this can be worked around by adding another method to the TableAdapter using partial classes that wraps the original Insert method.

Here’s some sample code:

namespace EventTableAdapters
{
    partial class EVENTTableAdapter
    {
        public int InsertQuery2(string EQUIPMENT, string PART, out System.Nullable EVENTID)
        {
            this.Connection.Open(); // If connection.Open() called after Insert() we lose the @@identity
            EVENTID = null;
            int RowsAffected = this.Insert(EQUIPMENT, PART);
            if ( RowsAffected > 0)
            {
                try
                {
                    IDbCommand cm = this.Connection.CreateCommand();
                    cm.CommandText = "SELECT @@IDENTITY";
                    EVENTID = Convert.ToInt32(cm.ExecuteScalar());
                }
                finally
                {
                    this.Connection.Close();
                }
            }

            return RowsAffected;
        }
    }
}

Then configure an ObjectDataSource to call InsertQuery2() instead.

Hat Tip to Bruce L for showing this technique.

Full Text Indexing in Ruby is Faster than Java

Wednesday, November 22nd, 2006

Jim Wiseman John Wiseman, who is porting Ferret to Lisp, reports on the blazing performance of Ferret.

(Ferret was originally a port of Lucene, but recent alteration to the file format has increased performence 5x over GCJ, and then the author ported to C to get an order of magnitude improvement.)

The moral of the story is not one of premature optimization, but working with pliable languages vs working with brittle ones.

Software for Bulgarian Asparagus Farmers

Tuesday, November 21st, 2006

You have to read the story behind this quote about developing software on top of the .Net 3.0 framework:

“I want to develop for the .NET 3.0 framework”

I don’t think you could find a smaller market segment if you tried. Perhaps writing software for Bulgarian asparagus farmers?

Joel On Software Discussion Group

BindingSource and Saving data

Sunday, November 5th, 2006

TIP:

If you bind controls to data using BindingSource, make sure you call

bindingSource1.EndEdit()

before you serialize to your data store. It’ll save a few red-faces.

Chui

ShortcutsEnabled on TextBox (WinForms DotNet) does not perform SelectAll with Control+A

Friday, November 3rd, 2006

In the KeyPress event handler


        If Asc(e.KeyChar) = 1 Then
            CType(sender, TextBox).SelectAll()
            e.Handled = True
        End If

technorati tags:, , , ,

ActiveX is the weakest link

Thursday, July 27th, 2006

Once in a while, it is gratifying to see how Microsoft’s embrace and extend comes back and bite them in the a***. Take Microsoft’s Internet Explorer, back when MS was defending their Windows OS turf against Netscape’s Browser OS. Microsoft, in their infinite wisdom, decided to extend the browser to include ActiveX applets. Now there is already a large base of ActiveX components on the Windows platform, so naturally, adding ActiveX components to web browsers would help entrench Microsoft’s dominance on the client side right?

As history has turned out, the answer is a resounding NO. Despite Microsoft’s security push on Windows XP to secure the operating system (which in-turn brought on Longhorn delays), ActiveX applets has become Internet Explorer’s Achiles heel. Spyware and malware authors are exploiting Active X vulnerabilities to hijack user’s PC, turning once healthy operating system into zombies, controlled by botnets.

Take a look at the Month of Browser Bugs weblog. Almost every Internet Explorer crash is due to a badly written ActiveX component. No matter how hard Microsoft works, the surface area of Active X components is simply too big to defend. Worse still, ActiveX on MS browsers have been supported for years, meaning Microsoft would have to take a quite bit of flak should they even attempt to disable ActiveX support.

Note, I am not referring to malicious ActiveX components, which Microsoft has partially addressed in XP SP2. XP SP2 adds a small hurdle that stops Internet Explorer users from accidentally installing ActiveX components. The crashes referred to above are ActiveX controls developed by Microsoft. A skilled programmer can engineer a crash that lets them install their software on your computer without your permission. I didn’t realize how many there are that are enabled for use with Internet Explorer. Some of them deal with the amazing page transition effects you see when you visit some web sites. Others deal with Windows HTML Help. Useful as they are, I’d rather not have these snazzy things if it means I don’t have to wipe my computer clean every year.

Now, some readers might wonder what about Firefox. Firefox supports applets too. However, these applets are not of the ActiveX variety. Firefox supports Java applets. The difference? ActiveX components are typically developed in C, C++, and VB. C and C++ are programming languages where the programmer has to take extra care to manage memory allocation and deallocation, otherwise, a program simply crashes. ActiveX components written in VB are markedly safer, as long as these VB components do not in turn use ActiveX components written in C or C++. In contrast, applets written in Java (like VB applets) suffer none of the problems of memory management (i.e. does not result in memory exceptions). In addition, Java applets can call a very limited number of routines that are developed in C, and this makes Java runtimes easier to defend against malicious websites.

Microsoft can’t afford to annoy clients who have developed legitimate business applications based on ActiveX applets, but at the same time Microsoft can’t concentrate on new product lines if it is constantly defending undefendable ground. Readers, if you were Bill Gates, what would you do? Would you cut your losses and run?

ASP.net GridView Shortcut

Monday, June 5th, 2006

When dealing with Strongly Typed datasets on the ASP.net GridView 2.0, I found myself writing one too many lines of code like this:

<asp:TemplateField HeaderText="Category">
  <ItemTemplate>
  <%# DataBinder.Eval(
    ((System.Data.DataRowView) Container.DataItem).Row,
   "CategoryRow.CategoryName") %>
  </ItemTemplate>
<asp:TemplateField>

Solution?

<asp:TemplateField HeaderText="Category">
  <ItemTemplate>
   <%# EvalEx(Container.DataItem, "CategoryRow.CategoryName") %>
  </ItemTemplate>
<asp:TemplateField>

protected object EvalEx(object DataItem, string Expression)
{
 return DataBinder.Eval(((DataRowView) DataItem).Row, Expression);
}

Don’t Fight the .Net GridView

Friday, June 2nd, 2006

The .Net GridView prefers to work through DataSources. I tried to use old style Fill dataset, then DataBind() and it simply doesn’t play well with Editing.

In addition, the ObjectDataSource.DataObjectTypeName is riculously underpowered. This version doesn’t get types of inner classes. It uses System.Web.Compilation.BuildManager.GetType instead of System.Type.GetType.


System.Type.GetType("MyStronglyTypedDataSet.MyTableRow"); // works
System.Web.Compilation.BuildManager.GetType("MyStronglyTypedDataSet.MyTableRow", true); // fails

Update 1 : Inner class notation is required:

System.Web.Compilation.BuildManager.GetType("MyStronglyTypedDataSet+MyTableRow", true); // fails

Update 2 : You still can’t use DataObjectTypeName
Turns out the MyStronglyTypedDataSet+MyTableRow doesn’t have a parameterless constructor.

Suddenly code generation without magic seems much more palatable.