Creating a handsome custom JavaScript library

jQuery, ExtJS, etc are some of the most sophisticated javascript libraries used current days.  But If you are as passionate as I am at some moment of your life you could wish to have your very own independent js library that can be used at any site.

Suppose you have created a custom library named js and want to use it like this ..

js("#id").hide();

You interested?.. keep reading.

Lets go and see how we can accomplish that –

Step 1: Create the foundation

JavaScript is an object oriented language and thus everything we do will be regarding objects. If you are reading this post, then you are already familiar with js and thus know that there are some browser object that javascript uses with DOM. We will need two of them to create our library one is the window and the other is the document object. Every single library or js obejct that you need to used must be registered as a property or field of window  object. So first we need to register our library. I will call my library js and the code that is needed to register the library is like this –

(function() {
   var window = this,
   undefined, _js = window.js;
})();

Lets see what this does. (Between you and me, I got this idea from jQuery) –

  1. The first and last line just defined the closure of the library
  2. The second line just saves the window object ( ofcourse when the library is loaded the this object would be the window itself) for later use
  3. The third line defines the undefined object in case it throws an exception if we use it in codes
  4. The second half says that I have a js names library that is to be used as window.js or simply js. The _js is used just an extra caution incase we need to use the library function inside it.

Step 2: Complete the definition

Uptil now our library js has only been declared, but we can’t use it just yet. We need to add functions and methods inside it so that we can manipulate them as library and also to access our DOM object like a jQuery type syntax we need to have a selector defined. Lets just complete our library as following –

//object initializarion
js = window.js = function(selector) {
    return new jsObject(selector);
};
//the custom javascript object
jsObject = function(selector) {
};

I will explaing what happended here. I just created an object protoype and initialized the js as an object of that type. Therefore js is now a valid javascript object and is ready to be implemented.

Step 3: Add Some features and Hook up with events.

Now before we move forward we have one little thing to care about, our library needs to be called when javascript is initialized. So we have to hook up a load event to the window load event and also bubble any event hooked up by other libraries. You don’t wanna mess up other libraries to create your own one. The code will look like this –

this.jsReady = function(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        };
    }
};

What we did here? We first checked that if there is already a function hooked up to be call when the window loaded, if yes we called it first then ours and if not then just hook our function with it that will be called automatically.

Step 4: Putting it all together.

Thats it! We just created our very own js library. Don’t believe me? Lets have a test. But for that we need some functions that we are going to use to test. Lets just add two more function hide() and show(). I will use jQuery as internal library for easy test and also use jQuery selectors to pass the dom objects to the library. So our library will look like this –

(function() {
    var window = this,
    undefined, _js = window.js;

    //object initializarion
    js = window.js = function(selector) {
        return new jsObject(selector);
    };

    //the custom javascript object
    jsObject = function(selector) {
        this.jsReady = function(func) {
            var oldonload = window.onload;
            if (typeof window.onload != 'function') {
                window.onload = func;
            } else {
                window.onload = function() {
                    if (oldonload) {
                        oldonload();
                    }
                    func();
                };
            }
        };

        //the hide function to test our code
        this.hide = function (){
            $(selector).hide();
        };

        //the showfunction to test our code
        this.show = function(){
            $(selector).show();
        };
    };
})();

Step 5: Using the library.

Its simple to use the library, just make sure you include jQuery before including our library and try to use the codes as this –

js(document).jsReady(function(){
   js($("< your selector id, class or anything>")).hide();
});

Have fun….

Advertisements
Posted in Creative JS, JavaScript, Scripting Language | Tagged , , , , , , | 4 Comments

Uploading files from iPhone to ASP.net web site

Hello All,

As a coder sometimes I have to crush my head on the desk for not finding a feasible solution to a problem. One problem that almost had me finished is uploading image files from iPhone to asp.net website. Both the website and iPhone application was developed by me and thus I had to find both the solution –

  • Uploading file data to the site
  • Then collecting that data and saving to folder
  • Passing additional parameters so that I can run security checks about the user who is uploading the file and also track for which item the file is being uploaded.

