Thursday, September 6, 2018

MS SQL Server: How to copy a standby DB (logs shipped) to another instance

Why we need to copy a standby database? The main reasons are the location & time. Normally the online DB will be in a server on datacenter/clouding, while the standby DB (logs shipped) will be in a local server. So if you have a big size DB, you may take time & traffic to transfer the backup of online DB to a local server for doing your needs. However, if you can copy the standby DB, it will be faster and save your traffic. After copying, your standby DB can still receive logs shipped from the online DB.

Below are steps to do this on the standby server.

1. Take offline the standby DB
Run the following command:

USE MASTER
GO
ALTER DATABASE [DBNAME] SET OFFLINE

2. Disable restoring job
On MS SQL Server Management Studio, go to SQL Server Agent >> Jobs >> right click on the restoring job >> select Disable, see the following for example:


3. Copy data file (.mdf) and log file (.ldf) of the standby DB to another place
To know where, you can right click on DB >> select Properties >>  select tab Files >> see Path column.

4. Take online the standby DB
Now, we take it back for continuing receiving logs shipped. Run the following command:

USE MASTER
GO
ALTER DATABASE [DBNAME] SET ONLINE
5. Enable restoring job again

After this step, you standby DB will run normally again.

Now we can create new DB and copy files in step 3 above to. Below are steps on the server which will run this copied DB.

6. Create new DB (same name with standby DB)
Run the following command (make sure new DB same names DBNAME_Data and DBNAME_Log with standby DB):

CREATE DATABASE [DBNAME]
ON
(NAME = 'DBNAME_Data', FILENAME = 'C:\SQL-Data-Folder\DBNAME.mdf')
LOG ON
(NAME = 'DBNAME_Log', FILENAME = 'C:\SQL-Data-Folder\DBNAME.ldf')

7. Take this new DB offline

ALTER DATABASE [DBNAME] SET OFFLINE

8. Copy files in step 3 overwrite files of new DB created

9. Grant permission for MSSQLSERVER working on copied files
On file explorer, right click on the file name >> select Properties menu >> select tab Security >> click Advanced button:


Change the owner and add full permissions on these files copied for user running SQL service (normally it is NT Service\MSSQLSERVER). See red boxes on above picture for example.

10. Take this new DB online

ALTER DATABASE [DBNAME] SET ONLINE

OK, now you have a copied DB of standby DB running. Have fun.

Tuesday, August 14, 2018

Using Chocolatey for managing NodeJS

What is Chocolatey? Let read here: https://chocolatey.org/about
Install & Upgrade Chocolatey => read here: https://chocolatey.org/install


1. Install NodeJS
Open CMD and the following command:

choco install nodejs -y

It will install latest NodeJS version and npm together.
For installing  long term support (LTS) version of NodeJS, run the command:

choco install nodejs-lts -y

2. Upgrade NodeJS
Run the command:

choco upgrade nodejs -y

It will upgrade to latest NodeJS + npm. In case you want to upgrade npm only, let run PowerShell as Administrator and execute below commands:

Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade
Or

npm-windows-upgrade -p -v latest

3. Uninstall NodeJS
Run the command:

choco uninstall nodejs -y

I love chocolatey ❤

Wednesday, July 25, 2018

MS SQL: How to configure log shipping with FreeFileSync over FTP/SFTP

In MS SQL, log shipping is a popular technique for:
  • Copy and sync a database to multiple servers
  • High availability / failover / disaster recovery / backup plan
  • Data warehouse / reporting server
Comparing with mirroring technique, although log shipping has late time (10-15 minutes) bigger than mirroring (few seconds) but we can use the secondary database(s) of log shipping for reading while we can not do anything with mirrored database (only one mirrored database). So depending on how your system wants, you can use both of these techniques or one of them.

Normally, log shipping is configured natively with a shared folder which the secondary server can access via  private / public network. You can configure the shared folder to limit for some users or some IP addresses (by firewall). However, the disadvantages of shared folder are security issues when sharing over Internet and we cannot control bandwidth when transferring file data.

In this article, I want to introduce you another way to do the log shipping via FTP/SFTP by using
by using FreeFileSync which can solve above disadvantages.

1. Prepare environment

