Tuesday, May 3, 2011

AJAX and MVC (C#)

I've never used AJAX and am, quite frankly, not much versed in JS either.

I have a page (Product Browser) that has the following breakdown:

  1. Navigation (First, Prev, 1, 2, 3 Next, Last) - full post back
  2. Items per Page drop down - I want to AJAX this
  3. Left Column - Filters - I want to AJAX this
  4. Product Display area - displays products based on 1, 2 & 3 above

I am starting with Item #2 and am trying to figure out how to change item 4 based off of the OnChange event for the drop down. I am at a loss as to where. or how, to start. Should it be AJAX? JQuery? A combination of both? And remember - it is in a MVC based app.

TIA

From stackoverflow
  • You can try this simple demo from my blog

  • AJAX is just a request pulling information from a page without refreshing the browser. You can use ASP.NET AJAX or JQuery's AJAX and you should get the same results.

    And JQuery is just a library to select and manipulate the DOM. JQuery has a few AJAX functions you can use as well but JQuery can be used for much much more.

    I don't know how ASP's version works exactly but AJAX is just a page request.

  • I would definately check out jQuery and not bother with MS's ajax implementation. For the things you want, you can check out jQuery's docs for $post for example or ajax/load functions.

    You can either add events to the controls on your page, like the carpets / area rugs radio buttons, or add that event to the submit button and then make a call to the products controller to retrieve a partial view that loads into the products div.

  • The answer to your question is definitely, "yes".

    I've got one in front of me right now, so I'll try to abstract it out.

    First, create a controller action that returns a JsonResult (rather than ActionResult). Other than its return type it's just like any other action, so you can send parameters, etc. The only thing that's really different is that you're going to return a JsonResult() object, setting its Data property and any other properties that you may need. Mine looks something like this (very pseudo-codish...):

    public JsonResult GetList(int parentId)
    {
      var results = dataRepository.GetById(parentId);
    
      return new JsonResult()
      {
        Data = results.ToArray();
      };
    }
    

    Now, in your view, create a script that looks something like this. Note that this is jQuery syntax, so it may look a bit unusual if you're not familiar with it.

    <script language="javascript" type="text/javascript">
    // When the document is ready, start firing our AJAX
    $(document).ready(function() {
      // Bind a function to the "change" event of our drop-down list
      $("#dropDownId").bind("change", function(e) {
        updateList();
      });
    }
    
    var retrieveData = function(path, parentId, fnHandleCallback) {
      // Use the getJSON method to call our JsonResult action
      $.getJSON(path, { parentId: parentId }, function(data) {
        fnHandleCallback(data);
      });
    };
    
    // The path parameter is our JSON controller action
    function updateList() {
      retrieveData("/Controller/GetList", $("#dropDownId").val(), handleResponse);
    }
    
    function handleResponse(data) {
      // Ok, now we have the JSON data, we need to do something with it.  I'm adding it to another dropdown.
      $("#otherDropDownId > option").remove();
    
      for (d in data)
      {
        var item = data[d];
    
        $("#otherDropDownId").append("<option value=\"" + item.Value + "\">" + item.Text + "</option>");
      }
    }
    </script>
    
    <%= Html.DropDownList("dropDownId", new SelectList(new List<SelectListItem>())) %>
    <%= Html.DropDownList("otherDropDownId", new SelectList(new List<SelectListItem>())) %>
    

    This is all very much off the top of my head, so let me know if something needs to be clarified or corrected.

    Edit

    As noted in my comment, in order to "AJAXify" your page, you don't really want to push everything around in your Model. Instead, it sounds like you want something like this:

    Controller action:

    public JsonResult GetPagedData(int page, int itemsPerPage, string[] filters)
    {
      var results = dataRepository.GetPagedItems(pageId, itemsPerPage, filters);
    
      return new JsonResult()
      {
        Data = results.ToArray();
      };
    }
    

    JS changes:

    var retrieveData = function(path, pageNumber, pageSize, filters, fnHandleCallback) {
      // Use the getJSON method to call our JsonResult action
      $.getJSON(path, { page: pageNumber, itemsPerPage: pageSize, filters: filters }, function(data) {
        fnHandleCallback(data);
      });
    };
    
    // The path parameter is our JSON controller action
    function updateList() {
      retrieveData("/Controller/GetPagedData", $("#pageNumber").val(), $("#dropDownId").val(), null, handleResponse);
    }
    

    I've intentionally ignored figuring out both the page number and the filters - they would follow essentially the same principles.

    Finally, when you're rendering the data you'll put it into your product grid rather than another drop-down.

    Keith Barrows : Thanks for the detailed example. Unfortunately, my ViewModel for this page is more complex than your example. ^_^ I have: ProductCatalogBrowserModel which contains 5 datasets within it (ProductMenu, ProductMenuByProductTypeView, ProductDetail, ColorFilterList, LifestyleFilterList). With that in mind, how do I pass back the whole thing - which is my Model object in the page?
    GalacticCowboy : So your Model contains all of the data for your page? One of the things AJAX/JSON will really help with is to lower the amount of data you're pushing around all the time. For example, only send enough initially to show the page, and then use AJAX/JSON to retrieve the rest of the page data "on-demand", such as when a drop-down selection changes.
    Keith Barrows : Hmm. Maybe I am making this more complicated than it should be. :) I am working on just the dropdown (ItemsPerPage) and trying to get the paging menu and product display to work correctly. I do not have a grid to put items into either. I have a PartialView where I assemble the right side of the page (paging menu & product listing). The code looks like (see next comment):
  • <% } %>