After Googling a lot I came to two very important posts at stackoverfow that helped me figure out the process of doing this. It was a long time ago so, I can’t remember the addresses of the post, so I just thought I can summarize the full process so that anyone who is about to break his skull can get some help. Ok, enough talk, lets see the process.

1. Selecting files from iPhone

First you need to able to select files from your iPhone. Anyone who has come this far can easily design a view that can select a file with the UIImagePickerControl. I used a UITextBox that was used to select the image. When user click on the textbox the image picker is shown and user then selects the image. After selecting the image the image is shown in a UIImageView under the textbox for review. Here is the code sample that does it ( I have removed unnecessary codes, so just copying won’t work, you have to merge it).

- (BOOL) textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return TRUE;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
if(textField == filename){
[description resignFirstResponder];
[filename resignFirstResponder];
//show file select dialog

UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
[imagePicker setDelegate:self];
#ifdef __i386__
[imagePicker setSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
#else
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
#endif
[self presentModalViewController:imagePicker animated:YES];
}
}

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)img
editingInfo:(NSDictionary *)editingInfo{
[picker dismissModalViewControllerAnimated:YES];
[self.image setImage:img];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissModalViewControllerAnimated:YES];
}

Don’t worry about the #ifdef used here, this is just a check that If the app is running from the simulator then it will not throw an exception. Here textField is the text field used to select the image and self.image is the UIImageView used to preview the image to the user. This also has a hidden use, I also used it as the image data cache when sending the file data to the server.

2. Sending file data to server

At the server, I just used a .aspx file to catch the uploaded file and then write a response to indicate if the file was collected or not. I will discuss about the page later, lets just see how we are to send the data to the server.

Once, the user selects the file, the image data is saved in the UIImageView used to preview the image. I just collected the data from the UIImageView and sent it to the server by manually appending into a HTTP post request.

- (IBAction) Upload{
NSData *imageData = UIImagePNGRepresentation([self.image image]);
NSString *urlString = [NSString stringWithFormat:@"http://%@/iphone/Upload.aspx?wid=%@&sskey=%@",[[SettingsManager instance] nurl],[[SettingsManager instance] wid],[[SettingsManager instance] sskey]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[NSData dataWithData:imageData]];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

if([returnString isEqualToString:@"Success"]){
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Upload" message:@"File successfully uploaded" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}else{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Upload" message:@"File upload failed" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
[returnString release];
}

The task is pretty simple, just grab the image data from the imageView, then append manually with the boundary, set the content type for the HTTP request and post the data. Don’t worry about the values used from SettingsManager class, this is a singleton class that I used to save data cache, nurl is the url to be used for sending data, wid is the id that will be associated with the file and sskey is the session key used to check for security. Just ignore the if part here we will discuss it later. We are now halfway through, now all we need a aspx page to save the file content. The next section will do that.

3. Saving file content

The aspx is very simple page with the following code at the page load to save the file content. I took the wid, and sskey from the url and the file from the httpinput stream and saved as necessary.

public partial class iphone_Upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String wid = Request.QueryString["wid"];
String sskey = Request.QueryString["sskey"];
try
{

//some check for the security

HttpPostedFile file = Request.Files.Count > 0 ? Request.Files[0] : null;
if (file == null)
{
Response.Output.Write("No file found");
Response.Output.Close();
return;
}
else
{
//Get an entry for file upload
string fileName = Utility.GetID(IDType.File);

String[] names = file.FileName.Split('.');
string src = fileName + "." + names[names.Length - 1];

file.SaveAs(Server.MapPath("~/userhud/uploads/") + src);
Response.Output.Write("Success");
Response.Output.Close();
return;
}
}
catch (Exception)
{
Response.Output.Write("Failure");
Response.Output.Close();
}
}
}

