Monday, February 7, 2011

__doPostBack is not working in firefox

The __doPostBack is not working in firefox 3 (have not checked 2). Everything is working great in IE 6&7 and it even works in Chrome??

It's a simple asp:LinkButton with an OnClick event

<asp:LinkButton ID="DeleteAllPicturesLinkButton" Enabled="False" OnClientClick="javascript:return confirm('Are you sure you want to delete all pictures? \n This action cannot be undone.');" OnClick="DeletePictureLinkButton_Click" CommandName="DeleteAll" CssClass="button" runat="server">

The javascript confirm is firing so I know the javascript is working, it's specirically the __doPostBack event. There is a lot more going on on the page, just didn't know if it's work it to post the entire page.

I enable the control on the page load event.

Any ideas?


I hope this is the correct way to do this, but I found the answer. I figured I'd put it up here rather then in a stackoverflow "answer"

Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.

Hope this helps if anyone else has the same problem. I still don't know what specifically was causing the problem, but that was the solution for me.

  • Is it because you are doing return confirm? seems like the return statement should prevent the rest of the code from firing. i would think an if statement would work

    if (!confirm(...)) { return false; } _doPostBack(...);
    

    Can you post all the js code in the OnClick of the link?

    EDIT: aha, forgot that link button emits code like this

    <a href="javascript:__doPostBack()" onclick="return confirm()" />
    
  • With or without the OnClientClick event it still doesn't work.

    The _doPostBack event is the auto generated javascript that .NET produces.

    function __doPostBack(eventTarget, eventArgument) {
    
        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
    
            theForm.__EVENTTARGET.value = eventTarget;
    
            theForm.__EVENTARGUMENT.value = eventArgument;
    
            theForm.submit();
    
        }
    
    }
    

    *The &95; are underscores, seems to be a problem with the stackoverflow code block format.

    Darren Kopp : no i mean post the
  • this might seem elemental, but did you verify that your firefox settings aren't set to interfere with the postback? Sometimes I encounter similar problems due to a odd browser configuration I had from a debugging session.

    From Paulj
  • Now that i think about it, as noted in my last edit, you want to drop the javascript: in the on client click property. It's not needed, because the onclick event is javascript as it is. try that, see if that works.

  • Are you handling the PageLoad event? If so, try the following

    if (!isPostBack)
    {
        //do something
    }
    else if (Request.Form["__EVENTTARGET"].ToLower().IndexOf("myevent") >= 0)
    {
        //call appropriate function.
    }
    

    Check if you are getting a call this way, if so then maybe the event is not wired and nedes to be explicitly called.

    From moza
  • what do you expect from "Enabled = 'false'" ?

    From Jimmy
  • I have had problems with firebug on some web forms, something to do with the network analyser can screw with postbacks.

    From seanb
  • Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.

    Hope this helps if anyone else has the same problem.

  • Check your User Agent string. This same thing happened to me one time and I realized it was because I was testing out some pages as "googlebot". The JavaScript that is generated depends on knowing what the user agent is.

    From http://support.mozilla.com/tiki-view_forum_thread.php?locale=tr&comments_parentId=160492&forumId=1:

    To reset your user agent string type about:config into the location bar and press enter. This brings up a list of preferences. Enter general.useragent into the filter box, this should show a few preferences (probably 4 of them). If any have the status user set, right-click on the preference and choose Reset

    From Terrapin
  • I had this exact same issue in a web app I was working on, and I tried solving it for hours.

    Eventually, I did a NEW webform, dropped a linkbutton in it, and it worked perfectly!

    I then noticed the following issue:

    ...

    I switch the order to the following, and it immediately was fixed: ...

    IE had no issue either way (that I noticed anyway).

    From pearcewg
  • I had this same problem (__doPostBack not working) in Firefox- caused a solid hour of wasted time. The problem turned out to be the HTML. If you use HTML like this:

    <input type="button" id="yourButton" onclick="doSomethingThenPostBack();" value="Post" />
    

    Where "doSomethingThenPostBack" is just a JavaScript method that calls doPostBack, the form *will not*** post in Firefox. It will PostBack in IE and Chrome. To solve the problem, make sure your HTML is:

    <input type="submit" id="yourButton" ...
    

    The key is the type attribute. It must be "submit" in Firefox for __doPostBack to work. Other browsers don't seem to care. Hope this helps anyone else who hits this problem.

    From Todd
  • Thanks to Todd, for me it was the 'type' value being set to 'button' instead of 'submit' that was the problem. Typical SharePoint code!

    From Andrew
  • I had a similar issue. It turned out that Akamai was modifying the user-agent string because an setting was being applied that was not needed.

    This meant that some .NET controls did not render __doPostBack code properly. This issue has been blogged here.

  • @Terrapin: you got this exactly right (for me, anyways).

    I was running User Agent Switcher and had inadvertently left the Googlebot 2.1 agent selected.

    In Reporting Services 2008 it was causing the iframes that reports are actually rendered in to be about 300x200 px, and in Reporting Services 2008 R2 is was throwing "__doPostBack undefined" errors in the Error Console.

    Switching back to the Default User Agent fixed all my issues.

Excel - Macro to conditionally copy rows to another worksheet

Does anyone have a macro or could point me to a way that I could conditionally copy rows from one worksheet to another in Excel 2003.

I'm pulling a list of data from Sharepoint via web query into a blank worksheet in Excel, and then I want to copy the rows for a particular month to a particular worksheet (e.g., all July data from Sharepoint worksheet to the Jul worksheet, all June data from Sharepoint worksheet to Jun worksheet, etc.).

