How to check if object is an array in Javascript
10 Jan 2018First check if your js implementation supports isArray:
if (Array.isArray)
return Array.isArray(v);
You could also try using the instanceof operator
v instanceof Array
How to check if a particular key exists in a JavaScript object or array?
10 Jan 2018if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:
obj.hasOwnProperty("key") // true
How do you safely encode a URL using JavaScript such that it can be put into a GET string?
10 Jan 2018You can use the built-in function encodeURIComponent(str) and encodeURI(str).
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
How do you check for an empty string in JavaScript?
10 Jan 2018For checking if a string is empty, null or undefined I use:
function isEmpty(str) {
return (!str || 0 === str.length);
} For checking if a string is blank, null or undefined I use:
function isBlank(str) {
return (!str || /^s*$/.test(str));
} For checking if a string is blank or contains only white-space:
String.prototype.isEmpty = function() {
return (this.length === 0 || !this.trim());
};
How do I loop through or enumerate a JavaScript object?
10 Jan 2018You have to use the for-in loop
for (var prop in p) {
if (!p.hasOwnProperty(prop)) {
//The current property is not a direct property of p
continue;
}
//Do your logic with the property here
}
How to validate and email address in javascript without jQuery
08 Jan 2018You can use the following regex (regular expression) to validate if a string is a valid email addredd or not.
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email.toLowerCase());
}
validateEmail('[email protected]');
// returns true
validateEmail('wrong@email@com');
// returns false
How to set/unset cookie with jquery
08 Jan 2018Use the plugin:
https://github.com/carhartl/jquery-cookie
You can then do:
$.cookie("test", 1);
To delete:
$.removeCookie("test");
Additionally, to set a timeout of a certain number of days (10 here) on the cookie:
$.cookie("test", 1, { expires : 10 });
If the expires option is omitted, then the cookie becomes a session cookie, and is deleted when the browser exits.
How to scroll to a specific element on a webpage using jQuery
08 Jan 2018How to scroll to a specific element on a webpage using jQuery
$('body').scrollTo('#target'); // Scroll screen to target element
$('body').scrollTo(500); // Scroll screen 500 pixels down
$('#scrollable').scrollTo(100); // Scroll individual element 100 pixels down
How to get query string values in JavaScript without jQuery
08 Jan 2018How to get query string values from Url in JavaScript without jQuery
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)
How to disable/enable input/textbox using jQuery
08 Jan 2018jQuery 1.6+
To change the disabled property you should use the .prop() function.
$("input").prop('disabled', true);
$("input").prop('disabled', false);
jQuery 1.5 and below
The .prop() function doesn’t exist, but .attr() does similar:
Set the disabled attribute.
$("input").attr('disabled','disabled'); To enable again, the proper method is to use .removeAttr()
$("input").removeAttr('disabled');
How to check whether a string contains a substring in JavaScript without jQuery
08 Jan 2018You can use the following code to check whether a string contains a substring in JavaScript without jQuery.
var string = "main string",
substring = "ain";
string.indexOf(substring) !== -1;
How to open new page or redirect to a new page using plain javascript without jQuery
19 May 2017Sometimes you need to open a new page or redirect to a webpage using javascript. You can do that without using a library like jQuery
// plain javascript
window.location.replace("http://geek.akhil.me");
// another method
window.location.href = "http://geek.akhil.me";
// if you are insistent on using jquery
$(location).attr('href', 'http://geek.akhil.me')
How to reload page using plain javascript without jQuery
07 Feb 2017Sometimes you need to reload/refresh the webpage using javascript. You can do that without using a library like jQuery
// plain javascript
window.location.reload();
// another method
window.location.href=window.location.href;
// one more if you like to be fancy
history.go(0);
How to show or hide HTML elements using javascript without jQuery
06 Feb 2017Sometimes you need to show and hide HTML elements using javascript. Ideally jQuery makes is very easy to do so but sometimes jquery is overkill if this is all you have to do. Use following code to accomplish this plain javascript.
// select the element by its id
var elem = document.getElementById('idOfTheElement');
// following line shows the element
elem.style.display = 'block';
// following line hides the element.
elem.style.display = 'none';
How to generate sql script from Entity Framework code first migrations
21 Jan 2016Just run the following command in the nuget package manager. This will generate the complete sql script for your migrations. This script would even work if some migrations have already been run on your database.
Update-Database -Script -SourceMigration:0
How to check if a checkbox is checked or not using jquery/javascript
04 Jan 2016Use this simple code to check if a checkbox is checked or not using jquery/javascript
Using simple javascript
<script type="text/javascript">
if(document.getElementById('idOfCheckbox').checked) {
//checkbox is checked
} else {
//checkbox is not checked
}
</script>
Using jquery
<script type="text/javascript">
if($('#idOfCheckbox').prop('checked')) {
//checkbox is checked
} else {
//checkbox is not checked
}
</script>
Script to delete/drop all tables, stored procedures, triggers, constraints and all the dependencies in one sql statement
13 Dec 2015Script to delete/drop all tables, stored procedures, triggers, constraints and all the dependencies in one sql statement
The file can be downloaded here
/* Drop all non-system stored procs */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])
WHILE @name is not null
BEGIN
SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Procedure: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped View: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Function: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
WHILE @name is not null
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint IS NOT NULL
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
EXEC (@SQL)
PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
WHILE @name IS NOT NULL
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint is not null
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
EXEC (@SQL)
PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Table: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
Disable / Block Candy Crush Requests on Facebook
23 Jun 2014Every now and then I see someone whining on the Social Media about how they are fed up with constant Candy Crush requests. Although it is super intuitive and easy to block such notifications people sometimes are not able to figure them out. To make it easier for them I am writing this small tutorial.
This works for all app/games on facebook.
Disable / prevent embedding of website page in an iFrame
26 May 2014There are a lot of sites on the internet that will use/embed your content using iFrames. In case you do not want people to do that you can prevent it using this simple javascript code. What this code will do is that it will redirect the page embedding your page to your page only. :)
All you have to do is just include this piece of code in the page you want to prevent from embedding.
<script type="text/javascript">
function noiFrame() {
try {
if (window.top !== window.self) {
document.write = "";
window.top.location = window.self.location;
setTimeout(function() {
document.body.innerHTML = '';
}, 0);
window.self.onload = function() {
document.body.innerHTML = '';
};
}
} catch (err) {
}
}
noiFrame();
</script>
Disable or block popup ads from websites
27 Dec 2013There are a lot of sites on the internet that will show a popup ad for any and every way you interact with them. They will even show a popup if you click somewhere in the empty space. Not only are these ads extremely annoying but these are mostly powered by shady ad providers who do very little to control the quality of their ads. This means these popups could be anything - malicious, offensive or pornographic. Although the inbuilt popup blocker of chrome is very efficient some sites are still able to bypass it. I have a neat trick for such sites. For the case of example I am going to use http://songspk.name since is the most spammy site that I know.
Please note that I do not promote the use of this or such sites and recommend that you do not pirate music.
- Open the site that you want to use http://songspk.name in our case.
- Hit F12 or right click anywhere in the empty space and select “Inspect Element”.
- A small box will open in the bottom of the window. In the bottom right corner of a window you will see a “gear” icon. Click it.
- It will open another secondry window inside the previous window.
- In this window under the “General” tab you will see an unselected checkbox (tick box). Mark the box as selected and that will disable all the javascript on the page.
- Now you can enjoy the website without worrying about the popups.
Now this process might disable some other features of the website as well but if the site has been developed logically and syntactically everything should work fine. In case the site does not work as you had expected you can always revert back using the exact same process. For more clarity check out the screenshots below
Delete duplicate rows from MSSQL or MySql database table
11 Jan 2013This is a very simple and efficient sql script that will help you delete duplicate entries from your sql databases. This is known to work well on MySQL and MSSQl but I am sure it will work well on any RDBMS system. You simply replace the column names with the ones which decide if the records are getting duplicated, table name and primary key identifier.
DELETE FROM [TABLENAME] WHERE PRIMARYKEY NOT IN
(SELECT Min(PRIMARYKEY) FROM [TABLENAME] GROUP BY COLUMN1,COLUMN2,COLUMN3...)
Lets take an example. Assuming you have a table called Students with columns Name, Email, DOB *and *FatherName. This table has an integer primary key column named Id. If you want to remove all but 1 entries for the rows where the Name and Email are same the query would be
DELETE FROM Students WHERE Id NOT IN
(SELECT Min(Id) FROM Students GROUP BY Name,Email)
Note: I recommend that you always take a backup of the data before you run any kind of command that deletes any rows. Its a very good habit and saves a lot of hassles in case something goes wrong.
My First jQuery plugin - PageQR
04 Jan 2013I just released my first open source jQuery plugin. Many a time I feel the need to open the webpage that I am browsing on my mobile phone. Usually I simply email the url of the page to myself and check the mail on my phone and open the link there. Then I installed a browser plugin that would create a QR code for the current page at the click of a button and I can scan that the page is open on the phone. Having done this quite a lot of time I felt that it makes sense for a website to have such a provision that whenever a page is being browsed it should have a QR code corresponding to that page url. Potential use cases for this plugin are
- Extremely useful during development of responsive design or checking the responsiveness of a webpage
- Reduce the time in opening the page on mobile device.
To fulfill this requirement I wrote a simple jQuery plugin that when added to the page will automatically add a QP code of the url to the page in a very unobtrusive manner (Example here) The plugin comes with a variety of useful options using which you can easily customize the behavior of the plugin. You can download the plugin from github here and the detail page for the project can be found here.
In case you have a feedback or have a suggestion please get in touch with me here
Open external links in new tab with jQuery
27 Dec 2012Be it writing a blog post or simply creating a website sometimes one has to add links of external sites to his web page. These could be reference posts to the current posts, links to external entities being talked about or even links to partner sites. It is a good practice to add external links in such a way that they open in a nw tab/window when clicked. This helps you in retaining your visitor without the risk of him not coming back once the reaches the external site.
One way of doing this is by being extra cautious at the time of adding the link and setting its target attribute to ‘_blank’ so that it opens in a new tab. An easier and extremely convenient approach would be to add a small piece of javascript to the website that automatically identifies external links and updates them to open in a new tab. Following is the javascript snippet that can be used to achieve this
jQuery(function($){
//Replace your domain name here
var domain="geek.akhil.me";
//Takes care of http
$('a[href^="http://"]')
.not('[href*="'+domain+'"]')
.attr('target','_blank');
//Takes care of https
$('a[href^="https://"]')
.not('[href*="'+domain+'"]')
.attr('target','_blank');
});
This code uses jQuery and just needs to be placed in the site and it will start working. Just change the domain name to your domain name.
Add smooth scrolling 'back to top' button on site with jQuery
26 Dec 2012Many websites, particularly blogs, that require a lot of scrolling to be read completely now contain a “Go to top” or “Scroll to top” feature. I am particularly fond of this feature as it enhances the usability of the site and saves a lot of time. I myself have added this feature to a lot of sites. It is a very easy implementation and you can easily add a “Scroll to top” button on your website using jQuery and CSS. No extra plugins required and i works across all browsers. You just need to include the following code in your website and your “Back to top” button would work easily.
###Javascript Code
$(document).ready(function(){
$('body').append('<div id="toTop">^ Back to Top</div>');
$(window).scroll(function () {
if ($(this).scrollTop() != 0) {
$('#toTop').fadeIn();
} else {
$('#toTop').fadeOut();
}
});
});
###CSS Code
#toTop
{
width: 100px;
border: 2px solid #f7f7f7;
background: #f7f7f7;
text-align: center;
position: fixed;
bottom: 10px;
right: 10px;
cursor: pointer;
display: none;
color: #333;
font-family: verdana;
font-size: 11px;
opacity: 0.6;
filter: alpha(opacity=60);
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
-o-border-radius: 30px;
border-radius: 20px;
-webkit-transition: all .25s linear;
-moz-transition: all .25s linear;
-o-transition: all .25s linear;
transition: all .25s linear;
padding: 5px;
}
#toTop:hover
{
background: #b3b3b3;
border: 2px solid #b3b3b3;
}
Needless to say, with basic understanding of HTML and CSS you can customize the look and feel of the button. In case you want to add a fancy image instead of simple button you can easily customize the code to make that work. Feel free to catch me on twitter in case you feed any clarification.
Create HTML select dropdown for states of any country
21 Dec 2012Every now and then we need to make web forms where we need to include address / location fields like country, state or city. For most of the cases we can easily use a textbox and if we are not too concerned about the sanity of the data the texbox method works out very well. But at many times it makes sense to have a dropdown field for country or state so that the quality of data can be maintained. Sanitized and consistent data is easy to maintain and work on.
Most of the times when you require such a dropdown you can easily search the relevant data on Google and with some work find the relevant data. If you are lucky you will find proper HTML code for the data otherwise you can always work with a plain text list. To reduce this process of finding and converting I have created this micro tool that will easily generate the code for HTML select for the states of any country in the world. It will also generate for you a dropdown list of all the countries in the world. This tool makes use of the Geoplanet api provided by Yahoo.
Please get in touch with me in case you have a query or a feedback. I tweet here @akhilrex
Create scrollable readonly textarea without using disabled
18 Dec 2012It is a common practice for sites to use a disabled textarea as a container for “Terms and Conditions” at the end of forms. The text area provides a nice and easily configurable structure and it is disabled so that no one is able to modify the contents. Though this technique works in most of the good browsers, our “favorite” Internet Explorer acts in its own way in this situation. Apart from setting the text to be non-editable which was desired, it renders the text area un-scrollable. Which means that if the complete text in the text area is not visible, the visitor using IE will not be able to scroll and read it. This is highly undesirable.
I encountered this problem recently. Though there could be many css and javascript solution of this problem, the easiest one and the most sensible one is using the power of the readonly attribute of text area. Instead of setting the text area as disable, you simply mark it as readonly. Now you have achieved both the requirements - the text area is uneditable as well as scrollable. The syntax to do this is very simple.
<textarea readonly>Your awesome "Terms and Conditions here"<textarea>
If you want to try I have setup a small example here
How to disable right click on images using jQuery
14 Dec 2012Many a times I get requests from clients and fellow developers that they want to secure the images on their sites and prevent people from downloading or saving them. Most of them want us to update the site so that no one can right click and save the images or drag the images on to their desktops or applications like Photoshop. My first response to such requests is DON’T. Not only does this degrade the user experience, it could be extremely annoying to many users. Many of the users might think that your site is malfunctioning or is infected. Also any kind of script that you might be using can be rendered useless by simply disabling javascript in the browser.
Even then a lot of people still insist that the script should be added to their site. So here is the script that will disable right clicking and dragging on images. Please note that this script uses jQuery and will only work if jQuery is added.
<script type="text/javascript">
$(document).ready(function(){
// this part disables the right click
$('img').on('contextmenu', function(e) {
return false;
});
//this part disables dragging of image
$('img').on('dragstart', function(e) {
return false;
});
});
</script>
You can test the code here
If you know a little bit of jQuery and css-selectors you can see that you can easily modify this script to disable/enable right click and dragging on any kind of HTML element. You can specifically disable right click on images with a special class or children of a specific element. I would again repeat that I do not recommend using this script if it can be avoided.
Remove Malicious code from Wordpress or Joomla
11 Dec 2012Hacking of sites is not a new phenomenon. Every day thousands of sites get hacked and serve as vehicles for hackers to carry forward with their vicious plans. Out of these most of the hacks are executed by bots that crawl the internet to find websites/servers with exploits and vulnerabilities and harness them to inject malicious code or functionality into the site. Prime purpose for this is Black Hat SEO or get traffic but some do it just for fun.
Recently some of my older sites that were built on Joomla (never use Joomla) were hacked where the hacker injected a piece of code into ever single php file of the application recursively. In this case manual cleaning and removal of code would amount to insane about of work and also is not feasible. I searched through the net and have found a nice php script that does the finding and removing very efficiently. It is a good quick start to recovery and gets rid of the malicious code very effectively. Following is the code that you can use.
Just create a new php file on your server and paste this code in it. Change the ‘Malicious Code’ to the actual malicious code and execute the script.
Disclaimer: This script worked for me and might also work in most of the cases. Even then I would recommend that you take a backup of everything before executing. I shall not be liable or responsible for any damage or loss of data due to using this script.
<?php
//Enter it as it is and escape any single quotes
$find='Malicious Code';
echo findString('./',$find);
function findString($path,$find){
$return='';
ob_start();
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($path.'/'.$file)){
$sub=findString($path.'/'.$file,$find);
if(isset($sub)){
echo $sub.PHP_EOL;
}
}else{
$ext=substr(strtolower($file),-3);
if($ext=='php'){
$filesource=file_get_contents($path.'/'.$file);
$pos = strpos($filesource, $find);
if ($pos === false) {
continue;
} else {
//The cleaning bit
echo "The string '".htmlentities($find)."' was found in the file '$path/$file and exists at position $pos and has been removed from the source file.<br />";
$clean_source = str_replace($find,'',$filesource);
file_put_contents($path.'/'.$file,$clean_source);
}
}else{
continue;
}
}
}
}
closedir($handle);
}
$return = ob_get_contents();
ob_end_clean();
return $return;
}
?>
Database Backup Script
10 Dec 2012Backing up and Restoring backups of databases are very common in any kind of project that involves databases. It is a common practice to take the backup of a database before you make any change to it. It is important in the way that it allows you to restore the database back to its original state in case anything goes wrong.
There are many ways to backup databases but the most common one is to run a database backup script that will take a backup of all the databases in the system excluding the system databases. Since the primary reason of maintaining this “geek” version of akhil.me is to maintain a repository of such utility items. It makes sense for us to include this database backup script in the system. Please note that this script is written keeping MS SQL in mind but I am sure you can easily modify it to use with other RDBMS systems.
The file can be downloaded here
DECLARE @name VARCHAR(50) -- database name
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name
SET @path = 'C:\Backup\'
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb')
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
BACKUP DATABASE @name TO DISK = @fileName
FETCH NEXT FROM db_cursor INTO @name
END
CLOSE db_cursor
DEALLOCATE db_cursor
Create and Install Windows 7 from USB
13 Oct 2012I know there are multiple ways to get this done and the internet is full of resources that will teach you how to do it but I am making this entry so that I know where to come back to whenever I have to create a new Windows 7 Bootable USB.
- Open the command prompt in “administrator mode”
- DISKPART
- LIST DISK
- SELECT DISK 1 (here disk 1 is the name of the USB drive)
- CLEAN
- CREATE PARTITION PRIMARY
- SELECT PARTITION 1
- ACTIVE
- FORMAT FS=NTFS
- ASSIGN
- EXIT
- Using the command prompt only navigate to the Windows DVD or the Windows ISO
- Navigate into the Boot folder
- D:/BOOT/BOOTSECT.EXE /NT60 U:
- Copy the content of the DVD on to the USB
And you are done :)