Wednesday, April 20, 2011

'JQuery' is undefined

I am working on a ASP.net project created with local file system settings. I am using MVC and Jquery. Jquery is working fine when I run the application in debug mode i.e. in ASP.net Development server. I am trying to host the application in IIS 7. In hosted mode, it does not recognize Jquery and gives scripting error 'Jquery is undefined'. The locations of the script files is unchanged in both modes. Can anybody have any clue what can be the reason and how to solve this.

My code look like this;

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="../../Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>

<script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>

<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>

<!-- YUI Styles -->
<link href="../../Content/reset.css" rel="stylesheet" type="text/css" />
<link href="../../Content/fonts.css" rel="stylesheet" type="text/css" />
<link href="../../Content/grids.css" rel="stylesheet" type="text/css" />
<!-- /YUI Styles -->
<link href="../../Content/knowledgebase.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
    //this hides the javascript warning if javascript is enabled
    (function($) {
        $(document).ready(function() {
            $('#jswarning').hide();
        });
    })(jQuery);
</script>

<asp:ContentPlaceHolder ID="ScriptContent" runat="server" />

....

From stackoverflow
  • This usually occurs when you have malformed HTML or JavaScript.

  • If there's no errors in your javascript (eg: missing brackets), then it's either not including the jQuery file, or you're trying to run some code which relies on jQuery before that file has loaded.

    Raja : How came its working fine on Asp.net application server
  • Try using Firebug 'Net' tab to see if the file gets loaded.

    You can also configure Firebug to fail on all errors and see when the error happens as compared to when jQuery gets loaded.

    MrBoJangles : I did what you said. I neglected to add the latest jQuery to the project. Thanks!
  • Jquery?!
    You mean jQuery?

    Javascript is case-sensitive. Jquery is not the same as jQuery.

    Raja : its JQuery is undefined. The case is fine and its working on ASP.net application server.
    EndangeredMassa : The case should be "jQuery" not "JQuery". But if it works on test, this isn't the issue.
  • For me, this error typically occurs when there is a true Javascript error in some of my code. This prevents the jQuery.js file from being fully parsed. Look in the Error Console in Firebug, Safari or another debugging-friendly browser.

  • After Using the FIrebug, I found out the files were not found as the relative path for the files doesn;t work. TO resolve the problem, we should use the Url.Content Method to reslove the path. For example:

    <script src="<%= Url.Content("~/Scripts/jquery-1.2.6.js")%>" type="text/javascript"></script>
    
    Pim Jager : You should encode the opening character for the script tag in this character from < to <
    Will Dean : It would be good to mark Andrey's answer as accepted...
    Kip : Why didn't the relative path work though? Care to explain what was different?
  • You could also try letting Google host jQuery for you:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
    

    This will avoid having to worry about the relative path to the script, avoid load on your server, and will be faster for users (who probably already have it in their browser's cache somewhere).

  • Common mistakes is that other Jquery Scripts are included first(Jquery.validation.js) before the Jquery.js

  • Raja is right, URL.Content works.

    <script src="<%= Url.Content("~/Scripts/jquery-1.2.6.js")%>" type="text/javascript"></script>
    

    Further, to prevent yourself from getting surprised at the moment you are migrating your application to an IIS server, don't use web development server but use IIS when developing.

    You can use IIS directly from visual studio by editing the the web properties:

    • Go to the tab 'Web'
    • Check 'Use Local IIS Web server'
    • Click 'Create Virtual Directory'
    • Go to the IIS Manager to disable anonymous access in the created virtual directory if applicable.
  • If all else fails, make sure the file has the right permissions set. This just happened to me!

    You can either right click the file in your directory and set the permission there, or just create another .js file in Visual Studio and copy and paste the contents over. Worked like a charm. :)

  • try

    <script src="<%= ResolveUrl("~/Scripts/jquery-1.2.6.js")%>" type="text/javascript"></script>
    
  • The path is wrong. Double check it.

  • 0 I do not know whether you guys found the solution to your problem or not. I was facing the same problem and going nuts to figure out why do I get "jQuery is undefined" error on the plugins i use. I tried all the solutions i get from the internet but no luck at all.

    But, suddenly something splash on my mind that may be the script files should be in order. So, I moved the jquery referece to first position and everything start working like charm.

    Remember guys, if you're using any plugins with jquery, make sure you use the folloing order of setting reference to those fiels.

    1.reference to the jquery library 2.reference to the other subsequent plug-in (dependant) libraries and so on...

    e.g.: 1. "script src="js/jquery-1.3.2.min.js" type="text/javascript"... 2. "script src="js/jqDnR.min.js" type="text/javascript"... 3. "script src="js/jquery.jqpopup.min.js" type="text/javascript"... 4. "script src="js/jquery.bgiframe.min.js" type="text/javascript"...

    Always make sure you must put the jquery reference to first and then the subsequent libraries.

    Hope, this solves your problem especially when you use with MasterPages. Its very strange that it works no matter what order you use when you don't use MasterPages but when you do, then it somehow requres the proper order.

    Good luck and happy coding,

    Vincent D'Souza

    John Fischer : Solved my problem. Thanks!
  • To elaborate on the "text/javascript" answer, "application/javascript" will work in firefox and load jQuery just fine. It won't, however, load the file in IE. Use "text/javascript":

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" ></script>
    
  • To add my problem/solution to this long list...

    I was using Windows 2003 to test the site in IE7. The site came up fine but jQuery didn't run at all. So I went straight to the http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js and found that ajax.googleapis.com was not on the list of safe sites. After adding *.googleapis.com everything worked fine. Silly oversight, but maybe this will help someone else in a similar situation.

  • Vincent D'Souza's solution worked out. Thanks.

  • Vincent D'Souza,

    You are absolutely right ! The order matters ! It solved my error 'jQuery' is undefined.

    Thanks!

Which Silverlight MVVM Test Project Type?

