Saturday, February 12, 2011

Moving from vb.NET (2003) to vb2005 What are some of the benefits?

We are changing from vs2003 to vs2005 and use vb as our primary language, I am looking for some of the changes to VB that will be helpful in our ASP.NET development. Can someone point me to a list (maybe from microsoft?) or provide some of their favaorite differences between the two versions?

  • Better IDE for one.

    From nportelli
  • I found the biggest improvements from .Net 1.1 to 2.0 were generics and yield return for easy implementation of ienumerables.

    From Mendelt
  • WHOA! Not so fast there, buddy! What's the rush? Relax, guy. Give it a few more years.

    Any .NET developer not working version 3.5 of the framework is just wasting time. Every single bit of it... Linq, WPF, lambdas, WCF, GENERICS, I could go on... Every SINGLE bit of it is gold. I'd rather play on a highway than target 1.1. Its like night and day.

    Do yourself and your team a favor... Skip 2k5 and hit 2k8.

    Greg D : Any advancement is positive, organizational inertia can be a pain. I'm still fighting to get colleagues to stop using VB6.
    Will : Organizational inertia in this case is costing developer productivity. And the majority of money brought into my shop is from vb6 apps, as well.
    Joel Coehoorn : generics are in 2.0.
    WACM161 : I agree with the 3.5 statement, unfortunately there is no money to go that far, we already have the vs2005 licenses but have no vs2008 ones and finance dept is unwilling to foot the bill to upgrade
    Will : Yes, generics are in 2.0. I didn't mean to imply you had to go to 2008 to get 'em.
    From Will
  • What's new in VB 2005 (from MS)

    The same topic covered in Code Magazine

    WACM161 : exactly what I was looking for , thank you
    From Torbjørn
  • From a language perspective, the addition of Generics and Nullable types (second link) (built on Generics) was a pretty compelling story for my work. The My namespace provides VB developers with quite a few shortcuts into "somewhat" more complicated features of the system.

    From an ASP.NET perspective, even though they weren't VB-specific, the addition of the Master Page framework and MembershipProvider architecture were also very valuable.

    Here's a fairly comprehensive list from Microsoft of all the Visual Studio 2005, language and major .NET framework changes.

    For what it's worth, you might consider just jumping over 2005 and right into 2008, with .NET 3.5.

    From John Rudy
  • Rick Strahl takes stock of the major changes and provides a personal perspective on some of the highs and lows.

    .NET 1.1 to .NET 2.0 Migration Article 1 Atricle 2

    From notandy
  • I personally find some of the IDE changes to be of the best benefit.

    • The fact that the designer DOESN'T re-format your code as it feels like it
    • The fact that standard layout is DEFAULT rather than grid layout
    • Improvements in intellesence

    In addition to the IDE changes, if I had to pick 1 .NET 2.0 thing that is a huge helper I would say generics.

How do I check if a tag exists in XSLT?

I have the following template

<h2>one</h2>
<xsl:apply-templates select="one"/>
<h2>two</h2>
<xsl:apply-templates select="two"/>
<h2>three</h2>
<xsl:apply-templates select="three"/>

I would like to only display the headers (one,two,three) if there is at least one member of the corresponding template. How do I check for this?

  • <xsl:if test="one">
      <h2>one</h2>
      <xsl:apply-templates select="one"/>
    </xsl:if>
    <!-- etc -->
    

    Alternatively, you could create a named template,

    <xsl:template name="WriteWithHeader">
       <xsl:param name="header"/>
       <xsl:param name="data"/>
       <xsl:if test="$data">
          <h2><xsl:value-of select="$header"/></h2>
          <xsl:apply-templates select="$data"/>
       </xsl:if>
    </xsl:template>
    

    and then call as:

      <xsl:call-template name="WriteWithHeader">
        <xsl:with-param name="header" select="'one'"/>
        <xsl:with-param name="data" select="one"/>
      </xsl:call-template>
    

    But to be honest, that looks like more work to me... only useful if drawing a header is complex... for a simple <h2>...</h2> I'd be tempted to leave it inline.

    If the header title is always the node name, you could simplifiy the template by removing the "$header" arg, and use instead:

    <xsl:value-of select="name($header[1])"/>
    
  • I like to exercise the functional aspects of XSL which lead me to the following implementation:

    <?xml version="1.0" encoding="UTF-8"?>
    

    <!-- test data inlined -->
    <test>
        <one>Content 1</one>
        <two>Content 2</two>
        <three>Content 3</three>
        <four/>
        <special>I'm special!</special>
    </test>
    
    <!-- any root since take test content from stylesheet -->
    <xsl:template match="/">
        <html>
            <head>
                <title>Header/Content Widget</title>
            </head>
            <body>
                <xsl:apply-templates select="document('')//test/*" mode="header-content-widget"/>
            </body>
        </html>
    </xsl:template>
    
    <!-- default action for header-content -widget is apply header then content views -->
    <xsl:template match="*" mode="header-content-widget">
        <xsl:apply-templates select="." mode="header-view"/>
        <xsl:apply-templates select="." mode="content-view"/>
    </xsl:template>
    
    <!-- default header-view places element name in <h2> tag -->
    <xsl:template match="*" mode="header-view">
        <h2><xsl:value-of select="name()"/></h2>
    </xsl:template>
    
    <!-- default header-view when no text content is no-op -->
    <xsl:template match="*[not(text())]" mode="header-view"/>
    
    <!-- default content-view is to apply-templates -->
    <xsl:template match="*" mode="content-view">
        <xsl:apply-templates/>
    </xsl:template>
    
    <!-- special content handling -->
    <xsl:template match="special" mode="content-view">
        <strong><xsl:apply-templates/></strong>
    </xsl:template>
    

    Once in the body all elements contained in the test element have header-content-widget applied (in document order).

    The default header-content-widget template (matching "*") first applies a header-view then applies a content-view to the current element.

    The default header-view template places the current element's name in the h2 tag. The default content-view applies generic processing rules.

    When there is no content as judged by the [not(text())] predicate no output for the element occurs.

    One off special cases are easily handled.