On the secondary server:
  • Setup FTP server (can use FileZilla Server) on the secondary server. Then configuring a FTP folder for receiving transaction log files from the primary server. For example, the FTP folder is configured with a local folder C:\FTP\FileSync.
  • Create a folder (e.g. C:\Translog) for copying log files synced from C:\FTP\FileSync to.
  • Grant full permission for user running SQL Server Agent service (normally it is NT Service\SQLSERVERAGENT, let check in Services tool) and user running SQL Server service (normally it is NT Service\MSSQLSERVER) to control the folder C:\Translog.
  • Open C:\Windows\System32\drivers\etc\host with Administrator right then add a line with IP to point the primary server name, for example: 192.168.72.100 PRIMARY_SERVER_NAME (to know the host name, open CMD on the primary server then run command hostname).
On the primary server:
  • Create a folder save log files exported (e.g. Z:\Translog). Grant full permission for user running SQL Server Agent service and user running SQL Server service to control the folder Z:\Translog.
  • Open C:\Windows\System32\drivers\etc\host with Administrator right then add a line with IP to point the secondary server name, for example: 192.168.72.101 SECONDARY_SERVER_NAME
  • Download FreeFileSync and install it on the primary sever.
  • Create a batch job on FreeFileSync for syncing files (Mirror way) from Z:\Translog to the FTP folder on secondary primary. See the tutorial video on https://freefilesync.org/tutorials.php and the following pictures for how to.
  • Setup RealTimeSync for the batch job for watching on Z:\Translog and syncing files real time. See the tutorial video on https://freefilesync.org/tutorials.php and the following pictures for how to.



2. Setup log shipping on the primary server by using MS SQL Management Studio

Make sure your DB is Full recovery model (or Bulk-logged). Right click on your DB >> select Properties menu and check & change in Options section:


Move to Transaction Log Shipping section and tick Enable this as a primary database...:


Then click Backup Settings button to pop up below form:


In the box Network path to backup folder..., let key \\YOURSERVER\SF or any kind of shared folder you want. That is a fake folder which we won't use, just key in for enabling OK button. The second box, let key in the folder Z:\Translog which you prepared. You can change the other parameters according your need. I recommend to use Compress backup option for saving bandwidth when transferring logs via Internet. Click OK button to finish this form.

In Monitor server instance area, tick Use a monitor server instance then click Settings button to bring up the following form:


Click Connect button then connect to the secondary server, you can change the value of Delete history after and click OK button to finish.

Back to Transaction Log Shipping section, click OK button to establish configurations for the primary server. It will enable the primary database for log shipping and create 2 jobs: LSBackup_XXX in SQL Server Agent >> Jobs of the primary server and LSAlert_XXX in SQL Server Agent >> Jobs of the secondary server.

Right click your DB, select menu Task >> Back Up... select Backup type as Full. Then backup your DB to disk. This backup file will be copied to the secondary server for initializing secondary database.

Before going to the secondary server and configuring, we will do a trick to get a script for running on that server. Open back Transaction Log Shipping section, on Secondary databases click Add button to open below form:


Click Connect button and connect to the Secondary server instance and Secondary database (e.g. TestDB). Select option "No, the secondary database is initialized" then move to Copy Files tab:


Key in the folder in the secondary server for copying transaction log files (e.g. C:\Translog_Copy). Move to Restore Transaction Log tab:


Select Standby mode and tick "Disconnect user..." to put the secondary database into read only mode and disconnect users when restoring. Then click OK button.
Back to Transaction Log Shipping section, in the bottom click Script Configuration >> Script Configuration to New Query Window, ah ha let see the script generated. Before viewing this script, let click Cancel button to close Transaction Log Shipping without doing any thing.


Go to the query window opened and copy the script between "Begin: Script to be run at Secondary" and "End: Script to be run at Secondary" to run on the secondary server later.

3. Setup log shipping on the secondary server

First of all, let restore the full backup of primary database on the secondary server by using RESTORE WITH STANDBY (you should restore before generating the script on the step above):


After restoring, you will see the DB with text (Standby / Read-Only). Open new query windows and paste copied script above into here (remember to choose msdb for running the script later):


