CAPTCHA This, Yo! - Early Alpha

by Jon Davis 14. July 2009 01:54

I've posted a mini-subproject:

http://www.CAPTCHAThisYo.com/

The site is self-explanatory. The idea is simple. I want CAPTCHA. I don't want to support CAPTCHA in my apps. I just want to drop in a one-liner snippet somewhere and call it done. I think other people share the same desire. So I now support CAPTCHA as a CAPTCHA app. I did all the work for myself so that I don't have to do that work. I went through all that trouble so that I don't have to go through the trouble .... Wait, ...

Seriously, it's not typical CAPTCHA, and it's Not Quite Done Yet (TM). It's something that'll evolve. Right now there isn't even any hard-to-read graphic CAPTCHA.

But what I'd like to do is have an ever-growing CAPTCHA questions library and, by default, have it just rotate through them randomly. The questions might range from shape detection to riddles to basic math. I'd really like to have some kind of community uploads thingmajig with ratings, so that people can basically share their own CAPTCHA solutions and they all run inside the same captchathisyo.com CAPTCHA engine. I'm just not sure yet how to pull that off.

Theoretically, I could take the approach Microsoft took when C# was initially released (long, long ago, in a galaxy far, far away), they had a cool insect sandbox game where you could write a .NET class that implements some interface and then send it up to the server and it would just run as an insect on the server. The objective of the game was to write the biggest killer/eater. I'm not sure how feasible the idea is of opening up all .NET uploads to the server, but it's something I'm pondering on.

Anyway, the concept has been prototyped and the prototype has been deployed is sound, but I still need to work out cross-site scripting limitations, bear with me. I still need to find a designer to make something beautful out of it. That said, feel free to use it and give feedback. Stand by.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C# | Computers and Internet | Cool Tools | Pet Projects | Techniques | Web Development

IIS Subweb Applications Are Virtual Directories

by Jon Davis 21. June 2009 14:32

Microsoft never ceases to amaze me how they keep showing the most obscure error messages and support documentation for the simplest of causes.

HTTP Error 500.19 - Internal Server Error

Description: The requested page cannot be accessed because the related configuration data for the page is invalid.
Error Code: 0x80070005
Notification: BeginRequest
Module: IIS Web Core
Requested URL: http://www.mysite.com/myapp/
Physical Path: ~~
Logon User: Not yet determined
Logon Method: Not yet determined
Handler: Not yet determined
Config Error: Cannot read configuration file
Config File: ~~
Config Source:

   -1:

    0:
More Information... This error occurs when there is a problem reading the configuration file for the Web server or Web application. In some cases, the event logs may contain more information about what caused this error.
 

I was getting IIS 7 error 500.19 on Windows Server 2008 over the weekend, and when I discovered it I spent hours on this error. Google didn't help; everyone pointed to invalid XML in the web.config or in applicationHost.config, or said that there must be an invalid DLL reference in applicationHost.config, or said that I need to add the proper users (IIS_IUSRs, Network Service, IUSR) to the directory and/or web.config. None of these solutions applied. There was nothing in my Windows event logs and enabling IIS tracing produced no log files.

It turned out to be a simple cause: the physical directory as configured in Basic Settings for the application was wrong. Why Microsoft did not include this rather obvious scenario in the Help file for this error is beyond me!!

In my case, my root web was working fine, but my subwebs were not working fine and I got this error for the subweb. The subweb was an individually configured ASP.NET application. I figured that this wasn't important because the root web was just a flat HTML file, but it mattered.

What happened in my case was that a few days ago I had relocated the root web, then updated IIS to point to the new directory. All of the subweb applications, however, were treated by IIS as virtual directories, each with its own physical directory mapping. So each had the stale path. More specifically, I moved "C:\dir\www.mysite.com" to "C:\dir\mysite.com", updated IIS for my site to point to \dir\mysite.com, and left it as such. The applications under ...\mysite.com were each pointing to the stale absolute path of C:\dir\www.mysite.com\[application] instead of picking up the relative path of their parent directory.

I had to update each subweb application's Basic Settings to point to the revised path, and the 500.19 error went away.

Hope this helps others like it would've helped me.

Jon

So Long, Farewell

by Jon Davis 15. May 2009 02:10

No I'm not killing off my blog. I am, however, going to stop being so cheap, and start hosting my IIS web apps, including this blog, on an external server for a change.