Sample data -
Date - Project - ID - Engineer
8/2/08 - XYZ - T0908-5555 - JS
9/4/08 - ABC - T0908-6666 - DF
9/5/08 - ZZZ - T0908-7777 - TS

  • If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?

    From RickL
  • This is partially pseudocode, but you will want something like:

    rows = ActiveSheet.UsedRange.Rows
    n = 0

    while n <= rows
    if ActiveSheet.Rows(n).Cells(DateColumnOrdinal).Value > '8/1/08' AND < '8/30/08' then
    ActiveSheet.Rows(n).CopyTo(DestinationSheet)
    endif
    n = n + 1
    wend

    From BKimmel
  • This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.

    You may want to add logic to sort your monthly data after it's all been copied

    Public Sub MoveData(MonthNumber As Integer, SheetName As String)
    
    Dim sharePoint As Worksheet
    Dim Month As Worksheet
    Dim spRange As Range
    Dim cell As Range
    
    Set sharePoint = Sheets("Sharepoint")
    Set Month = Sheets(SheetName)
    Set spRange = sharePoint.Range("A2")
    Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address)
    For Each cell In spRange
        If Format(cell.Value, "MM") = MonthNumber Then
            copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month
        End If
    Next cell
    
    End Sub
    
    Sub copyRowTo(rng As Range, ws As Worksheet)
        Dim newRange As Range
        Set newRange = ws.Range("A1")
        If newRange.Offset(1).Value <> "" Then
            Set newRange = newRange.End(xlDown).Offset(1)
            Else
            Set newRange = newRange.Offset(1)
        End If
        rng.Copy
        newRange.PasteSpecial (xlPasteAll)
    End Sub
    
    From theo
  • Thanks Theo - I'll have to give that a try.

    Unfortunately, it's not a one off exercise. I'm trying to put together a dashboard that my boss can pull the latest data from Sharepoint and see the monthly results, so it needs to be able to do it all the time and organize it cleanly.

    theo : No problem: Email me if you need a hand with it: theogeer@gmail.com
  • Here's another solution that uses some of VBA's built in date functions and stores all the date data in an array for comparison, which may give better performance if you get a lot of data:

    Public Sub MoveData(MonthNum As Integer, FromSheet As Worksheet, ToSheet As Worksheet)
        Const DateCol = "A" 'column where dates are store
        Const DestCol = "A" 'destination column where dates are stored. We use this column to find the last populated row in ToSheet
        Const FirstRow = 2 'first row where date data is stored
        'Copy range of values to Dates array
        Dates = FromSheet.Range(DateCol & CStr(FirstRow) & ":" & DateCol & CStr(FromSheet.Range(DateCol & CStr(FromSheet.Rows.Count)).End(xlUp).Row)).Value
        Dim i As Integer
        For i = LBound(Dates) To UBound(Dates)
            If IsDate(Dates(i, 1)) Then
                If Month(CDate(Dates(i, 1))) = MonthNum Then
                    Dim CurrRow As Long
                    'get the current row number in the worksheet
                    CurrRow = FirstRow + i - 1
                    Dim DestRow As Long
                    'get the destination row
                    DestRow = ToSheet.Range(DestCol & CStr(ToSheet.Rows.Count)).End(xlUp).Row + 1
                    'copy row CurrRow in FromSheet to row DestRow in ToSheet
                    FromSheet.Range(CStr(CurrRow) & ":" & CStr(CurrRow)).Copy ToSheet.Range(DestCol & CStr(DestRow))
                End If
            End If
        Next i
    End Sub
    
  • The way I would do this manually is:

    • Use Data - AutoFilter
    • Apply a custom filter based on a date range
    • Copy the filtered data to the relevant month sheet
    • Repeat for every month

    Listed below is code to do this process via VBA.

    It has the advantage of handling monthly sections of data rather than individual rows. Which can result in quicker processing for larger sets of data.

        Sub SeperateData()
    
        Dim vMonthText As Variant
        Dim ExcelLastCell As Range
        Dim intMonth As Integer
    
       vMonthText = Array("January", "February", "March", "April", "May", _
     "June", "July", "August", "September", "October", "November", "December")
    
            ThisWorkbook.Worksheets("Sharepoint").Select
            Range("A1").Select
    
        RowCount = ThisWorkbook.Worksheets("Sharepoint").UsedRange.Rows.Count
    'Forces excel to determine the last cell, Usually only done on save
        Set ExcelLastCell = ThisWorkbook.Worksheets("Sharepoint"). _
         Cells.SpecialCells(xlLastCell)
    'Determines the last cell with data in it
    
    
            Selection.EntireColumn.Insert
            Range("A1").FormulaR1C1 = "Month No."
            Range("A2").FormulaR1C1 = "=MONTH(RC[1])"
            Range("A2").Select
            Selection.Copy
            Range("A3:A" & ExcelLastCell.Row).Select
            ActiveSheet.Paste
            Application.CutCopyMode = False
            Calculate
        'Insert a helper column to determine the month number for the date
    
            For intMonth = 1 To 12
                Range("A1").CurrentRegion.Select
                Selection.AutoFilter Field:=1, Criteria1:="" & intMonth
                Selection.Copy
                ThisWorkbook.Worksheets("" & vMonthText(intMonth - 1)).Select
                Range("A1").Select
                ActiveSheet.Paste
                Columns("A:A").Delete Shift:=xlToLeft
                Cells.Select
                Cells.EntireColumn.AutoFit
                Range("A1").Select
                ThisWorkbook.Worksheets("Sharepoint").Select
                Range("A1").Select
                Application.CutCopyMode = False
            Next intMonth
        'Filter the data to a particular month
        'Convert the month number to text
        'Copy the filtered data to the month sheet
        'Delete the helper column
        'Repeat for each month
    
            Selection.AutoFilter
            Columns("A:A").Delete Shift:=xlToLeft
     'Get rid of the auto-filter and delete the helper column
    
        End Sub
    
  • Hello i am having some issue when am using two criterias,Can you please send me example VBscript with two or more criteria or for below example.

    In the below example I need to auto filter by 4 criteria’s

    From the main sheet I need to extract in the following way.

    1)steps one I need to extract only Active users = Testing into new sheet 1 Active users = Developer into new sheet 2 Active users = Integration into new sheet 3 Active users = all ..except (Testing,Developing,Integration) new sheet 4

    Column H we have Active & terminated and column G we have teams(testing,Intgration etc).

    From shankar85m

