asp.net – getting user confirmation before a postback

In asp.net web applications, it is common to have dozens — if not hundreds — of user controls that perform postbacks to the server, actions initiated by a user such as a button click. Often before a save, delete, or other critical action is performed, it is desirable to ask the user if they are sure.

In Asp.net web applications, buttons and other controls have two event properties that we are concerned with: onClick , and onClientClick .

The onClick event calls a specified function in the code-behind file. At this point, the postback has occurred, and any confirmation would have to take place with another rendered page — meaning lots of wasted time and wasted resources.  With the onClientClick event, we can interrupt the onClick event with our own javascript function or inline statement.

Using jQuery, we can bind function to all of these “confirm-able” user controls, which will interrupt the default post-back behavior  presenting users with a confirmation dialog box:

Using this method, we can target all user controls with the CSS class confirm. Additionally, if we wanted a broader reach, we could modify the jQuery selector to  input[type=button] or for all buttons, or all links.

The confirm box  var response = confirm("Are you sure?"); used in this example is a default JavaScript confirmation dialog box — which will be rendered differently per browser or platform — but you could easily swap this for any other confirmation script or function that returns a boolean value.

Creating a microformat / richsnippits resume

What are microformats?

Microformats are small patterns of HTML to represent commonly published things like peopleeventsblog postsreviewsand tags in web pages.

Microformats are the quickest & simplest way to provide an API to the information on your website. See what else you can do with microformats.

Have you ever searched for a recipe on Google, and wondered how the highlight data like ingredients or cook time on the search results? Microformats. Or, wondered how they can aggregate reviews, locations, and prices for a restaurant search? Microformats.

Make your resume semantically searchable and available by implementing microformats.

There are several types we will implement from the microformat standard, schema.org, for fields on our resume:

  • http://schema.org/Person
  • http://schema.org/PostalAddress
  • http://schema.org/CollegeOrUniversity
  • http://schema.org/Organization

Resume Sample

View the resume here, and a Google’s report on extracted data here.

 

Installing WordPress on a Windows Server (not through Gallery)

I administer a Windows server which runs multiple instances of WordPress.  Today I needed to install another instance, but the Gallery Installer through IIS kept failing. I resorted to installing manually, and wrote up this guide to installing WordPress on a Windows server manually. Hopefully this is what you are looking for!

This guide makes two assumptions:

  1. PHP is already installed on your server (PHP Install Guide)
  2. MySql is already installed on your server (MySql Install Guide)

1. Download the latest stable release of WordPress

The latest release is available for download a http://www.wordpress.org/download. Choose the .zip package.

2. Extract the .zip file