Keith Barrows : (Man, that looks ugly in the comments!) Basically, when originally rendering the page it creates X amount of
sections - 1 for each product. If, through AJAX, I increase the number of products per page I don't have the extra
elements to populate. It almost feels like the correct way to do this is to force a post back each time the user changes something.
GalacticCowboy : The beauty of AJAX is that you're writing directly to the DOM, so you create your own DIV tags when you need them - they don't have to already exist on the page.
Keith Barrows : Thanks. This has me started in the right direction! A lot of work yet to do and I will be posting more questions. :)
Keith Barrows : See "http://stackoverflow.com/questions/830520/-ajax-not-returning-data" to help me finish this off. The (data) piece is popping an error of "data is not defined"...

How to add Stroke to Text in AS3?

I am coding in AS3 and want to add a stroke to text that I'm displaying to the screen. My current code is:

format = new TextFormat("BN Elements", 14, 0xEEEEEE, false, false, false, null, null, "left");
format.font = "BN Elements"
scoreText = initText(starsleftText, format, "", 160,5, 545, 61);
scoreText = "Stroke This Text";

As the text is dynamically generated I can't create it as a text object in the Flash IDE - where I know to add a stroke I can use the "glow" function set to 1000% and Low quality.

I suppose my question is, how can I apply the "glow" filter effect with similar properties within AS3 directly? Or is there an alternative "stroke" function I don't know about?

From stackoverflow
  • It's pretty easy:

    http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/filters/GlowFilter.html (There's an example at the bottom of the page)

    I'm not sure if they've added anything new as far as adding a real stroke, but the glow filter 'stroke' works just as well with code.

    You could also create a pixel bender filter that would give you a bit more control over the effect, I can't seem to find any already written ones out there though:(

    quoo : oh also, beware, if the text is selectable, using the glow filter will add a stroke to the selection as well.
  • Flash generates its strokes from the edges of shapes. Since you are using text dynamically (not in authoring) Flash can render with either 1) device text which in drawn by the operating system, or 2) embedded text in your SWF file. In the first case, Flash doesn't (currently) have access to the edges to stroke them. In the 2nd, Flash uses a specialized sub-renderer for text that (again currently) doesn't support stroking, or for that matter, anything but solid color fills.

    Short answer: stroking of text currently isn't supported in the runtime, although the glow or pixel bender approach suggested is a good idea.

SQL Server- ORDER BY CASE problem

I have the following the query running dynamically

SELECT *
FROM Vehicles
WHERE (DKID IN (69954))
ORDER BY case when ImageName1 = 'na' then 0 else 1 end, Make , Model, Year DESC

This is returning the following error:

Error Executing Database Query. [Macromedia][SQLServer JDBC Driver][SQLServer]Incorrect syntax near 'na'.

Thanks in advanced for your help

