Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Wednesday, 20 July 2011

Creating an MVC 3 Web Application with the Razor View Engine, HTML5 and IIS Express 7.5


This was originally going to be a few simple steps, but I decided to go the whole hog. Good first read if your getting started with MVC3! (Rough knowledge required, when I say rough, I mean VS, aspx and O-O knowledge)


Creating new MVC 3 Web Application in VS 2010
1. Create a new MVC 3 Web Application
2. Select an Empty template from the templates dialog (the others ship with authentication that were not goign to use).
3. View engine, select Razor (This will allow us to use the Razor view engine which has slightly different markup and uses .cshtml files rather than .aspx pages). Note: Razor view can be rendered inside unit tests, something that aspx pages cannot.
4. Use HTML5 semantic markup, check it!
5. OK to create.

Note: You can see that quite a lot of libraries are included by default. You will also notice that JQuery (JS and CSS) is included as standard and we have a good base setup to begin developing our web application.



WHAT IS MVC and Order of execution

Init
Within an MVC application, you have a list of routes and filters defined when the application starts. These are defined the the Global.asax.cs file (yes it still exists!). The routes are referenced everytime a page is requested (URL is entered that is associated with the application). The routes describe which Controller will serve the view's content.

Controller
The Controller is responsible for all the business logic. This is the "C" part of MVC. The Controller may utilise the Model ("M" in MVC) to manipulate the datastore is some way (basically ask the database to grab something). The Controller may do some casting or validation on the data, then render the View (may also pass data to the view when rendering).

Model
The Model is all about the database and the database layer. Usually you will have a framework here for managing access and control to your database. In this example, we are using the entity framework. So we will have our .edmx files and our template files here. Our classes will also be defined here as they will be generated automatically from our database content!

View
The "V" in MVC. View's should know nothing about how the data is constructed and how the data works internally. The view should be essentially be dumb and told nothing about the data, other than anything required to display the data to the user. The reason for this aides the seperation of concerns principle of O-O programming. This allows us to clearly seperate are busienss logic. The rewards consist of: Unit testable busienss layer, designers can work with views without worrying about learning C#/VB etc.


Razor View Engine
I don't want to explain everything in this post or were gonna be writing a novel. Here is a good link by ScottGu on the Razor view engine. Either than, or you can just trust me that it's great!


Note about Razor 'master' pages and entry points
_ViewStart.cshtml - Does what it says! This is executed first and initialises the view.
_Layout.cshtml - Razor's answer to aspx master pages.



Creating a Controller
1. Right click the Controllers directory.
2. Add > Controller.
3. Name the controller HomeController (We already have a route defined in the Global.asax as default that points to a Home Controller - So there is no extra work required to link it up yet).
4. Set the template as an empty template
5. OK to create!
6. You will notice that you controller contains an Index method. Will will be executed by default when the user hits the 'Home' directory for your application. I.e. http://localhost/Home


Creating a View based off the Controller
1. Each method in our controller can map to its own view page. This is what we will be doing in this example. Once the controller is created, then creating a view is simple!
2. Open the HomeController, and right click on the Index method.
3. Select 'Add View...'
4. The view name will be Index by default. This is fine...
5. THe view engine will be Razor, this again is fine...
6. Creating a strongly typed view just means that this view will only accept classes of a single type. So if you are ALWAYS passing a TEST class to this view, then it should be strongly typed.
7. Partial view can be compared to an aspx user control. It's a partial view, not a complete one! This can be re-used throughout the web application. We are not creatign one of these now...
8. "Use layout or master page". We are using this (as describes before). Set this as the _Layout.cshtml file. It will reside in the Shared folder within Views (~/Views/Shared/_Layout.cshtml).
9. OK to create!



Setting up test server and launching application