how do I wait on console input in c# for 15 seconds or so.

I need to ask for input in console and wait for few sec may be a min after that I need to default to some value. How can basically time our on console input in c# and proceed with default settings? If you have sample code that would be great.

  • One way would be to loop, calling Console.In.Peek(), waiting for input or for enough time to go by.

  • See here, it uses a nice little polling technique on the console, which although a bit crude, very effective.

    From Mark
  • You could use the timer object in System.Timers.Timer and set it to 60 secs, enable it and if someone enters something into the console just disable it, if not then just handle the what happens in the Timer.Elapsed event.

    static void Main(string[] args)
            {
                System.Timers.Timer timer = new System.Timers.Timer(60000);
                timer.Elapsed += new System.Timers.ElapsedEventHandler(T_Elapsed);
                timer.Start();
                var i = Console.ReadLine();
                if (string.IsNullOrEmpty(i)) 
                {
                    timer.Stop();
                    Console.WriteLine("{0}", i);
                }
            }
    
            static void T_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                Console.WriteLine("Defult Values Used");
                var T = (Timer)sender;
                T.Stop;
    
            }
    

    Not sure if this is the best way. I have tested this but as I said it may not be the best way.

    ICR : The problem with this model is that ReadLine is a blocking call that doesn't return until the line has been entered, so whilst the default value may be sent when the timer is elapsed the program won't continue until the text has been entered.
    Nathan W : mmm yeah didn't really think of that. Bugger
    From Nathan W
  • You may want to consider doing something like adding a command line argument to act as a switch between an automatic mode using defaults and the full user input mode.

    If you use a specific interpretation of your request it becomes quite trivial. In this model the user is prompted for input. If they type nothing after a timeout period the default value is used. If they start typing something then no timeout is used. This also deals with the usability issue of giving up and using a default value when they're taking a long time to type something in.

        static void Main(string[] args)
        {
            Console.WriteLine("Please enter your name ");
            string input;
    
            if (TryReadLine(out input, 10000, true))
            {
                Console.WriteLine(input);
            }
            else
            {
                Console.WriteLine("[DEFAULT]");
            }
    
            Console.ReadKey(true);
        }
    
        const string timerString = "[{0} seconds until default value is used]";
    
        public static bool TryReadLine(out string s, double timeout, bool showTimer)
        {
            DateTime timeoutDateTime = DateTime.Now.AddMilliseconds(10000);
            DateTime nextTimer = DateTime.Now;
            while (DateTime.Now < timeoutDateTime)
            {
                if (Console.KeyAvailable)
                {
                    ClearTimer(timeoutDateTime);
                    s = Console.ReadLine();
                    return true;
                }
    
                if (showTimer && DateTime.Now > nextTimer)
                {
                    WriteTimer(string.Format(timerString, (timeoutDateTime - DateTime.Now).Seconds));
                    nextTimer = DateTime.Now.AddSeconds(1);
                }
            }
    
            ClearTimer(timeoutDateTime);
            s = null;
            return false;
        }
    
        private static void ClearTimer(DateTime timeoutDateTime)
        {
            WriteTimer(new string(' ', string.Format(timerString, (timeoutDateTime - DateTime.Now).Seconds).Length));
        }
    
        private static void WriteTimer(string s)
        {
            int cursorLeft = Console.CursorLeft;
            Console.CursorLeft = 0;
            Console.CursorTop += 1;
            Console.Write(s);
            Console.CursorLeft = cursorLeft;
            Console.CursorTop -= 1;
        }
    }
    

    Because I spend so long on it before I realised there was a better way, here is some code I just knocked up to read a string from the console, with a timeout. It also has the option to be able to print the current time left to the console. It's not tested very thoroughly, so is likely to have a lot of bugs. The callback feature uses the .NET 3.0 Action, though if this is for C# 2.0 you can just turn it into a delegate.

        static void Main(string[] args)
        {
            string input;
            Console.Write("Please enter your name (");
            int timerPromptStart = Console.CursorLeft;
            Console.Write("    seconds left): ");
            if (TryReadLine(out input, 10000, delegate(TimeSpan timeSpan)
                                              {
                                                  int inputPos = Console.CursorLeft;
                                                  Console.CursorLeft = timerPromptStart;
                                                  Console.Write(timeSpan.Seconds.ToString("000"));
                                                  Console.CursorLeft = inputPos;
                                              },
                                              1000))
            {
                Console.WriteLine(input);
            }
            else
            {
                Console.WriteLine("DEFAULT");
            }
            while (true) { }
        }
    
        /// <summary>
        /// Tries to read a line of input from the Console.
        /// </summary>
        /// <param name="s">The string to put the input into.</param>
        /// <param name="timeout">The time in milliseconds before the attempt fails.</param>
        /// <returns>Whether the user inputted a line before the timeout.</returns>
        public static bool TryReadLine(out string s, double timeout)
        {
            return TryReadLine(out s, timeout, null, 0);
        }
    
        /// <summary>
        /// Tries to read a line of input from the Console.
        /// </summary>
        /// <param name="s">The string to put the input into.</param>
        /// <param name="timeout">The time in milliseconds before the attempt fails.</param>
        /// <param name="timerCallback">A function to call every callbackInterval.</param>
        /// <param name="callbackInterval">The length of time between calls to timerCallback.</param>
        /// <returns>Whether the user inputted a line before the timeout.</returns>
        public static bool TryReadLine(out string s, double timeout, Action<TimeSpan> timerCallback, double callbackInterval)
        {
            const int tabLength = 6;
    
            StringBuilder inputBuilder = new StringBuilder();
            int readStart = Console.CursorLeft;
            int lastLength = 0;
            bool isInserting = true;
            DateTime endTime = DateTime.Now.AddMilliseconds(timeout);
            DateTime nextCallback = DateTime.Now;
            while (DateTime.Now < endTime)
            {
                if (timerCallback != null && DateTime.Now > nextCallback)
                {
                    nextCallback = DateTime.Now.AddMilliseconds(callbackInterval);
                    timerCallback((endTime - DateTime.Now));
                }
    
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo key = Console.ReadKey(true);
                    switch (key.Key)
                    {
                        case ConsoleKey.Enter:
                            Console.WriteLine();
                            s = inputBuilder.ToString();
                            return true;
    
                        case ConsoleKey.Backspace:
                            if (Console.CursorLeft > readStart)
                            {
                                Console.CursorLeft -= 1;
                                inputBuilder.Remove(Console.CursorLeft - readStart, 1);
                            }
                            break;
    
                        case ConsoleKey.Delete:
                            if (Console.CursorLeft < readStart + inputBuilder.Length)
                            {
                                inputBuilder.Remove(Console.CursorLeft - readStart, 1);
                            }
                            break;
    
                        case ConsoleKey.Tab:
                            // Tabs are very difficult to handle properly, so we'll simply replace it with spaces.
                            AddOrInsert(inputBuilder, new String(' ', tabLength), isInserting, readStart);
                            Console.CursorLeft += tabLength;
                            break;
    
                        case ConsoleKey.Escape:
                            Console.CursorLeft = readStart;
                            inputBuilder = new StringBuilder();
                            break;
    
                        case ConsoleKey.Insert:
                            isInserting = !isInserting;
                            // This may be dependant on a variable somewhere.
                            if (isInserting)
                            {
                                Console.CursorSize = 25;
                            }
                            else
                            {
                                Console.CursorSize = 50;
                            }
                            break;
    
                        case ConsoleKey.Home:
                            Console.CursorLeft = readStart;
                            break;
    
                        case ConsoleKey.End:
                            Console.CursorLeft = readStart + inputBuilder.Length;
                            break;
    
                        case ConsoleKey.LeftArrow:
                            if (Console.CursorLeft > readStart)
                            {
                                Console.CursorLeft -= 1;
                            }
                            break;
    
                        case ConsoleKey.RightArrow:
                            if (Console.CursorLeft < readStart + inputBuilder.Length)
                            {
                                Console.CursorLeft += 1;
                            }
                            break;
    
                        case ConsoleKey.UpArrow:
                            // N.B. We can't handle Up like we normally would as we don't know the last console input.
                            //      You might want to handle this so it works appropriately within your own application.
                            break;
    
                        case ConsoleKey.PageUp:
                        case ConsoleKey.PageDown:
                        case ConsoleKey.PrintScreen:
                        case ConsoleKey.LeftWindows:
                        case ConsoleKey.RightWindows:
                        case ConsoleKey.Sleep:
                        case ConsoleKey.F1:
                        case ConsoleKey.F2:
                        case ConsoleKey.F3:
                        case ConsoleKey.F4:
                        case ConsoleKey.F5:
                        case ConsoleKey.F6:
                        case ConsoleKey.F7:
                        case ConsoleKey.F8:
                        case ConsoleKey.F9:
                        case ConsoleKey.F10:
                        case ConsoleKey.F11:
                        case ConsoleKey.F12:
                        case ConsoleKey.F13:
                        case ConsoleKey.F14:
                        case ConsoleKey.F15:
                        case ConsoleKey.F16:
                        case ConsoleKey.F17:
                        case ConsoleKey.F18:
                        case ConsoleKey.F19:
                        case ConsoleKey.F20:
                        case ConsoleKey.F21:
                        case ConsoleKey.F22:
                        case ConsoleKey.F23:
                        case ConsoleKey.F24:
                        case ConsoleKey.BrowserBack:
                        case ConsoleKey.BrowserForward:
                        case ConsoleKey.BrowserStop:
                        case ConsoleKey.BrowserRefresh:
                        case ConsoleKey.BrowserSearch:
                        case ConsoleKey.BrowserFavorites:
                        case ConsoleKey.BrowserHome:
                        case ConsoleKey.VolumeMute:
                        case ConsoleKey.VolumeUp:
                        case ConsoleKey.VolumeDown:
                        case ConsoleKey.MediaNext:
                        case ConsoleKey.MediaPrevious:
                        case ConsoleKey.MediaStop:
                        case ConsoleKey.MediaPlay:
                        case ConsoleKey.LaunchMail:
                        case ConsoleKey.LaunchMediaSelect:
                        case ConsoleKey.LaunchApp1:
                        case ConsoleKey.LaunchApp2:
                        case ConsoleKey.Play:
                        case ConsoleKey.Zoom:
                        case ConsoleKey.NoName:
                        case ConsoleKey.Pa1:
                            // These keys shouldn't do anything.
                            break;
    
                        case ConsoleKey.Clear:
                        case ConsoleKey.Pause:
                        case ConsoleKey.Select:
                        case ConsoleKey.Print:
                        case ConsoleKey.Execute:
                        case ConsoleKey.Process:
                        case ConsoleKey.Help:
                        case ConsoleKey.Applications:
                        case ConsoleKey.Packet:
                        case ConsoleKey.Attention:
                        case ConsoleKey.CrSel:
                        case ConsoleKey.ExSel:
                        case ConsoleKey.EraseEndOfFile:
                        case ConsoleKey.OemClear:
                            // I'm not sure what these do.
                            break;
    
                        default:
                            Console.Write(key.KeyChar);
                            AddOrInsert(inputBuilder, key.KeyChar.ToString(), isInserting, readStart);
                            break;
                    }
    
                    // Write what has current been typed in back out to the Console.
                    // We write out everything after the cursor to handle cases where the current input string is shorter than before
                    // (i.e. the user deleted stuff).
                    // There is probably a more efficient way to do this.
                    int oldCursorPos = Console.CursorLeft;
                    Console.CursorLeft = readStart;
                    Console.Write(inputBuilder.ToString());
                    if (lastLength > inputBuilder.Length)
                    {
                        Console.Write(new String(' ', lastLength - inputBuilder.Length));
                    }
                    lastLength = inputBuilder.Length;
                    Console.CursorLeft = oldCursorPos;
                }
            }
    
            // The timeout period was reached.
            Console.WriteLine();
            s = null;
            return false;
        }
    
        // This is a rather ugly helper method to add text to the inputBuilder, either inserting or appending as appropriate.
        private static void AddOrInsert(StringBuilder inputBuilder, string s, bool insert, int readStart)
        {
            if (Console.CursorLeft < readStart + inputBuilder.Length + (insert ? -1 : 1))
            {
                if (!insert)
                {
                    inputBuilder.Remove(Console.CursorLeft - 1 - readStart, 1);
                }
                inputBuilder.Insert(Console.CursorLeft - 1 - readStart, s);
            }
            else
            {
                inputBuilder.Append(s);
            }
        }
    }
    
    From ICR