Locate and extract the .zip file (named “wordpress-[versionnumber].zip” to the location of choice. Typically this will be in your “inetpub>wwwroot” directory. Rename the default folder “WordPress” to your site name.

3. Add site in IIS

In IIS, right click on your server name in the treeview, and choose “Add Web Site…”. Enter your site name and path into the Add Site window. The important inputs here are the path and site bindings (domain name).

4. Create & Configure Database

Open the MySql command line tool, and log in using the admin credentials. First create a new database for WordPress to use:

Next, add the admin user to the new database:

Note: this code does include the quote marks

5. Set up wp-config.php

Wp-config.php is the file that contains all the critical settings for WordPress including database connection information. Locate wp-config-sample.php and rename it to wp-config.php.

Open wp-config.php using your IDE of choice, and make the following changes:

6. Final Configuration

Browse to the new WordPress installation. If your domain is not already pointing to the site (bound in step 3), the easiest way to open your site is to add an entry to the windows hosts file. The hosts file is located at “Windows > system 32 > drivers > etc”, named “hosts.” Open this file using notepad (right click, run as administrator), and add the following entry

Once this is saved, browse to the new WordPress installation using your browser of choice, and follow the onscreen prompt to create a user, name your site, etc.

JavaScript Constructors

Due to the familiar syntax of JavaScript, it is easy for experienced developers to make blunders without knowing it. One common problem is crafting object constructors. With some simple knowledge and scope checks we can create well formed constructors that function as developers expect.

Because syntax and control structures look very similar in classic OOP languages (Java, C#) to JavaScript, it can be easy for experienced developers to jump-in, make progress, and then shoot themselves in the foot due to misunderstanding core differences in underlying language design.

One of those core differences is how functions can function as objects with constructors.

In a classic OOP language, a class,  constructor, and usage might look something like this:

Although the syntax is similar, doing something like this in JavaScript will land you in a bad place:

Scope

The first and most pressing issue is scope management.  Look back up the the JavaScript example — The function used in place of a class, is just that: a Function. Whereas a custom class is a datatype, a template for data, our function is a function in the same way as this is a function:

Primarily, the problem is with the scope of the this keyword with in functions.  Inside of a OOP language class, the this keyword refers to the parent object — the class that it is inside of. For example:

However, in side of a JavaScript function, the this keyword refers to the global scope, or the window object. Thus:

For the uninitiated, this can cause big problems. For example, consider:

A function/object Building, which contains the properties height, location, and occupancy, which are assigned like this: this.location = “123 N. 789 W.” Since the this keyword refers to the window object, your function has just overwritten window.location, the property used in changing the current location (url) of the page. Whoops!

But wait, there is a solution!

It is true, that a JavaScript object/function is really just a function — but you can create new instances of the function using the new keyword. Not only does the new keyword created a new instance (so you can have multiple objects of the same type on a page), but also assigns the scope of the this keyword to the function, NOT the window object. So, to use the previous example without clobbering the global scope:

However, if you have ever written a line of jQuery, you might be shaking your head in disagreement. Like you, I write something like this weekly:

So, how does that work?

To make sure that jQuery object is allways called with the new keyword, it does it for you, every time. See the jQuery source constructor:

So, each time $(“#asdf”) is used, jQuery returns a new jQuery.fn.init object. Now, keep in mind that this is one of several hundred lines within jQuery’s constructor source, but the key section for this subject. We can implement this method, with a few checks, in our code very easily.

Conclusion and template

So, to avoid clobbering the global scope, and to be convenient for implementers of your code, here is a well functioning JavaScript constructor template that can be implemented in your code:

See a demonstration of new keyword usage

JS Bin

Camera Shake in Unity

After much Googleing for how to do a camera shaking effect in Unity, I decided to write my own small script to accomplish the effect. It combines both positional movement with rotational movement to simulate closely an actual camera shake.

The two key variables are:

shake_intensity

Shake_intensity determines the initial intensity of the shaking — how much variance to allow in the camera position.

shake_decay

Shake_decay controls is the amount that shake_intensity is decremented each update. It determines if the shake is long or short.

 

 

 

 

Unity Web Player. Install now!

 

 

 

JavaScript

C# (c# port by commenter georgeegonut. Thanks George!)

 

Creating your own JavaScript Library

One of the phases I went through while learning about JavaScript was the intense desire to write my own library, similar to jQuery (but massively scaled down).

My library has gone through several major revisions — and more than one complete re-write, but now is exactly what I started out hoping it would be: functional, clean, small, and a solid learning experience.

I’d like to share what I learned from this project, and I hope you share back with me through the comments!

Finished project demo

Step 1: Identify the purpose of your library

This might just be one of the toughest parts of the whole process!  If you are to the point in your JavaScript knowledge that you would like to build your own library, than you’ve likely used jQuery, mooTools, Prototype, or any number of other popular libraries.  I use jQuery extensively in my projects, and know that it is very capable in many aspects, including: animation, user input validation, AJAX loading/submitting, event handling,  etc. Knowing this, it is tempting to have lofty goals for your own library. One piece of advice: Don’t. 

Pick one particular function, or aspect of web development/design that you would like your library to handle. Pick a niche need, and be happy with yourself when you fill it.

I decided my library would be a simple way to manipulate elements visually. At this point, I didn’t quite know how — but all you need is the kernel of the idea.

Step 2: Mock-up how would use the library

You always mock-up a webpage before you start building it right? Whether on paper, Photoshop, or even in code, it helps to pretend what the finished product will look like before you build it. It helps you to see obvious bugs, conflicts, and unwanted interactions you don’t catch when looking at the problem mentally.

Have you ever mocked-up your code?  Write some implementation, pretending that the class or object you are dealing with exists. Trust me, it will solve problems!

I want my library to do visual stuff with elements, and I like how jQuery looks. How about this?

Looking at my pretend implementation, I can see 1 problem and a hand-full of design implementation points.

The problem: $ as a function name is likely to conflict with lots of other libraries. Through some Googleing, I learn at StackOverflow that functions must start with a $ (dollar-sign) _ (underscore) or letters.

We can also tell some design patterns:

  • _ is the function name
  • _ must accept one or more parameters
  • _ should return itself so that a dot-operator will work
  • _ must control its scope so that we can have more than one _() on a page
  • dot-operator methods must also return the _ object for chaining

Step 3: Code up an outline

At this point, we know enough about the goal of our library, and how we will implement it, to begin outlining the structure of our library.

It may be useful for some (me) to review javascript function/object  prototyping.

Step 4: Fix-up the constructor

Now don’t try and run your code just yet: we have a pretty big scope issue (besides no functionality):

When our _() function returns this , it is actually returning the entire window, or the global scope.  Therefore, when we call _().toggle() , we are asking the browser to call the toggle() method which belongs to the window. Obviously this fails.

This problem can be solved by recursively creating another _ object using the new keyword.

What is the new keyword in JavaScript?

 

For an in-depth look at this problem, read more about JavaScript constructors

Next to implement in our constructor: making the _() represent an element with some bonus error prevention.

First, we create an about object that will be returned, if the implementation doesn’t specify an element id. Next, we check if the id parameter was sent, and then create a variable to contain that element.

Here is a final version of the _() constructor:

 

Step 5: Prototype method implementation

This step is pretty fun: being creative, and implementing what you want your library to actually do!

I mentioned earlier that I wanted my library to do some visual manipulation of elements. Make a list of what you want to do. I came up with the methods:

  • hide ()
  • show ()
  • bgcolor (color)
  • val (value)
  • toggle ()
  • size (height, width)

The depth of this step depends on the functionality of your library. Mine were rather trivial to implement:

 

Demo or download the finished library here

Part 2 – Event Handling

Final thoughts

Writing my own small library was a good way for me to learn about JavaScript. One of the great ways to learn more is to study the code of other libraries and see how they work.

Did you use this tutorial to create your own library? I would really like to hear about it. Please leave me a comment below.

Cheers!

Update
Stack Overflow user W3Geek asked a question about part of this tutorial. Visit his question: How do these pieces of code function exactly? His question is focused on Step 4 about the object constructor. User Leland Richardson does an excellent job explaining this further — I’d direct you to his thorough explanation rather than duplicating it here.

Convert < address > tags into Google Map link using jQuery

Relevant Stack Overflow Question

While designing a page template for a University today, I realized that there were many areas of the future pages that would include street addresses: buildings, conferences, offices, ect..  I thought, “Wouldn’t it be nice if these addresses were links to Google Maps?” Then people could easily find directions or set their phone GPS whilst driving (at a red light of course).

However, I quickly realized that in such a large institution as I am, that no faculty member would take the time to include a maps link.  As always, such wondering is the stuff of inspiration.  With a little bit of thought, I began writing a little jQuery function that could fulfill my dream.

code:

The function scans the entire webpage for instances of the <Address> tag:

And surrounds the address with a link to Google Maps:

Here is the jQuery Function:

Update: 11/27/2012 – Bug fix and code prettyfication.

100% Height Div with 2 lines of code

2016 Edit: This post is really out-dated. If you are looking for a solution for 100% height divs, please use modern css as described here http://www.mikedoesweb.com/2016/modern-100-percent-height-css/

EDIT: This post has several code-blocks of JavaScript to keep two divs at an equal height. I recommend the last method, if you are using jQuery — It seems to be more adaptive to different div content, working in more situations.

Check out the DEMO first, to see if this is what you want

The problem: Creating a div that auto-expands to 100% height of its container. The most common occurrence would be creating a two column layout for a menu, sidebar ads, etc…

The solution that never actually works:

“Since divs automatically inherit the height of their parent, if your parent doesn’t have height set, you cant get 100% of nothing. Set the parents height and it will work.”  Pshaw, I say.  While this may be the accepted standards mantra, I have never seen it actually work in a modern browser.

100 Percent Div Tutorial
Div! Y U NO Expand?!?

The Easy Solution (in 2 lines of code):

Working Demo on jsfiddle

Well, that’s actually 4 lines, if you include the script tag… But just 2 lines of JavaScript.

If you would like to keep the expanding div from collapsing too far, or expanding to much, simply add a conditional statement around the second line, like so:

Short Explanation:

Line 1 creates a new variable “h” and assigns this variable the height of an element found. This does not return the “height:” as specified in CSS, it returns the actual height of the document as it is displayed on the screen.

Line 2 fills the “height:” style value of the other, shorter, element with the variable h + “px”

Put this code near the end of your document, probably right before the body tag, and it will run right when the page loads. You could also wrap this in a jquery $(window).load, or even a $(document).ready. As it is, though, there is no library dependency – just plain-old-JavaScript!

Or, do it with jQuery instead:

Commenter Ivan couldn’t get this code working for him, so he rewrote it using jQuery. I have further rewritten his original code to be a bit shorter, and activate when the content of both divs has fully loaded. I recommend this method — if you are already loading jQuery — as it seems to work much better with dynamically loaded content.

Working jQuery demo

 

Edit #2 — There is a jQuery plugin called equalHeight that accomplishes this pretty easily

Check out my post 100% height using jQuery for more information about it.

Tutorial: Opening a Pop-up window in ASP.net

There are many reasons that a user would want to open up a new window from your ASP site. Maybe the clicked on a button or a link, maybe the current page just isn’t doing if for them.  Maybe their current page has self-esteem

issues, or weight issues.  Maybe their current page is getting a little thin on top, or doesn’t really do to well in the bedroom.

Back to maybe they clicked on a button.

Opening a new window from current page is actually quite simple! and can be accomplished in three steps:

  1. Create a control on the page that can handle and “onClick” event. This could be a plain HTML button, an anchor tag, an image, whatever…
  2. Double clicking on the control will open the code for the new HTML control. It should look like this:

function Button1_onclick() { }

[pullquote]

Look what I made at School!!
[/pullquote]

Remember, for this to work you’ve got to use a plain HTML control, not a “runat=server” .net control. These are found in the HTML Tab on the left.

And finally, the code that goes inside is:

The parameters are (the url of the new window, the title of the new page, size stuff)

View the page, click on the button/link/whatever and Whala! a new window opens.

Tutorial: Pass data between pages in ASP.net

You have created the perfect webpage. Beautifully formed HTML, poetic CSS, artistic JavaScript, and cunning jQuery. And suddenly — a link — and all user data is lost!

By far, the simplest way to pass data between pages is by using URL variables. These little nuggets act quite a bit like two pages playing catch:

  • the first page throws some variables along with the URL
  • the second page must catch them

the throw

Get the data, save it as a string like this:

then send the data to a page like this

Thats it!

And now for a little explanation of part one:

the “?” after the url means “hey server, get ready… Im about to pass you some data.”

“name=” this is what im going to be passing you.

and “strName”… Here’s the data!

It’s pretty simple to pass multiple values too: just put an & symbol between variables, like this:

Be sure to put this inside of some sort of event in the code behind, like a button or linkbutton click.

the catch

This part is almost as simple to implement as the throw. The basic steps are:

  • get the variable from the url, if it is there
  • the store it, or use it right then

As your page is loading, your want to let the server know that you are expecting some data, and store it if there.

this is done by using:

Then you are free to do any ifs, fors, dos, or other whathaveyous on your string that you would like.

For example: Im expecting a username, but since i didn’t get one, send them back home: