Friday, March 4, 2011

Gwt-ext window positioning

How do I make an instance of gwtext.client.widgets.Window appear at specific DIV in my html ? I tried window.anchorTo(DOM.getElementById("Some_Div"),"left", new int[]{0,0}), thinking the window will anchor itself to div id="Some_Div" in my html. it didnt.

From stackoverflow
  • I haven't used the gwt-ext library in a couple of months, but you might want to try this if you haven't already. It should attach the widget where you want it. That said, there are some cases where the gwt-ext widgets react in ways that are not intuitive to someone who really understands the normal GWT widgets.

    RootPanel.get("Some_Div_Id").add( someWidget )
    
  • You should use

    window.alignTo(DOM.getElementById("Some_Div"),"tl-tl", new int[]{0,0});
    

    for positioning the window's top left to Some_Div's top left corner.

    These are the valid strings for position argument:

    Value  Description
    -----  -----------------------------
    tl     The top left corner (default)
    t      The center of the top edge
    tr     The top right corner
    l      The center of the left edge
    c      In the center of the element
    r      The center of the right edge
    bl     The bottom left corner
    b      The center of the bottom edge
    br     The bottom right corner
    

    Refer the Ext documentation for detailed explanation.

Starting from scratch...I need some direction...

Hi, I am interested in transitioning to a career in the IT field. I have no formal training of any kind with regard to computers. At this point I would consider myself a really strong end user of windows based programs and OSs. I know I have the technical ability but at this point, not the knowledge or training. I'm sort of the guy that everyone calls when their computer is not working or they don't know how to do something on it. I am interested in programming. Can anyone point me in a direction to get started with this? What type of programming should I study, Java, C++, etc...? What should I learn before those so that I will understand the terminology and application used in the courses? Any help is appreciated. I am very motivated so I am open to all suggestions.

Thank you.

Brian