For years now I've been hosting my blog here behind a home cable modem. As I post this--indeed this'll be the last night that this will be the case--I have a cheap virtual dedicated Linux server with Apache proxying out to my home IP on an alternate port. COX only blocks port 80 (the web port, and some other ones like SMTP's), so I have my router at home rigged to redirect traffic on the alternate port back to port 80 and to my internal web server's IP address (this is the same server that "serves" me prerecorded shows on my HDTV via Vista Media Center). The proxy/router setup works, but then COX keeps killing off my Internet connection. I keep having to stand up, go to the back room where the cable modem is, disconnect the cable modem power and coax, wait for 5 seconds, and reconnect everything. (Yes, the coax, too. It doesn't resync unless I do that.)

My web site tends to go offline all day while I'm at work. I've noticed that the disconnects happen routinely at about 3:15 PM and at about 1:45 AM, but they also happen erratically and sporatically throughout the day, and it often stays offline until human intervention (manual shutoff and powerup). And, I am beginning to suspect that they are actually monitoring network traffic and they disconnect me when they see any normal flood of inbound HTTP requests that come from two or more visitors at a time. It might also be heat-related; the disconnects are suddenly much more frequent lately, and coincidentally it's suddenly a lot hotter around here in this Arizona climate.

So I'm finally caving in; short of tunnelling the proxied HTTP packets, I can't beat COX at this game. I'm going to try a VPS from http://www.automatedvps.com/about.php .. They look like an under-established outfit but so far they are not just affordable for Win2008 virtual dedicated hosting, the VPS I've already snagged feels quite performant. I'll have all the Windows play dough I could ask for, and I won't have to worry about my blog or any major web site I might be hosting going offline because COX wants to keep us from hosting stuff.

Incidentally, before signing up with AutomatedVPS.com, I tried Mosso.com's Site Cloud. I'd been slobbering over their Kool Aid for so long, I had to give them a shot. It was ugly, though. Their control panel behaves erratically, frequently showing multiples of new objects being added until you refresh or until a Live Chat support staff deletes the extras. I had to throw the whole thing out when I saw that I had NO control over IIS 7 and the subweb applications and application pools.

------

UPDATE: Ouch. Yeah, that took a lil more time than I expected to transfer everything (see next post re SQL Express and Dynamic Ports), but it's switched now. 

My ‘Aha!’ Moment With Javascript

by Jon Davis 14. May 2009 01:25

9/27/2012 Note: This is an old 2009 blog entry, and it was recently promoted on DZone with no intention of making it a Big Link. I've since learned quite a bit more about Javascript fundamentals, correcting a few misgivings presented here, and you should, too. 

-- 

For most people this goes back to Javascript 101 but it’s worth blogging, in my opinion. A lot of people truly have no idea how much power is available on the client side of web apps, and they actually think that Javascript is dying.

The true power of Javascript was not made known to me until I had my aha! moment. It was about two or three years ago, and I think I could sum up (profusely, with freeze-dried concentration) what triggered my realization when these two essential facts became clear:

Discovery #1:

 

var myFunc = function() { };
var myObj = new myFunc();

 

.. is to Javascript what this is to C# ..

public class MyClass 
{
public MyClass() { } 
}
MyClass myObj = new MyClass();

 

 

That is to say, Javascript functions are functions (of course) but also “classes” (object prototypes) and constructors all rolled into one. So, for example, to accomplish this in C# ..

class MyClass {
void DoSomething() {
MessageBox.Show("something");
}
}
... 
MyClass myObj = new MyClass();
myObj.DoSomething();

.. you could do this in Javascript ..

function myFunc() { }
myFunc.prototype.doSomething = function() {
alert('something');
};
...
var myObj = new myFunc();
myObj.doSomething();

 

Or, you could assign the doSomething member function “at runtime” (dynamically appending the member to the object after the object has already been instantiated).

var myFunc = new function() {
this.doSomething = function() {
alert('something');
};
};
var myObj = new myFunc();
myObj.doSomething();
// or even
myObj.doSomethingElse = function() { alert('something else'); };
myObj.doSomethingElse();

Note that ‘this’ is used to reference the object instance that the function instance is. Incidentally, you can ensure “this” works when calling other objects’ functions by using function_name.call(object, params);.

That said, these things point out the dynamic nature of Javascript object members – you can append properties and functions to an object at runtime by using syntax like [object].doSomething = function() { }. It also shows that members on an object are akin to a string-keyed hashtable.

And that hashtable-like behavior brings about the second part of my “aha!” moment.

Discovery #2:

All user-defined objects, including functions, are ultimately string-keyed hashtables. That is not a limiting behavior but an extra feature because they are still real objects.

But JSON (Javascript object notation) objects are extraordinarily handy as alternatives to functions because of the expressive way you can declare them.

var myNewObject = {
member_A : "abc",
member_B : 123
};

.. is akin to C#’s ..

Dictionary<string, object> myNewObject = new Dictionary<string, object>();
myNewObject["member_A"] = "abc";
myNewObject["member_B"] = 123;

And it’s even more powerful when you consider that the members can be functions.

myNewObject = {
doSomething: function() {
alert('something');
}
};
myNewObject.doSomething(); // invoke
// or,
myNewObject = { };
myNewObject.doSomething = function() {
alert('something');
};
myNewObject.doSomething(); // invoke

.. can be implemented in C# 3.0 like so ..

delegate void SimpleMethod();
public static void RunSnippet()
{
var myNewObject = new Dictionary<string, object>();
myNewObject["doSomething"] = (SimpleMethod)(() =>
MessageBox.Show("something")
);
// .. 
((SimpleMethod)myNewObject["doSomething"])(); // invoke
}

In fact, take a look at this old blog post I saw at Ajaxian.com: http://colinramsay.co.uk/diary/2008/04/02/javascript-generation-a-change-of-heart/

In return, comparing the two languages reveals the power of C# 3.0, as well. C# 4.0’s dynamic objects will be trying even harder to “be powerful like Javascript already was”.

*evil grin*

Set Up IIS For An MVC App: When All Else Fails, Check View Config

by Jon Davis 29. April 2009 17:22

I got stumped today when trying to set up a CruiseControl.NET+RoboCopy powered development server deployment for an ASP.NET MVC web app. I set up MVC Framework (gets MVC into the GAC), did the wildcarding in the IIS app config, and everything worked fine, except for strongly typed views. I was confounded. The Event Viewer showed:

Exception information:
    Exception type: HttpParseException
    Exception message: Could not load type 'MyMvcApp.ViewPage<MyModel>'.

This turned out to be caused by a simple mistake. After cc.net compiles the app, RoboCopy copies all the .aspx files over to the web app, and ignores the .cs files, the .config files, etc., so that the .config files don’t get overwritten. I had manually deployed the main web.config file for the app, but I forgot that the Views directory also has a web.config.

Why there is a web.config in the Views directory, I don’t know yet. But the extra .config file in the Views directory is absolutely mandatory to get an MVC app working on IIS, or at least on IIS 6 anyway (haven’t tried 7).

Visual Studio 2008 Crashes When Using ASP.NET MVC (Nasty, NASTY Bug!)

by Jon Davis 16. April 2009 10:05

Some people (like me) have had issues with Visual Studio 2008 suddenly disappearing without errors when the developer user opens up an .aspx file, a .master file, or some other code file in an ASP.NET MVC project.

Had this show stopping issue beat me black and blue over the last 24 hours. I finally got past it when I used the /safemode switch with devenv.exe, but that disables all my lovely add-ins like Resharper. :(

Finally, one of the team members pointed me to “NDP20SP2-KB963676-x86.exe”. He had the same issue and tried to run this hotfix and it worked for him.

It seems to be working so far for me, too. The hotfix is here:

https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=16827&wa=wsignin1.0

File for Windows XP: NDP20SP2-KB963676-x86.exe

More info here: http://www.google.com/search?q=KB963676

AJAX Deferred Loader for ASP.NET

by Jon Davis 11. April 2009 14:19

Here’s a simple ASP.NET control that takes a URL parameter, renders a placeholder on the page, and uses Javascript to “lazy-load” the view content for that placeholder area. It basically does what my sprinkle.js did a long while back, but it takes advantage of ASP.NET controls and jQuery simplicity with its load() function.

It also has self-refreshing. This is good for updating a section of a page with progress information, without refreshing the entire page.

To use it,

  1. Compile the source code (below) to your Web Application project’s assembly, or create an assembly and reference the assembly in your project. You should put this control in its own namespace or in a “.Controls” namespace because of #2 below.
  2. Add a header to any page that would use it to explicitly import all controls under the namespace for which you’re using this control.
    <%@ Register Assembly="MvcApplication1" Namespace="MvcApplication1.Controls" TagPrefix="demo" %>
  3. Be sure jQuery is referenced on the page, ideally in the <head> tag. If you’re using Web Forms and <head runat=”server”>, the process of getting it in there is a little complicated but that’s a different topic. I’m using ASP.NET MVC and I just put it in the Master page. Ultimately, jQuery needs to be loaded before anything else loads, that’s your objective, so you figure it out.
    <html><!-- ... -->
    <head>
      <!-- ... -->
      <script language="javascript" type="text/javascript" src="../../Scripts/jquery-1.3.2.min-vsdoc.js"></script>
      <script language="javascript" type="text/javascript" src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.min.js") %>"></script>
      <!-- ... -->
    </head>
    <body><!-- ... -->
    </body>
    </html>
  4. Now you can reference inline. Note the “RefreshInterval” setting, which is an integer that indicates, in seconds, how often to refresh the region. In this sample, it updates every two seconds. Note also that the HTML that comes back from the referenced URL can include script markup that cancels the interval, such as if a process has completed.
     
    <demo:AjaxDeferredView runat="server" ViewUrl="~/Deferred" RefreshInterval="2">
        <asp:Panel runat="server">Please wait ...</asp:Panel>
    </demo:AjaxDeferredView>
  5. This is what gets outputted with the above tag. Note the “undefined, undefined” are there because the PostData and the Callback optional properties are not set on the control tag.
    <div id="ctl00_MainContent_ctl00">
        <div>
    		Please wait ...
        </div>
    </div>
    <script language="javascript" type="text/javascript"><!--
    $(document).ready(function() {
    	window['ctl00_MainContent_ctl00_interval'] = setInterval(function() {
    		$('#ctl00_MainContent_ctl00').load('http://localhost:5577/Deferred', undefined, undefined);
    	}, 2000);
    	$('#ctl00_MainContent_ctl00').load('http://localhost:5577/Deferred');
    });
    --></script>
  6. And finally, what the end user will actually see is a momentary, split-second, or too-fast-to-see placeholder being swapped out for the content at the loaded URL.
  7. Here’s an example of how to clear that interval in the sample ~/Deferred view that comes back, such as if a process has completed, or in this case after the 5th hit (from any visitor). This sample might be the actual page that is invoked from the AJAX call.  Note the ClearParentInterval control, and that the logic that changes its ClearInterval property precedes its position on the page.
    <%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
    <%@ Register Assembly="MvcApplication1" Namespace="MvcApplication1.Controls" TagPrefix="demo" %>
    <% Response.Cache.SetCacheability(HttpCacheability.NoCache); %>
    Welcome to my deferred content. 
    <%
        
        //live counter
        var i = (int)(Context.Application["defercnt"] ?? 0);
        i++;
        Context.Application["defercnt"] = i;
        %><%=i %>
        
    <% if (i >= 5) // shutdown interval after 5 views
     {
         ClearIntervalControl.ClearInterval = true;
     } %>
     <demo:ClearParentInterval runat="server" ID="ClearIntervalControl" />
    

    This outputs the following when ClearInterval is set to true. The point of the example is in the ID’ing of the <span> tag and in the <script> tag’s contents. It basically walks up the DOM tree by one parent to get the placeholder’s ID in the DOM, then tacks on “_interval” and assumes that to be the name of the interval (which it is).
    <div>Welcome to my deferred content. 5</div>
        
    <span id="ClearIntervalControl">
    </span>
    <script type="text/javascript" language="javascript">
    	var ClearIntervalControl_ClearIntervalParentRef = $('#ClearIntervalControl').parent().attr('id') + '_interval';
    	if (window[ClearIntervalControl_ClearIntervalParentRef]) {
    		clearInterval(window[ClearIntervalControl_ClearIntervalParentRef]);
    	}
    </script>
    

Here’s the control source:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace MvcApplication1.Controls
{
    public class AjaxDeferredView : System.Web.UI.Control
    {
        protected override void OnInit(EventArgs e)
        {
            if (string.IsNullOrEmpty(ContainerTag))
                ContainerTag = "div";
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.WriteLine();
            writer.WriteBeginTag(ContainerTag);
            writer.WriteAttribute("id", ClientID);
            writer.Write(">");
            base.Render(writer);
            writer.WriteEndTag(ContainerTag);
            writer.WriteLine();
            writer.WriteLine("<script language=\"javascript\" type=\"text/javascript\"><!--");
            writer.WriteLine("$(document).ready(function() {");
            if (RefreshInterval > 0)
            {
                writer.WriteLine("\twindow['" + this.ClientID + "_interval']"
                    + " = setInterval(function() {");
                writer.WriteLine("\t\t$('#" + this.ClientID + "').load('"
                    + ResolveFullUrl(this.ViewUrl) + "', " 
                    + GetDataArg() + ", " + GetCallbackArg() + ");");
                writer.WriteLine("\t}, " + RefreshInterval * 1000 + ");");
            }
            writer.WriteLine("\t$('#" + this.ClientID + "').load('"
                + ResolveFullUrl(this.ViewUrl) + "');");
            writer.WriteLine("});");
            writer.WriteLine("--></script>");
        }

        [PersistenceMode(PersistenceMode.Attribute)]
        public object PostData { get; set; }

        [PersistenceMode(PersistenceMode.Attribute)]
        public string Callback { get; set; }

        [PersistenceMode(PersistenceMode.Attribute)]
        public string ViewUrl { get; set; }

        [PersistenceMode(PersistenceMode.Attribute)]
        public string ContainerTag { get; set; }

        [PersistenceMode(PersistenceMode.Attribute)]
        public int RefreshInterval { get; set; }

        private string GetDataArg()
        {
            if (PostData == null) return "undefined";
            // todo: convert complex class to JSON
            return PostData.ToString();
        }

        private string GetCallbackArg()
        {
            if (string.IsNullOrEmpty(Callback)) return "undefined";
            return Callback;
        }

        private string ResolveFullUrl(string url)
        {
            var ret = new Uri(Request.Url, Page.ResolveUrl(url));
            return ret.ToString();
        }

        private HttpResponse Response
        {
            get { return HttpContext.Current.Response; }
        }

        private HttpRequest Request
        {
            get { return HttpContext.Current.Request; }
        }
    }

    public class ClearParentInterval : Control
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (string.IsNullOrEmpty(ContainerTag))
                ContainerTag = "span";
        }
        protected override void Render(HtmlTextWriter writer)
        {
            writer.WriteBeginTag(ContainerTag);
            writer.WriteAttribute("id", this.ClientID);
            writer.WriteLine(">");
            base.Render(writer);
            writer.WriteEndTag(ContainerTag);
            writer.WriteLine();
            if (ClearInterval.HasValue && ClearInterval.Value)
            {
                writer.WriteLine("<script type=\"text/javascript\" language=\"javascript\">");
                writer.WriteLine("\tvar " + ClientID + "_ClearIntervalParentRef = $('#" + this.ClientID +
                                 "').parent().attr('id') + '_interval';");
                writer.WriteLine("\tif (window[" + ClientID + "_ClearIntervalParentRef]) {");
                writer.WriteLine("\t\tclearInterval(window[" + ClientID + "_ClearIntervalParentRef]);");
                writer.WriteLine("\t}");
                writer.WriteLine("</script>");
            }
        }
        [PersistenceMode(PersistenceMode.Attribute)]
        public string ContainerTag { get; set; }

        public bool? ClearInterval { get; set; }
    }
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

Web Development

jqDialogForms: v1.1 Released And New Samples Posted

by Jon Davis 27. January 2009 23:30

I've updated jqDialogForms to v1.1. Watch this space: http://www.jondavis.net/codeprojects/jqDialogForms/

It is no longer a placeholder URL that points back to my blog post, it's an actual page dedicated to the library, with some basic samples already in place. I still need to add more samples and documentation such as the default options, all of which I plan on doing this weekend, but at least there's finally something there. 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

Web Development

Javascript: Blur Technique

by Jon Davis 8. January 2009 11:10

Nevermind.

Ehm, click to see what I neverminded and then view comments

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Web Development

Why Windows and IIS Developers Need To Try PHP, Ruby, Python, Pure Javascript, Or Something Else

by Jon Davis 5. January 2009 05:04

I've argued frequently here before that rather than being a master of one thing, it's better to be knowledgeable of many things, expert in a few. This is not the same as being a jack-of-all-trades because one would suck at all those things, but if you're better at some things, rather than a master of one thing, you might actually be better than the master of the one thing, because your experience is diversified.

Perfect analogy...

http://www.candychang.com/design/pages/milk_and_muffin.htm

"[Trying other things makes your specialty] taste better because now you know what makes it special ... and your appeciation of [your specialty] gives you a better understanding of all the other [alternative technologies]."

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Opinion | Software Development | Web Development


 

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

About the author

Jon Davis (aka "stimpy77") has been a programmer, developer, and consultant for web and Windows software solutions professionally since 1997, with experience ranging from OS and hardware support to DHTML programming to IIS/ASP web apps to Java network programming to Visual Basic applications to C# desktop apps.
 
Software in all forms is also his sole hobby, whether playing PC games or tinkering with programming them. "I was playing Defender on the Commodore 64," he reminisces, "when I decided at the age of 12 or so that I want to be a computer programmer when I grow up."

Jon was previously employed as a senior .NET developer at a very well-known Internet services company whom you're more likely than not to have directly done business with. However, this blog and all of jondavis.net have no affiliation with, and are not representative of, his former employer in any way.

Contact Me 


Tag cloud

Calendar

<<  May 2021  >>
MoTuWeThFrSaSu
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

View posts in large calendar