What's the best way to get the default printer in .NET

I need to get the default printer name. I'll be using C# but I suspect this is more of a framework question and isn't language specific.

  • The easiest way I found is to create a new PrinterSettings object. It starts with all default values, so you can check its Name property to get the name of the default printer.

    PrinterSettings is in System.Drawing.dll in the namespace System.Drawing.Printing.

    PrinterSettings settings = new PrinterSettings();
    Console.WriteLine(settings.PrinterName);

    Alternatively, you could maybe use the static PrinterSettings.InstalledPrinters method to get a list of all printer names, then set the PrinterName property and check the IsDefaultPrinter. I haven't tried this, but the documentation seems to suggest it won't work. Apparently IsDefaultPrinter is only true when PrinterName is not explicitly set.

    From OwenP
  • Another approach is using WMI (you'll need to add a reference to the System.Management assembly):

    public static string GetDefaultPrinterName()
    {
        var query = new ObjectQuery("SELECT * FROM Win32_Printer");
        var searcher = new ManagementObjectSearcher(query);
    
        foreach (ManagementObject mo in searcher.Get())
        {
            if (((bool?) mo["Default"]) ?? false)
            {
                return mo["Name"] as string;
            }
        }
    
        return null;
    }
    
  • What's the advantage of using WMI vs the PrinterSettings object?

    From Kevin Gale
  • If you just want the printer name no advantage at all. But WMI is capable of returning a whole bunch of other printer properties:

    using System;
    using System.Management;
    namespace Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                ObjectQuery query = new ObjectQuery(
                    "Select * From Win32_Printer " +
                    "Where Default = True");
    
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher(query);
    
                foreach (ManagementObject mo in searcher.Get())
                {
                    Console.WriteLine(mo["Name"] + "\n");
    
                    foreach (PropertyData p in mo.Properties)
                    {
                        Console.WriteLine(p.Name );
                    }
                }
            }
        }
    }
    

    and not just printers. If you are interested in any kind of computer related data, chances are you can get it with WMI. WQL (the WMI version of SQL) is also one of its advantages.

  • 1st create an instance of the printdialog object. then Call the print dialog object and leave the printername blank. this will cause the windows object to return the defualt printer name, write this to a string and use it as the printer name when you call the print procedure

    Try

            Dim _printDialog As New System.Windows.Forms.PrintDialog
    
            xPrinterName = _printDialog.PrinterSettings.PrinterName '= "set as Default printer"
    
        Catch ex As Exception
            System.Windows.Forms.MessageBox.Show("could not printed Label.", "Print Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    

In ASP.net Webforms how do you detect which Textbox someone pressed enter?

In ASP.net Webforms how do you detect which Textbox someone pressed enter?

Please no Javascript answers.

I need to handle it all in the code behind using VB.NET.

  • I suspect it cannot be done without javascript - when you hit enter, the browser submits the form - it doesn't submit what field had the focus. So unless you use JS to add that information to the form being submitted, you're out of luck.

    From zigdon
  • Without using Javascript, you just can't. That information is not conveyed from the client browser to the server.

  • As far as I know there is no possible way for a server side script to detect that. It simply does not get sent to the server. It must be done client-side (i.e. With Javascript) and then sent to the server.

  • Why do you need to determine the which TextBox was pressed? Are you looking to see which TextBox was being focused so that you can trigger the proper button click event?

    If you are looking to do something like this, one trick I've done was to "group" the appropriate form elements within their own panel and then set the "DefaultButton" property accordingly.

    Doing this allows me to have a "Search by Name", "Search by Department", "Search by Id", etc. Textbox/Button combination on a single form and still allow the user to type their query parameter, hit Enter, and have the proper search method get invoked in the code behind.

    Brian Boatright : problem is I have three fields and two buttons. username/password, and search. each needs separate validation and the default action should be intuitive. i've spent a lot of time today on this and I can't believe how hard this is to do using WebForms...
    From Dillie-O
  • I solved this for one site's search by looking at the Request.Form object, server side to see if the search box had a value. I did it in a base class that all my pages (or a base class for the masterpage) inherit from. If it has a value, the odds are pretty good somebody typed something in and hit enter and so I handled the search.

    Brian Boatright : Yea. That's what I'm doing but now the validation for the username/password is being launched by the search button as well. I'm using ValidationGroup but it's not working.
  • In the event handler, the "source" object (the first parameter of the event handler) is the object raising the event. Type it to button and get the name, or use reflection to get information out of the non-typed object.

    In addition, if the control is a child of a web control that you do not have raise its own events (just saying...) then you can use OnBubbleEvent to determine what's going on. OnBubbleEvent also has a "source" parameter you can type, or use reflection on.

    From nathaniel

In Delphi, how can you have currency data types shown in different currencies in different forms?

I need to write a Delphi application that pulls entries up from various tables in a database, and different entries will be in different currencies. Thus, I need to show a different number of decimal places and a different currency character for every Currency data type ($, Pounds, Euros, etc) depending on the currency of the item I've loaded.

Is there a way to change the currency almost-globally, that is, for all Currency data shown in a form?

  • I'd use SysUtils.CurrToStr(Value: Currency; var FormatSettings: TFormatSettings): string;

    I'd setup an array of TFormatSettings, each position configured to reflect each currency your application supports. You'll need to set the following fields of the TFormat Settings for each array position: CurrencyString, CurrencyFormat, NegCurrFormat, ThousandSeparator, DecimalSeparator and CurrencyDecimals.

    From
  • Even with the same currency, you may have to display values with a different format (separators for instance), so I would recommend that you associate a LOCALE instead of the currency only with your values.
    You can use a simple Integer to hold the LCID (locale ID).
    See the list here: http://msdn.microsoft.com/en-us/library/0h88fahh.aspx

    Then to display the values, use something like:

    function CurrFormatFromLCID(const AValue: Currency; const LCID: Integer = LOCALE_SYSTEM_DEFAULT): string;
    var
      AFormatSettings: TFormatSettings;
    begin
      GetLocaleFormatSettings(LCID, AFormatSettings);
      Result := CurrToStrF(AValue, ffCurrency, AFormatSettings.CurrencyDecimals, AFormatSettings);
    end;
    
    function USCurrFormat(const AValue: Currency): string;
    begin
      Result := CurrFormatFromLCID(AValue, 1033); //1033 = US_LCID
    end;
    
    function FrenchCurrFormat(const AValue: Currency): string;
    begin
      Result := CurrFormatFromLCID(AValue, 1036); //1036 = French_LCID
    end;
    
    procedure TestIt;
    var
      val: Currency;
    begin
      val:=1234.56;
      ShowMessage('US: ' + USCurrFormat(val));
      ShowMessage('FR: ' + FrenchCurrFormat(val));
      ShowMessage('GB: ' + CurrFormatFromLCID(val, 2057)); // 2057 = GB_LCID
      ShowMessage('def: ' + CurrFormatFromLCID(val));
    end;
    

What's the best way for a developer to start his/her own business?

I'm a developer who is interested in entrepreneurship, but also loves building good software. What would be the best avenue for me to own my own business? Would a service-based model work better, or should I go the ISV route and try to build a business around a product?

Also, if you have started your own business, have you been successful, and would you recommend it to others? Or is the industry such that it's better to remain employed by a decent company?

  • I can't claim to know "the best" way, but the below book gave me many insights into how to get started,

    http://www.amazon.com/Micro-ISV-Vision-Reality-Bob-Walsh/dp/1590596013

    From Nescio
  • If you love building good software then don't go the service route -- unless you're exceptionally lucky to find clients who really do care about good software, as opposed to how quickly can you get something/anything working.

    Of course, the downside to building a business around a product, is the requirement to have a product first. Unless you're independently wealthy, I'd try the build a demo in your spare time route, and try to pitch to get initial investment once it does something remotely impressive.

  • Often, the difficult thing is finding a valuable problem to solve. A problem that people will be happy to pay money to have solved. And then, validating that this problem can be solved with software. You can also find a problem that is caused by software.

    In the first case, you're likely looking at writing a product. In the other case, you are probably looking at offering a service.

    One thing that going into business taught me is that starting a new business is not the best way to get into a mode where you will write "good" software. At least, not all the time. If you become an entrepreneur, you will have to make compromises. And often, this means that you will have to make sacrifices with your architecture or design. You can still deliver a quality product or a good service. But when you are an entrepreneur, getting there is usually more important than taking the high road.

  • There's a great Hanselminutes podcast and blog post series by Leon "SecretGeek" Bambrick that are all about how to set yourself up as a "micro ISV", a small 1-2 man shop. Bambrick steps through an ordered list of steps, which he used to develop and market his product "TimeSnapper".

  • A point Joel Spolsky made in one of the Stack Overflow podcasts is that if you sell your time, then your income is proportional to how much time you have, and growth is limited. In contrast, if you develop products, your income is proportional to how many people want to buy them. So, products is where the big money is, assuming you can make something people will buy.

    Clay Nichols : "The problem with selling your time is that you're always running out of inventory"
  • Of course it depends what you're good at, what you want to spend your time doing, etc. but I found it very easy to start a consulting business by slowly taking on more and more side work until I could not keep up with it and my day job, so I quit my day job. The biggest advantage of this approach is obviously that you are never without income. The disadvantage is that you will be stretched thin in the last days while you are working a full time job and also building your business, but it's hard to start any kind of business without working very hard in the beginning.

    Having done this, I think the best advice I can give is that you should hire other people to do anything you have to do that you aren't good at (accounting, filing, marketing, sales, etc) right away and stay focused on the things you are good at (presumably writing code, etc).

    Wedge : Could you give more details on how you started consulting? What skills you found most important. What you'd do different starting out if you had the chance. How you find work. That sort of thing.
    Brian Sullivan : Agree with previous comment. How did you find side work? Was it thru a staffing company? Did you already have some kind of network of contacts that you could get business from?
    Scott : Chamber of Commerce is a GREAT place to start finding work. There is a lot of work there.
    From John
  • I'm currently working through eWork, as an independent consultant. I've tried other approaches earlier and I have to say this concept is best for me, in the current situation.

    It's like an agent. They hunt jobs for you (and others) and take care of the legal details. They interface to the customer, and you. Your job remains to just Do the Work.

    This concept has blossomed in Nordic countries in the last couple of years. I would think there's something similar in the States/UK/central Europe as well, is there?

    The problem with going completely solo is to get the reputation (for good payment) and to get to the big companies (normally they have contracts with other companies, and you would be left out). Here the agent takes you in.

    If you like product-based instead, iPhone/iPod apps seems to be booming, eh? :D

    From akauppi
  • I agree with Richard, although I did a combination of both. Initially, I linked with a client and went the 'service' route. The main thing was how quickly can you get the features in and bugs out - not much weight was given to the overall UI design nor anyone cared about the architecture of codebase (some of the features were one-off anyway). After I established enough financial backup from 'service' mode, I was able to dedicate significant chunk of my time to some good quality software - ISV style. Something built for the masses, nicely packed, etc. To show I'm not just talking from the top of my head, you can go to www.guacosoft.com and judge yourself. I'll just say that it does sell fine.

    However, after 2 mostly successful applications being sold online, and after about of year doing it, I still make much more from this 'service' deal. It all depends on the products you can create: if you can create a lot of small niche apps, or a few quality killer-apps, than you can be successful. Otherwise, it's just 'candy money', you can't really make a living out of it.

    Now, to determine whether you can do it, better ask your friends than evaluate yourself. Lay out some ideas for the applications you would make, write down what would make them stand out from other apps. of that type that are already available, and present that to some other people. Make sure to tell them they can tell you whatever they really think (it's hard to jugde someone's idea bad if you see they are really enthusiastic about it).

    Well, just my $0.02

  • A mix I would say... create software for clients in freelance mode is a good way to gather some money, pay the bills etc..

    But in the long time you'll like to have something that works for you while you sleep. You can always invest your money in a high interest fund or even consider real estate. that would put your money to work.

    I tell you this because as developers we usually miss the big picture and forgot that there are other ways of winning money.

    The more exciting of course is programming, I would suggest services(services as a page where your users subscribe for a monthly fee, not selling your time in Freelance mode) over products. even a product need to be sell one and again, and you'll end up spending more time looking for costumers than programming.

    In a service, as long as they are satisfied, the clients just keep paying the monthly fee.

    You of course must be alert all the time to go ahead of their necessities and programming new things all the time (you don't want to play the Hare in the Turtle and the Hare tale).

    But that's just me, a friend of mine pay his university selling a Point Of Sale he made in a local commercial area.

    From levhita
  • I would recommend reading Paul Grahams's How to Start a Startup.

    Speaking from experience, don't quit your day job and rush into setting up your own ISV. Its better to build a business/product slowly either doing it in your spare time, or building something your clients need (if you run a services-based company).

    Scott : Gotta love Paul Grahams writings if your into being a entrepreneur.
    From andyuk
  • Look at the book Getting Real by 37signals if you decide to take the Web Application with a monthly fee route.

    From levhita
  • Here are my views based off many years of doing my own stuff, some good and some bad :)

    1. You need to understand that there are two sides to your business. One side is the actual business as in accounting, invoicing, markets etc the boring stuff and the other is actually doing what you love like writing code. Most of us aren't good at both.

    2. You don't have to build something new, it is a perfectly valid business model to just copy somebody successful and take some market share. Ok you may be be original but at least you know the idea sells.

    3. The more streams of revenue you can create the better off you'll be.

    It is hard work without fail! I sometimes work a 12 hour day and then work 4 more hours on my own projects every day ... what is a weekend? ;) When you're your own boss there is no weekend ...

    Good luck.

  • The Internet has made it much easier for small software companies to reach large markets for a low cost. I have successfully built a one-man software product business ('microISV') over the last 3 years. It is hard work, but very rewarding.

    Things to bear in mind:

    • Venture capital comes with all sorts of strings attached and it isn't the only way. If you have savings (or are prepared to work in your spare time) you can grow a software product business organically with minimal investment of money and a large investment of time.

    • There are over a billion people on the Internet. Even fairly obscure markets may be big enough to support several small companies. You don't have to be the next SAP/Google/Microsoft.

    • If your product has no competitors, either you are a genius or there is no market. Unfortunately, it is almost certainly the latter.

    • The software is only part of the equation. You need a good product AND good marketing AND good support. If you aren't prepared to get serious about marketing (or partner with someone else who is) stay with the day job.

    • Your initial idea is almost certainly wrong. Cut the feature set to get version 1.0 out within 6 months and iterate like crazy from there based on customer feedback.

    • Don't expect to get rich quick.

    Some blog posts I wrote that may be of interest to would-be software entrepreneurs:

    Selling your own software Vs working for the man

    Radical new software business model

    If you aren't embarassed by v1.0, you didn't release it early enough

    10 questions to ask before you write a single line of code

    How much money will my software make and what has that got to do with aliens

    icelava : "either you are a genius or there is no market" - Blue Ocean Strategy - create your own viable sustainable market without the bloody competition.
    Andy Brice : Creating a new market can be very expensive. Even if you do manage it you will have competition soon enough.
    From Andy Brice
  • One point that has been missing from the other answers is to address what happens if you want to not only start a business, but want to switch careers in the process.

    For example, a friend of mine left a career in IT to start a gun-refinishing and manufacturing company.

    While I'm not suggesting you do that, per se (after all, then he'd have more competitors ;)), don't discard the thought of changing your career in the process. Maybe you have a real itch to do something "physical", like farming or plumbing. Maybe you don't.

    But don't reject off-hand switching what you do if/when you decide to start a company.

    From warren
  • I would recommend service. The danger in the product is that there are always bigger competitors, which could wipe you out of the markets in days not because you are a bad software writer ( have bad product ) , but simply because they have the nxyou amount of resource to compete against you.

    Service could be changed.

    My personal advices for business overall. The people you deal with are the most important. If you estimate that something will cost 100 in reality it will cost you 120, with time it is double fold increase.