From stackoverflow
  • If everyone already calls you to fix their computers, you may want to start with charging them instead of doing it for free. You could even avoid the trip to their house if you use Joel's Co-Pilot product. (Good enough plug, Joel? :)

  • Now it's good time to choose whether you want to do web-based applications or desktop applications.

    For web-based applications, it really doesn't matter what you start with. People have good experiences with PHP, Ruby, Python, C#, Java and so on. I recommend PHP, because it's path of least resistance.

    For desktop applications, download Visual C# Express edition. It has brilliant form designer, you can get something done even without writing any code. Just drag & drop some controls on window, set some properties (visually) and hit "Run".

    tvanfosson : Please do NOT try to decide what kind of programming you want to do before you've ever done any. The kinds of applications you end up writing probably have more do to with who will hire you than with what you want to do on your first job anyway.
    lubos hasko : I'm not saying he's got to decide for life but web-based and desktop paradigms are so different that he simply has to choose one before anything else.
    tvanfosson : Disagree. I learned Java writing Swing-based applets and C# writing .Net web applications. If you just mean don't confuse yourself by trying to learn two different frameworks at once, I can see the point in that.
  • Following this course or a similar one would probably be a good way to start. Then what you should do next depends on what kind of programming you'd like to learn (desktop app, web, iphone, ... ). The answer to that will determine which languages you should learn. Once you know or have an idea start going through tutorials.

    Make sure you're always working on some concrete and feasible project. The best way is to learn by doing.

    As far as terminology and such, just make sure to use wikipedia and google extensively whenever you encounter some unknown term. At first the explanations/definitions will seem daunting but it all starts becoming coherent after a little while.

    I'd also recommend making python or java your first language. There are several books that teach intro programming based on those.

  • First get a real OS like BSD or Gentoo Linux, something you have to work on yourself. Then start learning to code with the WikiBooks on Programming!

  • This question has probably been asked on this board before, but I've never answered it so...

    It really depends on your intelligence and your opportunities. In general - use the opportunities that life throws your way as a business case to learn/write software.

    • Does someone need a website (offer to do it)?
    • Can you think of a useful batch script for yourself (learn scripting)?
    • Does someone want to manage photos (use one of the open source projects to learn from)?
    • Do you game (learn some lua)?

    If you're 1400+ SAT and/or 160+ IQ:

    • Go RTFM - most programming related things will come second nature to you. Early on, focus on design - learn object-oriented thinking. Don't worry about a particular language or syntax - those will become second nature.
    • You will probably enjoy the Functional Languages

    If you're 1200-1400 SAT and/or 130+ IQ:

    • There are a bunch of universities (MIT and such) that have open sourced their course ware. Go watch the videos and see what comes easily to you.
    • The best series for laymen to learn are the Head Start books
    • C#/Java are appropriate starting places (because of skill required and marketability)

    If you're < 1200 SAT and/or 130+ IQ:

    • Learn HTML, Javascript, Batch Scripting, SQL (these aren't programming per se... but the skills are marketable and useful). SQL will allow you to focus on one small aspect of programming that can be useful by itself. You'd be able to get jobs reporting and if you practice a lot, you can do some DBA type work.
    • Learn PHP, Perl, Ruby on Rails, VB etc. (not to say that people who work in these languages aren't bright, but these are a bit lighter and easier to learn). The market rates for these skills aren't as high.

    If you're < 1000 SAT and/or 100 IQ:

    • Go directly into management.
    • Read parts of magazines and learn the buzzwords and acronyms

    EDIT

    Based on the down votes, it looks like the < 1000 SAT don't have a sense of humor.

    Willie Wheeler : Heh, this one was funny. :-) Got an upvote from me.
    tvanfosson : No. Actually I think it's because I've seen high IQ people who think they understand everything and actually understand nothing when it comes to programming. Intelligence != aptitude. And I have a 1400+ SAT, FWIW.
    Greg Dean : LOL, somehow you've managed to relate SAT scores and ability to code.
    mson : @gdean I don't mean to correlate SAT scores with ability. I mean to correlate SAT scores with potential capacity to learn to code. E.g. A high school sophomore with a 1600 SAT probably can't code very well, but he can be readily self-trained or taught.
    mson : @gdean The best measure of success at anything is tenacity, but there is not a standardized measure of it... So, SAT and IQ are a decent approximation of a standardized measurable quantity. People have varying levels and speeds of learning. I think it's important to know what is appropriate.
  • I would recommend that you consider a degree in computer science or computer engineering if at all possible. There is a wealth of knowledge to be gained by formal education. If this is not possible, then look into courses at your local community college. Take some basic courses on computer organization (operating systems, memory organization, I/O) for a basic understanding of how your program will really work on the hardware. Take a language course -- probably Java or C# -- and learn the principles of object-oriented design. If they offer it, take a programming project course to learn how to work with other people in writing software.

    I think it's best to learn from a real person until you have enough of a background to pick up the material in an on-line course. If you feel that you are already at that point, MIT and some other schools have the materials from some of their courses on-line. Personally, I think you will learn better if you are paying for a class, but only you know if you need this extra motivation.

    If you want to jump right in, not take any classes at all, and get right at it, then I would recommend that you start with Agile Web Development with Rails. It has a pretty good description of what's going on from a high-level standpoint and will walk you through creating an application in Ruby on Rails. You could use this as a guide to whether you can continue down the self-learning path or need some formal education.

  • I'm high 130s IQ and 1300 SAT but a college drop out that went on the road to pursue music (self taught musician I might add). Thanks for all this information everyone. I really appreciate it.

    Brian

    mson : You have the potential to be a fantastic programmer. You've got the intelligence and humility required, now you just have to apply the elbow grease. Discipline is a far better predictor of success than intelligence - so make sure that when things get tough, you stick it out.
    mson : Also - use your current situation to branch out. See if you can apply your knowledge of music into programming.
    Greg Dean : congrats, don't listen to mson
  • For someone just starting out, with some time on their hands, I would recommend that you pick up a robust yet user friendly scripting language such as Ruby or Python. Play around with it, write some stuff. There are good beginner books for both of these languages, I think you can get a number of them for free.

    In any case, after coding for a little while, pick up a copy of The Pragmatic Programmer and read it. It will introduce a number of concepts, give you a set of good working habits and give you directions that you can start learning more.

    Someone recommended switching the OS on your computer to *NIX, this is a great suggestion too. You might start with Kubuntu which is popular and easy to use. But you can find the flavor that suits you best on distrowatch.

  • Before you spend good money on formal educations, try some tutorials and start writing simple programs. A personal phonebook or anything you can finish in a day or two. The important thing is to determin if you enjoy coding.

    This is very important. Most people can understand the concepts involved in programming, at least in the beginning. No doubt you will too, especially since you have some basic computer knowledge and obviously like to solve problems.

    But if you don't enjoy coding, the actual writing of code, the creative momentum you feel just writing code to create something. If you don't enjoy this and solely focus on the end result, you won't get very far, regardless of education or IQ. In that case maybe the thing for you is a field higher up in abstraction, like database administration or sys admin brackets.

    Good luck!

    /Robert

  • I truly appreciate all the input here. I'm going to start with MIT 6.00 Intro to computer science and programming and see how I react to it.

    Thanks,

    Brian

    PS - Are any of you in the Nashville Area? If so shoot me an email, I'd like to meet for a coffee or whatever and talk computer science. evinrude7 @ hotmail . com

how to create multi select auto complete combobox ??

IN my case i want to implement multi select auto complete combobox using html,javascript,jsp.

Is there any body who knows how to implement it.

Which will be similar to text field shown in stackoverflow while adding multipal tags to any question.

From stackoverflow
  • I would recommend an Ajax-driven auto-complete JavaScript combo-box, especially if you have a large set of data to query.

    Otherwise, various javascript libraries (like Yahoo UI) do provide this kind of combo-box.

    For instance, this combo-box based on ExtJS checkbox does offer a multi-select feature.

    : how to make this to work as multiselect..
    joej : Yep - this is not a not a multi-select solution. I've tried jquery.multiselect.js, fcbkcomplete, and the tokenizing autocomplete text entry ... and I'm getting tired. Those are the top jquery choices. Each comes with its own "gotchas" Most are: CSS ... don't lend themselves to complex forms, browser issues ... broken visually or broken functionality in IE and user-interface issues (supports backspace? delete, arrows, etc.?) and just bugs (can't take slashes, can fall into endless loops, etc). There doesn't appear to be a really solid, easily styled jquery version of such a beast.

How do I Send SMS to Active Directory Users