Yes, nearly done! We just modify the script a little bit to change the fake shared folder (\\YOURSERVER\FORDER) to the local folder (C:\Translog) on the secondary server which is the FTP folder to receive log files transferred from the primary server, see below for your idea:


That's it. Run the script. It will create 2 scheduled jobs: LSCopy_XXX (for copying file from C:\Translog to C:\Translog_Copy per 15 minutes) and LSRestore_XXX (for restoring transaction logs in C:\Translog_Copy to the secondary database per 15 minutes) in SQL Server Agent >> Jobs. You can go there to change the schedule of 2 these jobs.

Voila! You got the secondary database synced with primary database with interval 15-30 minutes (depending the time between LSCopy_XXX and LSRestore_XXX).

That's all. Any comment is welcome.

Monday, July 16, 2018

Windows RDP: Solving the error "This could be due to CredSSP encryption oracle remediation"

Do you get the error as below when remoting your server?


It is normally caused by your Windows client getting new update on CredSSP but your Windows server is not.
For long term, you should update your server for more security.
For temporary solution, you can do the following steps on your Windows client to able to remote your server:

1. Open Run box, key gpedit.msc to open Local Group Policy Editor.

2. Navigate to Computer Configuration >> Administrative Templates >> System >> Credentials Delegation >> Encryption Oracle Remediation. Then select  Enable >> Vulnerable >> OK.


3. Finally, open CMD (run as Administrator), run the command: gpupdate /force
to update the policy immediately.

Hope you can remote your server and update it. Have a nice day.

Monday, January 15, 2018

Integrate Facebook comment plugin into your website and notify via email

Facebook comments plugin allows Facebooker comment on a content on your website. The comments of customers or users (guests) are very important for almost website owners. To encourage guests leave their comments, beside the content must be attractive, the responds for comments also should be quickly.

In this article, I'll show you how to integrate Facebook comment plugin into your website and receive the notification via email when a comment is dropped on your website. Let go through below steps.

1. Create a Facebook page

If you still don't have a Facebook page, let create one soon. Facebook page is representative for your website or your business on Facebook. Increasing number of Facebookers who likes or follows your Facebook page will increase the chance to broadcast your website / business on Facebook. Facebook page also is used as an official account to response to comments. Especially when you have many administrators or moderators for your Facebook page.
To create a Facebook page, let go to: https://www.facebook.com/pages/create

2. Create a Facebook app

Facebook app is a gateway to interact with Facebook's assets. If you want to do any things with Facebook, you should have a Facebook app.
If you still don't have a Facebook app, let create one via: https://developers.facebook.com/docs/apps/register

3. Embed Facebook comments plugin into your website

Link your website with your Facebook app & page. To do this, let add meta tags fb:app_id & fb:pages into all pages of your website, for example:
<meta property="fb:app_id" content="645919975544702" />
<meta property="fb:pages" content="174460585975791" />
To get your Facebook app id, go to the Dashboard of your app, see the following sample:


To get your Facebook page id, go to Page >> About and find Page ID at the bottom:


Next, let add Facebook's JavaScript SDK and comment box into each page on your website where you want to guests leave comments. To get the code and comment box, you can go to https://developers.facebook.com/docs/plugins/comments, find Comments Plugin Code Generator section and put your parameters into boxes then click Get Code button. See below picture for example:

You can change the settings of comment box based on your need, for example I want to show 10 newest comments, I do:
<div class="fb-comments" data-href="https://baby.shopqua.com/ba-lo-tui-cap-xach/ba-lo-cho-be" data-numposts="10" data-order-by="reverse_time" data-width="100%"></div>
For counting number of comments of an URL, let use fb-comments-count:
<span class="fb-comments-count" data-href="https://baby.shopqua.com/ba-lo-tui-cap-xach/ba-lo-cho-be"></span>comments
The above are important settings that I think you should do, for other settings & how to monitor comments, please see more on: https://developers.facebook.com/docs/plugins/comments

4. Set up your Facebook app

If you need a page profile for your app, let go to your app >> Settings >> Advanced >> App Page and click Create New Page button.


Or you can select an existing page there if the page has same name with the app and categorized as App Page. To change Category or Name of the existing page, click About menu of the page and click Edit link of Category or Name:


