Wednesday, April 13, 2011

How to expose HTTP return (error) codes with JMX?

We would like to monitor HTTP error codes (e.g. per minute) for later graphing.

How can we expose HTTP return (error) codes with JMX?

Are there code samples or have you done something like that? Is this contained in Tomcat per default?

About the implementation: Should the code increase a JMX counter and set it to 0 every minute? Thanks for ideas.

From stackoverflow
  • Add a JMX bean which has one field per HTTP error you care about. Increment each field as errors drop in. The JMX console will turn that into a nice curve. I wouldn't reset the value but that mostly depends on what features your console has to show a statistic on a value.

    Stephan Schmidt : And set the JMX value from a Servlet Filter at each request?
  • If you're looking to derive rates of errors and graph those, you're better off having the server return a total count of errors. That way the client can then derive a rate independent of the server (e.g. per minute/per hour/per day).

    More importantly, you won't miss any temporary surges in the data. If the server is deriving a rate and your client process doesn't pick it up (if it's not monitoring at that particular time, say), then it's lost forever. Whereas maintaining a count will record the total number of errors.

    SNMP agents (and similar) take this approach, allowing clients to monitor and derive values as they see fit.

Displaying time in JSP page.

This was my line in demo.jsp demo

Hello there!!! The time is <%= new java.util.Date()%>

which when i opened in firefox doesn't show the time. instead displays the same line: "The time is <%= new java.util.Date()%>"

From stackoverflow
  • If you go to this link, it has examples, with source, that show you how to do it properly. See the "Date" example under JSP 1.2 examples.

    Another recommendation: Learn JSTL and use its format tags to format time and date properly. Don't use scriptlets.

  • It looks like you're putting <%= new java.util.Date()%> in the wrong place, and it is being treated as text rather than code, it should look something like this:

    <td width="100%"><b>&nbsp;Current  Date 
    and time is:&nbsp; <font color="#FF0000">
    
    
    <%= new java.util.Date() %>
    </font></b></td>
    

    If you post a code sample, it'll help a lot.

    Some examples here too: http://www.roseindia.net/jsp/jsp_date_example.shtml

    Dave

  • I'm assuming that your JSPs are compiling.

    The <%= %> notation implicitly invokes the instance's toString() method. Since constructors in Java don't return a reference to the newly created instance, you're trying to do this:

    new java.util.Date().toString() //! illegal
    

    Try this instead:

    <% java.util.Date now = new java.util.Date() %>
    <%= now %>
    

Obtaining a table by the item type in LINQ to SQL

How can you make something like this generic

return from items in _db.Table
    select items;

I would like to do something like this

public class Data<T> ( where T is the model object )

so the Table will change to the value of T

How would this look as a generic class with a save method for instance

Thanks

From stackoverflow
  • ... _db.GetTable<MyType> ...
    
  • In LINQ-to-SQL, the data-context has GetTable<T>():

    var table = _db.GetTable<T>();
    etc
    
    Marc Gravell : Did you mean this for leppie? I had brackets in my post... try adding them...
  • Adding to Marc Gravell's answer, you could have a generic update method that looks like this:

    public void Update(TEntity entity, TEntity original)
    {
        using (DataContext context = CreateContext())
        {
            Table<TEntity> table = context.GetTable<TEntity>();
    
            table.Attach(entity, original);
            context.SubmitChanges();
        }
    }
    

In Common Lisp, why do multi-expression bodies of (if) statements require (progn)?

Is this just a bit of historical cruft left over from the 1950s or is there some reason syntactically why multi-expression bodies of (if) forms require (progn)? Why can't you wrap the multiple expressions in a set of parentheses like with (let):

   (if some-cond
     ((exp1) (exp2) (exp3)) ; multi exp "then"
     (exp4)) ; single exp "else"

It appears it would be trivial to write a macro to test each body to see first if it is a list and then if it is, if its first element is also a list (and thus not a function invocation) and then to wrap its subcomponents inside a (progn) accordingly.

From stackoverflow
  • There are already macros for the expanded version. This book is really good: http://www.gigamonkeys.com/book/ Your answer is in this chapter: http://www.gigamonkeys.com/book/macros-standard-control-constructs.html

    The standard macros are when and unless.

  • Not all expressions are lists. For (let ((a 42)) (if some-cond (a b c) (d e f))) you would not know whether (a b c) should be interpreted as a call to the function a or as an implicit progn.

  • In Lisp, parentheses indicate function application, not grouping. What would your expression mean if exp1 was a function that returned a function? Would it be called with the arguments (exp2) (exp3) or not?

  • When you have no 'else' branch, standard macros when and unless help. Otherwise it's better to use cond if you have multiple expressions in any branch.

  • is there some reason syntactically why multi-expression bodies of (if) forms require (progn)?

    The answer is "yes", although perhaps not for the reason you're expecting. Because Common Lisp (unlike Scheme and other Lisps) requires funcall, your proposal is not ambiguous. Even if it were ambiguous, as long as your users know that parentheses imply progn here, it would work.

    However, no other constructions* in the language have optional single/double parentheses. Plenty of constructions have implicit progns, but their parenthetical syntax is always the same.

    For example, cond has an implicit progn for each branch:

    (cond (test1 body1) (test2 body2) ...)
    

    You can't switch back and forth:

    (cond test1 exp1 (test2 body2) t exp3)
    

    So, even though your proposal isn't ambiguous, it doesn't fit the syntax of the rest of the language. HOWEVER! Like you said, the macro is trivial to implement. You should do it yourself and see if it works well. I could easily be wrong; I'm pretty biased since almost all my Lisping is in Scheme.

    *Except case. Hmf. Now I think there may be others.

  • Common Lisp is not perfect because it is perfect, it is perfect because it is perfectable.

    The whole language is built upon 25 special operators; if is one of those, progn is another.

    if provides just the basic mechanism of testing a condition, then jumping to either one or the other code address. progn provides the basic mechanism of doing several things and returning the value of the last.

    There are several macros in the language standard that build on this -- e.g. when, unless, cond, case.

    If you want, you have several options to make something like what you envision: for one, you could write an ifm macro that expects implicit progns as then- and else-clauses, or you could write it like you said, so that it detects the intent, or you could even write a read macro to add syntactic sugar for progn.

  • In Common Lisp, this code:

    (if t
        ((lambda (x) (+ x 5)) 10)
       20)
    

    will return 15. With your proposal, I think it would see that the true-clause is a list, and automatically convert it to:

    (if t
        (progn (lambda (x) (+ x 5)) 10)
       20)
    

    which would return 10. Is that right?

    I'm not sure it's "trivial" to distinguish between "list" and "function invocation" in CL. Do you intend for this change to be non-backwards-compatible? (New and interesting Lisp dialects are always cool, but then it's not Common Lisp.) Or can you give an example of what you have in mind?

  • Because the syntax for IF (<- HyperSpec link) is defined as:

    if test-form then-form [else-form] => result*
    

    There are no begin or end markers. There is a THEN-FORM and not THEN-FORM*. PROGN is a mechanism to define a sequence of forms, where the forms are executed from left to right and the values of the last form are returned.

    It could have been defined like this:

    my-if test-form (then-form*) [(else-form*)] => result*
    
    (defmacro my-if (test then &optional else)
      (assert (and (listp then) (listp else)) (then else))
      `(if ,test (progn ,@then) (progn ,@else)))
    
    (my-if (> (random 10) 5)
           ((print "high")
            :high)
           ((print "low")
            :low))
    

    Well, there is already a construct that supports multiple forms: COND.

    (cond ((> (random 10) 5)
           (print "high")
           :high)
          (t
           (print "low")
           :low))
    

    The typical style is to use COND when multiple alternatives have to be tried and when there are multiple then/else-forms. IF is used when there is only one test and both a then and an else form. For other cases there is WHEN and UNLESS. WHEN and UNLESS support only one or THEN forms (no else form(s)).

    I guess it is good to have at least one conditional form (IF in this case) that comes without added layers of parentheses. Writing

    (if (> (random 10) 5)
        (progn
           (print "high")
           :high)
        (progn
           (print "low")
           :low))
    

    is then a small price to pay. Either write the additional PROGNs or switch to the COND variant. If your code would really benefit from IF with multiple then and else forms, then just write that macro (see above). Lisp has it, so that you can be your own language designer. It is important though to think about introducing a macro: is my macro correct? does it check errors? is it worth it? is it readable (for others?)?

Polymorphism AND type safety in parallel inheritance chains

I have two parallel inheritance chains:

Chain1:
Animal <- Lion
       <- Gazelle

Chain2:
Food   <- Meat
       <- Grass

I want to implement the "Eats" polymorphic property on Animal. This is how it looks like:

public abstract class Animal
{
  public abstract Food Eats { get; set;}
}


public class Lion : Animal
{
  public override Food Eats
  {
     get { return new Meat();}
     set 
     {
       if (value is Meat) DoSomething(value);
       else throw new Exception("Lions only eat meat. " + 
                                "You better learn that, dude!");
     }
  }
}

However, this code is not type safe. Should I feed my Lion with grass, I will be confronted with my bug only in runtime.

Could someone provide me with a code example that facilitates type safety using Generics without sacrificing polymorphism?

From stackoverflow
  • Hmm, maybe you could modify your first inheritance chain:

    Animal - Carnivore - Lion - Tiger - ... - Herbivore - Sheep

    Then, you could maybe do something like this:

    public class Animal<T> where T : Food
    {
        public abstract T Eats { get; set; }
    }
    
    public class Carnivore : Animal<Meat>
    {
       ...
    }
    

    I haven't tested, it is just an idea that I have ...

  • Animal can be a generic class:

    public abstract class Animal<T> where T : Food
    {
        public abstract T Eats {get;set;}
    }
    

    then you can make lion a meat eating animal like this

    public class Lion : Animal<Meat>
    {
        //etc...
    }
    

    But this is not be an optimal solution. You can't use animal as a polymorphic interface any more because you need to know details about it's implementation to use it. This might just not be the place for polymorphism.

  • I think this is a bit of a false dilemma. Food seems to be closer to an interface than an abstract base class, since it doesn't sound like Meat is going to be very similar to Grass at all. Instead, consider something like:

    public interface IFood {
      public boolean IsForCarnivores();
    }
    
    public class Lion : Animal {
      ...
      public override IFood Eats
      {
        get { ... }
        set 
        {
          if (value.IsForCarnivores()) DoSomething(value);
          else throw new Exception("I can't eat this!");
        }
      }
    }
    
    Mr. Lame : This does not make the Eats property any more type safe as it was in the original question. Should you feed the Lion with Grass, you still do not get compiler error. Furthermore, it is not false dilemma but covers real life scenario.
  • Using composition over inheritance:

    Instead of inheriting based on digestive system, break off digestion into its own set of classes.
    First, an interface that describes different ways to eat.

    public interface IDigest
    {
      void Eat(Meat food);
      void Eat(Plant food);
      void Eat(Offal food); //lol nethack
    }
    

    Carnivores eat meat, can eat herbs sometimes, and don't like crap:

    public class Carnivorous : IDigest
    { 
      public void Eat(Meat food)
      {
        Console.Write("NOM NOM");
      }
      public void Eat(Plant food)
      {
        if(Starving)
         Console.Write("Ugh, better than nothing.");
        else
          Vomit();
      }
      public void Eat(Offal food)
      {
        Vomit();
      }
    }
    

    Herbivores are picky and would rather die than eat meat (I know, save your comments, this is an example)

    public class Herbivorous : IDigest
    { 
      public void Eat(Meat food)
      {
        Vomit();
      }
      public void Eat(Plant food)
      {
        Console.Write("NOM NOM");
      }
      public void Eat(Offal food)
      {
        Vomit();
      }
    }
    

    Omnivores eat anything. Witness a state fair.

    public class Omnivorous : IDigest
    { 
      public void Eat(Meat food)
      {
        Console.Write("NOM NOM");
      }
      public void Eat(Plant food)
      {
        Console.Write("NOM NOM");
      }
      public void Eat(Offal food)
      {
        Console.Write("NOM NOM");
      }
    }
    

    All animals must eat, so they must have a digestive system, along with other systems.

    public abstract class Animal
    {
      /* lots of other stuff */
      public IConsume DigestiveSystem {get;set;}
      /* lots of other stuff */
    }
    

    Hippies are an animal class with known tastes; it configures itself on instantiation. It is also possible to inject behaviors and systems from the outside.

    public class Hippie : Animal
    {
      public Hippie()
      {
        /*stuff*/
        DigestiveSystem = new Herbivore();
        BodyOdorSystem = new Patchouli();
        /*more stuff*/
      }
    }
    

    And finally, let's see a hippie eat a burger.

    public static void Main()
    {
      Hippie dippie = new Hippie();
      Meat burger = new Meat("Burger", 2/*lb*/);
      dippie.DigestiveSystem.Eat(burger);
    }
    

    When modeling complex systems like animals, I'd prefer composition over inheritance ANY DAY. Complex systems can explode an inheritance tree with the quickness. Take three animal systems: omnivore/herbivore/carnivore, water/air/land, and nocturnal/diurnal. Let's not even worry about how to decide which classification becomes the first point of differentiation for Animals. Do we extend Animal to Carnivore first, to WaterLiving first, or to Nocturnal first?

    Since an omnivore can live in the air and prefer the night (bat*) and also be a day walking land creature (humans), you have to have an inheritance path that hits every single option. That's an inheritance tree with 54 different types already (its early, be kind). And Animals are much more complex than this. You could easily get an inheritance tree that had millions of types. Composition over inheritance, definitely.

    *New Zealand Short Tailed bat, for example, is omnivorous.

    Mr. Lame : Actually, you did not answer the correct question, it is about the parallel inheritance chain problem. (Animal kingdom is just the typical textbook example for polymorphism). If complex inheritance things are in concern, I would go for ontologies. But I reward your humorous examples!
    Will : The answer was already given and accepted. I was more interested in showing an alternative design. Inheritance is powerful, but easily abused.

Rollup Column for Normalized Sums (SQL) - Part 1

I have a table like so:

object_id | vote
1 | 2
1 | -1
1 | 5
2 | 3
2 | 1
3 | 4
3 | -2

I want this result (for this particular example, object_ids 1 and 2 are part of a group, defined elsewhere, and I'm looking for the normalized_score so that the sum always = 1. object_id 3 is part of an unused group.):

object_id | normalized_score
1 | 6/10
2 | 4/10

[added 3:05PM] 10 here is the sum of the votes for object_id in (1,2). There's a whole other set of logic to come up with the (1,2), I was just trying to give the cleanest question so people don't have to worry about that part.

[added 3:10PM] As pointed out in the comments, if the score for one of the objects is below 0, a problem arises. Here is the rule, "IF the score for any outcome_id is -x, AND that is the minimum score for the set, ADD x to all scores in order to zero-out the minimum score". I can do this on my own time though outside of SQL - so it's a bonus only if somebody has the cahones to try to tackle it in SQL.

If I do a self join, I can get the sum. I can't figure out how to get the normalized sum. Ideally this will work in both MySQL 5.x and Sqlite3. Otherwise, I can do this with two separate queries and just do the work in post-processing.

From stackoverflow
  • The comments are quite correct.. but I'll make the assumption that 10 is just some number you picked out of your... nose.

    SELECT object_id AS ObjectID, SUM(vote) + '/10' AS NormalizedVote FROM table GROUP BY object_id

    Enjoy.

    Adam Nelson : I'm sorry, I wasn't clear. '10' is the sum of all the other votes in that group - otherwise this would be a trivial question. I'll update the question.
  • -- SQL solution
    SELECT 
      object_id AS ObjectID, 
      (SUM(CASE SIGN(vote) WHEN 1 THEN vote ELSE 0 END) - 
        ((CASE SIGN(MIN(vote)) WHEN -1 THEN MIN(vote) ELSE 0) * 
         (COUNT(1)))) + '/10' AS NormalizedVote
    FROM table 
    GROUP BY object_id
    
    Adam Nelson : Similarly to the one I marked as the answer (although that one is fixable), the SUM() includes the votes for object_id=3, which won't work. I like that there's no subquery though - thanks for the input.
  • The solution without compensating for negative votes (I include this one because its much easier to read/understand):

    SELECT object_id
    ,      SUM(vote) + '/' + total AS normalized_score
    FROM   tabel
    ,      (
           SELECT sum(vote) AS total
           FROM   tabel
           ) 
    GROUP BY object_id, total
    

    Full solution:

    SELECT object_id
    ,      SUM(vote + minvote) + '/' + (total + minvote * count) AS normalized_score
    FROM   tabel
    ,      (
           SELECT sum(vote) AS total
           ,      CASE WHEN MIN(vote) < 0 THEN
                      -MIN(vote)
                  END AS minvote
           ,      COUNT(*) AS count
           FROM   tabel
           ) 
    GROUP BY object_id, total, minvote, count
    

    (I don't have access to MySQL, so I wrote a query in Oracle and replaced || for +. Hope it works in MySQL or at least helps :))

    Adam Nelson : Yeah - I was thinking a subquery was necessary. I usually try to avoid those, and I'm sure there's a non subquery solution, but that should be good enough for fewer than a few hundred thousand records - which is fine for now. Thanks for a great answer.

ORM and SOA in the .NET world

From my experience the major ORM frameworks for .NET (NHibernate, LinqToSql, Entity Framework) work best when they keep track of loaded objects. This works fine for simple client-server applications, but when using three- or more tier architecture with Web Services in a Service Oriented Archtitecture, this is not possible. Eventually, by writing a lot of code to do the tracking yourself it could be done, but isn't ORM supposed to simplify DB access?

Is the idea to use ORM in service oriented architecture good at all?

From stackoverflow
  • The ORM framework will help you only when directly talking to the database. Even in service oriented architectures, ORMs can only help to reduce the load when programming that final layer. You'll need other techniques -- like WCF -- to handle the service part. I'm not aware of anyone integrating ORM and services yet, but it should be pretty straight forward to annotate the same classes as entities and DataContracts.

  • LLBLGen Pro has change tracking inside the entities. This means that you can fetch a graph from the database using prefetch paths (so one query per graph node) and serialize it over the wire to the client, change it there, send it back and directly save the graph as all change tracking is inside the entities (and is serialized inside the XML as compact custom elements).

    Disclaimer: I'm the lead developer of llblgen pro.

    Rumen Georgiev : Thanks for the suggestion, sounds great, exactly what I miss. I'll take a look when I can.
    Colin Desmond : My understanding from this podcast (http://www.dotnetrocks.com/default.aspx?showNum=451) is that Entity Framework v4 (ships with VS2010) also has this capability. It allows its entities to be serialised to other tiers in the architecture, changes made, then serialised back to the tier where the original context is and persisted back to the DB.
  • It depends what you mean by 'SOA'. Exposing domain objects in service contracts is rarely good service design - it exposes internal implementation details, there's a greater likelihood of change to a published contract, and versioning becomes very difficult.

    If you create custom message documents (eg WCF DataContracts) for your service endpoints, it's relatively easy to use ORM to implement the service. Typically you would reload the domain object from the database and map changed properties (or call a method), then persist the changes.

    If your service is mostly CRUD methods, your custom message will effectively be a DTO. You will need to manually manage optimistic concurrency and domain object mapping.

    Update: This is an old answer, so I'd like to point out that EF4 also now includes change tracking in entities. I still maintain this is poor service contract design, but if you're just after a distributed application framework, it's probably a good option.

    Rumen Georgiev : This approach is good from SOA point of view, because it keeps contracts as simple as possible. But the additional reloading before saving objects hits performance. If we use direct DB access from the client, we can just call save. My idea is to achieve this pattern with web service.
    Sam : It sounds like you're looking for something like ADO.NET Data Services. I would be questioning whether the value delivered by a web service layer outweighs the additional complexity over direct DB access from the client. Two-tier systems are unfashionable, but are more performant & with less code.
    Sam : I'd also point out that SOAP serialisation/deserialisation is sometimes more of a performance bottleneck than one extra query hitting the database - if performance is your main objective, ensure you measure, measure, measure.
    Lucas Jones : Wah! SOA, WCF, ORM, CRUD, DTO! My brain's going to explode ... ;)
  • SignumFramework has tracking inside of the entities as well. It also has a full Linq provider, but is ment to work with new databases only (it generates the schema from your c# entities, not the oposite).

    Change Tracking: http://www.signumframework.com/ChangeTracking.ashx

    Disclaimer: I'm the lead developer of Signum Framework :)

  • I would humbly suggest that you stop trying to use distributed objects as an architectural pattern. It is just not as effective as either a messaging architecture or a RESTful style.

    If you don't like the overhead of transferring data in and out of messages then I would suggest you look at REST. However, not REST in the way ADO.NET Data services does it, that is just distributed objects over HTTP.

    REST is more about exposing an ugly(but machine readable) UI on the server and using the client to make it look pretty. In REST there is no knowledge of domain entities on the client so you don't need to send them across the wire.

  • Take a look at the description of upcoming synchronization and disconnected sets in DataObjects.Net

  • You can use memcached as a second level cache with NHibernate - is that what you meant by 'Keeping track of' ?

Redefine/alias a resource in WPF?

Is there a way to redefine/alias an existing SolidColorBrush (or any other resource, actually)?

Case in point: I have a brush in an external ResourceDictionary that I want to reference by my own key instead of the original key. I don't want to be dependent on the external reference, since the actual brush is prone to change in the future.

From stackoverflow
  • <Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
        <Window.Resources>
         <SolidColorBrush x:Key="SomeExternalResource">Red</SolidColorBrush>
        </Window.Resources>
        <Grid>
         <Grid.Resources>
          <StaticResourceExtension ResourceKey="SomeExternalResource" x:Key="SomeAliasedResource"/>
         </Grid.Resources>
    
         <Border Background="{StaticResource SomeAliasedResource}"/>
        </Grid>
    </Window>
    

    I don't want to be dependent on the external reference, since the actual brush is prone to change in the future.

    You'll still be dependent on the external resource, just not in as many places.

    HTH, Kent

    Paul Stovell : the only limitation to this is that you can't reference both the original and the alias if used within the same resource dictionary, as they will override each other. i am assuming this applies to multiple dictionaries you merge at application scope.
    Kent Boogaart : Judging by the way the question is worded, he doesn't want to reference the original - only his alias. Referencing the original would defeat the purpose of creating the alias.
    Inferis : That works. Thanks!

Javascript calendar not working

Hi.

My JavaScript calender is working in IE but it is not working in Mozilla.

My code:

  <table>
   <tr style="height: 5px;">
    <td>
     <asp:TextBox ID="txtBorderedDate" runat="server" CssClass="TextBoxMandatory" Enabled="false"></asp:TextBox>
    </td>
    <td class="FieldButton_bg" style="height: 5px;"> 
     <a onclick="javascript:showCalendarControl(ctl00_SaralConetentPlaceHolder_txtBorderedDate);" href="#">
       <img src="../Images/iconCalendar.png" style="width: 20px; height: 20px; vertical-align: bottom;" border="0" />
     </a>
    </td>
   </tr>
  </table>
From stackoverflow
  • I'm not sure if this has anything to do with the problem (you should post some more of your code), but you shouldn't hard code the ID of the controls in ASP.NET. Also, I think some quotes might be missing in the showCalendarControl() call.

    Replace this:

    <a onclick=
     "javascript:showCalendarControl(ctl00_SaralConetentPlaceHolder_txtBorderedDate);" ...
    

    With this:

    <a onclick="showCalendarControl('<%= txtBorderedDate.ClientID %>');" ...
    

    Some of the parent controls of txtBorderedDate might get rendered differently in different borders, thus resulting in a different client-side ID of the textbox control.

    Cerebrus : +1 but I doubt this is reason... JS based Calendars are complex dynamic structures that have a lot of dynamically created elements. In this case, he seems to be passing the ID of the textbox which will receive the selected value of the calendar.
    M4N : It's hard to tell, with only that short code extract.

What every programmer should know about __ ?

I found a couple of essays like this:

  1. What every programmer should know about Memory?
  2. What every programmer should know about Floating-Point arithmetic?

I am currently reading the first paper. What other similar essays do you know of?

From stackoverflow

Is ASP.NET MVC flexible?

Can it easily be combined with jQuery, (ASP.NET) Ajax, ASP.NET webforms, other frameworks. What about pulling dynamic code from ASP.NET MVC into for example classic ASP?

Does the MVC model mean that it is easy to customize code?

Background:

  1. I have some experience that it can lead to problems to integrate frameworks relying on Javascript with each other?
  2. We have a classic ASP where we write new stuff in ASP.NET, and include .aspx code in the ASP files.
  3. I am looking for some OS frameworks for stuff we need, and i think MVC based ones should be easier to adopt (KIGG)
From stackoverflow
  • ASP.NET MVC ships with jQuery as the default javascript framework, so no worries there. There aren't really any ties in the framework itself to jQuery so you could also switch it out with a framework of your choice. MVC comes with it's own AJAX implementation that builds on the base ASP.NET Ajax implementation (at least in javascript), so there is AJAX support but I think you'll find that it's different -- no UpdatePanels, for instance -- but you're able to do similar things.

    You can mix WebForms with MVC, but you'll need to set up IgnoreRoutes for those URLs so they don't get processed. I confess that I haven't found a need to do this yet, but then I don't use third-party controls. That might be an area where, at least for now, you still need some WebForms. I've never used classic ASP and likely won't so I can't help you there.

  • You can use any Javascript framework with MVC, they have included Jquery as the default but any can work with it.

    As far as flexibility, we have deployed a working site with ASP.NET webforms, MVC and .NET 1.1 libraries, so yes it is flexible.

    In our experience ASP.NET MVC is the best thing MS have done for web development, especially if you like to control closely your html output and use web standards in your layout and design. We have used it for 6 Months and we are NEVER going back to web forms.

    Have fun!

3D flex, rotate around a random point for a container (with partial solution!)

I'm trying to find the best way to rotate a container (or anything for that matter) using the matrix3D features in flash 10 for flex.

I have managed to get a container to rotate around a point that is not its registration point but I’ve only managed this by turning off the clipping on a container then placing the contents somewhere other than (0,0,0). This does work, but it’s not very intuitive and sucks when trying to place several items or even if you need to move the rotation point.

Using the matrix3D class seems to be the way to go, but I'm not sure exactly how.

Cheers

Additional info - If my container is at (0,0,0) on the stage and I wish to rotate around the middle X coord of container then I translate by container.width/2 for the X then rotate and translate back again. This works fine. BUT if my container is say at (10, 0, 0) then if I translate the same as above and add the extra 10 then it doesn't work.

Soloution (which is complete rubbish - please explain if you can) As has been suggested you need to translate, rotate, then -traslate. I knew this but it never worked.
BUT see the soloution below, I don't get it. (panel is the object I'm rotating, I call function both() )

private function rotateOnly() : void {
        panel.transform.matrix3D.appendRotation(36, Vector3D.Y_AXIS);
}

private var valueToMove : Number = 300;
private var translateUpOrDown : Boolean = false;
private function translateOnly() : void {
    if(translateUpOrDown){
            panel.transform.matrix3D.appendTranslation(valueToMove, 0, 0);
    translateUpOrDown = false;
} else {
    panel.transform.matrix3D.appendTranslation(-valueToMove, -0,0);
    translateUpOrDown = true;
}
 }

 //I do not run both chunks of code here at once, this is only to show what I've tried   
 private function both() : void {
     //IF I call this function and call this chunk then the rotation works
        translateOnly();
        rotateOnly();
        translateOnly(); 


     //If I call this chunk which does the exact same as the above it does NOT work!!
        panel.transform.matrix3D.appendTranslation(valueToMove, 0,0);
panel.transform.matrix3D.appendRotation(36, Vector3D.Y_AXIS);
panel.transform.matrix3D.appendTranslation(-valueToMove, 0,0); 
 }
From stackoverflow
  • Rotation matrices always rotate around the origin.

    Rotation of an object around an arbitrary point P usually requires:

    1. translation of the object by -P
    2. rotation of the object as required
    3. translation of the object by P
    kenneth : Yip i've tried that. I've taken the matrix3D of the container, done a appendTranslation(-x, -y, -z) then did a appendRotation, then another appendTranslation(x, y, z). i've tried other variations using the matrix3D class but I can't get it quite right.
    Andy Li : Alnitak's solution is assuming the object is at origin.
  • have you considered simply moving the pivot vector ?

    var matrix:Matrix3d = new Matrix3d();
    matrix.appendRotation(degrees, axis, new Vector3d(container.width/2,container.height/2,0));
    
    kenneth : I have indeed tried that and it had some unexpected results (not the results I was after anyway). The livedocs really need more info or examples to show the 3D working as you can't get at the source code of the matrix3D class (unless I'm wrong there, but I couldn't).
  • OK, the solution would be -

    1 - create your own component with vars for the original X, Y, Z and width and height. These will be used for convenence to save extra matrix operations. E.G extend the Box class and just add those var to the new class.

    2 - add component to app, something like the below. (the orig values are because the actual x,y,z so on will change during rotation but you need to orig values to calculate the correct rotation.

    <local:RotationContainer 
      id="movingBox" 
      width="50"
      origWidth="50"
      height="60"
      origHeight="60"
      x="80"
      origX="80"
      y="70"
      origY="70"
      z="0"
      origZ="0"
      enterFrame="rotateObject(event)"
      />
    

    3 - use the following code when rotating, call in the above enterFrame event

    private var translateUpOrDown : Boolean = false;
            private function translateOnly(obj : Object, valueToMoveX : Number,  valueToMoveY : Number) : void {
    
             if(translateUpOrDown){
              obj.transform.matrix3D.appendTranslation(valueToMoveX, valueToMoveY, 0);
              translateUpOrDown = false;
             } else {
              obj.transform.matrix3D.appendTranslation(-valueToMoveX, -valueToMoveY, 0);
              translateUpOrDown = true;
             }
            }
    
            private function rotateOnly(obj : Object) : void {
             obj.transform.matrix3D.appendRotation(rotationAmount, Vector3D.Y_AXIS);
            }
    
            private function rotateObject(event : Event) : void {
    
             var offsetX : Number = (event.currentTarget.origWidth / 2) + event.currentTarget.origX;
             var offsetY : Number = (event.currentTarget.origHeight / 2) + event.currentTarget.origY;
    
             translateOnly(event.currentTarget, offsetX, offsetY);
             rotateOnly(event.currentTarget);
             translateOnly(event.currentTarget, offsetX, offsetY);
            }
    

    4 - thats it. This will rotate around the center point, on the Y axis. Change the offset values for different points of rotation.

    UPDATE As pointed out you do not need to move the calls into separate function, but you will need to use the above so that you can get at the original width, height, x & y (providing your not hard coding all the values)

Elegant database design help... (MySQL/PHP)

Hi, I'm building a movies website... I need to display info about each movie, including genres, actors, and a lot of info (IMDB.com like)...

I created a 'movies' table including an ID and some basic information. For the genres I created a 'genres' table including 2 columns: ID and genre. Then I use a 'genres2movies' table with two columns:movieID and the genreID, to connect between the genres and the movies tables...

This way, for example, if a movie have 5 different genres I get the movieID in 5 different rows of the'genres2movies' table. Its better than including the genre each time for each movie but...

There is a better way for doing this???

I need to do this also for actors, languages and countries so performance and database size is really important.

Thanks!!!

From stackoverflow
  • You are in the right track. That's the way to do many-to-many relationships. Database size won't grow much because you use integers and for speed you must set up correct indexes for those IDs. When making SELECt queries check out the EXPLAIN - it helps to find the bottlenecks of speed.

    Jonathan : I'm not database expert.. what do you mean by correct indexes??? For the 'movies' database I use ID as primary key. For 'genres' also, and for movies2genres' I set the movieID and genreID both as primary keys.. Is this correct??
  • It sounds like you are following proper normalisation rules at the moment, which is exactly what you want.

    However, you may find that if performance is a key factor you may want to de-normalise some parts of your data, since JOINs between tables are relatively expensive operations.

    It's usually a trade-off between proper/full normalisation and performance

  • You're on exactly the right track - this is the correct, normalized, approach.

    The only thing I would add is to ensure that your index on the join table (genres2movies) includes both genre and movie id and it is generally worthwhile (depending upon the selects used) to define indexes in both directions - ie. two indexes, ordered genre-id,movie-id and movie-id,genre-id. This ensures that any range select on either genre or movie will be able to use an index to retrieve all the data it needs and not have to resort to a full table scan, or even have to access the table rows themselves.

How do I embed openads (Openx) ads in an iPhone application

I have tried using iframe, javascript and image tag Ad tags in iPhone application, but none of them work. When a user clicks on an image, the browser is launched but then nothing happens (you get a blank page). Anyone know how to proceed?

From stackoverflow
  • To proceed: debug it. A standard OpenX click URL will do a redirect. What URL is the browser sticking at?

    I don't know anything about iPhone applications, but I do know about interfacing to OpenX. You possible should consider using the OpenX API, which will allow you to pull all the information you need into the 'back end' of your application, then use it as you need.

  • Proplem in iphone must be active enable java in iphone safari settings

Anyone using SpiraTeam?

We've been using Mantis for some time now at my shop and it has performed well. The powers that be have decided we'll be using a commercial tool called SpiraTeam from this point forward. Has anyone had experience with this tool? I noticed that it has import ability from Jira and a few other systems but didn't see one for Mantis. I'm still bummed about the move but change is coming so we've got to make the best of it. Has anyone migrated historic data out of Mantis into this tool or another closed tool? What were your experiences?

From stackoverflow
  • Well, we've been using SpiraTeam now for just shy of 6 months and while it has some interesting ideas, like a step-by-step test section, I think the interface is pretty clunky and really wish we were still using Mantis. On of the really useful things in Mantis was how easy it was to see at a glance what showed up in each new build. Haven't found anything like this in SpiraTeam.

Jython Netbeans with JavaSE

Hello everyone,

I want to develop a Java application mixing java with jython. I am using the IDE Netbeans with the python plugin. How do i work on this? (There is a built in support for Groovy with javaSE from IDE call Groovy classes from Java code, and Java classes from Groovy code but not for jython)

ref: http://www.netbeans.org/features/groovy/index.html

From stackoverflow
  • Netbeans 6.5 supports both Python and Jython.

    http://www.netbeans.org/features/python/

    Assuming you are using that version with the Python plug-in, it's just a matter of setting the runtime you wish to use via the platform manager (here's where you would choose Jython).

    alt text

    Joonas Pulakka : But how does setting the runtime help developing Java application that mixes Java and Jython?
  • I would also want to add that since 6.5 release, the Python bits have been vastly improved upon. So, if you want to try the new but unstable builds, please grab one from http://deadlock.netbeans.org/hudson/job/python/

    Also, please refer to various documents linked from http://wiki.netbeans.org/Python and my blog posts at http://amitksaha.blogspot.com/search/label/nbpython

    In case of problems, please let us know on the mailing list.

    Sridher : I am using 6.7m2, for groovy they are modifying the ant build script with groovyc compiler enabling it from properties window. how we can do that with jython ?
    Amit : Do what? Please be a bit more concrete..
  • If you want to develop a Java application that blends with Jython and works outside NetBeans, then NB's ability to use Jython runtime doesn't help much. Instead, you have basically two choices:

    • You can compile your Python to Java classes using jythonc.
    • Or: you can embed the Jython interpreter inside your Java app.

    To embed, you need to create a Jython library to be included in your Java app. Do this by going to Tools -> Libraries, select New Library, and add the stuff at NetBeans' Jython directory there (C:\Program Files\NetBeans 6.5\python1\jython-2.5 in my machine). You need jython.jar and at least most of the stuff at the javalib directory.

    James McMahon : Exactly, if your looking to combine code with the flexibility of groovy your not going to have much luck.

problem in getting cell value from grid view

I want to get the cell value from a grid view.

I am using the following code but it produces an error.

Code:

cmd.Parameters.Add("@ProjectCode", SqlDbType.VarChar).Value = ((GridView)TeamMemberGrid.Rows[e.RowIndex].Cells[1].Controls[0]).ToString();

Note:

@ProjectCode is one of the fields in the grid view.

From stackoverflow
  • TableCell has a Text property.

    thiru : how to get grid view cell value
  • I think its:

    cmd.Parameters.Add("@ProjectCode", SqlDbType.VarChar).Value = ((GridView)TeamMemberGrid.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
    
    thiru : this only produce error question and ur answer are same
    thiru : this is also produce error
    BenB : I guess the next question would therefore be... What is the error produced?!
  • As Leppie has already stated, the TableCell object exposes a Text property which will give you access to the text contents of a TableCell.

    What you need to understand is that the TeamMemberGrid.Rows[e.RowIndex].Cells[1] statement returns a TableCell object referencing the specified TableCell in your GridView.

    So your statement becomes :

    cmd.Parameters.Add("@ProjectCode", SqlDbType.VarChar).Value = TeamMemberGrid.Rows[e.RowIndex].Cells[1].Text;
    

    Finally, the reason for the cast seems unclear in your statement so I removed that.

Request.ServerVariables("SCRIPT_NAME") Not Returning Anything

Branching off from this link it seems that Request.ServerVariables("SCRIPT_NAME") doesn't return anything. I've just set up a simple loop to see if anything comes out at all but with no luck. Any ideas?

For Each s As String In Request.ServerVariables
   Label1.Text += s
Next

ServerVariables brings back a list of Strings in key->value form as defined in System.Collections.Specialized.NameValueCollection

EDIT: It seems to be a problem with getting the ServerVariables from a page using master pages. In my code behind model I'm defining the following:

Public Partial Class Test
    Inherits System.Web.UI.Page

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Response.Write(Context.Request.ServerVariables("SCRIPT_NAME"))
  End Sub
End Class

This doesn't work, quite simply. If I enter the code within the Page_Load event within the .aspx page, however, by doing the following:

<% Response.Write(Context.Request.ServerVariables("SCRIPT_NAME")) %>

Then it works fine. Any ideas as to why that's happening?

From stackoverflow
  • The definition at http://msdn.microsoft.com/en-us/library/ms524602.aspx says "A virtual path to the script being executed, for example, "/vdir/default.asp". This is used for self-referencing URLs.". I think the ".asp" part may be a hint as to why this isn't working for ASP.NET.

    I recommend against ever using Request.ServerVariables. Anything created for use in Classic ASP or ISAPI should make you nervous.

    Kezzer : It's still used in *.aspx files, just in a different context, that is, the Http Context.
    John Saunders : I know ServerVariables are used, but is Context.Request.ServerVariables("SCRIPT_NAME") still filled in for .ASPX?
    Kezzer : Yup, works fine. I can't see what alternative there is anyway?
    John Saunders : HttpContext.Current.Request.Url.AbsolutePath. Consider: you're not running a script.
  • If you are trying to return the script name, try:

    Request.CurrentExecutionFilePath
    

    and if you just wanted the script name without the path, you could use:

    Path.GetFileName(Request.CurrentExecutionFilePath)
    

    Path.GetFileName() requires the System.IO namespace

    Kezzer : Good call, but getting the path hadn't seemed to be the problem, it was just where it was output (check my edit) :)
  • I tried your code, and get the result you want :

    <% Response.Write(Context.Request.ServerVariables("SCRIPT_NAME")) %>
    

    Returns : /TESTERS/Default.aspx

    You can replace it with this, returns same result :

    string path = HttpContext.Current.Request.Url.AbsolutePath;
    

    Returns : /TESTERS/Default.aspx

    Kezzer : Getting the actual path isn't the problem, it's getting it from the code behind model in the master page that's the problem. It seems to only work if it's within the page unfortunately.
  • Are you sure you're not getting this back?

    Using Response.Write from the code behind (either in the page or the master page) will output the string at the top of the page (usually), before the rest of the HTML, etc, which is probably not where you're expecting to see it.

    I put a literal control on a master page, before the content placeholder:

    On Master: <asp:Literal id="LiteralMaster" runat="server"></asp:Literal>
    

    And then setting it's Text property in the master page's Page_Load event to:

    LiteralMaster.Text = Context.Request.ServerVariables("SCRIPT_NAME")
    

    I also added a literal control in the content placeholder on a page that used this master page:

    On page: <asp:Literal id="LiteralPage" runat="server"></asp:Literal>
    

    And in the page's Page_Load event I had the following:

    LiteralPage.Text = Context.Request.ServerVariables("SCRIPT_NAME")
    

    Which resulted in:

    On Master: /LittleTest/UsingMaster.aspx
    On page: /LittleTest/UsingMaster.aspx

    Modifying my page's Page_Load event to become:

    LiteralPage.Text = Context.Request.ServerVariables("SCRIPT_NAME")
    Response.Write("From response.write: " &
      Context.Request.ServerVariables("Script_Name"))
    

    Resulted in the following display in my browser:

    From response.write: /LittleTest/UsingMaster.aspx
    On Master: /LittleTest/UsingMaster.aspx
    On page: /LittleTest/UsingMaster.aspx

    However, the html looked more like:

    From response.write:/LittleTest/UsingMaster.aspx
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <title></title>
      </head>
      <body>
        <form name="aspnetForm" 
          method="post" action="UsingMaster.aspx" id="aspnetForm">
          <div>
            On Master: /LittleTest/UsingMaster.aspx
            <br />
            On page: /LittleTest/UsingMaster.aspx
          </div>
        </form>
      </body>
    </html>
    

    Edit to respond to comment

    You are assigning the string representation of a NameValueCollection element to the contents of your label, this is just the NAME, not the combination of the NAME and the VALUE

    Try the following:

    For Each s As String In Request.ServerVariables
      Label1.Text += s & ": " & Request.ServerVariables(s)
    Next
    

    For more info, take a look at the MSDN docs:

    HttpRequest.ServerVariables

    Kezzer : We're very aware of this ;) if you look at the top of my question I actually assign the output to a label which exists on the screen. The other code I wrote was just something I wrote here, it wasn't my actual code - the chances are it wouldn't output as it's using the master page anyway.
    Zhaph - Ben Duguid : See my edit - this code was tested with a page using a masterpage - I was able to output the value of ServerVariables("Script_Name") correctly from the page_load events of both the master page and the page itself.