From stackoverflow
  • Try enclosing the case statement in parentheses.

    SELECT *
    FROM Vehicles
    WHERE (DKID IN (69954))
    ORDER BY 
        (case when ImageName1 = 'na' then 0 else 1 end), Make , Model, Year DESC
    
  • works for me

    here is repo script

    use tempdb
    go
    
    create table Vehicles(DKID int,ImageName1 varchar(50),
                              Make int, Model int, Year int)
    
    insert Vehicles values (69954,'na',1,1,2007)
    insert Vehicles values(69954,'bla',1,1,2008)
    go
    
    SELECT *
    FROM Vehicles
    WHERE (DKID IN (69954))
    ORDER BY case when ImageName1 = 'na' then 0 else 1 end, 
    Make , Model, Year DESC
    
  • are you running this query dynamically?, if so you might need to escape the quotes around 'na':

    SELECT *
    FROM Vehicles
    WHERE (DKID IN (69954))
    ORDER BY case when ImageName1 = ''na'' then 0 else 1 end, Make , Model, Year DESC
    
    Patcouch22 : I am running it dynamically, however the escape quotes still provide the same error.
    KM : try replacing 'na' with char(110)+char(97), which will be slow, but will help diagnose it more...
    Patcouch22 : that did allow it to run...
    KM : that shows that you are not escaping it properly, is "na" a constant or part of the dynamic query? edit your question to show that is generating the query, the propblem is there.
  • Your query works fine for me in SQL Mgmt Studio... Maybe try it this way instead to see if it gets you anywhere:

    SELECT
        case when ImageName1 = 'na' then 0 else 1 end as OrderCol,
        *
    FROM Vehicles
    WHERE (DKID IN (69954))
    ORDER BY OrderCol,Make,Model,Year DESC
    
  • You're using JDBC. Is there probably a transformation / interpretation from JDBC? Try making the 'na' a parameter. Check if there is a certain syntax in JDBC for string constants in queries. I don't use JDBC, so I could be completely wrong.

  • As KMike said, it looks like you didn't not escape properly.

    Basically, when you ran your statement, it did not generate a syntactically correct SQL statement from the dynamic SQL.

    Generally, when I am writing dynamic sql, I use a print statement to print the generated SQL. I can then review the generated sql visually for obvious mistakes, and then execute it it to make sure it works as expected.

    If I made a mistake in the dynamic SQL, it will usually be revealed here.

How do you make your Java application memory efficient?

How do you optimize the heap size usage of an application that has a lot (millions) of long-lived objects? (big cache, loading lots of records from a db)

  • Use the right data type
    • Avoid java.lang.String to represent other data types
  • Avoid duplicated objects
    • Use enums if the values are known in advance
    • Use object pools
    • String.intern() (good idea?)
  • Load/keep only the objects you need

I am looking for general programming or Java specific answers. No funky compiler switch.

Edit:

Optimize the memory representation of a POJO that can appear millions of times in the heap.

Use cases

  • Load a huge csv file in memory (converted into POJOs)
  • Use hibernate to retrieve million of records from a database

Resume of answers:

  • Use flyweight pattern
  • Copy on write
  • Instead of loading 10M objects with 3 properties, is it more efficient to have 3 arrays (or other data structure) of size 10M? (Could be a pain to manipulate data but if you are really short on memory...)