When creating a test project for a Silverlight MVVM application, should I create a standard C# test project - aimed at the ViewModel, or a Silverlight Test project aimed at the view, or (gulp) both...

From stackoverflow
  • In order to test Silverlight, you will need to create a Silverlight class library project ... you will not be able to create a "standard" test project, as Silverlight uses a stripped-down framework, and has alternate dependency requirements. For example, Silverlight references mscorlib ... you will not be able to add this easily to a "standard" project, as this reference is controlled by project template.

    ib.

    Mark Cooper : Yep you are right. The standard project fell on it's knees straight away. It wasn't able to cope with any objects inheriting from UserControl. I suspect that more serious issues would have followed, have switched to the SL Test Project and all is fine.

Injecting Javscript into a page

I'm writing a web-based game that involves clicking links on various sites on the internet. I know it sounds strange but the basic premise is that you start on my page where you click a link to some page on another site. You continue to follow links until you get to the page you are trying to reach. Think WikipediaGame.org. The difference being that I don't have control over the actual pages with the links.

What I need to be able to do is track all the links that they clicked, and when they get to the final page, I want to send them back to my site (or something along those lines).

What I was thinking was that perhaps I could somehow intercept the page requests and inject some javscript to track which links they clicked. Is this possible? Has anyone done anything like this? Obviosuly this could pose a security risk. Do I have any other options? I want to avoid making the user collect a list of all the links and then post them into a textbox on my site.

From stackoverflow
  • Maybe a bookmarklet to send the current page to your site? That way the user would have complete control over the list of links shared with a minimal amount of work.

  • To make this cross-browser compatible -- I'm not sure if there is a way without writing a plugin for each browser. But, I could be wrong too :-)

    You could try to make a bookmarklet (Javascript that runs when the user clicks a certain bookmark), but that wouldn't run automatically on every page the user loads; the user would have to click on it to run it.

    If you want to just support Firefox, you could write a Greasmonkey script that would run on every page/site. But, that would limit the scope of your users.

  • You cannot do this using javascript alone. You need to either write a firefox plugin, or a GM script.

  • I don’t know how you would inject JavaScript into someone else’s pages, which would then send you messages. That actually sounds like something a virus would do.

    I think you could accomplish something like what you want using an iframe.
    A simple method would be to include an iframe preset to load the “start” location on your site, and then include a button on the outer page for the user to post back their current location (in the iframe).

    When the button on your page is pressed you could query the current state of the iframe…
    References to the window generated by the iframe and to the document loaded into the iframe can be obtained via the frames array using the name attribute.

     window.frames[iframeName]  <br/>
     window.frames[iframeName].document  <br/>
    

    The frames array method of referencing has broad support, even among quite old browsers, as long as you attach a name attribute to the iframe. For best results, use both name and id.

    For more up-to-date browsers, the document inside the iframe can also be referenced via contentWindow (IE win) and contentDocument (DOM) properties of the iframe element:

    // IE5.5+ windows
    document.getElementById(iframeId).contentWindow
    document.getElementById(iframeId).contentWindow.document
    or,
    // DOM 
    document.getElementById(iframeId).contentDocument
    

    EDIT: As the comments below suggest, it looks like most browsers prevent you from using an iframe this way. You can start a window anwhere you want, but you are not allowed to communicate with it if it is not on your same domain. I guess you could build a "Man in the Middle" scenerio, where you flow all the trafic through your server first, but that is not very practical.

    Here is a good example of jQuery controlling an iframe

    http://wwwendt.de/tech/dynatree/doc/sample-iframe.html

    Hope that helps.

    erikkallen : I don't think this is allowed. Modern browsers don't like cross-site scripting
    bobince : Indeed, you will only be able to read the location or do anything else useful with the frame when it is on the same site as the parent window.
  • I'm not sure you can accomplish this the way you're envisioning. Without writing a browser plugin, I would look at what sites like KeepVid are doing. They have you create a bookmark on your toolbar, and the bookmark url is this:

    javascript:document.location='http://keepvid.com/?url='+escape(window.location);

    That essentially passes the url the user is presently on over to keepvid. If you use this concept, you can have your user click the bookmark button to register that url to you and you can collect that and pass the user back to where they were.

  • So i figured out what to do. I'm using an iframe like this:

    <iframe src="Puzzle/ContinuePuzzle" />

    It points the source to my Mvc Controller. In my controller I do a WebRequest for the actual url that I want and then parse the Html and stick my own javascript in the page. The page acts and looks like the other site, but it's actually coming from my site.

Send data between class and form?

Hey guys. The other day, I asked how to create a message box in your class, but one of the answers stated that was it wasn't the correct approach. I understand that this is because it really defeats the point of a class.

My program reads word by word from a string file, and checks if each word is in the database. I want to put every word not found into a ListBox on the form, which can have multiple selections.

How do i send that data back to the form each time a new word is found?

Thanks,

Ash

