Monthly Archives: November 2013

Using a Database

Most of the websites now use a Database to save their data from where it can be accessed whenever needed. Lets take the example of Facebook, Google, Tumblr. and all other websites. They use a Database to use all the user related Text information.

The general example is the messages that you send to the friends on Facebook, posts that you share with your circles or the blogging posts that you share with followers on Tumblr. website.

Everytime you share the post there is a query execution on the server-side code which saves all this data to a database which is connected to the website.

I will assume you created the website using WebMatrix, StarterSite template. Lets continue the process.

Firstly go to the Database workspace, that is just at the left bottom of the WebMatrix. You’ll get to work with the Database without using any other software or management software for the database. That is why I love WebMatrix – All in one software.

You remember how we interacted with the form? Lets continue that job and save the text information that is shared with the website and save it to the Database table.

First, create a table inside the StarterSite database and name it as Forms. Go to database workspace –> Click on Create Table in the top banner and name it as Forms

Then write the First Column name as Id and select int for the database and check the boxes that are infront of it. To be clear and simple for you, the checkboxes that you are going to check mean that this column (Id) will be the primary column and its value will not match with any other of its own value, that’s why a userid of Facebook user is never similar to any other user.

Now name a new column as Text and set its datatype to nvarchar [max(4000)], nvarchar means n number or characters, where n will be the value in the (…). In this case the 4000 will be n.

A tricky thing here is what does 4000 actually mean?

This means that this column will contain a total number of 4000 characters, but the max term with it means a data of 2GB, since each character uses 2 bytes then this means that this column will accommodate upto 1 billion characters. That’s more like it isn’t it? But when you write a value without max, lets say 400 then only 400 characters will be written and others will truncate into a string and will be removed. First 400 will be saved and others will be discarded.

There are some other data types for Sql Server too. Some of them are, bit (which means true false) will only have 2 values, you need to write either True or False to it; it is a bool.

Image datatype is for binary data. You can save images to the database too, but that’s not a good idea for a developer. You can read all other data types here, they will guide you at best.

http://technet.microsoft.com/en-us/library/ms187752.aspx

Advertisements

Some general mistakes in jQuery syntax by us

Well, in the previous post I taught and described how jQuery can be used to create dynamic pages. But at the same time there are some errors made by us, which we totally forget while writing the code.

For example the basic and the first mistake that even a professional would do is the following line