From stackoverflow
  • You don't say what sort of objects you're looking to store, so it's a little difficult to offer detailed advice. However some (not exclusive) approaches, in no particular order, are:

    • Use a flyweight pattern wherever possible.
    • Caching to disc. There are numerous cache solutions for Java.
    • There is some debate as to whether String.intern is a good idea. See here for a question re. String.intern(), and the amount of debate around its suitability.
    • Make use of soft or weak references to store data that you can recreate/reload on demand. See here for how to use soft references with caching techniques.

    Knowing more about the internals and lifetime of the objects you're storing would result in a more detailed answer.

  • I suggest you use a memory profiler, see where the memory is being consumed and optimise that. Without quantitative information you could end up changing thing which either have no effect or actually make things worse.

    You could look at changing the representation of your data, esp if your objects are small. For example, you could represent a table of data as a series of columns with object arrays for each column, rather than one object per row. This can save a significant amount of overhead for each object if you don't need to represent an individual row. e.g. a table with 12 columns and 10,000,000 rows could use 12 objects (one per column) rather than 10 million (one per row)

    Boune : Good trick for minimizing the number of objects.
    Boune : I agree that a memory profiler is a good starting point for someone who does not know which Class instances are taking all the memory. The question is more, if I know in advance I will have 10M pojo#1 in memory, how do minimize the consumption of each instance?
  • Ensure good normalization of your object model, don't duplicate values.

    Ahem, and, if it's only millions of objects I think I'd just go for a decent 64 bit VM and lots of ram ;)

    Brian Agnew : Which is quite possibly the most cost-effective solution :-)
    duffymo : +1 - That's cutting to the heart of the issue.
    Fortyrunner : Great answer. Using caches of data and reducing duplicate records and fields is a major saver.
    Boune : How do you minimize the number of duplicated values? Original question mentions usage of Enum, String.intern, object pools. How would you insure that values are not duplicated?
    krosenvold : @Boune There may be combinations (subsets) of values that are duplicate.
  • I want to add something to the point Peter alredy made(can't comment on his answer :() it's always better to use a memory profiler(check java memory profiler) than to go by intution.80% of time it's routine that we ignore has some problem in it.also collection classes are more prone to memory leaks.

  • Normal "profilers" won't help you much, because you need an overview of all your "live" objects. You need heap dump analyzer. I recommend the Eclipse Memory analyzer.

    Check for duplicated objects, starting with Strings. Check whether you can apply patterns like flightweight, copyonwrite, lazy initialization (google will be your friend).

  • You could just store fewer objects in memory. :) Use a cache that spills to disk or use Terracotta to cluster your heap (which is virtual) allowing unused parts to be flushed out of memory and transparently faulted back in.

  • A fancy one: keep most data compressed in ram. Only expand the current working set. If your data has good locality that can work nicely.

    Use better data structures. The standard collections in java are rather memory intensive.

    [what is a better data structure]

    • If you take a look at the source for the collections, you'll see that if you restrict yourself in how you access the collection, you can save space per element.
    • The way the collection handle growing is no good for large collections. Too much copying. For large collections, you need some block-based algorithm, like btree.
    Boune : How would you define better data structures? How would you implement that?
  • Spend some time getting acquainted with and tuning the VM command line options, especially those concerning garbage collection. While this won't change the memory used by your objects, it can have a big impact on performance with memory-intensive apps on machines with a lot of RAM.

  • If you have millions of Integers and Floats etc. then see if your algorithms allow for representing the data in arrays of primitives. That means fewer references and lower CPU cost of each garbage collection.

    1. Assign null value to all the variables which are no longer used. Thus make it available for Garbage collection.
    2. De-reference the collections once usage is over, otherwise GC won't sweep those.
    Boune : I disagree with item 1. I would just let the gc do what it is suppose to do. There are only a few cases (arrays, collections) where this could be useful, not all variables. http://stackoverflow.com/questions/449409/does-assigning-objects-to-null-in-java-impact-garbage-collection

.htaccess redirect after replace a word?

Hello, I need to use .htaccess file to replace a world in URL

something like this:

example URL: http://example.com/oldword/test-page.html

redirect to: http://example.com/newword/test-page.html

how can I use mod_rewrite to redirect every URL containt "/oldword/" to the same URL after replacing that word?

From stackoverflow
  • This should do it for you:

    RewriteRule ^oldword/(.*)   /newword/$1   [L]
    

    Edit: It might not work exactly depending on your RewriteBase settings, but it'll be close.

    Second Edit: If you need to have a 301 Moved Permanently header associated with the old URLs, you can do something like this as well:

    RewriteRule ^oldword/(.*)   /newword/$1   [R=301,L]
    
  • Hi,

    see here:

    <IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /
    RewriteRule ^oldword(.*)$ http://%{HTTP_HOST}/newword$1 [L]
    </IfModule>
    

    ciao,

    Chris

    Gumbo : It’s better to leave the protocol, host and port part away like zombat did. Additionally your rule would also redirect `/oldword-and-some-more` to `/newword-and-some-more` and I don’t think that’s what chiaf wanted.

windows user domain account question

Hi

I have one question regarding domain account. I have one domain controller where all the user information are stored. I have joined the domain on my laptop but I observed that I am able to log-in using domain credentials even if domain controller is down. How is this possible?

Kind Regards PK

From stackoverflow
  • You're using cached credentials. You can disable this in the registry if you want.

  • If you've logged on to the laptop prior to the Domain Controller being down, your credentials are cached locally on the machine.

    This occurs so that you can use your domain credentials to log into the machine even if you are disconnected from the network (working from home, etc.).

  • Windows will cache previous user login credentials locally so you can still log in if the DC is down. You shouldn't be able to access network resources that might need you to login though.

Simple inter-proccess communication in Qt4

I need to make so that my application can have only one instance running at a time. Also when it's launched with a command line parameter ( like when registered to open certain file types ) it should pass the parameter to an existing instance and quit immediately without displaying graphical interface. You all probably know what I mean. The framework used is Qt 4, and it seems like it must have some facilities for that. Any ideas?

From stackoverflow
  • There is a Qt Solutions project doing this:

    Qt Single Application

  • It's also possible to implement a this sort of class oneself using QSharedMemory (see QSharedMemory::attach() ). It's capable of being used for both determining whether other instance is already running and communicating/sending messages. Except some pointer magic and memory copying it's quite straightforward.

  • There are several ways to do inter process communication. Examples can be found in Qt's examples section.