Dummy web service

I received a WSDL file for a web service interface that our system should call somewhere in the future.

Until then, I'd like to setup a dummy/mockup web service that does nothing else than to log the web service invocations and return dummy data.

What I've done so far is to generate Java objects from the WSDL file.

What's the fastest way to setup such a mockup web service when you already have an application server (here: JBoss) running?

  • We just faced this same problem, and found SoapUI to be the perfect tool. Given a WSDL it'll create a service on your machine you can call, and it allows you to edit the response as you need.

    Brian : I've just done some drive-by work with WSDLs, and I've got to agree with you: SoapUI is an amazing tool.
    From Danimal
  • You can also use Fiddler, a HTTP Debugging Proxy. You can easily configure Fiddler to return a pre-defined HTTP response with its AutoResponder feature when a request is sent to a particular URL.

    From Eoin
  • You can use Apache Axis's wsdl2java to generate skeleton classes from the WSDL:

    Just as a stub is the client side of a Web Service represented in Java, a skeleton is a Java framework for the server side. To make skeleton classes, you just specify the "--server-side --skeletonDeploy true" options to WSDL2Java.

    ...

    The skeleton class is the class that sits between the Axis engine and the actual service implementation.

    You would effectively be creating your own version of the server-side implementation of the web service. You can then implement the skeleton to return some stub/dummy data, deploy that to your application server, and then make web service calls to your skeleton just as you would to the live web service.

    From matt b

gcc for MIPS, 3.4.4 or 4.3.2?

We've made a number of changes to gcc 3.3.2 (for MIPS) to support the vagaries of an embedded system we're working on. gcc 3.4 and later appear to have substantially improved the MIPS code generation, so I'm planning to port our changes forward. The question is which gcc version should I target: 3.4.4 or straight to 4.3.2? Its a substantial amount of work to port the changes, I don't want to do it twice and pick the better result.

The Linux-MIPS project still recommends gcc 3.4.4, and MIPS Technologies maintains a modified SDE toolchain based on gcc 3.4.4. Though my embedded system is not running Linux, I respect their expertise.

From what I've read the MIPS backend does not benefit from the higher level optimizations in 4.x, and actually produces slower code than 3.4.4. Can anyone confirm or deny this?

  • I haven't used MIPS since the classroom so I can't directly answer your question.

    I would suggest sending an e-mail to someone on the Linux-MIPS project, and ask when they plan to upgrade. Assuming it is not soon. It looks like 3.4.4 is a worthy upgrade.

    From J.J.

Good book for learning Sharepoint development

What would you recommend? I know C# and ASP.NET well, but I haven't touched Sharepoint before.

  • Inside Windows Sharepoint Services by Ted Pattison is an absolute must read for any sharepoint developer.

  • I liked Microsoft SharePoint 2007 Development Unleashed for its treatment of Sharepoint's object model.

    From Galwegian
  • Developer's Guide to the Windows SharePoint Services by Todd Bleeker is a really great starting point.

  • I agree with Charles, that Ted's Inside WSS 3 is an absolute must for every SPDev. But the book I generally give to my new .net developers when they are getting into SharePoint for the first time is Scot Hiller's Microsoft SharePoint: Building Office 2007 Solutions in C# 2005.

    Here's the author's quote about the intended audience:

    "..the audience for this book is an intermediate professional developer who was just assigned the project of bringing SharePoint 2007 into the organization."

  • Charles Graham has it right here. Inside WSS 3 by Ted Pattison should be the first book anyone picks up if they're interested in SharePoint development. Every person on our SharePoint team has their own copy of this book on their bookshelf. No shared library copy for this puppy! It is written for someone exactly like you too (knows .net but has never worked with SharePoint).

    WSS is the base framework for all that is SharePoint. If you ever plan on moving on to development using other SharePoint products (Microsoft Office SharePoint Server Standard/Enterprise/Internet), you will need to know the information contained in this book.

    From knight0323
  • I must second the voices for Inside Windows SharePoint Services and especially Todd's Developer's Guide to Windows SharePoint Services. Both are excellent all-round books that will get you started without knowing anything SharePoint specific.

    One thing to be aware, and a second reason why these two books are especially good, is that SharePoint spans many different topics. Once you start to know SharePoint you may want to specialize in a particular field. One thing is the MOSS/WSS choice, but you still have a lot of sub choices, such as Web Content Management, Business Intelligence, Workflow, Design, etc. Each of these sub areas will require a lot of study and most have excellent books available. Ask again if you need tips for specific areas.

    To do a bit of shameless self-promotion, I am also writing a SharePoint book, Building the SharePoint User Experience. The topics will go extremely deep into how the user experience is built and how user experience elements work. It is not a user interface book, it is pure, hardcore development, focused on understanding how the user experiences SharePoint.

  • This question has been already discussed here with the same suggestions WSS/MOSS Book on stackoverflow.

  • Definitely Inside WSS 3.0 by Ted Pattison

ListView with LINQ Datasource insert template

It seems like this should be straightforward but I'm boggling. I've got my listview all setup and bound to my LINQ datasource. The source is dependent on a dropdown list which decides which branch information to show in the listview. My edit template works fine but my insert template won't work because it wants the branch ID which I want to get from the dropdownlist outside the listview but I don't know how to both bind that value and set it in my template. It looks like this:

<InsertItemTemplate>
    <tr style="">
      <td>
         <asp:Button ID="InsertButton" runat="server" CommandName="Insert" 
               Text="Insert" />
     </td>
      <td>
       <asp:TextBox ID="RechargeRateTextBox" runat="server" 
          Text='<%# Bind("RechargeRate") %>' />
         </td>
              <td>
       <asp:Calendar SelectedDate='<%# Bind("StartDate") %>' ID="Calendar1"  runat="server"></asp:Calendar>                                    
       </td>
           </tr>
    </InsertItemTemplate>

I need to get a label in there that binds to the value of a databound asp dropdownlist outside of the listview so that the insert will work.

  • Use the OnSelectedIndexChanged (with AutoPostBack=True) callback for the DropDownList to manually set the values in the ListView to the defaults for that branch when the value of the DropDownList changes.

    protected void BranchDropDownList_OnSelectedIndexChanged( object sender, EventArgs e )
    {
        DropDownList ddl = (DropDownList)sender;
        RechargeRateTextBox.Text = BranchManager.GetRechargeRate( ddl.SelectedValue );
    }
    

    Wrap the whole thing up in an UpdatePanel and it can all happen via AJAX.

    From tvanfosson
  • I ended up going with this, thanks twanfosson.

    protected void ListView1_ItemInserting(object sender, System.Web.UI.WebControls.ListViewInsertEventArgs e)
            {
                e.Values["BranchID"] = DropDownList1.SelectedValue;
            }
    
    From Echostorm

What are the real challenges for a developer migrating between programming languages?

Many developers will claim that moving from one programming language to another is relatively simple especially if the languages are based on similar paradigms. However, in practice the effort comes not from learning the syntax of the language but in developing a deep understanding of the language nuances and more importantly knowing what is offered in the language’s libraries. For example, switching from Java to .Net is not difficult from a syntactic perspective but programming efficiency requires a good knowledge of the available libraries. Switching from PHP to .Net could present an even greater hurdle given the language disparities.