The guide on https://developers.facebook.com/docs/plugins/comments has a section to enable comment mirroring which allows comments from your webpage will also appear as comments on your Facebook Page post and vice-versa. Using comment mirroring, you can receive a notification on Facebook Pages Manager mobile app when you got a comment on your web page. However it will be deprecated soon according to the post https://developers.facebook.com/blog/post/2017/11/07/changes-developer-offerings. So you won't receive the notification on Facebook Pages Manager mobile app more.

Don't worry, I'll show you a way to get this notification via email. For beginning, let setup a webhook when a new comment is posted. See Webhooks section on https://developers.facebook.com/docs/plugins/comments for how to. More than thousands of words, I post here my pictures:

In the Webhooks section, Facebook also gives a sample mywebhook.php in PHP. Let rename it to commentwebhook.php and modify it in next step to do what we want.

5. Modify commentwebhook.php

The message sent to this webhook file has the format of JSON, however it lacks some important info. So we need to get this info via Facebook API.
To access Facebook API, you need an access_token. You can get it via Facebook Graph API Explorer: https://developers.facebook.com/tools/explorer


You can test APIs in this tool to get experience on data returned. If you want to have a sample code, let scroll down and click Get Code button at the bottom. The sample code is one among of kinds: Android SDK, iOS SDK, JavaScript SDK, PHP SDK, cURL.
Below is the source code of my commentwebhook.php file:

if ($_GET['hub_verify_token'] === 'XXXXXXXXX-123456789-ABCdef') {
  echo $_GET['hub_challenge'];
}

$entry = file_get_contents('php://input');
file_put_contents('commentwebhook.log', "\n" . $entry, FILE_APPEND);

//get input message
$input = json_decode($entry, true);
$message = $input['entry'][0]['changes'][0]['value']['message'];
$fb_comment_id = $input['entry'][0]['changes'][0]['value']['id'];
$created_time = $input['entry'][0]['changes'][0]['value']['created_time'];
$from_name = $input['entry'][0]['changes'][0]['value']['from']['name'];
$from_id = $input['entry'][0]['changes'][0]['value']['from']['id'];

//get more details
$access_token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$url = "https://graph.facebook.com/v2.6/$fb_comment_id?access_token=$access_token&fields=permalink_url";//fields=permalink_url,message,from,created_time
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($ch);
curl_close($ch);
$output = json_decode($resp, true);
$permalink_url = $output['permalink_url'];

//send email
$bodyHtml =
"<h1><a href='https://www.facebook.com/$from_id'>$from_name</a></h1>
<h2>$message</h2>
<h3>On: <a href='$permalink_url'>$permalink_url</a></h3>";
$bodyText = "$from_name:\n  $message\n  On: $permalink_url";
$url = 'https://api.elasticemail.com/v2/email/send';
try {
 $post = array('from' => 'youremail@yourdomain.com',
 'fromName' => 'Your Website Name',
 'apikey' => '00000000-0000-0000-0000-000000000000',
 'subject' => 'You have a comment',
 'to' => 'recipient1@gmail.com;recipient2@gmail.com',
 'bodyHtml' => $bodyHtml,
 'bodyText' => $bodyText,
 'isTransactional' => true);

 $ch = curl_init();
 curl_setopt_array($ch, array(
  CURLOPT_URL => $url,
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => $post,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HEADER => false,
  CURLOPT_SSL_VERIFYPEER => false
 ));

 $result=curl_exec ($ch);
 curl_close ($ch);

 file_put_contents('commentwebhook.log', "\n" . $result, FILE_APPEND);
}
catch(Exception $ex){
 file_put_contents('commentwebhook.log', "\n" . $ex->getMessage(), FILE_APPEND);
}


You can also get the source code from my GitHub: https://github.com/vnheros/facebookcomment

In the code, I use ElasticEmail for sending notification email without worrying about email server and inbox. If you like, you can register here for an ElasticEmail free account (can send up to 5000 emails free per day).

OK, now you have a power tool for notifying you immediately when getting a comment on your webpage. Happy?
That's all for today. Any comment is welcome!

Subscribe to RSS Feed Follow me on Twitter!