Ways to avoid eager spool operations on SQL Server

I have an ETL process that involves a stored procedure that makes heavy use of SELECT INTO statements (minimally logged and therefore faster as they generate less log traffic). Of the batch of work that takes place in one particular stored the stored procedure several of the most expensive operations are eager spools that appear to just buffer the query results and then copy them into the table just being made.

The MSDN documentation on eager spools is quite sparse - does anyone have a deeper insight into whether these are really necessary (and under what circumstances). I have a few theories that may or may not make sense, but no success in eliminating these from the queries.

The .sqlplan files are quite large (160kb) so I guess it's probably not reasonable to post them directly to a forum.

So, here are some theories that may be amenable to specific answers:

o The query uses some UDF's for data transformation, such as parsing formatted dates. Does this data transformation necessitate the use of eager spools to allocate sensible types (e.g. varchar lengths) to the table before it constructs it?

o As an extension of the question above, does anyone have a deeper view of what does or does not drive this operation in a query?

Nigel

  • My understanding of spooling is that it's a bit of a red herring on your execution plan. Yes, it accounts for a lot of your query cost, but it's actually an optimization that SQL Server undertakes automatically so that it can avoid costly rescanning. If you were to avoid spooling, the cost of the execution tree it sits on will go up and almost certainly the cost of the whole query would increase. I don't have any particular insight into what in particular might cause the database's query optimizer to parse the execution that way, especially without seeing the SQL code, but you're probably better off trusting its behavior.
    However, that doesn't mean your execution plan can't be optimized, depending on exactly what you're up to and how volatile your source data is. When you're doing a SELECT INTO, you'll often see spooling items on your execution plan, and it can be related to read isolation. If it's appropriate for your particular situation, you might try just lowering the transaction isolation level to something less costly, and/or using the NOLOCK hint. I've found in complicated performance-critical queries that NOLOCK, if safe and appropriate for your data, can vastly increase the speed of query execution even when there doesn't seem to be any reason it should.
    In this situation, if you try READ UNCOMMITTED or the NOLOCK hint, you may be able to eliminate some of the Spools.
    (Obviously you don't want to do this if it's likely to land you in an inconsistent state, but everyone's data isolation requirements are different)
    The TOP operator and the OR operator can occasionally cause spooling, but I doubt you're doing any of those in an ETL process...
    You're right in saying that your UDFs could also be the culprit. If you're only using each UDF once, it would be an interesting experiment to try putting them inline to see if you get a large performance benefit. (And if you can't figure out a way to write them inline with the query, that's probably why they might be causing spooling)
    One last thing I would look at is that, if you're doing any joins that can be re-ordered, try using a hint to force the JOIN order to happen in what you know to be the most selective order. That's a bit of a reach but it doesn't hurt to try it if you're already stuck optimizing.

    ConcernedOfTunbridgeWells : Read isolation may well be applicable as the process queries from a staging area copied from the source. Additionally, even if this does not fix my particular issue it adds a bit of insight as this is not mentioned in any of the MSDN literature that I could find concerning eager spool operations.
    Grank : I'm glad it was some help. We might be able to help you further if you posted the SQL code in question (genericized if necessary of course)
    From Grank

GUID Behind the Scenes

I am wondering, what goes into the creation of a GUID. I don't mean what is used to create a GUID in a specific language (NewID() in SQL, new GUID() in C#), I mean when you call those methods/functions, what do they do to make the GUID?

  • The details of GUIDs, including the algorithm used to generate them is described on wikipedia.

    From Rob Walker
  • Hash function. Its complicated.

    http://en.wikipedia.org/wiki/GUID#Algorithm Knows more than I do.

  • Are you looking for something more than Wikipedia?

    From Karg
  • Also, RFC 4122 (which is referenced in the Wikipedia article) describes how GUIDs should be built.

  • Raymond Chen has a great explanation of how they work

    EBGreen : That is a good article, but it is versio 1 of GUID creation which no one should be using anymore.
  • A word of caution that a very great deal of what you read on the Internet about GUID creation may well be wrong, or at least out of date for your specific platform.

    I once single-stepped through a heap of Windows code to settle an argument about GUID creation on WinXP. Unfortunately, it turned out that I was wrong (i.e. I lost the argument), but so was Larry Osterman, so I felt slightly better about it.

    From Will Dean
  • In short, it's not complicated at all. GUID (or UUID) Version 4 (current) is a partially random number, plain and simple (122 out of 128 bits are random, the rest are used for storing version and revision). The trick is that the possible values of this number are so many that the probability of a hit is for most practical purposes, zero.

    EBGreen : I would say that it is a partially random number. Some parts of it are not random at all.
    From Sklivvz

Does K.I.S.S play a role in your development, if so, do you prosper from it?

In my programming life I work with the principle "K.I.S.S." - keep it simple stupid. This works out pretty well for me although the projects and tasks get even more complicated (at least for me in my project life). Do you use this principle? Why? Why not? Do you prosper from kiss or do you think this is impossible?

  • Yes, it plays a major role. We do Test-Driven Development here, so we write the tests for only what the requirements state. That way we only write code that we need, that is executed.

    Beyond that, we all strive to keep things simple in general; complications lead to errors. We prefer to write less code to solve the problem (this doesn't mean using as many hacks to get fewer lines of code). Sometimes we have to do difficult and complicated things, but we try to encapsulate the yuckiness into its own class.

    And the "stupid" part is to remind us all that we're not as good as we think we are :)

    The net result is that most bugs are mostly simple to debug.

    From Ed Schwehm
  • I constantly strive for simple solutions, and often refactor code with the expressed intent of simplifying it typically prior to adding new features. Simple is easier to test, and usually there is less of it. Less effort means quicker turn-around.

    /Allan

    From Allan Wind
  • A good implementation of K.I.S.S is not to use more than 3 levels of nesting.

    Generally that's about where people start getting confused, and you should probably try put a function in instead.

    Tasks and projects on the other hand will always get complicated. Just using K.I.S.S. for the programming side of things will make your life easier.

    ( You may have to write the same code 3 times to get it simple enough and good enough however )

  • Yes. "Cleverness" is not generally approved of in our team. We try to be "clever enough" but no more clever.

    Code which tries to be "clever" generally only achieves:

    • Unmaintainability, because it's cleverer than its author
    • Failure in edge cases, because it's not QUITE clever enough

    For example, rather than setting database network permissions automatically in the database setup component installer, it is left to the operations team to do manually (albeit by running a script they keep under source control), because the code to do it automatically would be slightly too clever. It would work perfectly until someone changed the IP address numbering scheme or something.

    From MarkR
  • Yes, KISS is key (not the band ;)

    from the Zen Of Python: http://www.python.org/dev/peps/pep-0020/

    Beautiful is better than ugly.
    Simple is better than complex.

  • Keeping everything simple, is actually a lot more complex than the alternative of introducing complexity when it is required.

    The opposing extremes are actually more similar than first glance -- you'll know of coders who get nothing done trying to simplify everything, and other coders who get nothing done trying to make it as complex as they can.

  • The K.I.S.S. is very important in my eyes. Simple and small functions are easy to read and to understand and tend to be less error-prone.

    But I also saw code, where some one used nested ternary conditionals instead of if-then-else statements, which might be hard to read in some cases. Before the code starts to get unclear, I prefer to spend some "extra" lines of code. Even simple line breaks might help to make the code easier to understand.

    From koschi
  • The main way in which I strive to keep things simple is to assure that functions fit on one screen in the IDE. This is a novel approach at my current gig, but it is bleeding out into the rest of my team and I have gotten comments from other developers noting that they prefer to debug my code than their own.

    From clweeks
  • KISS plays THE role. Sometimes I feel like I'm fighting an uphill battle to keep things simple, but it sure is better than the alternative.

  • Everything can benefit from the KISS methodology just as they can in life. When explaining the code to a new developer it helps if the design and flow is exactly that, simple. It can clear up all kinds of caveats from having to remember what you did 6 months ago to being able to implement new features.

    When it comes to the end of the day you want to know that people can understand what you have done and you want to have a user that likes it as well as being able to understand it yourself. All of these things benefit from a K.I.S.S approach.

How do you manage "pick lists" in a database.

I have an application with a number of "pick list" entities (used to populate single choice dropdown selection boxes). These entities need to be pulled from the database. How do I persist these entities in the database? Should I create a new table for each pick list? Is there a better solution?

  • Depending on your needs, you can just have an options table that has a list identifier and a list value as the primary key.

    select optionDesc from Options where 'MyList' = optionList
    

    You can then extend it with an order column, etc. If you have an ID field, that is how you can reference your answers back... of if it is often changing, you can just copy the answer value to the answer table.

    From neouser99
  • If you don't mind using strings for the actual values, you can simply give each list a different list_id in value and populate a single table with :

    item_id: int

    list_id: int

    text: varchar(50)

    Seems easiest unless you need multiple things per list item

    From Chris J
  • We actually created entities to handle simple pick lists. We created a Lookup table, that holds all the available pick lists, and a LookupValue table that contains all the name/value records for the Lookup.

    Works great for us when we need it to be simple.

    From mattruma
  • I've done this in two different ways: 1) unique tables per list 2) a master table for the list, with views to give specific ones

    I tend to prefer the initial option as it makes updating lists easier (at least in my opinion).

  • We have followed the pattern of a new table for each pick list. For example:

    Table FRUIT has columns ID, NAME, and DESCRIPTION.
    Values might include:
    15000, Apple, Red fruit
    15001, Banana, yellow and yummy
    ...

    If you have a need to reference FRUIT in another table, you would call the column FRUIT_ID and reference the ID value of the row in the FRUIT table.

    From Alex B
  • Try turning the question around. Why do you need to pull it from the database? Isn't the data part of your model but you really want to persist it in the database? You could use an OR mapper like linq2sql or nhibernate (assuming you're in the .net world) or depending on the data you could store it manually in a table each - there are situations where it would make good sense to put it all in the same table but do consider this only if you feel it makes really good sense. Normally putting different data in different tables makes it a lot easier to (later) understand what is going on.

  • There are several approaches here.

    1) Create one table per pick list. Each of the tables would have the ID and Name columns; the value that was picked by the user would be stored based on the ID of the item that was selected.

    2) Create a single table with all pick lists. Columns: ID; list ID (or list type); Name. When you need to populate a list, do a query "select all items where list ID = ...". Advantage of this approach: really easy to add pick lists; disadvantage: a little more difficult to write group-by style queries (for example, give me the number of records that picked value X".

    I personally prefer option 1, it seems "cleaner" to me.

    From Alex
  • Well, you could do something like this:

    PickListContent
    
    IdList  IdPick  Text  
    1       1       Apples
    1       2       Oranges
    1       3       Pears
    2       1       Dogs
    2       2       Cats
    

    and optionally..

    PickList
    
    Id    Description
    1     Fruit
    2     Pets
    
    From Blorgbeard
  • In the past I've created a table that has the Name of the list and the acceptable values, then queried it to display the list. I also include a underlying value, so you can return a display value for the list, and a bound value that may be much uglier (a small int for normalized data, for instance)

    CREATE TABLE PickList(
        ListName varchar(15),
        Value varchar(15),
        Display varchar(15),
        Primary Key (ListName, Display)
    )
    

    You could also add a sortOrder field if you want to manually define the order to display them in.

    JC : Also, you could add an IsActive column for when you need to remove things from the list but still keep them in the DB for referential integrity.
    theo : Good addition JC
    From theo
  • Create one table for lists and one table for list_options.

     # Put in the name of the list
     insert into lists (id, name) values (1, "Country in North America");
    
     # Put in the values of the list
     insert into list_options (id, list_id, value_text) values
       (1, 1, "Canada"),
       (2, 1, "United States of America"),
       (3, 1, "Mexico");
    
  • You can use either a separate table for each (my preferred), or a common picklist table that has a type column you can use to filter on from your application. I'm not sure that one has a great benefit over the other generally speaking.

    If you have more than 25 or so, organizationally it might be easier to use the single table solution so you don't have several picklist tables cluttering up your database.

    Performance might be a hair better using separate tables for each if your lists are very long, but this is probably negligible provided your indexes and such are set up properly.

    I like using separate tables so that if something changes in a picklist - it needs and additional attribute for instance - you can change just that picklist table with little effect on the rest of your schema. In the single table solution, you will either have to denormalize your picklist data, pull that picklist out into a separate table, etc. Constraints are also easier to enforce in the separate table solution.

    From JasonS
  • It depends on various things:

    • if they are immutable and non relational (think "names of US States") an argument could be made that they should not be in the database at all: after all they are simply formatting of something simpler (like the two character code assigned). This has the added advantage that you don't need a round trip to the db to fetch something that never changes in order to populate the combo box.

      You can then use an Enum in code and a constraint in the DB. In case of localized display, so you need a different formatting for each culture, then you can use XML files or other resources to store the literals.

    • if they are relational (think "states - capitals") I am not very convinced either way... but lately I've been using XML files, database constraints and javascript to populate. It works quite well and it's easy on the DB.

    • if they are not read-only but rarely change (i.e. typically cannot be changed by the end user but only by some editor or daily batch), then I would still consider the opportunity of not storing them in the DB... it would depend on the particular case.

    • in other cases, storing in the DB is the way (think of the tags of StackOverflow... they are "lookup" but can also be changed by the end user) -- possibly with some caching if needed. It requires some careful locking, but it would work well enough.

    From Sklivvz
  • This has served us well:

    SQL> desc aux_values;
     Name                                      Type
     ----------------------------------------- ------------
     VARIABLE_ID                               VARCHAR2(20)
     VALUE_SEQ                                 NUMBER
     DESCRIPTION                               VARCHAR2(80)
     INTEGER_VALUE                             NUMBER
     CHAR_VALUE                                VARCHAR2(40)
     FLOAT_VALUE                               FLOAT(126)
     ACTIVE_FLAG                               VARCHAR2(1)
    

    The "Variable ID" indicates the kind of data, like "Customer Status" or "Defect Code" or whatever you need. Then you have several entries, each one with the appropriate data type column filled in. So for a status, you'd have several entries with the "CHAR_VALUE" filled in.

  • Two tables. If you try to cram everything into one table then you break normalization (if you care about that). Here are examples:

    LIST
    ---------------
    LIST_ID (PK)
    NAME
    DESCR
    
    
    LIST_OPTION
    ----------------------------
    LIST_OPTION_ID (PK)
    LIST_ID (FK)
    OPTION_NAME
    OPTION_VALUE
    MANUAL_SORT
    

    The list table simply describes a pick list. The list_ option table describes each option in a given list. So your queries will always start with knowing which pick list you'd like to populate (either by name or ID) which you join to the list_ option table to pull all the options. The manual_sort column is there just in case you want to enforce a particular order other than by name or value. (BTW, whenever I try to post the words "list" and "option" connected with an underscore, the preview window goes a little wacky. That's why I put a space there.)

    The query would look something like:

    select
      b.option_name,
      b.option_value
    from
      list a,
      list_option b
    where
      a.name="States"
    and
      a.list_id = b.list_id
    order by
      b.manual_sort asc
    

    You'll also want to create an index on list.name if you think you'll ever use it in a where clause. The pk and fk columns will typically automatically be indexed.

    And please don't create a new table for each pick list unless you're putting in "relationally relevant" data that will be used elsewhere by the app. You'd be circumventing exactly the relational functionality that a database provides. You'd be better off statically defining pick lists as constants somewhere in a base class or a properties file (your choice on how to model the name-value pair).

    From Ed Lucas
  • To answer the second question first: yes, I would create a separate table for each pick list in most cases. Especially if they are for completely different types of values (e.g. states and cities). The general table format I use is as follows:

    id - identity or UUID field (I actually call the field xxx_id where xxx is the name of the table).  
    name - display name of the item  
    display_order - small int of order to display.  Default this value to something greater than 1
    

    If you want you could add a separate 'value' field but I just usually use the id field as the select box value.

    I generally use a select that orders first by display order, then by name, so you can order something alphabetically while still adding your own exceptions. For example, let's say you have a list of countries that you want in alpha order but have the US first and Canada second you could say "SELECT id, name FROM theTable ORDER BY display_order, name" and set the display_order value for the US as 1, Canada as 2 and all other countries as 9.

    You can get fancier, such as having an 'active' flag so you can activate or deactivate options, or setting a 'x_type' field so you can group options, description column for use in tooltips, etc. But the basic table works well for most circumstances.

  • I've found that creating individual tables is the best idea.

    I've been down the road of trying to create one master table of all pick lists and then filtering out based on type. While it works, it has invariably created headaches down the line. For example you may find that something you presumed to be a simple pick list is not so simple and requires an extra field, do you now split this data into an additional table or extend you master list?

    From a database perspective, having individual tables makes it much easier to manage your relational integrity and it makes it easier to interpret the data in the database when you're not using the application