$('button').click(function () {
 // functions..
}

Above code looks well, doesn’t it? Actually this would work when you’re using an online editor such as jsfiddle.net because they don’t need to be written or provided some extra code lines.

So, what was the error? The basic and the very simple to get error was that the above code in your own app should start with a document ready function, such as

$(document).ready(function () {
  $('button').click(function () {
    // functions here..
  }
}

Which will force the jQuery to work when the document is ready. Otherwise your jQuery code won’t work.

To be noted here, there is no difference in ‘ and ” in jQuery. You can use them both and the above code would be

$(document).ready(function () {
  $("button").click(function () {
    // functions here..
  }
}

Both will work. So, if there is any other error that humans catch, please share it in comments I will update the post and also if there is error in my code please share that too! :)

Some basics of jQuery

Well, I guess our website is now a good to go for uploading and deleting the files from the server. But that doesn’t look that much cool, is it?

Adding some pro features

So lets start adding some professional features to it! For example, lets try to add some names or some more content to the page or lets just add some cool styles to the page like showing the form or hiding the form. Should we? Okay then,

First Step:

First step we will do will be to go to this site: http://jquery.com/ and download the latest version of jQuery or even download the recommened one. Don’t like to read and do all that stuff? Its ok! Try to add this link in the head section of your website

<script href="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

But for those of you, who don’t like to add unknown stuff to their websites, you can download the file attached below in this post 🙂 You will read alot there, but please note that this method isn’t preferred. First or second would be great.

Lets begin the coding

Ok, so I guess you are now having your website connected to the powerfull JavaScript Library jQuery. Try to understand, that jQuery itself is a JS. It is not something else, it in the code behind the scenes makes a use of the pure js and lets you easily handle the events on the browser.

Understanding the methods

Now lets start understand how we can handle the events on an elements using jQuery.

In basic js, you wrote the stuff as

<element onclick="functionname"></element>
// such as
<button onclick="submitform"></button>

Now to handle the event you did something like

<script>
  function submitform() {
    // remember functions are methods so you must use
    // (). You can pass parameters through this too. 
    // and here you submitted the form or validated it 
  }
</script>

But jQuery makes it simpler and easier. How? Look for yourself

<script>
   // now lets use the input of text as the name
   // and the submit as the button to execute the change
   $('#submit').click(function () {
     var name = $('#name').val(); // val is a method; thus ()
     alert(name); // alert the name for the user..
   });
</script>

<!-- body elements are as under -->

<input type="text" name="name" id="name" />
<input type="submit" value="Submit" id="submit" />

The above code will first take the user’s input for the name and then it will show the name as an alert when the user will click submit. You can see the code working by the usage of the id (#).

Now lets understand what other stuff jQuery can do for us.

Hiding and showing the content

If we want to hide the content, or show a content sometime when we want it to be visible to the user such as a popup; customized one. Then we can make a use of jQuery and toggle it using

<button></button>

// jQuery for this will be
$('button').hide();
$('button').show();
$('button').toggle();

Now, you might want to ask what is toggle? Toggle means if the element is hidden it will show it, if it is visible it will hide it! Its a round-off for the hide/show methods. You can also use the speed for the process in milliseconds. Forexample if you write 1000 in the paranthesis then the process will take 1 second and will hide or show in a perfect manner for the user to understand that something is coming up for me to fill in or view.

Changing CSS properties for elements

There are some other uses of jQuery too, such as changing the CSS for the current element. We can do that using

$('element').css({
  // write the properties here such as
  "width": "100px",
  "height": "50px"
});

And so on. jQuery is an endless library of JS. You will find each and everything and will be able to edit and customize the page effects using just jQuery.

Good luck.

Uploading and saving Files

In the previous chapter, I showed some code and its properties of how it can be used to save the data from a form to a text (.txt) file. Now its time for you to understand how and why media files are different from the simple form.

You need to encode the data of the media being sent to the server before it is sent to the server. For that you use an enctype and set a value to it inside the form element. Like the following

<form method="post" enctype="multipart/form-data">

Now, when the form will be submitted, everything in it, will be first encoded to the relative type and then sent to server. Please note that the files (such as images, audio, video) need to be encoded. So that the server can process on them.

Now create the form in the page as

<form method="post" enctype="multipart/form-data">
  <input type="file" name="image" accept="image/*" />
  <input type="submit" value="Upload" />
</form>

Now when this form will be submitted the image will be submitted alongwith the data. Note the accept attribute, I have specified image in it, which will force the browser to only select the image (.jpg, .png etc) files not others such as audio (.mp3, .wav etc) and others.

Now lets get to the server-side code:

if (IsPost) {
      int numberOfFiles = Request.Files.Count;
      for(int i =0; i < numberOfFiles; i++) {
          var uploadedFile = Request.Files[i];
          if (uploadedFile.ContentLength > 0) {
              fileName = Path.GetFileName(uploadedFile.FileName);
              fileSavePath = Server.MapPath("~/App_Data/UploadedFiles/" +
                fileName);
              uploadedFile.SaveAs(fileSavePath);
          }
       }
   }

A little elaboration

Now lets get the knowledge of the above code, and lets understand how it works.

You might be familiar with loops and variables upto now. This code makes use of that thing. You will be looping through the images that were selected, but note that this is required only when you are using multiple attribute for the form input element such as

<input type="file" name="image" accept="image/*" multiple />

Otherwise, you don’t require that.

Now, the first code that is a request to count the files that were selected. Then it counts there value and uses it as a condition inside a loop. Then after that, it goes back and keeps getting each file and saves it to the server using SaveAs. Note that in this code, we are using UploadedFile variable for each of the media file that is being sent. You can try to edit the code and see how it works. Good luck with it!