Note: I recommend using IIS Express (7.5 latest at time of writing) or something different to the visual studio server for this application. MVC uses URL Routing (aka URL rewriting before MVC), so sometimes the routing gets a little confusing with the visual studio development server. IIS7 handles URL routing out of the box (Whereas more steps were requried for IIS 6, and you can't install IIS7 on windows XP). However, IIS Express 7.5 solves all of these problems becaue it performs both nicely!


Setting up IIS Express 7.5
1. If you don't have it, its a lightweight seperate install. Simply get it via the web platform intaller
2. Right click the web application in Visual Studio > Properties.
3. Web tab
4. Use local IIS Web server
5. Check "Use IIS Express".
6. Click create virtual directory button
7. OK to execute application!


Now, simply execute the application and you'll be presented with a very blank dull webpage. Congratulations, you did it! It's the start of something good, trust me!



Reference Links
Building an MVC 3 App with Database First and Entity Framework 4.1
Creating an MVC3 Application with Razor and JS

Wednesday, 15 June 2011

Facebook Connect - Post to wall feed


After using Facebook Connect for a while, you can soon find out how shoddy the documentation is. There seem to be about 5000 half-written API's, most out of date and even the Facebook API documentation is barely holding itself together.

Anyway, here's a small JS snippet on how to post to a user's wall. The user must first allow the application pushing rights, or an error will occur.

I have already written a great blog entry on getting started with Facebook Connect, check it out here!


Pre-requisites
- Check out the above link if you have no idea how to get started!
- Allow pushing rights (publish_stream)
- Ensure your already dealing with an authentication session (I have added the code to ensure you already have a valid session in the code below)


Javascript Code
FB.getLoginStatus(function (response) {
    if (response.session) {
 
        var params = {};
        params['message'] = 'This is the main message';
        params['name'] = 'This is the name of the link';
        params['description'] = 'This is the link description';
        params['link'] = 'http://www.URLToNavigateTo.com';
        params['picture'] = 'http://www.FULLpathtoimage.com/image.png'; // 90x90 px
        params['caption'] = 'Small caption appearing under the link';
 
 
        FB.api('/me/feed', 'post', params, function (response) {
            if (!response || response.error) {
                // Error occured posting to the fb wall
            }
        });
 
    } else {
        // User isn't authenticated with facebook
    }
});



This will produce the following result...

Friday, 10 June 2011

Javascript: Pass parameter into setTimeout


Sometimes passing a parameter into a function, specified within a setTimeout() function isn't so straight forward. Different browser garbage collectors operate differently, and your function sometimes won't be executed at all.

Here is a method that works in all browsers. You need to specify the function within an anonymous function, and set the parameter to null.

Code Sample
var foo = "Hello World";
setTimeout(function () { helloWorld(foo); foo = null }, 3000);
 
function helloWorld(foo)
{
    alert(foo);
}

Wednesday, 8 June 2011

CKEditor - WYSIWYG editor for web pages


CKEditor is a text editor to be used inside web pages. It's a WYSIWYG editor, which means that the text being edited on it looks as similar as possible to the results users have when publishing it. It brings to the web common editing features found on desktop editing applications like Microsoft Word and OpenOffice.

Because CKEditor is licensed under flexible Open Source and commercial licenses, you'll be able to integrate and use it inside any kind of application. This is the ideal editor for developers, created to provide easy and powerful solutions to their users.


Download Here

Thursday, 16 December 2010

[ASP.NET] Pass your own arguments to the ClientValidationFunction in a CustomValidator


When using a CustomValidator in asp.net you can specify a ClientValidationFunction to run on your client side. This function need to have 2 parameters (sender, args). The sender is the customvalidator control and the args is where you can specify the result of your validation(args.IsValid) and also access to the value of the control attached to you custom validator(args.Value). This is very useful for more complex validation on client side.

http://alejandrobog.wordpress.com/2009/09/27/pass-your-own-arguments-to-the-clientvalidationfunction-in-a-customvalidator/

Friday, 8 October 2010

ASP.NET/JQUERY - Maintain Scroll Position of DIV (example uses a treeview)


Today I had the task of maintaining the scroll position of an asp:TreeView control. Keeping it short and sweet; here's what I came up with.

I noticed that when rendered in the browser, the TreeView is rendered as a div... and from back in the days of remembering window positions after post backs, I knew this wouldn't be much different.

The solution I was working on used JQuery already and I found it useful to pull out references to server controls using the 'endwith' syntax. You can also get client id's, it doesn't matter to an extent.


Code behind
protected void Page_Load(object sender, EventArgs e)
{
    this.AddEvents();
}
 
private void AddEvents()
{
    ScriptManager.RegisterStartupScript(this, this.GetType(), "Load", "PageLoad();", true);
    this.tvOrganisation.Attributes.Add("onscroll", "saveScrollPosition(this)");
}


In the above code i'm attaching an onscroll event to the Treeview. I'm also adding a form load function in javascript so that I can initialise anything in here.


Page Markup
<script type="text/javascript" src="LOCATION OF JQUERY HERE/jquery-x.x.x.js"> </script>
<script type="text/javascript">
    function saveScrollPosition(div) {
        $("[id$='hdnTVScrollYPos']").val(div.scrollTop);
        $("[id$='hdnTVScrollXPos']").val(div.scrollLeft);
    }
 
    function restoreScrollPosition() {
        $("[id$='tvTREEVIEWNAME']").scrollTop($("[id$='hdnTVScrollYPos']").val());
        $("[id$='tvTREEVIEWNAME']").scrollLeft($("[id$='hdnTVScrollXPos']").val());
    }
 
 
    function PageLoad() {;
        restoreScrollPosition();
    }
</script>
 
 
<asp:HiddenField ID="hdnTVScrollXPos" runat="server" Value="0" />
<asp:HiddenField ID="hdnTVScrollYPos" runat="server" Value="0" />


Here i'm using two hidden fields to hold the values of X and Y. This will maintain throughout postback and uses a cookie-less approach towards maintaining these details. The JavaScript speaks for itself.

Wednesday, 29 September 2010

Javascript: Namespaces and O-O examples...


I'm not sure how common practise this is, but where I currently work we have a standard whereby we placed common JavaScript functionality in separate files and what could be called classes. I'm sure most developers out there do group common functions in files and import them when needed. This is fine, but it doesn't promote certain O-O practises like information hiding and the feel of objects, methods and properties. This is what this post aims to achieve.

I have attached a sample project file which declares a JavaScript name space in a separate file, declares a Messages 'class' in another and a sample HTML page which invokes various methods and properties against it. Sample can be found at the end of this post.


Namespace declaration - Must be imported first
/******************************
** BANTY Namespace definition
******************************/
var BANTY = BANTY || {};
BANTY = (function() {
    return {
        helloWorld : function() {
            return "Helllo World!";
        }
    }
}());



Class definition
/******************************
** Define Messages class
*******************************/
if (!BANTY.Messages) BANTY.Messages = {};
BANTY.Messages = (function() {
 
    // private declarations here
    var pi_Message;
 
    var pi_ChangeMessage = function (newMsg) {
        pi_Message = newMsg;
    };
    
    
    // public declarations here
    return {
        publicProperty : "This is a public property",
        
        init : function (Args) {
            pi_Message = "Message initialised.";
        },
        
        showMessage : function () {
            return "The value of the message is: " + pi_Message;
        },
        
        changeMessage : function (msg) {
            pi_ChangeMessage(msg);
        },
    };
}());



Example HTML Page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Javascript O-O Example</title>
    <script src="Banty.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
</head>
<body style="font-family: verdana; font-size: 8pt">
    <div id="tagged"></div>
 
    <script src="BANTY.Messages.js" type="text/javascript"></script>
    <script type="text/javascript">
    $('#tagged').append('<br /><div><font color="0000FF"><b>Information hiding principles...</b></font></div>');
    $('#tagged').append('<div>Can I see BANTY?:<b> '+ (BANTY ? 'Yes' : 'No') +'</b></div>');
    $('#tagged').append('<div>Can I see BANTY.helloWorld?:<b> '+ (BANTY ? 'Yes' : 'No') +'</b></div>');
    $('#tagged').append('<div>Can I see BANTY.Messages?:<b> '+ (BANTY.Messages ? 'Yes' : 'No') +'</b></div>');
    $('#tagged').append('<div>Can I see BANTY.Messages.publicProperty?:<b> '+ (BANTY.Messages.publicProperty ? 'Yes' : 'No') +'</b></div>');
    $('#tagged').append('<div>Can I see BANTY.Messages.showMessage?:<b> '+ (BANTY.Messages.showMessage ? 'Yes' : 'No') +'</b></div>');
    $('#tagged').append('<div>Can I see BANTY.Messages.pi_Message?:<b> '+ (BANTY.Messages.pi_Message ? 'Yes' : 'No') +'</b></div>');
    $('#tagged').append('<div>Can I see BANTY.Messages.pi_ChangeMessage?:<b> '+ (BANTY.Messages.pi_ChangeMessage ? 'Yes' : 'No') +'</b></div>');
 
 
    $('#tagged').append('<br /><div><font color="0000FF"><b>Show and Change Messages...</b></font></div>');
    $('#tagged').append('<div><b> BANTY.helloWorld:</b> '+ BANTY.helloWorld() +'</div>');
    $('#tagged').append('<div><b> BANTY.Messages.report():</b> '+ BANTY.Messages.showMessage() +'</div>');
    $('#tagged').append('<div><b> BANTY.Messages.init():</b> '+ BANTY.Messages.init() +'</div>');
    $('#tagged').append('<div><b> BANTY.Messages.report():</b> '+ BANTY.Messages.showMessage() +'</div>');
    $('#tagged').append('<div><b> BANTY.Messages.changeMessage(newmsg):</b> '+ BANTY.Messages.changeMessage("newmsg") +'</div>');
    $('#tagged').append('<div><b> BANTY.Messages.report():</b> '+ BANTY.Messages.showMessage() +'</div>');
    </script>
</body>
</html>



Example Output

Information hiding principles...
Can I see BANTY?: Yes
Can I see BANTY.helloWorld?: Yes
Can I see BANTY.Messages?: Yes
Can I see BANTY.Messages.publicProperty?: Yes
Can I see BANTY.Messages.showMessage?: Yes
Can I see BANTY.Messages.pi_Message?: No
Can I see BANTY.Messages.pi_ChangeMessage?: No

Show and Change Messages...
BANTY.helloWorld: Helllo World!
BANTY.Messages.report(): The value of the message is: undefined
BANTY.Messages.init(): undefined
BANTY.Messages.report(): The value of the message is: Message initialised.
BANTY.Messages.changeMessage(newmsg): undefined
BANTY.Messages.report(): The value of the message is: newmsg




Download Sample Files Here

Thanks go out to my company for putting this standard in place.

Friday, 23 April 2010

JQuery: Select elements containing an attribute


Here's a simply JQuery snippit that will select all elements using the selector which contain a specified attribute...

This will select all table rows (TR's) of a table with an ID of 'tblTest' that have an attribute 'uniqueid'.
$("table#tblTest tr[uniqueid]")

Javascript: Add/Remove classes from elements


Here's a simple way of achiving this without any bloating libraries (I.e. JQuery etc.)
There is also a 'HasClass' method, which becomes quite useful.

function hasClass(ele, cls) {
    return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
    if (!this.hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
    if (hasClass(ele, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
    }
}

Thursday, 21 January 2010

Javascript: protocol


Useful explanation on the" javascript:" protocol


Friday, 13 November 2009

onclick vs. onmousedown and onmouseup


I've been trying for the last couple of hours as to why I couldn't select a row in my GridView using right click... it seemed to work fine for left click, but right click had issues (I had my attribute for the row set to 'onclick')

What I was doing so making a context menu appear, but I wanted the row to select itself before the menu appeared. After many vain attempts of simulating left click behaviour, adding pointers to the left clicks behaviour into the code... I simply changed the attribute to onmouseup, and presto! it works!

strange, but I do recall when attemping to disable right clicks on webpages, the onmousedown/up event is captured, so it must be how the browser interprets the keypresses for each.

Wednesday, 26 August 2009

Stop Postback in .NET


For example, if i had an ImageButton object and I would like some Javascript to execute upon clicking this control, I would add the JS on code behind like so...


btnViewParts.Attributes.Add("OnClick","ViewParts(); return false;");

The return false; Portion of this code prevents the postback.