From stackoverflow
  • I suggest you make a method something like this:

    /* ... */
    
    public IEnumerable<string> FindMissingWords(
                                   string fileName, IEnumerable<string> toSearch)
    {
        List<string> missingWords = new List<string>();
    
        // todo: the appropriate code for looking up strings in the file, using 
        // the filename and the strings that we passed into the function.
    
        // if you find one, add it to missingWords
    
        return missingWords;
    }
    

    Then call that method from your form, and add each string it returns to your box.

    (If you're not familiar with IEnumerable, don't worry -- it's just a interface that defines a sequence of things, like an array or a list. You could pass an array of strings instead, but it would be a little less precise.)

  • If the class has a reference to the form, the it can just update the form directly.

    someForm.SomeListBox.Items.Add(someWord);
    

    If the form has a reference to the class, you can have the class raise an event like

    public delegate string WordNotFoundHandler(string word);
    public WordNotFoundHandler event WordNotFound ;
    

    and have the form handle that event

    theClass.WordNotFound += AddItemToListBox
    
    void AddItemToListBox(string word)
    {
    someListBox.Items.Add(word);
    }
    

    the advantage of doing it this way instead of one huge call that returns all the words is that it provide a faster ui response time, especially when done by a separate thread

    mquander : A more elegant way of accomplishing this same goal (returning them one at a time as you find them) would probably be to use an iterator block with yield return.
    Ash : what do you mean when you say iterator block with yield return? Like store it up and send it in a bulk if you get me?
    Sung Meister : "someForm.SomeListBox.Items.Add(someWord);" That never seems like a good idea unless you expose a facade method that hides a direct access to "SomeListBox". Just create "Add" in the form so you can call "someForm.Add(someWord)"
    Jacob Adams : @Sung Meister - I agree. In reality, I don't like the first approach at all since you're still taking a dependency on a the form from your business class.
  • This is what I'd do (or similar) :

        bool done = false;
        while(true)
        {
            string foundstring;
            done = searchforstring(out foundstring);
            if(done)
                break;
            // Not done, so take what we found and add it to the listbox
            this.BeginInvoke(new Action<string>(delegate(string input)
                { this.listBox.BeginUpdate(); this.listBox.Items.Add(input); this.listBox.EndUpdate(); }),
                new object[] { foundstring });
    
            }
    

    Substitute the name of your listbox control and I think that'll work. Or you can break out the anonymous method into its own object. The idea is that every time you find a new string, you dispatch a worker to execute the update in the "main application thread" (hence the BeginInvoke() call). I'm not TOTALLY sue if the begin/endUpdate() calls are strictly necessary, but they might be.

    Obviously how you GET the strings is up to you, but this should be the way to get it into the listbox on-the-fly assuming your app is multi-threaded. If it isn't multithreaded, a straight-out Invoke() (instead of BeginInvoke) should work to update the listbox immediately, but that'll probably degrade performance of your search.

    Ash : Hey Kevin, sorry to be a pain but can you explain the difference between multi and singloe threadind please? I know its something to do with he way its processed. Sorry for silly questions, start uni this year loll
    Kevin : I'll do a little better than that: http://www.albahari.com/threading/ It's an online e-book called "Threading in C#" and is one of the best primers on the concept that I've seen. Very clear, and shows all of the major "gotchas" involved. I hope it helps.
  • You do not want to couple your form with the class that searches and find words from a file. Here is an Event-based solution

    Basically what you have to do is to expose an event in the class that reads and find words from a file (I named it as WordFinder for an illustration.)

    WordFinder exposes an event called WordFound that is raised when a new word is found.

    public class WordFinder
    {
        public event EventHandler<WordFoundEventHandler> WordFound = delegate { };
        public event EventHandler NoWordsFound = delegate { };
    
        protected virtual void OnWordFound(WordFoundEventHandler e)
        {
            var wordFoundHandler = WordFound;
            wordFoundHandler(this, e);
        }
    
        private void OnNoWordsFound(EventArgs e)
        {
            var noWordsFoundHandler = NoWordsFound;
            noWordsFoundHandler(this, e);
        }
    
        public void FindWords(string fileName)
        {
            //.. read file and find word
            //.. When a word is found,
            OnWordFound(new WordFoundEventHandler(foundWord));
    
            // Keep a counter somewhere and check if any words has been found, 
            // if no words are found, then raise "NoWordsFoundEvent"
            OnNoWordsFound(EventArgs.Empty);
        }
    }
    
    public class WordFoundEventHandler : EventArgs
    {
        public string FoundWord { get; private set; }
    
        public WordFoundEventHandler(string foundWord)
        {
            FoundWord = foundWord;
        }
    }
    

    Now your form would simply register to the event of WordFinder and add a new item when a new word is found.

    public partial class Form1 : Form
    {
        private readonly WordFinder _WordFinder;
    
        public Form1()
        {
            InitializeComponent();
    
            _WordFinder = new WordFinder();
            _WordFinder.WordFound += WordFinder_WordFound;
            _WordFinder.NoWordsFound += WordFinder_NoWordsFound;
        }
    
        private void WordFinder_WordFound(object sender, WordFoundEventHandler e)
        {
            // Add item to the list here.
            foundWordsListBox.Items.Add(e.FoundWord);
        }
    
        private void WordFinder_NoWordsFound(object sender, EventArgs e)
        {
            MessageBox.Show("No words found!");
        }
    
        private void findWordsButton_Click(object sender, EventArgs e)
        {
            _WordFinder.FindWords(/* pass file name here */);
        }
    }
    

Create Your Own .NET Assembly Cache

Hello everyone,

In a .net application I am writing, I need to locally cache assemblies from various locations so my application can use them even if the original locations are unavailable. I cannot use the GAC (primarily because I want portability and also because the assemblies might not be signed).

Does anyone know of any .net code which supports this functionality already? I need the cache to be able to tell me if a particular assembly is already in the cache and handle different versions of assemblies as well. It is likely that I will have to resort to writing my own assembly cache, but I thought I would ask this question because I don't really want to "re-invent the wheel" if it has already been done.

From stackoverflow
  • The Mono project had to (re)implement the GAC and it works on Windows. I would start there.

  • I ended up having to write my own assembly cache...

    Here's the basics of how it works, in order to help others if they need to implement their own assembly cache:

    • The cache is a folder with a corresponding wrapper class in the application.
    • The method to install an assembly in the cache returns a string 'token' (the name under which the assembly is installed) which the caller can save and use to retrieve the assembly later.
    • The method to retrieve an assembly takes the token and returns an object which encapsulates the cached assembly's information.

    When installing an assembly, first compare an incoming assembly's bits to the bits of each of the already cached assemblies and determine if the assembly is already installed (if all the bits are the same, they must obviously do the same thing). If the assembly is already installed, then return the name of the previously cached assembly. If it is not already installed, allow multiple versions to be installed by finding an available variant of the assembly name in the cache folder (e.g assembly.dll, assembly - (2).dll, assembly - (3).dll, etc), cache the assembly in the folder, and return its cached name to the caller.

    As far a security and strong naming goes, it does not make sense in my application to do strong name verification, as it would be what Bruce Payette calls "lawn gnome mitigation" (a security countermeasure which an attacker could merely walk around). If an attacker decided to poison an assembly, he would also have access to the location where the strong name would be stored and could easily change it to his strong name. It ends up being the user's responsibility to use assemblies only from sources he trusts. If the user installs a malicious assembly, it is his fault, not mine. Still, to provide a little more protection for the user, the use of external assemblies in my application will disabled by default. For other applications, though, it might make sense to implement strong name verification as an extra layer of security.

Where to write log for Windows app

I've got a .NET Windows application that's deployed via ClickOnce to a Web server. There are approximately 100 users at any given time, all centrally located. I'm using log4net to log within the application, but I'm having trouble arriving at the best place to put the log.

I've tried having them write to a shared network location, but some users have experienced poor I/O with that approach. I've tried logging to the user's temp folder, but that makes it harder to retrieve the logs. I haven't tried the event log because I will probably have to jump through some hoops to get that working, and I'm not sure if it's worth it. I've never tried database logging, but I've always assumed that it would be relatively slow.

Does anybody have experience with logging in a Windows application deployed in a corporate environment? Any suggestions on where I can put the log so that it will be (1) quick, (2) reliable, and (3) accessible?

From stackoverflow
  • The problem with Database logging isn't the speed: it's the reliability. You log for when things go wrong, and if something's going wrong already the odds of an inaccessible DB aren't in your favor.

    Generally, you want to write to a local text file and somewhere else like a network share or DB. If you're having IO/speed problems you can use the text file as a buffer and write logs to the contended resource in batches. Then you periodically flush the local 'backup' logs.

    John M Gant : Do you know if it's possible to configure log4net to do that?
    Joel Coehoorn : I know you can configure it to log to both db or newtork share _and_ local file. I'm not aware if you can get it to batch/buffer logs. I doubt it will do it exactly as I described, but you could build the flushing/recovery logic directly into your app.
  • What about the ApplicationData folder? On Vista that would be something like this:

    C:\Users\Ray\AppData\Local\MyCompanyName

    If you want a central location I would go with the database logging. But as Joel said, you'll want both a local location that always works (or as close to it) and a central place to collect logs for when things are working normally.

    Joel Coehoorn : He's worried about collecting them centrally.
  • If the app is a typical two-tier job, logging to the database with AdoNetAppender is probably appropriate. AdoNetAppender batches up log messages in chunks of up to 100, though you'll probably want to configure it to write through on at least WARN severity events.

    You may also want to consider logging to the All Users Application Data directory, although this may make it equally unwieldy to retrieve logs. Perhaps consider adding a shortcut somewhere?

    Finally, if log accessibility issues are a common theme in your organization, you may want to consider a log collection app such as Splunk.

  • log4net supports database appenders for some major databases. This might be a better alternative if you have a suitable database available. Approach with caution, however, because it could reduce the reliability of your application if not managed correctly.

    You could use it in conjunction with local file logging by using a BufferingForwardingAppender to batch your network logging and send only when you get a message that exceeds a certain threshold. That way, you can have sufficient context to trace errors, but only when errors occur.

    <appender name="BufferingForwardingAppender" type="log4net.Appender.BufferingForwardingAppender">
    <bufferSize value="1024" />
    <lossy value="true" />
    <evaluator type="log4net.Core.LevelEvaluator">
      <threshold value="ERROR"/>
    </evaluator>
    <appender-ref ref="DatabaseAppender" />
    

    Michael Haren : Sorry, @Michael Meadows--I didn't mean to step on your edit
  • You could try somewhere under the CommonAppData folder - i.e., CommonAppData\YourAppName\Logs - provided that you ensure size limits and/or periodic cleanups. People are used to periodically clean up the temp folders but are wary of starting ot dig around CommonAppData, AppData or LocalAppData.

    Writing anywhere else but here or into Temp will sooner or later get you in trouble on Vista and higher.

    If the logs are not vital, i.e. if irreplaceable data won't get lost if someone deletes the log, I would definitely go for a subfolder in Temp and have a separate task scheduler job upload them. It's the least painful place.

  • I've used log4net with ms sql databases. I generally put them a dedicated db, on a different server, if possible. That way if there are problems with the application server or db, I don't lose my logging.

    Speed was never an issue.

  • You could use a combination of local logging, and you could sync the logs to a centeral database at successful log off.

    It depends on what kind of logging you want to do and how your application is running. If the application doing the logging is a client side application, then if you write to the event logs it may not be helpful.

    If you do want to write to the event logs, it's fairly straight forward:

    http://support.microsoft.com/kb/307024

    One more thing, if you are looking for a location that you know the user has access to for sure, you can use isolated storage, but the fact that you were trying to write to a shared folder makes me thing that you want one central location for your logs, in which case a DB is probably your best bet, and my top suggestion may be best for you.

  • In our applications we log4net and use a common log file for all our users, in the CommonAppData directory (C:\Documents and Settings\All Users\Application Data\Company\Product). In this case our installer has to manually set the file permissions for the directory and log file so all users can access it, the default permissions are only for the user that installs the application.

    We also log unhandled exceptions (when we can) to the event log using a top-level exception handler (using an implementation similar to: http://www.wintellect.com/cs/blogs/jclark/archive/2005/03/30/simple-main.aspx). We use the event log since all bets are off about the state of the file streams that are opened. Again, our installer has to set up the event log source in the Application event log.

    If you do use the event log, make sure your logging is pretty minimal. If you log a lot of events since the event log can get filled up pretty quickly, and the default policy on XP is for the event log to start dropping events if the log is full, and the default size is relatively small (512 KB, and only overwrite events older than 7 days).

Code Curiosity

I was looking at the YUI Compressor and came across this piece of code in the ECMA.NET project (Continuation file if you are interested).

protected internal override int FindPrototypeId (string s)
    {
        int id;
        #region Generated PrototypeId Switch
    L0: {
            id = 0;
            string X = null;
            if (s.Length == 11) { X = "constructor"; id = Id_constructor; }
            if (X != null && X != s && !X.Equals (s))
                id = 0;
        }
    EL0:
        #endregion
        return id;
    }

I have no idea what L0: and EL0: are doing here and have never seen this before. The term seems too rudimentary for google as well.

Anyone know anything about this?

From stackoverflow
  • They look like lables for use as goto targets. See http://msdn.microsoft.com/en-us/library/13940fs2.aspx for more information.

    Ty : I was afraid of that.
    C. Ross : C# has goto's? ...
    Scott Dorman : @Ty, @C. Ross: Yes, C# has goto's. In fact, loops are really nothing more than syntax sugar around a goto.
  • They look like labels to me. The label is not used in this example (because it is generated code?), but can be used to jump another place. You could use goto L0; to jump the the first label. As an example, the following code writes just "Hello, World" because it skips the middle Write():

    Console.Write("Hello, ");
    goto Last;
    Console.Write("Cruel ");
    Last:
    Console.WriteLine("World");
    
  • Those are labels, as in GOTO.

  • L0 and EL0 look like labels for the goto statement

  • They're obviously labels, but I don't think that they're used as goto targets. I imagine that they're designed to be recognized by a code generation tool of some kind. The code generation tool "owns" the code between L0 and EL0, which probably just means "end L0."

How do I create a recursive replacement in mod_rewrite?

I'm fairly new to mod_rewrite and I am attempting to convert a URL from

http://example.com/foo/bar/blah/etc.html

into

http://example.com/stuff/foo_bar_blah_etc.html

The assumption is that there is not a set number of directories between the domain and the file name therefore I cannot just write a single rewrite rule with 3 placeholders. I could conceivably create 5 or 6 rules with zero to 5 placeholders but I have a feeling there is a better way. Can someone please help me with this?

From stackoverflow
  • Try this:

    RewriteRule (.*)/(.+) $1_$2 [NS]
    RewriteRule (.*) stuff/$1 [NS]
    
    martinatime : Thanks for the quick response. Once I have a chance to test it I will accept your answer.
    chaos : What I originally posted doesn't work, I'm afraid. I've edited it to something that testing shows more functional.
    martinatime : I think you meant to use [N] for the flags for the first line.
  • I think you could do this to replace one slash at a time with an underscore:

    RewriteRule ^/(.+)/(.*?)$ /$1_$2 [N]
    RewriteRule ^.*$ /stuff$0
    

    The [N] flag causes Apache to restart the URL rewriting process from the first rule. If you have other rules that apply to the URL before these two, remember that they'll be invoked on every iteration as well.

    An alternative, which may or may not be more efficient, would be to use an external program to handle the rewriting. You'd put this in your Apache configuration file (instead of the above)

    RewriteMap slashtouscore prg:/usr/local/bin/slashtouscore.pl
    RewriteRule ^/(.*)$ /stuff${slashtouscore:$1}
    

    and then you'd need to create the executable script /usr/local/bin/slashtouscore.pl with the contents

    #!/usr/bin/perl
    $| = 1;
    while (<>) {
        s|/|_|g;
        print;
    }
    

    (It doesn't have to be a Perl script, of course, any program with the same function will do - and of course the filename can be whatever you want, as long as it's accessible to Apache)

    Note that none of this is tested.

    martinatime : Thanks for the thorough answer.

Using Rhino Mocks, why does invoking a mocked on a property during test initilization return Expected call #1, Actual call #0?

I currently have a test which tests the presenter I have in the MVP model. On my presenter I have a property which will call into my View, which in my test is mocked out. In the Initilization of my test, after I set my View on the Presenter to be the mocked View, I set my property on the Presenter which will call this method.

In my test I do not have an Expect.Call for the method I invoke, yet when I run I get this Rhino mock exception:

Rhino.Mocks.Exceptions.ExpectationViolationException: IView.MethodToInvoke(); Expected #1, Actual #0..

From what I understand with Rhino mocks, as long as I am invoking on the Mock outside the expecting block it should not be recording this. I would imagine the test to pass. Is there a reason it is not passing?

Below is some code to show my setup.

public class Presenter
{
    public IView View;

    public Presenter(IView view)
    {
        View = view
    }
    private int _property;
    public int Property
    get { return _property;}
    set
    {
       _property = value;

       View.MethodToInvoke();
    }
}

... Test Code Below ...

[TestInitialize]
        public void Initilize()
        {
            _mocks = new MockRepository();
            _view = _mocks.StrictMock<IView>();
            _presenter = new Presenter(_view);
            _presenter.Property = 1;            
        }
[TestMethod]
        public void Test()
        {
            Rhino.Mocks.With.Mocks(_mocks).Expecting(delegate
            {                
            }).Verify(delegate
            {
                _presenter.SomeOtherMethod();
});
        }
From stackoverflow
    1. What exactly are you trying to test in the Test method?
    2. You should try to avoid using strict mocks.
    3. I suggest using the Rhino's AAA syntax (Arrange, Act, Assert).
  • The problem lied with me not understanding the record/verify that is going on with Strict mocks. In order to fix the issue I was having this is how I changed my TestInitilize function. This basicaly does a quick test on my intial state I'm setting up for all my tests.

    [TestInitialize]
        public void Initilize()
        {
            _mocks = new MockRepository();
            _view = _mocks.StrictMock<IView>();
            _presenter = new Presenter(_view);
    
            Expect.Call(delegate { _presenter.View.InvokedMethod(); });
            _mocks.ReplayAll();
            _mocks.VerifyAll();
            _mocks.BackToRecordAll();
            _presenter.Property = 1;
        }
    
    Igor Brejc : Again, are you sure you need strict mocking? Your scenario looks more like using an ordinary mock which does not force you to specify all of the expectations. And if you use AAA, it's much simpler to code it.
  • Why in the world would you want to test the same thing each time a test is run?

    If you want to test that a specific thing happens, you should check that in a single test.

    The pattern you are using now implies that you need to - set up prerequisites for testing - do behavior - check that behavior is correct and then repeat that several times in one test

    You need to start testing one thing for each test, and that help make the tests clearer, and make it easier to use the AAA syntax.

    There's several things to discuss here, but it certainly would be clearer if you did it something like:

    [TestMethod]
    ShouldCallInvokedMethodWhenSettingProperty()
    {
       var viewMock = MockRepository.GenerateMock<IView>()
    
       var presenter = new Presenter(viewMock);
    
       presenter.Property = 1;
    
       viewMock.AssertWasCalled(view => view.InvokedMethod());
    
    }
    

    Read up more on Rhino Mocks 3.5 syntax here: http://ayende.com/Wiki/Rhino+Mocks+3.5.ashx

wrapping text using jQuery

I was wondering how I might search out any text in a document and wrap it in a link structure using jQuery.

For example - Search the whole document for the text 'target heart rate' and transform it into

<a href="jvscrt:popup('heartrate.cfm')">target heart rate</a>

Any ideas?

thanks! Chris

From stackoverflow
  • You'll need to:

    • Have a conversion rule - i.e. "text to convert" -- url -> "convert.cfm". You can achieve this with a simple hash array.

    • Now, you'll need to search for the text() contained inside all your matching DOM elements. If you find it, you'll need to split the contents in 3 parts: before and after the text + the text itself.

    • Now create the anchor and join the three parts together and replace the old content.

    That's how text highlighint, for example, is done in most cliet-side scripts.

    Since you asked for just an idea, I'll leave the fun coding for yourself ;)

    Seb : You can replace the content with .text() or .html(), depending on whether your contents contain HTML tags or not. First get the contents with text() (var text = element.text()), then split and join using standard JavaScript functions, and then set back with element.text(newText). Hope that helps :)
  • Use the find method along with contains. Probable something like

    $("p").find(":contains('target heart rate')")
          .wrapInner($("<a href="jvscrt:popup('heartrate.cfm')"></a>"));
    

    or something like that.

    I could be totally wrong. Check http://docs.jquery.com

  • jQuery wrap function maybe?

    Also consider the text highlight plugin which highglights keywords. instead of highlighting you could create links out of them. More specifically the following lines:

    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    // change the above to create an anchor and add href etc
    
    altCognito : This won't do the trick, it will replace all of the text.
  • This is close:

    var findIt = 'Javascript';
    
    $.expr[":"].containsNoCase = function(el, i, m) {  
        var search = m[3];
        if (!search) return false;
        // we'll use text to find what we want...
        return eval("/" + search + "/ig").test($(el).text());
    };  
    
    
    $("p:containsNoCase('"+ findIt +"')").each(function() {
      // and then html when we are ready to replace
      var ht = $(this).html();  
      var pos= ht.indexOf(findIt);
      var start = ht.substring(0, pos);  
      var end = ht.substring(pos+findIt.length);
    
      $(this).html(
          start
          +'<a href="javascript:alert(\'heartrate.cfm\')">'+findIt+'</a>'+end);
    
    });
    

    But what you are looking for is a tough thing to provide. You want to search only the text of elements, but need to update the HTML content of the element where it was found (in order to add links). When you go back and use html() to update the element, you'll end up potentially replacing things you don't mean to.

    For example this is fine:

    <p>Hey, Javascript is fun.</p>
    

    Where as this has issues:

    <p><img src="something/Javascript.png">Whee, yaa Javascript</p>
    

    The text within the image src is replaced errantly. If there's a way you can find the position of the matching text within an element not surrounded by, or within a tag, it would be possible to replace it cleanly. Of course you can use text(), but then you can't use any HTML in what you are adding back in :(. Maybe I'll check back and see if anyone has anything else to offer.

  • I'm such a gomer:

    Text highlighting plugin for jQuery.

    You can probably use this to get the job done. Just change out the wrapping with your anchor (your link) element.

JavaScript help with forms?

So, I have a form that consists of 4 inputs, username, password, email, and name.

I am sick and tired of having to make a javascript function for each of them, because each input is a text input, and when a user clicks the input box I have it change the background of the input to a different color.

So heres how I coded:

The form inputs:

<input type="text" name="username" id="usernameInput" onclick="changeUsername(); return false;" onblur="changeUsernameback(); return false;">

<input type="text" name="password" id="passwordInput" onclick="changePassword(); return false;" onblur="changePasswordback(); return false;">

and the other two forms are the same, only with different names and different id's and javascript functions.

MY Javascript:

function changeUsername() {
 document.getElementById('usernameInput').style.background='#FFFF00';
}

function changeUsernameBack() {
 document.getElementById('passwordInput').style.background='#FFFF00';
}

and the other three are just like that only setup for their own specific id.

AND when creating CSS, I have to make different ID's for all 4 inputs.

What I want to know is: Is there a way I can only make one CSS id, and one javascript function to change all inputs? Because I know when you just use one function for all, javascript tries to change all at once..

I was thinking something like

document.getElementById('inputText'+[i]).style.background='#FFFF00';

and then when I give each input an id I could just automatically increment them on the page such as input1, input2, input3 etc.

But that doesn't seem to work? Maybe I am coding it wrong? Please help..

From stackoverflow
  • You COULD do this:

    <input type="text" name="username" id="usernameInput" onfocus="change(this);" onblur="changeBack(this);">
    <input type="text" name="password" id="passwordInput" onfocus="change(this);" onblur="changeBack(this);">
    

    With this javascript:

    function change(el) {
        el.style.background='#FFFF00';
    }
    
    function changeBack(el) {
        el.style.background='#FFFF00';
    }
    

    A couple of notes:

    • You are using onclick - while that may work, I think what you want is onfocus.
    • As far as I know, it is not necessary to return false; on either of these events.


    While the above will work with plain Javascript, I am obligued to suggest the jQuery way:

    <input type="text" name="username" id="usernameInput">
    <input type="text" name="password" id="passwordInput">
    

    And then do this with jQuery:

    $(function() {
        $('input').focus(function() {
            $(this).css('background-color', '#FFFF00');
        }).blur(function() {
            $(this).css('background-color', '#FFFF00');
        });
    });
    

    I personally feel this is cleaner, as inline javascript events are ugly, but the first one should work.

    Grant Wagner : I understand why you included the recommendation for jQuery (since everyone else is suggesting it). But this is a JavaScript author who had to ask how to make a function to change the background color of an input more generic. I think jQuery would just confuse him at this point.
    Paolo Bergantino : I just thought I'd throw it in there, but you are definitely right.
    TStamper : +1 i agree with your suggestion
  • <input type="text" name="whatever" id="uniqueVal" onclick="return gotFocus(this);" onblur="return lostFocus(this);">
    
    function gotFocus(el) {
        el.style.background = 'Red';
        return false;
    }
    
    function lostFocus(el) {
        el.style.background = 'Blue';
        return false;
    }
    

    I personally like returning false from these types of functions to reduce the amount of code I have to write in the HTML element attribute.

  • You should try using jQuery - that's what we use. It would be very simple using jQuery.

    <script>
    $(document).ready(function(){
      $(".PrettyInput")
        .focus(function() { $(this).css("background-color", "#FFFF00"); })
        .blur(function() { $(this).css("background-color", "#FFFF00"); });
    });
    </script>
    
    <html>
    <body>
      Username: <input type="text" class="PrettyInput" />
      Password: <input type="text" class="PrettyInput" />
    </body>
    </html>
    
  • Here's a complete example using jQuery.

    <html>   
    
      <head>
    
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
        <script>
          $(document).ready(function(){
          $("input:text")
            .focus(function() { $(this).css("background-color", "#FFFF00"); })
            .blur(function() { $(this).css("background-color", "#FFFFFF"); });
          });
        </script>
    
      </head>         
    
      <body>
    
        <form>
          Username: <input type="text" /> 
          Password: <input type="text" />   
        </form>
    
      </body>
    
    </html>
    
  • Is there a way I can only make one CSS id, and one javascript function to change all inputs?

    Yes, you can attach one event handler to many elements simply by assigning it as a function; the subject element comes in as ‘this’. You don't even need an ID.

    For completeness, since no-one else seems to have said it, it's quite possible to have the advantages of non-inline, unobtrusive event handlers without dragging in the whole of jQuery (which is probably a bit excessive if all you want is a few highlighting inputs):

    <input type="text" name="username" />
    <input type="text" name="password" />
    
    <script type="text/javascript">
        function inputFocussed() {
            this.style.backgroundColor= 'yellow';
        };
        function inputBlurred() {
            this.style.backgroundColor= 'white';
        };
    
        // Bind to input[type=text]
        //
        var inputs= document.getElementsByTagName('input');
        for (var i= inputs.length; i-->0;) {
            if (inputs[i].type=='text') {
                inputs[i].onfocus= inputFocused;
                inputs[i].onblurred= inputBlurred;
        }   }
    </script>
    

Xml schema: empty targetNamespace

Is it legal to use no targetNamespace attribute or an empty one in an Xml schema?

If so then what does it mean, are we "adding" something to the "empty namespace" (which always exists) or creating an "anonymous namespace" which is not related to other schemas?

How would an instance xml document look like, do elements need to be explicitly bounded to some namespace?

From stackoverflow
  • Yes, definitely. XML namespaces are optional - you can leave them out if you wish to do so, and if you don't get into any trouble with ambigious XML elements in your "XML world" :-)

    Marc

  • See XML Schema Part 0: Primer for a very concise description of how undeclared targetNamespaces work.

    As for an empty targetNamespace, that's not valid. From the spec:

    Since the empty string is not a legal namespace name, supplying an empty string for targetNamespace is incoherent, and is not the same as not specifying it at all. The appropriate form of schema document corresponding to a ·schema· whose components have no {target namespace} is one which has no targetNamespace attribute specified at all.

Optimize memory usage of a collection of Strings in Java

I have a large number of name - value pairs (approx 100k) that I need to store in some sort of cache (say a hash map) where the value is a string with an average of about 30k bytes in size.

Now I know for a fact that a large number of the values have exactly the same string data. In order to avoid having to allocate the identical string data several times, I would like to somehow reuse a previously allocated string thus consuming less memory. In addition this needs to be reasonably fast. i.e. scanning through all the previously allocated values one-by-one is not an option.

Any recommendations on how I could solve this problem?

From stackoverflow
  • String.intern() will help you here (most likely). It will resolve multiple instances of the same string down to one copy.

    EDIT: I suggested this would 'most likely' help. In what scenarios will it not ? Interning strings will have the effect of storing those interned string representations permanently. If the problem domain is a one-shot process, this may not be an issue. If it's a long running process (such as a web app) then you may well have a problem.

    I would hesitate to say never use interning (I would hesistate to say never do anything). However there are scenarios where it's not ideal.

    Tom Hawtin - tackline : String.intern can be quite slow. It also places the String into the permanent generation, which could well cause GC performance problems.
    Brian Agnew : The permanent generation is an issue, granted. The question doesn't have the context in which this is to be used. If it's a standalone app, then it may well be ok. Otherwise (say a ong running web app), then not. As ever, solutions need to be evaluated in the context of where they'll be used.
    Stu Thompson : @Brian Agnew: My I suggest you edit and expand your answer then to include context? Comments don't count, if you get my drift.
  • String.intern is the obvious choice as Brian says. But if you don't want to intern across all the String in memory, you can use a Set to first see if the value is present. Here's untested code. You will have to work out removing from reverse map when removing from main

      class Map2<K, V> implements Map<K, V>
      {
        Map<K, V> _map = Maps.newHashMap();
        Set<V, V> _rev = Maps.newHashMap();
    
        V put(K k, V v) {
          if (_rev.containsKey(v)) {
            V prev = _rev.get(v);
            return _map.put(k, prev);
          } else {
            _rev.put(v, v);
            return _map.put(k,v);
          }
       }
    
    Tom Hawtin - tackline : ConcurrentMap has putIfAbsent, which might be useful.
    Ingo : I like this solution, it's no overkill with weak references etc. To optimize even more on storage, one could just search the existing values in the Map, given that the total number is small (say <10000). Upvote!
  • Do not use String.intern (there have been various memory issues related to this through the years). instead, create your own cache, similar to String.intern. basically, you want a Map, where each key maps to itself. then, before caching any string, you "intern" it:

    private Map<String,WeakReference<String>> myInternMap = new WeakHashMap<String,,WeakReference<String>>();
    public String intern(String value) {
      synchronized(myInternMap) {
        WeakReference<String> curRef = myInternMap.get(value);
        String curValue = ((curRef != null) ? curRef.get() : null);
        if(curValue != null) {
          return curValue;
        }
    
        myInternMap.put(value, new WeakReference<String>(value));
        return value;
      }
    }
    

    note, you use weakreferences for the keys and values so that you don't keep references for strings which you are no longer using.

    kdgregory : james? as in JT?
    james : yep, tis JT. too funny that i wrote your code for you.
    StaxMan : No, this is very BAD advice. Most such comments refer to rather old issues for now obsolete JVMs. There is absolutely nothing wrong with String.intern() for long-living shared Strings. Much less than issues with roll-your-own replacements.
  • It somewhat depends upon how you are creating the String.

    One possible way is to use TreeSet that uses a Comparator that can compare existing Strings and the source of your new String. Use SortedSet.tailSet and an Iterator to find an existing String. Or alternatively NavigableSet.ceiling/floor or a TreeMap with a similar setup.

    I wrote a weblog entry about another technique to cache immutable objects (in particular Strings), but that is more suitable for smaller objects.

    String.intern has performance problems.

  • Agreed with others on not using String.intern(): once you've put a string there, it will never go away. Look to early revisions of Xerces for why this is a bad idea.

    A better solution is to use a WeakHashMap, wrapping the value in a WeakReference:

    private Map<String,WeakReference<String>> _map 
        = new WeakHashMap<String,WeakReference<String>>();
    
    public synchronized String intern(String str)
    {
        WeakReference<String> ref = _map.get(str);
        String s2 = (ref != null) ? ref.get() : null;
        if (s2 != null)
            return s2;
        str = new String(str);
        _map.put(str, new WeakReference(str));
        return str;
    }
    

    This code is from an article that I wrote on the Java reference objects. You'll find the explanation there.

    EDIT: need to create a new string here (and I'll update the article) because the original might be a substring of a far larger character array. I thought that was fixed around JDK 1.3, but apparently not (at least not in 1.5).

    PintSizedCat : Interning a string will not mean that it will 'never go away', you can garbage collect the perm gen though it may not be so efficient it can and will get garbage collected if there are no strong references to it.
    kdgregory : The permgen, at least in the Sun JVM, is managed separately from the rest of the heap. If you can point to code that removes strings from the intern table, then I'm willing to retract my statement.
  • You could compress the strings. A 30K string should get a good compression ratio. I wrote a hack to compress large String as an exercise, but you could use a byte[] of the compressed data to store the String.

    A 30K character string will use about 60KB (2 bytes per character) so even using getBytes() is likely to be an improvement.

  • Do you actually need Strings, or do you just need any old CharSequence? If not, then consider implementing a "compact" CharSequence such as the one I suggest in the link.

Show dialog on outbound calls

I want to be able to show a dialog on outbound calls. The dialog is used to ask the user if he wants 1. dial the phone number directly 2. Dial through the PBX.

If option two is chosen, i want to dial a specific number and send the dialed number as DTMF.

  1. How do I catch and stop outgoing calls?
  2. How do I get the dialed number?
From stackoverflow
  • It appears that it is not possible to intercept outgoing calls in Windows Mobile (see this thread for example). To be honest, I would be surprised if this was possible, as it would be a security risk for the platform. Anyone could write viruses or trojan horses that redirect calls through a specific network. Also, the operators wouldn't be happy about this "feature".

    One solution would be to write an application and ask the users to place their calls through its user interface. You could then initiate either a regular call or a call through the PBX easily. You need of course to integrate the contacts, but this isn't hard. Have a look at the Microsoft.WindowsMobile.PocketOutlook namespace.

  • Firstly (and possibly a little off topic) there is actually a built-in WM6 feature for allowing calls to be routed either over the cell network or over SIP using the built-in dialer. If SIP calling (or "Internet Calling" as the UI has it) is enabled and there is a WiFi connection the call will be routed over SIP, if not it will route over GSM in the normal way. There is actually also a registry setting that enables the calls to routed over SIP if there is a 3G/HSDPA connection available too.

    Most manufacturers do not ship the part of the WM6 OS that enables this functionality on their device ROMs (presumably mindful of their call revenue), however it can easily be installed on most WM6 devices.

    Secondly if this is not what you are after (if you don't want to use SIP but use a calling card or need to have the choice after you place the call) I can tell you it must be possible to do what you want to do because this app does it - magicall. One way I can think of doing this is to get notification of the call, immedialety end it, wipe it from the log, put up your PBX or Cell dialog, and then place the call again in the way the user requested. This has the disadvantage that if the original call was started programmatically the app that did so will think the call was ended prematurely. It may also be possible using another technique, but that is where my knowledge runs out...

  • It can be done through TAPI. I'm hiring a person through elance.com to do it.

  • It is possible. I did it some years ago for a calling card application. It requires C++, however.

    I'm quite sorry, I can't remember anything about how I did it, but is IS possible.

    Just start looking here: TAPI Reference