What are the real overheads for a developer to move to a different language in the same paradigm? What if the paradigms are different?

  • For me it would finding good bloggers and useful sites on the language. After a while you get to know where the best people are. Those people and sites are good sources of information for learning the subtleties.

    From harriyott
  • leaving your comfort zone. I think this is one of the biggest reasons some developers don't learn new languages.

    But for others, this is what drives them.

    From levi rosol
  • The biggest challenge (for me) is usually the API, rather than the language itself (.NET notwithstanding). For example, I've been using Microsoft's C++ and C# for a lot of years (Delphi before that). But I have great difficulty getting started on Java; even trivial projects can take me a while. Not because the language is difficult (it's not), but because the APIs are different, and arranged differently.

    It takes months to get up to speed on an API to the point you can use it fluently, and years to become "good" and learn all the ins and outs of the language. That's daunting for a lot of developers, because you basically have to devote a significant amount (if not all) of your time and effort toward working in the new language to become an expert at it. Many times, the incentive to move out of your current area of expertise just isn't there.

    Bill the Lizard : Spot on. I'm always amazed at developers who say they can "learn" a new language in 3 days. Sure, you can learn the syntax, but knowing how to use the language is entirely different.
    DannySmurf : Absolutely. It takes months to get up to speed on an API to the point you can use it fluently, and years to become "good" and learn all the ins and outs of the language. I think I'll put that in my answer, actually.
    Mark Baker : I do think Java's libraries are particularly poor, but it's a problem picking up any new platform. What makes it worse is that it's hard to know what to search for, you pretty much have to just read large chunks of the documentation.
    From DannySmurf
  • Same paradigm is much easier because it is really just a matter of grasping the various libraries and locating them quickly as you mentioned.

    If the paradigms are different than this switch is more difficult. Moving from a static to dynamic language or a procedural to OOP language will require a different mind set. This will take more time but it is possible and still a very good exercise.

    It may be similar to learning foreign languages. If you speak English, than moving to another Latin based language is far easier than going to something like Greek.

  • Moving within the same paradigm is relatively easy. I find that switching between Java and .NET painless because both platforms offer similar functionality and similar libraries. But switching paradigms could be a real challenge.

    My students usually have a hard time going to Functional and Logical languages after learning Java even though the functional and logic programming are easier.

    Another problem is switching between types of applications. For example, if you are accustomed to building desktop applications in Java then suddenly try to build web applications in .NET the switch is hard because you are not only learning new languages but new fields of programming.

    Another challenge is the tool sets that are available for a particular language. Java and .NET have similar tools but with some differences. If you learned to program using Visual Studio then it is possible that features of Visual Studio become confused with the language. I see students having this problem all the time. When you switch to Java and there is no equivalent menu option of wizard in the new IDE it could cause problems.

    I advocate to persons learning programming to learn the core concepts of the paradigm rather than the specific language because it makes you more portable in the future. A person comfortable with Object Oriented Concepts will have an easier time switching between Java and .NET or Python than a person who simple learned how to program in C#.

    Richard Dorman : Understanding the core concepts is essential but management often make the mistake of assuming that having a core understanding implies that your library knowledge in one language migrates easily to another language. I believe this takes longer and is more costly than is expected.
  • Just like learning a new human language, for me the biggest problem lies on typical constructions you need to do to solve a problem.

    I know that perhaps learning "while" or "for" loops in several languages aren't so difficult - but when your problem goes up one level of abstraction (iterate through this array) you'll find yourself using "[" instead of "(" and vice-versa.

    The learning curve can be even steeper if, besides learning a new language, you have to learn a new framework. When I went from typícal ASP.Net to MVC (using NVelocity) I kinda felt myself completely lost - all my knowledge on how to solve typical problems with asp.net control had to be forgotten.

    Finally, the biggest challenge happens when you change between languages with different paradigms - because you can no longer think in the same way to solve a problem. Like - when moving from C# to Prolog, instead of thinking in functions, arguments, class hierarchy, etcs... I had to think only in states, events linked to data changes and event chaining via recursion - it was madness but I could finish my university homework.

    From rshimoda
  • Coming from 15+ years of C++ background I just had to move to Java for a new project I am working on, and this is a rather painful step. There are tools and frameworks for almost everything, but the learning curve is enormous! The new syntax is nothing to worry about, the API is more difficult, but the most difficult area is to find the way through the all the frameworks.

    Also, having to use Eclipse as IDE is a step back in terms of stability and reliability compared to Emacs. The features of Eclipse are really compelling, but the bugs in the IDE cause constant hassle.

    From struppi

What is the C# Using block and why should I use it?

What is the purpose of the Using block in C#? How is it different from a local variable?

  • Using calls Dispose() after the using-block is left, even if the code throws an exception.

    So you usually use using for classes that require cleaning up after them, like IO.

    So, this using block:

    using (MyClass mine = new MyClass())
    {
      mine.Action();
    }
    

    would do the same as:

    MyClass mine = new MyClass();
    try
    {
      mine.Action();
    }
    finally
    {
      if (mine != null)
        mine.Dispose();
    }
    

    Using using is way shorter and easier to read.

    From Sam
  • Placing code in a using block ensures that the objects are disposed (though not necessarily collected) as soon as control leaves the block.

    From DannySmurf
  • If the type implements IDisposable, it automatically disposes it.

    Given:

    public class SomeDisposableType : IDisposable
    {
       ...implmentation details...
    }
    

    These are equivalent:

    SomeDisposableType t = new SomeDisposableType();
    try {
        OperateOnType(t);
    }
    finally {
       t.Dispose();
    }
    
    using (SomeDisposableType u = new SomeDisposableType()) {
        OperateOnType(u);
    }
    

    The second is easier to read and maintain.

    Jon Skeet : Note that in general the finally block will check for nullity before calling Dispose. Not that it matters when you're calling a constructor, but...
    John : If you declare the variable outside the using block and then create a new instance in the using statement it may not dispose the item.
    From plinth
  • From MSDN:

    C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

    The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

    In other words, the using statement tells .NET to release the object specified in the using block once it is no longer needed.

    tvanfosson : This gives the rationale for using "using", while @plinth shows what it actually does.
    Robert S. : Indeed. This is the answer to "What is the purpose of the Using block in C#?"
    raven : @tvanfosson: FYI, the ampersand character is meant to imply that you are directing your comment at a user, as I've done at the beginning of this comment. You don't need to prefix every reference to another user with this character as you did when you mentioned plinth.
    Scott Ferguson : @raven: FYI, that's not an ampersand, this is: & :)
    From Robert S.
  • It is really just some syntatic sugar that does not require you to explicity call Dispose on members that implement IDisposable.

  • using (B a = B())
    {
       DoSomethingWith(a);
    }
    

    is equivalent to

    B a = new A();
    try
    {
      DoSomethingWith(a);
    }
    finally
    {
       ((IDisposable)a).Dispose();
    }
    
  • The using statement obtains one or more resources, executes a statement, and then disposes of the resource.

Iterating through list and creating summary lines on the fly

EDIT: I missed a crucial point: .NET 2.0