How do I send an SMS to Active Directory Users. I want to design a small application (in C#) for my telecom operator client that will send various SMS based notifications to their (AD) users by using their SMS gateway.

From stackoverflow
  • I'm assuming you mean that the mobile number is stored in AD & you wish to pull this number out with a query and use the API provided by your SMS gateway to send a message?
    You may want to look at this code sample. You can query AD with System.DirectoryServices. Finding the mobile phone number attribute in the AD schema may be a little easier with AD Explorer Hope this helps.

Asp.net - what are the best latest tools /frameworks, etc to look at . . .

Ok, i have done a bunch of asp as well as asp.net right when it came out. A friend is starting a non profit organization and he wants me to put together a site for him. I figured i would kill 2 birds with one stone and look to freshen up my skills on the latest that the web has to offer in asp.net, web 2.0, etc.

The site requirements are pretty simple:

  1. Organization mission statement
  2. Users ability to register
  3. Photos, content
  4. Blog posts
  5. Ability to donate directly on the site (maybe through paypal)

So my questions is what are the best tools to start here given its going to be hosted on windows ASP.net platform 3.5. Any other frameworks that i should be looking at.

Where is the best place to start?

I could easily build the site just putting a table together and a bunch of static pages but i figured if it made sense to utilize and help freshen my skills, it would be worth the efforts of the learning curve.

Feel free to suggest any other items that i haven't listed.

From stackoverflow
  • Have a look at ASP.Net MVC and JQUERY also take a look at S#Arp as a nice platform to build your site upon. It setups ASP.Net MVC, with nHibernate and has really good guidance on a good DDD structure.

  • In case you've overlooked it, The AJAX Control Toolkit -

    addresses three needs. First it gives website developers a place to get components to make their web applications spring to life, second it gives a set of great examples for those wishing to write client-side code, and third it is a place for the best script developers to get their work highlighted.

    For an open source functioning CMS system, look at N2. N2 is a lightweight CMS framework to help you build great web sites that anyone can update. The user interface is intuitive and empowering. The developer story is something quite exquisite.

End of file descriptor in a grammar implementation

I am working on a compiler implementation and wish to check if the end of file has been reached?

I know that this can be done using the yywrap() function in the lex file, but the requirement is that we want if the EOF is explicitly defined as in the hex value 0x1a, then how do we reference that.

Example:

main() { printf("Check EOF marker\n"); '0x1a' <-- the actual EOF marker.

I want the above not to be a syntax error, but to be reported as an error Unbalanced parentheses, Or is wrongly defined.

Can the above be done? My requirement is just to have the EOF token in the parser, which unfortunately, I have not been able to do so till date :-((, the rest of the work will be easily done as then, I just have to give a rule such as:

print    :    print_stmt '(' stmt_valid ')' colon '\n' 
{
    OK do the rest
}
         |    print_stmt '(' stmt_valid ')' colon end_indicator
{
    print error message and close application.
}
From stackoverflow
  • Make your lexer return a token for the EOF.

    I suggest that you return the token for two cases:

    1. getc() returned -1 (the usual EOF sign). In this case, make the token text empty

    2. getc() returned '\x1a'. In this case, put this character in the token text.

    This allows your grammar to differentiate between these two cases.

Best practices for formatting a message for MessageBox.Show(...) in Winforms for Vista

In XP/2003 I had become accustomed to writing my MessageBox.Show(..) code like this :

MessageBox.Show("Title", "Sorry an error has occured!\n" +
                         "You may want to try one of the following:\n\n" +
                         "1. Reboot your machine\n" +  
                         "2. Buy a new machine\n" +  
                         "3. Report your error on StackOverflow.com.\n");

i.e. I formatted the message nicely and readable. If I didnt then it would fill the whole width of the screen and was not very friendly.

Now when the same message box comes up in Vista it is formatted completely differently and it introduces its own linefeeds and generally looks a lot worse.

What is the best practice for this for an application for both Vista and XP - short of writing my own message box class.

What are others doing to overcome this problem

From stackoverflow
  • Just a remark, but in Vista, is not a TaskDialog more appropriate for this kind of dialog ?

    alt text

    Otherwise, this thread does mention a way to insert newlines in a Messagebox.

    MessageBox.Show( "This" & Environment.NewLine & "is" & Environment.NewLine & "a test",
                     "Lines", MessageBoxButtons.YesNoCancel)
    

    See Environment.Newline property

How to capture events from a dynamically created button control in asp.net?

How can a program capture generates events from a dynamically created button control in asp.net?

From stackoverflow
  • You can attach the event programmatically:

    Button myButton = new Button();
    myButton.Click += new ClickEventHandler...etc
    
  • Button ButtonDeleteFromDB = new Button();

    ButtonDeleteFromDB.Text = "Delete";

    ButtonDeleteFromDB.ID = "btnDeleteFromDB" + ctrlCount.ToString();

    ButtonDeleteFromDB.Click += new EventHandler(ButtonDeleteFromDB_Click);

    Call the event in foll manner :

    private void ButtonDeleteFromDB_Click(object sender, EventArgs e) { }

How do I manually add additional rows to the bottom of an ASP.NET gridview?

I have a situation where I'm populating a gridview with a bound data source, and want two additional rows at the very bottom; one to show the sum of values in the columns and one to show the average of values in the columns. I can quite easily calculate these values by aggregating information taken from the rowDataBound event, but don't know how to go about manually adding the additional two rows to the gridview. Any help much appreciated.

From stackoverflow
  • You can use the Footer just like you use Headers in gridview.. whereas another solution is use a query in such way:

    query 1 : ur original qry

    UNION

    query 2 : ur query which contains sum

    (This applies only if you dont apply paging to ur grid)

  • If it's a single row of information you can use summary footer. See Displaying Summary Information in the GridView's Footer.

    alt text

    If you want two additional rows, you can stuff rows into an IList. At the business logic layer, you can add more rows to the list returned by DAL.

How to Improve Web Development Using Virtualization in asp.net?

Improving Web Development Using Virtualization

From stackoverflow
  • http://aspnet.4guysfromrolla.com/articles/102908-1.aspx

  • Virtualization is, in essence, creating multiple miniature (virtual) PCs inside of your primary PC. One of the great benefits of this is that it allows you to isolate and test an application or set of applications in an environment that is free of other things to interfere. It used to be that in order to get a new machine with a new development environment on it you had to have another piece of hardware, or you had to rebuild your system to the new environment. With virtualization, you simply install the new environment that you need into one of the virtual machines and you run it as necessary. When you're done you can shut it down.

    Virtualization is the ultimate in isolation -- it can allow you to do things on one piece of hardware that are simply not possible without it. For instance, you can install software in a test environment on a member server because it won't run on a domain controller. You simply fire up two virtual machines at the same time -- one being the domain controller and the other being the member server. Both virtual machines can run on the same physical hardware at the same time without either being aware that they are sharing a machine. The result is a quick way to implement testing environments.

    Virtualization technology allows for the virtual systems to be frozen in place. In other words, the exact spot in the machine that you are at can be frozen for an indefinite period of time. If you work on one project until it's released and stable and need to come back in a year and start working on it again, you can freeze the system when you stop working on the project and then restart it a year -- or more – later. When the system is restarted it will be like time had not passed. The system will be restored exactly as it was left.

    This particular feature is great for developers who support multiple systems including consultants who have different clients with different projects that they will have to support over time. You don't have to worry about recreating an environment to test a bug fix; you simply thaw out your virtual machine and go.

    Virtualization programs have a feature described as Undo disks. Undo disks allow you to operate on the system and if you decide that you don't want to save your work you simply don’t' accept the changes in the undo disks. Poof. Like magic everything that you did is undone and it's like it never happened.

How would you improve this simple class to be more loosely coupled?

As you can see below, in the constructor I'm instantiating a validation object so I can validate a user's email in a set method. Is this architecture best practice or flawed? Can I avoid making my User class directly dependent on my Validation class?

Class User {
  Private Email

//constructor
User() {
  Validation = new Validation
}

SetEmail(NewValue) {
  if (Validation.isEmail(NewValue)) {
    Email = NewValue
  }
}

And a related question: When a set method receives an invalid value, what is the proper response? I see 2 options

  1. Don't set the value and return false
  2. Set the value anyway, but set an error property for the object. (so if User.Error is set I know something went wrong)

I suspect #1 is best practice because you can then assure the value of any object property is always valid. Correct?

From stackoverflow
  • I would:

    1. Break the coupling to the concrete Validation object via dependency injection: define an abstract (pure virtual) Validation class, make a concrete validation class derive from it, and pass in ("inject") a reference to the abstract Validation class in the User class's constructor.

      For an excellent discussion of how and why to do this in C++, see Robert Martin's 1996 article on the subject from The C++ Report.

    2. Rather than returning false or silently setting some property, raise an exception. That's what they are there for.

    Bill the Lizard : I'm not sure I understand. Are you saying that User should extend and abstract Validation class?
    Tim Lesher : No--separate the concrete Validation class into an interface (an abstract class) and an implementation (a concrete class), and make the User class depend only on the interface, not the implementation, of Validation. I don't do this for every class (a la J2EE), but decoupling is the #1 use case.
    Bill the Lizard : Okay, I understand now. I do that all the time, I just didn't know the name for it.
  • The proposals so far all seem to be way overkill, especially with all the IOC and AOP stuff.

    1. The User class needs an email address, so create an EmailAddress class and have the User class accept one via a property and/or its constructor. That validation can be as simple as whether the input EmailAddress reference is null or not.

    2. The EmailAddress class can be a simple but generally reusable implementation (consider basing it on the RFC document). It should be immutable and should throw an exception from its constructor on invalid input.

    3. Ideally, the EmailAddress class should be composed of an EmailUserId class (based on the RFC?) and a InternetDomain class (based on the RFC?), since an email address is a composite data structure. Again, each of those classes should manage immutable instances and should throw an exception on construction with invalid input.

    "Validation" strikes me as not a "thing" but rather a generic "action". Therefore, it lends itself to being a method rather than a class. In this case, I tend to implement the validation in each of these classes as a private static method (valid(input)) that is invoked from the constructor, in languages like Java or C#. Often, it becomes useful to expose that functionality publicly in the form of a question (isValid(input)).

    EDIT:

    Are you suggesting that every distinct data type I need to validate should have it's own class?

    That is one solid way of addressing the issue, commonly known as a Value Type (thanks for the reminder, Frank). The result will be a few (dozen or two) well-defined, reusable classes like perhaps EmailAddress, PhoneNumber, PersonName, etc. The presented alternative is likely to result in a "god class" with a mixture of functionality that is not reusable, not easy to test, and difficult to maintain.

    There are other ways to partition the solution, but my suggestion does have the advantage of being mature, well understood, and consistent with a large set of solid design principles. I would certainly recommend trying it before attempting to invent your own.

    Frank Krueger : That is to say EmailAddresses are Value Types. Excellent solution Rob.
    Cory House : Are you suggesting that every distinct data type I need to validate should have it's own class? So I'd need a name class, address class, city class, zip class, etc? I currently have a validation class with many methods (email, phone, etc). You suggest splitting each method into it's own class?
    : Yes I believe that is what he is saying. It might seem wrong to make a class for something like zip code but it's just part of breaking things up to represent a single concept.

PHP - sort an array based on another array?

Is it possible in PHP to do something like this? How would you go about writing a function? Here is an example. The order is the most important thing.

$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';

And I'd like to do something like

$properOrderedArray = sortArrayByArray($customer, array('name', 'dob', 'address'));

Because at the end I use a foreach() and they're not in the right order (because I append the values to a string which needs to be in the correct order and I don't know in advance all of the array keys/values).

I've looked through PHP's internal array functions but it seems you can only sort alphabetically or numerically. Would I have to implement some sort of sorting function with array_walk?

Thank you in advance!

From stackoverflow
  • There you go:

    function sortArrayByArray($array,$orderArray) {
        $ordered = array();
        foreach($orderArray as $key) {
         if(array_key_exists($key,$array)) {
          $ordered[$key] = $array[$key];
          unset($array[$key]);
         }
        }
        return $ordered + $array;
    }
    
    alex : Thank you very much!
    Eran Galperin : You're very welcome :)
    alex : So you can join 2 arrays with a + sign? I never knew that, I've been using `array_merge()`!
    grantwparks : Is this better than using `usort()` or `uasort()`?
    Neil Aitken : Excellent function, Thanks Eran.
  • function sortArrayByArray(array $toSort, array $sortByValuesAsKeys)
    {
        $commonKeysInOrder = array_intersect_key(array_flip($sortByValuesAsKeys), $toSort);
        $commonKeysWithValue = array_intersect_key($toSort, $commonKeysInOrder);
        $sorted = array_merge($commonKeysInOrder, $commonKeysWithValue);
        return $sorted;
    }
    
    alex : I didn't know you could cast function arguments like that in PHP!
    OIS : Arrays and classes only.
  • IF you have array in your array, you'll have to adapt the function by Eran a little bit...

    function sortArrayByArray($array,$orderArray) {
        $ordered = array();
        foreach($orderArray as $key => $value) {
            if(array_key_exists($key,$array)) {
                    $ordered[$key] = $array[$key];
                    unset($array[$key]);
            }
        }
        return $ordered + $array;
    }
    

Mxml and as3 confusion [simple]

Hi,

I was wondering i can call an as3 function defined in script from mxml code just like this:

<mx:Line x="translateX(xmin);" .. >


<mx:Script>
   <![CDATA[

   // do some basic math
   private function translate ...

If not possible do i have to convert everything to as3 ?

Thanks

From stackoverflow
  • Yes you can.

  • You can but a straight-up function call like that needs to go into an event attribute in MXML, i.e. "when this event is dispatched, invoke this function." The classic example being:

    <mx:Button label="Hello" click="myFunction()"/>
    

    You can use a function as you have illustrated above provided that it's in a binding expression and the arguments passed to the function are bindable:

    <mx:Line x="{positionLine(xmin)}"/>
    
    // defined somewhere in a mx:Script block
    [Bindable] private var xmin : Number;
    

Thoughts on Entity Framework

I was wondering what people thought about the decision to support Entity Framework over LINQ-to-SQL? I have an application I'm developing originally in LINQ-to-SQL. I found it the perfect solution for our application.

While attempting to port to Entity Framework I was surprised how rough it was. IMHO, not even close to being ready for prime time. No lazy loading, no POCOs, horrible dependency on inheritance. I found it largely unusable in my case and instead decided to stick with LINQ-to-SQL until somehow this Entity Framework can get more polished.

Anyone else have similar experience with it?

From stackoverflow
  • I think it depends on the application platform. When my team set out to create a new ASP.net app, we wanted to go with EF... but after playing around with it for a bit, we went with Linq-To-SQL. In a web environment, managing the L2S datacontext was a lot easier. Also, we liked that L2S entities expose the original Id field (e.g. EmployeeTypeId), unlike EF, which would only have the child entity exposed. In a web environment, a lot of times you really don't need that extra information, the Id is enough because it is a reference to a dropdown list that has already been loaded (and probably cached).

    Jiyosub : Not exposing the IDs was another issue I had. Also, if you wanted to support many to many you had to design a table only with the ids and no other fields or it wouldn't manage the relationship.
  • That is pretty much my view. See my previous reply here. This other question wasn't specifically about the problems in EF, but yes: it has a fair few glitches. For example (in addition to your existing options):

    • no support for Expression.Invoke (re-using expression trees to form a more complex expression)
    • no support for table-UDFs, which can be used to create well-defined, callable methods in the database that are still composable with sort/skip/take etc

    LINQ-to-SQL handles both just fine...

    Richard Szalay : @Marc Gravell Any thoughts on EF4? I'm curious to whether it resolves your issues with the original.
    Marc Gravell : @Richard - I haven't (yet) had the opportunity to re-evaluate.
    Jiyosub : I have moved on to PLINQO to try to make up some of the gap. So for, EF4 doesn't show much improvement.
  • L2S is more mature for what it is made for.

    And I will still consider EF as a BETA realease.

    there is lot of discussion around EF, you can find alot more in related questions.

  • I agree. There are too many bugs and design flaws in Entity Framework v1 (the .net 3.5 SP1 version) to make it usable in real-world development. EFv4 looks more promising though...

  • I've heard that L2S is quickly going the way of the dodo. There is a little bit of chatter about a move to opensource - but the ADO.NET group at Microsoft is planning to push all their efforts towards EF...

    Sad too, because I find Linq2SQL extremely easy to work with and the thought of porting all my code makes me a little sick.

    Update on LINQ to SQL and LINQ to Entities Roadmap

How to get a list of column headers of a listview based on displayindex?

If the AllowReorder column of a listview is set to true, how do I get a string list of the columnheader texts based on their displayindex at runtime? listview.Columns only returns columns in the original order.

From stackoverflow
  • C# 2.0? Or C# 3.0? The LINQ answer (C# 3.0, with either .NET 3.5 or .NET 2.0/3.0 with LINQBridge) is a lot easier ;-p

    i.e.

        var names = (from col in listView.Columns.Cast<ColumnHeader>()
                     orderby col.DisplayIndex
                     select col.Text).ToList();
    

    vs:

            List<ColumnHeader> cols = new List<ColumnHeader>();
            // populate
            foreach (ColumnHeader column in listView.Columns) {
                cols.Add(column);
            }
            // sort
            cols.Sort(delegate(ColumnHeader x, ColumnHeader y) {
                return x.DisplayIndex.CompareTo(y.DisplayIndex);
            });
            // project
            List<string> names = cols.ConvertAll<string>(delegate(ColumnHeader x) {
                return x.Text;
            });
    

    Either way, that gives you a List<string> of the column header text values.

ASP.NET MVC and REST URI's

How would I handle something like the below uri using ASP.NET MVC's routing capability:

http://localhost/users/{username}/bookmarks/ - GET
http://localhost/users/{username}/bookmark/{bookmarkid} - PUT

Which lists the bookmarks for the user in {username}.

Thanks

From stackoverflow
  • first you need to create a new route in global.aspx

    routes.MapRoute("Bookmarks", "{controller}/{user}/{action}/{id}");
    

    then add a new action

    public class UsersController : Controller
    {
        [AcceptVerbs("Post")]
        public void Bookmarks(string user, int? id)
        {
    
            //add your bookmark
        }
    }
    
  • You can use the [AcceptVerbs] attribute on your action method

    public class BookmarksController : Controller
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public void Bookmarks(string user)
        {
    
            //add your bookmark
        }
    
        [AcceptVerbs(HttpVerbs.Post)]
        public void Bookmarks(string user, int? id)
        {
    
            //add your bookmark
        }
    }
    

UpdateModel prefix - ASP.NET MVC

I'm having trouble with TryUpdateModel(). My form fields are named with a prefix but I am using - as my separator and not the default dot.

<input type="text" id="Record-Title" name="Record-Title" />

When I try to update the model it does not get updated. If i change the name attribute to Record.Title it works perfectly but that is not what I want to do.

bool success = TryUpdateModel(record, "Record");

Is it possible to use a custom separator?

From stackoverflow
  • Not unless you implement your own ModelBinder. If you look at the source code for the DefaultModelBinder on www.codeplex.com/aspnet, you'll see that when you specify a prefix it constructs the name by concatenating the prefix, a period, and the name of the property. Unfortunately, the method on DefaultModelBinder that does this is private static and thus cannot be overridden in a derived class.

  • Another thing to note is that the prefix is to help reflection find the proper field(s) to update. For instance if I have a custom class for my ViewData such as:

    public class Customer
    {
        public string FirstName {get; set;}
        public string LastName {get; set;}
    }
    
    public class MyCustomViewData
    {
        public Customer Customer {get; set;}
        public Address Address {get; set;}
        public string Comment {get; set;}
    }
    

    and I have a textbox on my page

    <%= Html.TextBox("FirstName", ViewData.Model.Customer.FirstName) %>
    

    or

    <%= Html.TextBox("Customer.FirstName", ViewData.Model.Customer.FirstName) %>
    

    here is what works

    public ActionResult Save (Formcollection form)
    {
        MyCustomViewData model = GetModel(); // get our model data
    
        TryUpdateModel(model, form); // works for name="Customer.FirstName" only
        TryUpdateModel(model.Customer, form) // works for name="FirstName" only
        TryUpdateModel(model.Customer, "Customer", form); // works for name="Customer.FirstName" only
        TryUpdateModel(model, "Customer", form) // do not work
    
        ..snip..
    }
    
    Brad Wilson : You can simply the second example to: <%= Html.TextBox("Customer.FirstName") %>
  • There is a reason not to use . as ID/Name in HTML bcs it is not standard. For example, the will break if there is a dot in target.

    jcm : Underscores are used for the HTML/CSS IDs. The dot is only used for form input names.
  • that was bad decision to use period. Underscore would have been better.

    This means you have to separately define all your ids.

    ie. Textbox now has Html.TextBox("test.test", new{@id="test")

How Can I Avoid Using Exceptions for Flow Control?

I have been assigned a project to develop a set of classes that act as an interface to a storage system. A requirement is that the class support a get method with the following signature:

public CustomObject get(String key, Date ifModifiedSince)

Basically the method is supposed to return the CustomObject associated with the key if and only if the object has been modified after ifModifiedSince. If the storage system does not contain the key then the method should return null.

My problem is this:

How do I handle the scenario where the key exists but the object has not been modified?

This is important because some applications that use this class will be web services and web applications. Those applications will need to know whether to return a 404 (not found), 304 (not modified), or 200 (OK, here's the data).

The solutions I'm weighing are:

  1. Throw a custom exception when the storage system does not contain the key
  2. Throw a custom exception when the ifModifiedSince fails.
  3. Add a status property to the CustomObject. Require caller to check property.

I'm not happy with any of these three options. I don't like options 1 and 2 because I don't like using exceptions for flow control. Neither do I like returning a value when my intent is to indicate that there was no value.

Nonetheless, I am leaning towards option 3.

Is there an option I'm not considering? Does anyone have strong feelings about any of these three options?


Answers to this Question, Paraphrased:

  1. Provide a contains method and require caller to call it before calling get(key, ifModifiedSince), throw exception if key does not exist, return null if object has not been modified.
  2. Wrap the response and data (if any) in a composite object.
  3. Use a predefined constant to denote some state (UNMODIFIED, KEY_DOES_NOT_EXIST).
  4. Caller implements interface to be used as callbacks.
  5. The design sucks.


Why I Cannot Choose Answer #1

I agree that this is the ideal solution, but it was one I have already (reluctantly) dismissed. The problem with this approach is that in a majority of the cases in which these classes will be used, the backend storage system will be a third party remote system, like Amazon S3. This means that a contains method would require a round trip to the storage system, which would in most cases be followed by another round trip. Because this would cost both time and money, it is not an option.

If not for that limitation, this would be the best approach.

(I realize I didn't mention this important element in the question, but I was trying to keep it brief. Obviously it was relevant.)


Conclusion:

After reading all of the answers I have come to the conclusion that a wrapper is the best approach in this case. Essentially I'll mimic HTTP, with meta data (headers) including a response code, and content body (message).

From stackoverflow
  • You can create a special final CustomObject as a "marker" to indicate unchanged:

    static public final CustomObject UNCHANGED=new CustomObject();
    

    and test for a match with "==" instead of .equals().

    It might also work to return null on unchanged and throw an exception on does not exist? If I had to choose one of your 3, I would choose 1 because that seems the most exceptional case.

    Spencer K : This does introduce a series of if, then, else checks that every call to this method has to muck around with. You're almost better off then with Exceptions, cause at least they're enforced, and more structured.
    Software Monkey : Yes, but exceptions introduce a series of try/catch/finally, so the net gain is only enforcement, at the cost of performance? And the exception handling is more verbose, and more distant from the causative code. So... it depends... The OP asked how to avoid exceptions.
  • Looking for an object that does not exist seems like an exceptional case to me. Coupled with a method that allows a caller to determine if an object exists, I think it would be ok to throw the exception when it doesn't.

    public bool exists( String key ) { ... }
    

    Caller could do:

    if (exists(key)) {
       CustomObject modified = get(key,DateTime.Today.AddDays(-1));
       if (modified != null) { ... }
    }
    
    or
    
    try {
        CustomObject modified = get(key,DateTime.Today.AddDays(-1));
    }
    catch (NotFoundException) { ... }
    
  • If it is acceptable, you may return an amplified CustomObject (a wrapper), which contained values which represented the object and its modification state, if any, etc.

  • The problem with exceptions is they are meant to signal a "fail fast" scenario (i.e. if not processed, an exception will stop an application) due to an exceptional and abnormal behavior.

    I do not think that "the scenario where the key exists but the object has not been modified" is an exceptional one, certainly not an abnormal one.

    Hence I would not use exception, but rather I would document the action the caller need to do in order to correctly interpret the result (property or special object).

    OscarRyz : Yeap, in this case an exception a bad decision.
    tvanfosson : Where did the key come from? If you have the key, then the object ought to exist and if it doesn't then it's an exceptional case.
    VonC : @Buzzer: may be so, but does the application has to *stop* if your exception goes unchecked ? I do not think so.
    Spencer K : Then make the exception checked. Unchecked exceptions are either unrecoverable or unhandle-able at the current level. They can be bubbled up to a layer that notifies someone of the event, then waits till action is been taken. Exceptions are not the best solution, but are viable in this instance.
  • How strict is the requirement for that method signature?

    It seems as though you are working on a project that is still in progress. If the consumers of your class are other developers, can you convince them that the method signature they have asked for is insufficient? Perhaps they haven't yet realized that there should be two unique failure modes (key does not exist and object has not been modified).

    I would discuss it with your supervisor if that is an option.

  • With the given requirement you cannot do this.

    If you designed the contract, then add a condition and make the caller invoke

    exists( key ): bool
    

    The service implementation look like this:

    if ( exists( key ) ) {
        CustomObject o = get( key , Date modifSince );
        if( 0 == null ) { 
          setResponseCode( 302 );
        } else {
          setResponceCode( 200 );
          push( o );
       }
    
    } else {
          setResponseCode( 400 );
    }
    

    The client remains unchanged and never notice you've validated upfront.

    If you didn't design the contract Probably there's a good reason for that or probably it's only the designer ( or architect ) fault. But since you cannot change it, then you don't have to worry either.

    Then you should adhere to the specifications and proceed like this:

     CustomObject o = get( key , Date modif );
    
     if( o != null ) {
          setResponseCode( 200 );
          pus( o );
      } else {
         setResponseCode( 404 ); // ether not found or not modified.
      }
    

    Ok, you're not sending 302 in this case, but probably that is the way it was designed.

    I mean, for security reasons, the server should not return more information than that [ the probe is get( key, date ) only return either null or object ]

    So don't worry about it. Talk with your manager and let him know this decision. Comment the code with this decision too. And if you have the architect in hand confirm the rationale behind this strange restriction.

    Chances are they you didn't see this coming and they can modify the contract after your suggestion.

    Sometimes while wanting to proceed right we may proceed wrong and compromise the security of our app.

    Communicate with your team.

    Dustin : 404 == not found, 304 == not modified. If one result means two different things, that's going to bite someone someday.
    OscarRyz : Yes, but maybe that's the intention. For instance. Log in into Yahoo! with a fake account. The server says: "Invalid ID or password." They don't say "the account does not exists" There's a good reason for this. Yahoo won't tell you if an account exist and the password is wrong. Even when they could.
    OscarRyz : This may be a security constraint imposed by the security consultant in the enterprise ( we all have one right? ) Oooor maybe, the designer just forgot this scenario ( that never happens right? The design is ALWAYS correct ) We don't know. Problably this service was used internally and now is pub
  • I'd still return null.

    The intention of the property is to return the object that was modified after the specified date. If returning null for no object is ok, then surely returning null for an unmodified object is ok too.

    I personally would return null for a non-modified object, and throw an exception for a non-existing object. That seems more natural.

    You're quite right to not use exceptions for flow control BTW, so if you only have those 3 options, your gut instinct is right.

    Robin : This is the only reasonable solution. If the qualifier for the method is not met, then it should return null, I don't see the point of anything else. The null on invalid key is questionable and could go either way. A Map would return null, other classes would throw IllegalArgumentException.
    Robin : Of course the invalid key case is already determined, so null for both.
  • You could follow the .Net library pattern of and have a public static readonly field in the custom object called CustomObject.Empty that is of type CustomObject (like string.Empty and Guid.Empty). You could return this if the object is not modified (the function consumer will need to compare against it).
    Edit: I only just spotted that you're working in Java, but the principle still applies

    This gives you the option of the following

    • Return null if the key doesn't exist.

    • Return CustomObject.Empty if the key exists but the object has not been modified.

    The drawback is that the consumer would need to know the difference between a null return value and a CustomObject.Empty return value.

    Perhaps the property would be more aptly called CustomObject.NotModified as Empty is really intended for Value types as they cannot be null. Also NotModified would convey the meaning of the field more easily to the consumer.

  • It sounds like you actually want to return two items: the response code and the object found. You might consider creating a lightweight wrapper that holds both and return them together.

    public class Pair<K,V>{
      public K first;
      public V second;
    }
    

    Then you can create a new Pair that holds your response code and the data. As a side effect to using generics, you can then reuse this wrapper for whatever pair you actually need.

    Also, if the data hasn't expired, you could still return it, but give it a 303 code to let them know that it is unchanged. 4xx series would be paired with null.

    Spencer K : This isn't bad, but this should be more strongly typed, and doesn't need to be made generic.
    Apocalisp : That Pair type couldn't be any more strongly typed, and why would you not want to make things as generic as possible? Polymorphism is a good thing.
    Apocalisp : Instead of returning both a found object and a response code, you could return EITHER the found object or a failure code. This can be made type-safe with a disjoint union type like Either.
    Spencer K : Poor choice of wording. Yes, it is strongly typed, but "Pair" is vague. Pair of what? Yes you specify "Pair", but what does Integer mean? There's generic, and then there's confusing. Hopefully at least then, the code is typed in a wrapper or something.
  • The (intended) interface regarding the requirements is seriously broken. You try to do unrelated things within one method. This is the road to software hell.

    OscarRyz : Amén! And there's no way back from there.
    DoctaJonez : I second that! Its not a good situation to be in.
  • Provide a Callback as the argument where the Callback class could either be event driven, or setter driven.

    You have your class's interface define the various errors that can occur, passing in the CustomObject as the parameter for the event, if needed.

    public interface Callback {
      public void keyDoesNotExist();
      public void notModified(CustomObject c);
      public void isNewlyModified(CustomObject c);
      .
      .
      .
    }
    

    In this way, you allow the implementor of the Callback interface to define what to do when the event occurs, and you can choose through the interface, whether that conditions requires the passing of the retrieved object. Lastly, it reduces the complexity of the logic on a return. Your method does that once. Implementors of the API don't require doing it at all, as it's done for them.

is possible to include a subreport or 2 reports in the same Crystal Report?

Hi Folks, im using Crystal Repots in vs2008, so im using datasets with procedures to get the data from the db, my escenario is the following:

In the same Crystal Report, i have to show two reports, basically using the sames datasets, and the same database, but they are diferents querys (have grouping and summing instead)

is this possible? and if it is how can i solute this, using database expert? or cross-tab? what option of crystal reports supports this operations?

Thanks in advance :)

From stackoverflow
  • You should be able to insert a "sub report" in Crystal on your primary report. You can pass parameters from the main report to the sub report and utilize a whole different command in the sub report. I'm not sure the exact keyboard sequence to insert a sub report in VS2008, but in CR 2008, it's as simple as using the file menu INSERT > SUB REPORT.

    Angel Escobedo : im trying it now, thanks... maybe the query is so hardcode it expect grouping by columns that not exists in the database explicit, so here we go...
  • Based on my own experiences, I have to agree with Greg - a subreport is probably the easiest-to-maintain solution to your problem. In the case of VS2008, the steps to follow are:

    1. Go to the Crystal Reports -> Insert -> Subreport menu option.
    2. Click where you want to place the subreport on the main report.
    3. The 'Insert Subreport' form will be displayed. Either choose an existing report, or create a new one using the Report Wizard. In the Report Wizard, you can also choose from the existing datasets un your project.

    To link your main report to the subreport right-click on the Subreport, and choose 'Change Subreport Links'.

    Hope that helps.

  • I could not print the subreport created. Whenever I click the print button, it takes me to main report and export main report in a pdf instead of doing the same for subreport. Will you please let me know why it is happening so in Crystal Report 10.5 and Asp.Net (VS 2008). It works fine in VS 2005 (ASP.Net and Crystal Report 10.2)