The code is simple. Just get the file and other values and manipulate as necessary. One thing you might notice I outputed ‘Success’ or ‘Failure’ directly to the stream and closed it. In this case that If block that we used in 2, will come in hand to notify user about successful or failed uploads. The Utility.GetID() is a method I used to generate a unique id for each file uploaded to overcome the fact that I might overwrite s file while uploading.

4. Conclusioin

In this post I have tried to summarize the process of uploading image files from iPhone to ASP.Net web sites. Hope that this might be helpful for you. Your suggestions are always welcome.

Posted in IPhone, Mobile Developement | Tagged , , , , , , , , , , , | 18 Comments

Chapter 1: JavaScript – A Client-Side Scripting Language

Its been long since my last post. After a long time I have got this day a little free time myself so does for you. Many a time peoples ask me of teaching them JavaScript, well then I thought why not write a tutorial for them! Well here we go. If any of you find anything wrong let me know. I am not the inventor of JavaScript, so I don’t know all. Okay, enough with the chatting, lets start …

JavaScript is probably the most sophisticated client-side scripting language I have ever seen. We have VBScript, we have C#, we have PHP, but none of them can match the functionality, features and dynamism that JavaScript possesses.

If you are intermediate to JavaScript, you can skip this post and go forward, but if you need to know about what is a client-side scripting language, read it. A client-side scripting language is different from a programming language in so many ways –

  • Firstly, unlike a programming language, a scripting language is never ever compiled to build an output binary file, instead they are executed one statement at a time and execution breaks if any errors occur or the code finishes.
  • Secondly, a client-side scripting language run in a specific environment, in other words, inside a browser and is fully dependent on the browser to give it all kinds of supports. Whereas, a programming language output runs on an operating system.

You might have notice the fact that I am saying client-side scripting language not simply scripting language. Thats because a scripting language normally runs in a script host on the server machine. All the codes of the scripting language is run and the output is sent back as mere HTML markup to the client side. But JavaScript is never run in the server, instead it is sent as it is to the client side with the HTML markup. Then it is the client’s responsibility to run the code and show the output to the user and by clients I mean, your browser –  Internet Explorer, FireFox, Opera, Chrome, Safari; whatever that might be.
But beware of that fact that, not all these browsers user the same JavaScript engine, and thus you might need to check if the browser support your specific JavaScript codes. But don’t be alarmed, almost all the browser support almost all kinds of functionalities, there are few exceptions, but they are not so frequently used.

Posted in Learn JavaScript | 5 Comments

Windows XP Browser not opening Microsoft or Antivirus Sites

Hi,

If you are using windows xp and you face the problem that whenever you open microsoft or some specific antivirus site, the browser just doesn’t open it. Well, thats probably because of the windows cd that you used or downloaded is pirated and they do not want you to go into that sites.

There is a solution for this problem, but its not permanent. To be able to browse those sites, just go to services and restart the service named ‘DNS Client’ and voila! you are in.

Actually when your system boots, DNS Client is called automatically with some parameters to stop you from browsing those sites. Restarting it resets them and you are free to visit any site.

Now, if you are smarter than more of us, then use an auto executable batch to run after each boot, but make sure it is the last batch ran.

Posted in Operating System, Windows XP | 1 Comment

WCF Web Service – Enabling JSON – Solution 1

Hello!

The main reason I am posting this really simple post only because, even though it is simple, it wasted a lot of time for me. There are several ways to enable JSON request and response for WCF web service. But the easiest I think is this one

1. Just select AJAX Enabled Web Service from the add new item window if you are using Visual Studio ( I used VS2010). By default this will talk to the clients with JSON. There you go.

2. But, If you really want to know whats the difference between AJAX Enabled Web Service and WCF Web Service, open the new added AJAX Enabled Web Service. Just over the class declaration you will notice a line that says –

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

The second line is the main reason. It enabled the service to allow JSON type messaging from a client.

Now, I know this is not the only solution, you can also enable JSON response/request in a WCF Service, but I have not really tested that case, will post as soon I am done…

If this is found helpful, don’t forget to leave a comment, thanks.

Posted in Web Service | Tagged , , | 5 Comments