Consider the case where I have a list of unsorted items, for the sake of simplicity of a type like this:

class TestClass
{
    DateTime SomeTime;
    decimal SomePrice;

    // constructor
}

I need to create a report-like output, where the total prices for each day are accumulated. There should be one line for each item, folled by the appropriate summary lines.

Take this test data:

List<TestClass> testList = new List<TestClass> { 
new TestClass(new DateTime(2008,01,01), 12),
new TestClass(new DateTime(2007,01,01), 20),
new TestClass(new DateTime(2008,01,01), 18)
};

The desired output would be something like this:

2007-01-01: 
20
Total: 20

2008-01-01: 
12
18
Total: 30

What's the best way to approach such scenarios? In the case of such a list, I would implement the IComparable interface for TestClass, so that the list can be sorted.

To create the report itself, something like this could be used (let's assume that we have methods for tasks like accumulating the prices, keeping track of the current date etc):

for (int i=0;i<testList.Count;i++)
{
    if (IsNewDate(testList[i]))
    {
        CreateSummaryLine();
        ResetValuesForNewDate();
    }

    AddValues(testList[i]);
}

// a final summary line is needed to include the data for the last couple of items.
CreateSummaryLine();

This works alright, but I have a strange feeling as far as the second "CreateSummaryLines" is concerned.

In what ways do you handle such situations (especially considering the fact, the we need to work with a List<> of items rather than a pre-categorized Dictionary or something like that)?

  • Crucial question: are you using .NET 3.5, thus allowing LINQ to be used? If so, you can group by SomeTime.Date and then process each date separately.

    If you have massive amounts of data, you may find my Push LINQ project useful - but otherwise straight LINQ to Objects is your best bet.

    Grimtron : Missed that important information: .NET 2.0 is to be used.
    Marc Gravell : Then use LINQBridge since you seem to be using C# 3.0
    From Jon Skeet
  • [edit] Since you are using .NET 2.0 with C# 3.0, you can use LINQBridge to enable this.

    LINQ; something like:

            var groups = from row in testList
                      group row by row.SomeTime;
            foreach (var group in groups.OrderBy(group => group.Key))
            {
                Console.WriteLine(group.Key);
                foreach(var item in group.OrderBy(item => item.SomePrice))
                {
                    Console.WriteLine(item.SomePrice);
                }
                Console.WriteLine("Total" + group.Sum(x=>x.SomePrice));
            }
    
    Grimtron : Missed that important information: .NET 2.0 is to be used.
    Marc Gravell : I've added the 2.0 thing via LINQBridge
    tvanfosson : You might want to consider grouping by row.SomeTime.Date unless you've already done the work of truncating the times when creating the instances of TestClass.
  • What version of C#/.NET are you using? If you're up to date, have a look at LINQ. This allows grouping your data. In your case, you could group by date:

    var days = from test in testList group test by test.SomeTime;
    foreach (var day in days) {
        var sum = day.Sum(x => x.SomePrice);
        Report(day, sum);
    }
    

    This way you could report a list of values for each day, along with the sum of money for that day.

    Grimtron : Missed that important information: .NET 2.0 is to be used.
  • Your desired output feels like you want to make a data structure that represents your summary data. You want to pair a date with a list of TestClass objects, then have a collection of those. You could use a HashSet or a Dictionary for the collection.

    For the summary, pair data structure can implement ToString for you.

    From plinth
  • Okay, so if you can't use LINQ:

    (I'm using var to save space, but it's easy to translate to C# 2.0 if necessary...)

    var grouped = new SortedDictionary<DateTime, List<TestClass>>();
    foreach (TestClass entry in testList) {
      DateTime date = entry.SomeTime.Date;
      if (!grouped.ContainsKey(date)) {
        grouped[date] = new List<TestClass>();
      }
      grouped[date].Add(entry);
    }
    
    foreach (KeyValuePair<DateTime, List<TestClass>> pair in testList) {
      Console.WriteLine("{0}: ", pair.Key);
      Console.WriteLine(BuildSummaryLine(pair.Value));
    }
    
    From Jon Skeet
  • Regardless of how you generate the report output, if you are going to be doing this regularly in your application consider putting together a report interface and implementing classes for this interface to localize the logic for creating the report in one place rather than scattering the code to create reports throughout your application. In my experience, applications typically have (or grow) requirements for multiple reports and, eventually, multiple formats.

    If you've only got one report, don't worry about it until you write your second one, but then start working on a reporting architecture that makes it easier to extend and maintain.

    For example (and using @Marc Gravell's code):

    public interface IReport
    {
       string GetTextReportDocument();
       byte[] GetPDFReportDocument();  // needing this triggers the development of interface
    }
    
    public class SalesReport : IReport
    {
       public void AddSale( Sale newSale )
       {
           this.Sales.Add(newSale);  // or however you implement it
       }
    
       public string GetTextReportDocument()
       {
           StringBuilder reportBuilder = new StringBuilder();
           var groups = from row in this.Sales
                        group row by row.SomeTime.Date;
           foreach (var group in groups.OrderBy(group => group.Key))
           {            
              reportBuilder.AppendLine(group.Key);
              foreach(var item in group.OrderBy(item => item.SomePrice))            
              {
                 reportBuilder.AppendLine(item.SomePrice);
              }
              reportBuilder.AppendLine("Total" + group.Sum(x=>x.SomePrice));
          }
    
          return reportBuilder.ToString();
       }
    
       public byte[] GetPDFReportDocument()
       {
            return PDFReporter.GenerateDocumentFromXML( this.ConvertSalesToXML() );
       }
    

    ... the rest is left as an exercise for the reader ...

    From tvanfosson

Elegant way to search for UTF-8 files with BOM?

For debugging purposes, I need to recursively search a directory for all files which start with a UTF-8 byte order mark (BOM). My current solution is a simple shell script:

find -type f |
while read file
do
    if [ "`head -c 3 -- "$file"`" == $'\xef\xbb\xbf' ]
    then
        echo "found BOM in: $file"
    fi
done

Or, if you prefer short, unreadable one-liners:

find -type f|while read file;do [ "`head -c3 -- "$file"`" == $'\xef\xbb\xbf' ] && echo "found BOM in: $file";done

It doesn't work with filenames that contain a line break, but such files are not to be expected anyway.

Is there any shorter or more elegant solution?

Are there any interesting text editors or macros for text editors?

  • If you accept some false positives (in case there are non-text files, or in the unlikely case there is a ZWNBSP in the middle of a file), you can use grep:

    fgrep -rl `echo -ne '\xef\xbb\xbf'` .
    
    From CesarB
  • find -type f -print0 | xargs -0 grep -l `printf '^\xef\xbb\xbf'` | sed 's/^/found BOM in: /'
    
    • find -print0 puts a null \0 between each file name instead of using new lines
    • xargs -0 expects null separated arguments instead of line separated
    • grep -l lists the files which match the regex
    • The regex ^\xeff\xbb\xbf isn't entirely correct, as it will match non-BOMed UTF-8 files if they have zero width spaces at the start of a line
    MSalters : You still need a "head 1" in the pipe before the grep
  • I would use something like:

    grep -orHbm1 "^`echo -ne '\xef\xbb\xbf'`" . | sed '/:0:/!d;s/:0:.*//'
    

    Which will ensure that the BOM occurs starting at the first byte of the file.

  • What about this one simple command which not just finds but clears nasty BOM? :)

    find . -type f -exec sed 's/^\xEF\xBB\xBF//' -i.bak {} \; -exec rm {}.bak \;
    

    I love "find" :)

    If you want just to show BOM files, use this one:

    grep -rl $'\xEF\xBB\xBF' .
    
    From Denis
  • find . -type f -print0 | xargs -0r awk '
        /^\xEF\xBB\xBF/ {print FILENAME}
        {nextfile}'
    

    Most of the solutions given above test more than the first line of the file, even if some (such as Marcus's solution) then filter the results. This solution only tests the first line of each file so it should be a bit quicker.

    From

External dependencies / Header files

In a windows MSVC6.0 compiler, if there is a workspace with one project in it, what files would be in the Header Files folder and what files would be in the External Dependencies folder?

I thought those files which are explicitly included (#include <*.h> are to be in the Header Files folder and thsoe which are in turn included by added header files, will be in External Dependencies folder? But doesnt seem to be case.

So what is the difference between the two?

-AD

  • After looking at the structure of header files and #include *.h in the workspace i found following:

    1.) Those files which are not explicitly added to the Projects Header Files folder, but are nonetheless included using the #include directive, by different header and source files, are added to the project automatically by MSVC under the folder External Dependencies

    But now i have a question, is it better to let MSVC add those header files as External Dependencies or is it better to add it explicitly in the Header Files folder, or is there no difference in the two?

    -AD

    From goldenmean
  • The folders in the tree view are purely for your convenience (at least in vs200x - I don' remember ever changing hem in vc6).
    You can rename them to anything you want and put any files in any folder you want. I generally create folders based on the parts of the program (ie gui, server, fileIO ) and put the header and cpp files for classes in the same folder so I can quickly find the definition and declaration.

  • Header files listed as external dependencies are not analysed and available in the class view tab. Moving a file from external dependencies to header files includes it into the class view.

How do I capture the audio that is being played?

Does anyone know how to programmatically capture the sound that is being played (that is, everything that is coming from the sound card, not the input devices such as a microphone).

  • You can use the Waveform Audio Interface, there is an MSDN article on how to access it per PInvoke.

    In order to capture the sound that is being played, you just need to open the playback device instead of the microphone. Open for input, of course, not for output ;-)

    From Treb
  • Assuming that you are talking about Windows, there are essentially three ways to do this.

    The first is to open the audio device's main output as a recording source. This is only possible when the driver supports it, although most do these days. Common names for the virtual device are "What You Hear" or "Wave Out". You will need to use a suitable API (see WaveIn or DirectSound in MSDN) to do the capturing.

    The second way is to write a filter driver that can intercept the audio stream before it reaches the physical device. Again, this technique will only work for devices that have a suitable driver topology and it's certainly not for the faint-hearted.

    This means that neither of these options will be guaranteed to work on a PC with arbitrary hardware.

    The last alternative is to use a virtual audio device, such as Virtual Audio Cable. If this device is set as the defualt playback device in Windows then all well-behaved apps will play through it. You can then record from the same device to capture the summed output. As long as you have control over the device that the application you want to record uses then this option will always work.

    All of these techniques have their pros and cons - it's up to you to decide which would be the most suitable for your needs.

  • Hi, I need this capability as well but can't seem to do it using the methods suggested. Using waveIn does not let me open anything but my real microphone input. I don't understand - how can I open the playback device for input?

  • If you were using OSX, Audio Hijack Pro from Rogue Amoeba probably is the easiest way to go.

    Anyway, why not just looping your audio back into your line in and recording that? This is a very simple solution. Just plug a cable in your audio output jack and your line in jack and start recordung.

  • You have to enable device stero mix. if you do this, direct sound find this device.