Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European Visual Studio 2017 Hosting - HostForLIFE.eu :: Shortcuts For Debugging In Visual Studio

clock November 28, 2018 10:06 by author Peter

Debugging is one of the most important aspect of programming. It is crucial to successful software development, but even many experienced programmers find it challenging. With the help of keyboard shortcuts , it can be made faster. So here is the list of all shortcut keys available in visual studio for debugging.

Debugging Shortcuts in Visual Studio
 

Shortcut

Description

Ctrl-Alt-V, A Displays the Auto window to view the values of variables currently in the scope of the current line of execution within the current procedure
Ctrl-Alt-Break Temporarily stops execution of all processes in a debugging session. Available only in run mode
Ctrl-Alt-B Displays the Breakpoints dialog, where you can add and modify breakpoints
Ctrl-Alt-C Displays the Call Stack window to display a list of all active procedures or stack frames for the current thread of execution. Available only in break mode
Ctrl-Shift-F9 Clears all of the breakpoints in the project
Ctrl-Alt-D Displays the Disassembly window
Ctrl-F9 Enables or disables the breakpoint on the current line of code. The line must already havek a breakpoint for this to work
Ctrl-Alt-E Displays the Exceptions dialog
Ctrl-Alt-I Displays the Immediate window, where you can evaluate expressions and execute individual commands
Ctrl-Alt-V, L Displays the Locals window to view the variables and their values for the currently selected procedure in the stack frame
Ctrl-Alt-M, 1 Displays the Memory 1 window to view memory in the process being debugged. This is particularly useful when you do not have debugging symbols available for the code you are looking at. It is also helpful for looking at large buffers, strings, and other data that does not display clearly in the Watch or Variables window
Ctrl-Alt-M, 2 Displays the Memory 2 window
Ctrl-Alt-M, 3 Displays the Memory 3 window
Ctrl-Alt-M, 4 Displays the Memory 4 window
Ctrl-Alt-U Displays the Modules window, which allows you to view the .dll or .exe files loaded by the program. In multiprocess debugging, you can right-click and select Show Modules for all programs
Ctrl-B Opens the New Breakpoint dialog
Ctrl-Alt-Q Displays the Quick Watch dialog with the current value of the selected expression. Available only in break mode. Use this command to check the current value of a variable, property, or other expression for which you have not defined a watch expression
Ctrl-Alt-G Displays the Registers window, which displays CPU register contents
Ctrl-Shift-F5 Terminates the current debugging session, rebuilds if necessary, and then starts a new debugging session. Available in break and run modes
Ctrl-Alt-N Displays the Running Documents window that displays the set of HTML documents that you are in the process of debugging. Available in break and run modes
Ctrl-F10 Starts or resumes execution of your code and then halts execution when it reaches the selected statement. This starts the debugger if it is not already running
Ctrl-Shift-F10 Sets the execution point to the line of code you choose
Alt-NUM * Highlights the next statement to be executed
F5 If not currently debugging, this runs the startup project or projects and attaches the debugger. If in break mode, this allows execution to continue (i.e., it returns to run mode).
Ctrl-F5 Runs the code without invoking the debugger. For console applications, this also arranges for the console window to stay open with a “Press any key to continue” prompt when the program finishes
F11 Executes code one statement at a time, tracing execution into function calls
Shift-F11 Executes the remaining lines of a function in which the current execution point lies
F10 Executes the next line of code but does not step into any function calls
Shift-F5 Available in break and run modes, this terminates the debugging session
Ctrl-Alt-V, T Displays the This window, which allows you to view the data members of the object associated with the current method
Ctrl-Alt-H Displays the Threads window to view all of the threads for the current process
F9 Sets or removes a breakpoint at the current line
Ctrl-F11 Displays the disassembly information for the current source file. Available only in break mode
Ctrl-Alt-W, 1 Displays the Watch 1 window to view the values of variables or watch expressions
Ctrl-Alt-W, 2 Displays the Watch 2 window
Ctrl-Alt-W, 3 Displays the Watch 3 window
Ctrl-Alt-W, 4 Displays the Watch 4 window
Ctrl-Alt-P Displays the Processes dialog, which allows you to attach or detach the debugger to one or more running processes

 



European Visual Studio 2017 Hosting - HostForLIFE.eu :: Live Unit Testing With Visual Studio 2017

clock November 14, 2018 08:41 by author Peter

Visual Studio 2017 v15.3 or higher versions support Live Unit Testing. This feature executes the already-written test cases automatically as a programmer makes the code changes. Live Unit Testing helps a developer to do the following:

 

  • It executes all the impacted Test Cases as a programmer modifies the code and makes sure changes do not break Unit Test Cases.
  • Through the Visual Studio editor, the programmer sees the code coverage in a realistic view.
  • It also indicates which line is covered or not using Live Unit Testing.
  • Live Unit Testing is supported in  both .NET Framework and .NET Core.

Enabling
Live Unit Testing is only available in Visual Studio 2017 with the Enterprise edition. We can enable the Live Unit Testing by going to the following menus - Test > Live Unit Testing > Start.

After enabling the Live Unit Testing for a project, Live Unit Testing shows options as Start, Pause, Stop and Reset.

Configuration
The default configuration can be changed from the Visual Studio Menu Tool > Options > Live Unit Testing > General. We can configure the Live Unit Testing for the Battery and Memory usages, Testcase Timeout, and Logging Level can be set as needed.

Setup Project Solution

  • Open the Visual Studio 2017.
  • Create one Windows Library Project as “ClassLibrary1” and Change the “Class1.cs” to the “AreaCalculator.cs”.
  • Right click on the solution and add a Unit Test Project as “UnitTestProject1” and change the “UnitTest1.cs” to the “AreaCalculatorTest.cs”
  • Add the Reference of the “ClassLibrary1” project to the “UnitTestProject1”.
  • Add the using statement “using ClassLibrary1;” to the “AreaCalculatorTest.cs” in the using statement section.
  • Build the Solution.

Demo
Open the AreaCalculator.cs and add the code as per the below screenshot.
Open the AreaCalculatorTest.cs and paste the below code. I have not added the Test Method for the triangle’s area calculation and incorrectly calculated the Test Method of the square’s area, just to show some behavior of Live Unit Testing.

Replace the below code in the AreaCalculatorTest.cs file
Now start the Live Unit Testing from the Test menu, then an automatic background process triggers and we see an icon in-line with code. Description of each icon is mentioned here

  • Green Tick Mark represents that this Method is covered for the unit testing.
  • Cross Mark represents that this method is covered for the unit testing, but the test case failed during execution.
  • Blue Negative Mark represent that this method is not covered for the unit testing so a test case needs to be created.

Below screenshots represent each icon of the Live Unit Testing

Icon’s in AreaCalculator.cs


Icon’s in AreaCalculatorTest.cs


So, with the help of Live Unit Testing of Visual Studio, a developer will know about the impact of the changes he is making, and if it's covered for unit testing or not. This is an awesome feature of Visual Studio 2017



Windows Server 2016 SSD Hosting - HostForLIFE.eu :: Load Balancing

clock September 21, 2018 11:48 by author Peter
What is Load Balancing ?
Distributing network traffic across multiple servers effectively is called Load Balancing.To meet high volumes, it generally requires adding more servers. Load Balancer routes the client requests to the servers in an optimized way and takes care that no server is overworked. If a new server is added to the group, It will start sending requests to this new server.


Load-Balancing Algorithms
Why did algorithms come into the picture ? Actually Load Balancer selects the server based on two factors,
  • periodically pinging server to check its availability.
  • defined algorithms - based on which load-balancer selects the server.
Algo 1 Least Connection (Default algorithm)
The least connection is the default algorithm to select server. Server which has the least number of active transactions is picked by Load Balancer to handle request. Load Balancer maintains records of transactions for each server.

Now discuss this in detail: Let's say all the servers have the same capacity and still some of the servers are overloaded as there may be the situation that the client stayed in those servers for longer duration and connected to other severs for shorter duration. Active connections on the server where client stayed longer will pile up and hence based on the least connection algorithm Load Balancer will route the request in the server with least active connections,

Weighted Least Connections

Now let's consider the above Least Connection algorithm with different server capacities (CPU/RAM etc.). You would definitely want to allocate more requests to the higher capacity server than the lower capacity servers. Weighted Least Connection is the solution.

Let's say there are 2 servers, server 1 and server 2 and server 2 has high configuration.With this algorithm Load balancer will allocate more requests to server 2 to utilize it better. Like Least Connection this also allocates request to the server withthe least number of active connections but the higher configuration server will handle more requests based on the right proportion defined during the Load Balancer setup. Weight proportion is calculated by the server capacity. Server 1 : Capacity X, Server 2 : Capacity : 10X the weight for each server would be 1:10 . There might be the scenario if you don't want to overload any of the servers for some reason, you may use this algorithm to give extra weight to other servers.

Round Robin

Round Robin is a vastly used and simple algorithm. Load Balancer distributes requests in the cyclic order irrespective of server inefficiencies. Both the Servers are ready to take request, suppose request comes and load-balancer routes to Server 1 then if a second  request comes it will be routed to Server 2. The third and fourth will be routed to Server 1 and 2 respectively in a cyclic order. Even if one of the server has stronger configuration i.e. RAM, CPU etc. As per Round Robin algorithm Load-Balancer will follow the cyclic order.

Algo 4 Weighted Round Robin

Like Round Robin this is also cyclic but the higher configuration server will handle more requests.Rest it is same as Weighted Least connection algorithm i.e. weight would be defined during Load Balancer setup and high weight server will handle more requests.

i.e. if weight proportion to server 1 and server to is 1:10. first 10 requests will go to server and 11th request will go to server 1 and next 10 request will go to server 2 and so on.

Algo 5 IP Hash

This algorithm generates a hash key using client and server IP addresses which means this key would be assigned to client for subsequent requests which assure that the client is routed to the same server that it was using earlier.This algorithm can be used to achieve Session Persistence or Sticky Session.

Session Persistence

In the multiple server environment a user might experience losing cart items during navigation. Persistence session or sticky session is the culprit. As you know Http is a stateless protocol which means in subsequent requests it doesn't maintain any information about the user so to identify server uses client's ip or cookie to track users session. Sticky session is to make sure all the requests goes to the same server which has its user's session tracking information.

Layer 4 & Layer 7 Load Balancing

In Layer 4 Load Balancing , Load balancer decides the server on which it will redirect the requests on the basis of the IP addresses of the origin and destination servers (Network Layer : Layer 3) and the TCP port number of the applications (Transport Layer : Layer 4).
On the other hand Layer 7 Load Balancing decides routing on the basis of OSI Layers 5, 6, and 7 which together makes Http. To get an overview of OSI Model, please read my post .


European Visual Studio 2017 Hosting - HostForLIFE.eu :: Using the BackgroundWorker component

clock September 20, 2018 11:12 by author Peter

The BackgroundWorker allows you to execute operations that take a long period of time such as database transaction or file downloads, asynchronously on a separate thread and allow the user interface to remain responsive.


Start an Operation in the Background
First, you need to add an instance of the BackgroundWorker component to your application, if you use visual studio, just drag it from the toolbox to your application or you can create it manually as follow:
BackgroundWorker backgroundWorker1 = new BackgroundWorker(); 

To start the operation in the background you have to call the RunWorkerAsync() method of the BackgroundWorker, when you call this method the BackgroundWroker starts the execution of the background operation by raising the DoWork event, the code in the DoWork event handler is executed on a separate thread.
BackgroundWorker backgroundWorker1 = new BackgroundWorker(); 
//start the operation on another thread 
private void btnStart_Click(object sender, EventArgs e) 

    backgroundWorker1.RunWokerAsync(); 

//DoWork event handler is executed on a separate thread 
private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e) 

    //a long running operation 
    Thread.Sleep(5000); 


You can send a parameter to the background operation using the RunWorkerAsync() method. You can receive this parameter by using the Argument property of the instance of DoWorkEventArgs in the DoWork event handler then you cast it to use it in the background operation.

BackgroundWorker backgroundWorker1 = new BackgroundWorker(); 
//start the operation on another thread 
private void btnStart_Click(object sender, EventArgs e) 

    backgroundWorker1.RunWokerAsync(2000); 

//DoWork event handler is executed on a separate thread 
private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e) 

    int input = (int)e.Argument; 
    //a long running operation 
    Thread.Sleep(input); 


Reporting progress of a background operation using BackgroundWorker

By using the BackgroundWorker you have the ability to report progress updates of the executing operation. To use this options you must set the WorkerReportsProgress to true.

To start report progress you call ReportProgress() method and use it to pass a parameter that have the value of the percentage of the progress that have been completed. This method raises the BackgroundWorker.ProgressChanged event. In the event handler of the ProgressChanged you can recieve the value of the progress precentage on the main thread using the ProgressPercentage property of the instance of ProgressChangedEventArgs.

BackgroundWorker backgroundWorker1 = new BackgroundWorker(); 
backgroundWorker1.WorkerReportsProgress = true; 
//start the operation on another thread 
private void btnStart_Click(object sender, EventArgs e) 

    backgroundWorker1.RunWokerAsync(); 

//DoWork event handler is executed on a separate thread 
private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e) 

    //a long running operation 
    for (int i = 1; i < 11; i++) 
    {    
        Thread.Sleep(2000); 
        backgroundWorker1.ReportProgress(i*10); 
    } 

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 

    progressBar1.value = e.ProgressPercentage; 


Canceling a background operation using BackgroundWorker

With the BackgroundWorker you have the ability to cancel the background operation, to do this you first must set WorkerSupportsCancellation property to true.

The next step is to call the CancelAsync() method by doing so you set the CancellationPending property to true, by polling the CancellationPending property you can determine whether or not to cancel the background operation.

BackgroundWorker backgroundWorker1 = new BackgroundWorker(); 
backgroundWorker1.WorkerSupportsCancellation = true; 
//start the operation on another thread 
private void btnStart_Click(object sender, EventArgs e) 

    backgroundWorker1.RunWokerAsync(); 

//a buttun to cancel the operation 
private void btnCancel_Click(object sender, EventArgs e) 

    backgroundWorker1.CancelAsync(); 

//DoWork event handler is executed on a separate thread 
private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e) 

    //a long running operation 
    for (int i = 1; i < 11; i++) 
    { 
        Thread.Sleep(2000); 
        backgroundWorker1.ReportProgress(i*10); 
        if(backgroundWorker1.CancellationPending) 
        { 
            e.cancel = true; 
            return; 
        } 
    } 


Alert the user in the completion of the background operation
When the background operation completes, whether because the background operation is completed or canceled, the RunWorkerCompleted event is raised. You can alert the user to the completion by handling the RunWorkerCompleted event.

You can determine if the user canceled the operation by using the Cancelled property of the instance RunWorkerCompletedEventArgs.
BackgroundWorker backgroundWorker1 = new BackgroundWorker(); 
//start the operation on another thread 
private void btnStart_Click(object sender, EventArgs e) 

    backgroundWorker1.RunWokerAsync(); 

//a buttun to cancel the operation 
private void btnCancel_Click(object sender, EventArgs e) 

    backgroundWorker1.CancelAsync(); 
}  
//DoWork event handler is executed on a separate thread 
private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e) 

    //a long running operation 
    for (int i = 1; i < 11; i++) 
    { 
        Thread.Sleep(2000); 
        backgroundWorker1.ReportProgress(i*10); 
        if (backgroundWorker1.CancellationPending) 
        { 
            e.Cancel = true; 
            return; 
        } 
    } 
}  
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 

    if(e.Cancelled) 
    { 
        MessageBox.Show("Operation Cancelled"); 
    } 
    else 
    { 
        MessageBox.Show("OperationCompleted"); 
    } 


Return a value from the background operation
You can return a value from the background operation that in the DoWork event handler using the Result property of the DoWorkEventArgs instance, and you can receive it in the RunWorkerCompleted event handler using the Result property of the RunWorkerCompletedEventArgs instance.

BackgroundWorker backgroundWorker1 = new BackgroundWorker(); 
//start the operation on another thread 
private void btnStart_Click(object sender, EventArgs e) 

    backgroundWorker1.RunWokerAsync(); 

//DoWork event handler is executed on a separate thread 
private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e) 

    //a long running operation here 
    Thread.Sleep(2000); 
    //return the value here 
    e.Result = 10; 

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 

    //recieve the return value here 
    int returnValue = (int)e.Result; 



Node.js Hosting Europe - HostForLIFE.eu :: How to Use Inheritance in Node.js ?

clock September 12, 2018 08:29 by author Peter

In this post we'll take a glance on inheritance of objects in Node.js. we'll learn to use utility module to achieve inheritance in Node.js. but confine mind that you simply will write plain JavaScript to attain inheritance in Node also.

You'll use Object.create() to inherit one object to a different in Node.js also.

In this post we'll learn to use util module to achieve inheritance in Node.js. First, you should to import util module in your application.
var util= require(‘util’);

After importing util module, allow us to say you have got an object as below,
function Student()

 this.name = "G Block";
 this.age = 40;
};


Just for demonstration allow us to add function in object using prototype,
Student.prototype.Display= function(){
 console.log(this.name + " is " + this.age + " years old");
 };


Next we tend to we progressing to make ArtsStudent object which is able to inherit Student object.
function ArtsStudent()
{
 ArtsStudent.super_.call(this);
 this.subject = "music";
 }; 
util.inherits(ArtsStudent,Student);


Second line of code in ArtsStudent object is very important,
ArtStudent.super_.call(this);

If you don’t call constructor of parent object as shown in above code snippet then on making an attempt to access properties of parent object will come undefined. In last line ArtStudent inherits Student using util.inherits() function ,

util.iherits(ArtsStudent,Student);

Next you can create instance of ArtsStudent and call function of parent object as below,
var a = new ArtsStudent();
a.Display();


Inheritance will be chained to any order. If you want you can inherit object from ArtsStudent as well. Inherited object will contain properties from both ArtsStudent and Student objects. So let us consider one more example,
function ScienceStudent()
{
 ScienceStudent.super_.call(this);
 this.lab = "Physics";
}
util.inherits(ScienceStudent,ArtsStudent);
var b = new ScienceStudent();
b.Display();

On this example ScienceStudent object inherits both Student and ArtsStudent objects. With this example, you can work with inheritance in Node.js using util module. I hope it works for you!

HostForLIFE.eu Node.js Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



Windows Server 2016 SSD Hosting - HostForLIFE.eu :: PowerShell Script To Reading SQL Data, Creating CSV File And Push To SFTP/FTP Path?

clock September 7, 2018 11:16 by author Peter

The below powershell cmdlets are used to create csv files by querying the SQL server.

All the variables containing the server name and DB details:
    #Variable to hold variable 
    $SQLServer = "XX.XX.XXX.XX" 
    $SQLDBName = "TestDB" 
    $uid ="domain\userID" 
    $pwd = "password123"  
    #SQL Query 
    $SqlQuery = "SELECT * from tableName;" 
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection 
    $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;" 
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand 
    $SqlCmd.CommandText = $SqlQuery 
    $SqlCmd.Connection = $SqlConnection 
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter 
    $SqlAdapter.SelectCommand = $SqlCmd  
    #Creating Dataset 
    $DataSet = New-Object System.Data.DataSet 
    $SqlAdapter.Fill($DataSet) 
    $DataSet.Tables[0] | out-file "\\location\test.csv" 


Note
When Intergrated Security ="true" is used, the cmdlets use current logged in user credentials - network credentails if Integrated Security ="false" we need to use the declared $uid and $pwd while establishing the connection.

The File is saved in the location or FTP path as test.csv
The SFTP is Secured FTP; the following powershell command helps to move any file to the SFTP location and it needs "Posh-SSH module" We need to install this module.https://github.com/darkoperator/Posh-SSH

The Powershell variable mentioned in the below code snippnet stores all the details of the SFTP or FTP server, where the files need to be moved.
    #Declaring Variable 
    $sourceSFTPIP = "xx.xx.xxx.xx" 
    #IP address of the SFTP server 
    $LocalFilePath = "C:\test.csv"; 
    $SFTPPath = ".\sharedFilePath\"  
    # folder location inside SFTP server 
    $secpasswd = ConvertTo - SecureString "password" - AsPlainText - Force 
    # the below object is used to key in the username and password automatically rather than promt the user to username and password 
    $mycreds = New - Object System.Management.Automation.PSCredential("username", $secpasswd) 
    # Module need to use SFTP Path 
    Install - Module - Name Posh - SSH# get sftp password this command can be used 
    if user need to feed in the user name and password at the time of running the script 
    # $credential = Get - Credential# Creating PS session to be used 
    $session = New - SFTPSession - ComputerName $sourceSFTPIP - Credential $mycreds - AcceptKey 
    # Move File using ps session 
    Set - SFTPFile - SessionId $session.SessionId - LocalFile $LocalFilePath - RemotePath $SFTPPath 
    $session.Disconnect() 


We need to disconnect the session that was created to do this operation. Once it has run,  the file that is present in sharepath is moved to the SFTP server location.



European Visual Studio 2017 Hosting - HostForLIFE.eu :: Visual Studio IntelliCode Preview Available

clock August 24, 2018 11:08 by author Peter

Recently, Microsoft has announced the availability of Preview of Visual Studio IntelliCode in its Build 2018 developer’s conference. This is a new experimental tool for Visual Studio users bringing more of the company’s artificial intelligence smart to software development.

It is a set of AI-assisted capabilities which improves the developer’s productivity with features like contextual, IntelliSense and focused reviews for pull requests.
 
The company states -
“The IntelliCode extension augments productivity features in Visual Studio 2017 with insights based on understanding your code combined with machine learning. The first iteration of this extension enhances your IntelliSense experience by sorting completion items—which are recommended in your code context--to the top of the list.”
 
According to the company, IntelliCode is now applicable only for C# code but in future, it will be upgraded to support more languages.

 



Windows Server 2016 SSD Hosting - HostForLIFE.eu :: How To Securely Delete Files From Your Servers?

clock August 15, 2018 11:40 by author Peter

Do you know what happens when you delete a file in a GUI or run rm file.txt on the command line? If you said the file is deleted, you are only half right. In fact, the data stays just where it was before you “deleted” it. You can’t see it because the link the operating system used to identify the file and show it to you no longer exists. But the data is untouched until the operating system uses the space for a different file.

It’s easy to restore data that has not been securely deleted. That’s bad news if the hard drive the data is on is sold, leased to someone else, or thrown in the trash. There are business, security, and legal consequences if server data is not securely deleted.

The only way to securely delete data is to overwrite it. You could also destroy the drive, but businesses typically lease servers that they don’t have physical access to or they own. They need to be able to securely delete data remotely. A quick rm doesn’t cut it.

Before I outline the best way to securely delete a file or volume, a word of warning. If you do this, the data will be gone forever — that’s the point. Before running any of these commands, make sure you really mean it.

Securely Deleting A File

As I have already said, rm removes directory entries. It does not delete data. To securely delete the data, you must use a tool that both removes the link and overwrites the data.

One such tool is shred, which will repeatedly overwrite the file’s data with random bytes.

shred -u file.txt

Shred overwrites the file three times with random data, although you can specify how many times the data is overwritten with the -n option. If you don’t use the -u option, shred will overwrite the data but it won’t remove the file.

Securely Deleting A Drive

The shred utility can securely erase drives, but we’ll explore an alternative.

Before running these commands, check that you have correctly identified the drive you want to erase. The command will run on the boot and root drives without warning.

Linux represents drives as files. For example, the file /dev/sda1 represents the “first” drive on your server. The dev directory is not a normal directory, but a collection of special files representing devices connected to the server.

To see the drives connected to a server, run this command,

`fdisk -l`

Identify the drive that you intend to erase all data from and take note of the special filename. We’re going to use dd to overwrite the data on this drive with either random data or zeroes. The dd command “converts and copies a file”.

In this case, we’re going to take data from a special file and overwrite our target drive with it. Linux provides several special files that generate a stream of data, including /dev/zero and /dev/urandom, which contain lots of zeros and pseudorandom data respectively.

dd if=/dev/urandom > /dev/ss__ # replace __ with drive number

Here, we designate /dev/random as the input file and direct its data to overwrite the drive. This will destroy all data on the drive.

For added security, you can repeat the dd command several times or alternate between random data and zeros with:

dd if=/dev/zero of=/dev/sd__ # replace __ with drive number

On modern high-density drives, multiple passes are usually not necessary, but it doesn’t hurt.

Limitations

There are some limitations to this approach that you should be aware of. If the data is being backed up to a different drive, it may remain accessible. If the drive uses a modern journaling filesystem like ext4, some data may not be erased properly. SSD wear leveling can also interfere with secure deletion.

For sensitive data, it may be best to use an encrypted volume rather than relying on secure deletion. The data from an encrypted volume cannot be recovered without the key even if it has not been securely deleted.



European Visual Studio 2017 Hosting - HostForLIFE.eu :: Customize Visual Studio Code Shortcuts

clock August 10, 2018 11:13 by author Peter

A couple of months ago, I started using Visual Studio Code for my development activities. I found myself very uncomfortable with the keys and shortcuts. I have been using Visual Studio for more than 6 years now. So, I was very comfortable with the keys and shortcuts of that. The difference in shortcuts was creating a challenge for me. Should I remember a different set of shortcuts for VS Code? Should I start using some other editor?

Then, I started to customize the VS Code shortcuts. If you are also facing the same issues, then it's time you should consider customizing the Visual Studio Code shortcuts. It’s not worth spending energy on remembering a new set of shortcuts for a specific editor. Following are some tips,

  1. Open keyboard shortcuts in Visual Studio Code and update the shortcuts as per your need.
    Press ctrl+K, ctrl+s to open the keyboard shortcut window. This looks something like below.
  2. You can see the Edit button on the right side of the row (highlighted one). On click of the Edit button, it will ask you to change the combination you want to execute the command for.

    You can change the combination for your convenience.

  1. You can open keybindings.json file and update as per your need.
    To open the keybindings.json, you need to open the Keyboard shortcuts first by pressing ctrl+k, ctrl+s. You can click on the keybindings.json file.
  2. This will open the default keybindings. This is a JSON file which can be modified to get your desired shortcuts.
  1. You can have your custom JSON file with your shortcut commands.
    When you open default keybindings.json file in the right-hand side window, it opens a keybindings.json file where you can write your custom keys and commands.

Given are a couple of commands I have added in the keybindings.json file to work with the VS Code. Please let me know your feedbacks/ comments. Are there better ways I am not just aware of?



Node.js Hosting in Europe - HostForLIFE.eu :: Forgot Password Email Notification Using Node js

clock August 8, 2018 09:22 by author Peter

Before starting the code you need an account in send grid which will send the notification to your mail. Generally we use email notifications for forget passwords in your applications. You can follow the below steps to get the task done and if you have any queries please leave a comment below.

We require a few modules from npm to send the notification through the mail.

  • npm install formidable
  • npm install crypto
  • npm install async
  • npm install nodemailer

In my router.js file the following code will be present 
app.route('/forgotpasswordResponse') 
.post(userCtrl.forgotpasswordResponse); 


When I run my services and hit the above Url  from postman it will take you to the forgotpasswordResponse method. We are using post method in postman where we need to pass Email id as parameter

In forgotpasswordResponse my code is somthing like this,
exports.forgotpasswordResponse = function(req, res, next) { 

var input=req.body; 
//console.log(input); 
async.waterfall([ 
function(done) { 
    crypto.randomBytes(20, function(err, buf) { 
        var token = buf.toString('hex'); 
        done(err, token); 
    }); 
}, 
function(token, done) { 
    MongoClient.connect(url, function(err, db){  
        var dbo = db.db("Here is your DB Name"); 
        //console.log(req.body.Email); 
        var query = { Email : req.body.Email }; 
        dbo.collection('CLC_User').find(query).toArray(function(err,result){ 
            if(result.length == 0){ 
                req.flash('error', 'No account with that email address exists.'); 
            } 
            var myquery = { Email: result[0].Email }; 
            var newvalues = { $set: {resetPasswordToken: token, resetPasswordExpires: Date.now() + 3600000 }}; 
            dbo.collection("CLC_User").updateOne(myquery, newvalues, function(err, res) { 
                if (err) throw err; 
                console.log("1 document updated"); 
            }); 
             

           // console.log(result[0].Email); 
            done(err, token, result); 
        }); 
    }); 
}, 
function(token, result, done,Username,password) { 
    var emailVal = result[0].Email; 
    console.log(emailVal); 
    var Username=""; 
    var password=""; 
    MongoClient.connect(url, function(err, db){  
    var dbo = db.db("Here willbe your db name"); 
    dbo.collection('Accountsettings').find().toArray(function(err,result){ 
        if (err) throw err; 
        Username=result[0].UserName; 
        password=result[0].Password; 
       // console.log(Username); 
       // console.log(password); 
           // res.json({status : 'success', message : 'Records found', result : result}); 
     

    // console.log(Username); 
    var smtpTransport = nodemailer.createTransport({ 
        service: 'SendGrid', 
        auth: { 
          user: Username, 
          pass: password 
        } 
      }); 

    const mailOptions = { 
        to: emailVal, 
        from: '[email protected]', 
        subject: 'Node.js Password Reset', 
        text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' + 
            'Please click on the following link, or paste this into your browser to complete the process:\n\n' + 
            'http://' + req.headers.host + '/reset/' + token + '\n\n' + 
            'If you did not request this, please ignore this email and your password will remain unchanged.\n' 
    }; 
    smtpTransport.sendMail(mailOptions, function(err) {                
        console.log("HI:"+emailVal); 
        res.json({status : 'success', message : 'An e-mail has been sent to ' + emailVal + ' with further instructions.'});             
        done(err, 'done'); 
    }); 
}) 
}); 

 
], function(err) { 
if (err) return next(err); 
 
}); 


In my case  I am using waterfall methologie for this method with will execute acyn in method, In the above code initially I am updating the collection with resetPasswordToken and resetPasswordExpires using email id and getting my send  grid credentials from db form  Accountsettings collections. If you can observe in mailOptions text "req.headers.host" will be the link which will get in you mail with token.

When you click on Url which you got in the email it will redirect you to another page to set the password.

Again we need to go to route.js and the code will be some thing like this. It will take to html page which we can reset the password,
app.route('/reset/:token') 
.get(Resetpassword.resetpasswordResponse);  

This time I am passing the token which I stored in db as "resetPasswordToken". Now it will take you to resetpasswordResponse method and the code is below,
exports.resetpasswordResponse = function(req, res) { 
console.log("welcome"); 
MongoClient.connect(url, function(err, db){ 
var dbo = db.db("Here is you db"); 
dbo.collection('CLC_User').findOne({resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) { 
    if (!user) { 
        res.json({message: 'Password reset token is invalid or has expired.'}); 
    }else{ 
        console.log("coming"); 
        fs.readFile("api/Controllers/resetpassword.html", function (error, data) { 
            console.log("its working"); 
            if (error) { 
                console.log(error); 
                res.writeHead(404); 
                res.write('Contents you are looking are Not Found'); 
            } else { 
                //res.writeHead(200, { 'Content-Type': 'text/html' }); 
                res.write(data); 
            } 
            res.end(); 
        }); 
    } 
}); 
}); 


Your html code in resetpassword.html will be like this,
<!DOCTYPE html> 
<html> 
<head> 
<title>Reset Password</title> 
<script src="https://code.jquery.com/jquery-1.12.4.js"></script> 
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 
</head> 
<body> 
<h4 class="postdata" style="text-align:center;"></h4> 
<div class="main-agileits"> 
<h2 class="sub-head">Reset Password</h2> 
<div class="sub-main">     
    <form method="post"> 
        <span class="senddata"></span><br><br> 
             
        <input placeholder="Enter Password" name="password" class="password" type="password" required=""><br><br> 

        <input placeholder="Confirm Password" name="confirmpassword" class="confirmpassword" type="password" required=""><br><br> 
         
        <input type="submit" name ="submit" value="RESET PASSWORD"> 
         
    </form> 
</div> 
</div> 
</body> 
</html> 


<script type="text/javascript"> 

$( document ).ready(function() { 
$("input[name='submit']").on("click", function(){ 
$(".senddata").html(""); 
var url = window.location.href; 
var password = $('.password').val(); 
var confirmpassword = $('.confirmpassword').val(); 

if( password == confirmpassword){ 
    $.post(url,{Password : password},function(result,status){ 
    var msg = result.status; 
    var msgdata = result.message; 
    if(msg == "success"){ 
        $(".postdata").html(msgdata); 
        $(".main-agileits").css("display","none") 
    }else{ 
        return false; 
    } 
}); 
}else{ 
    $(".senddata").html("Passwords did not match"); 
}        
return false; 
}); 

}); 

</script>


the next step is send the Email notification after changing the password.The code is
app.route('/reset/:token') 
.post(setpassword.setpasswordResponsemail); 

exports.setpasswordResponsemail = function(req, res) { 
async.waterfall([ 
function(done) { 
    MongoClient.connect(url, function(err, db){ 
        var dbo = db.db("Your Db name goes here");  
        dbo.collection('CLC_User').findOne({resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) { 
            if (!user) { 
                res.json({message: 'Password reset token is invalid or has expired.'}); 
            } 
            //console.log(user); 
            var myquery = { resetPasswordToken: req.params.token }; 
            var newvalues = { $set: {Password: req.body.Password,resetPasswordToken: undefined, resetPasswordExpires: undefined, modifiedDate : Date(Date.now()) }}; 
            dbo.collection("CLC_User").updateOne(myquery, newvalues, function(err, result) { 
                if (err) throw err; 
                //console.log("result ======" + result); 
                console.log("1 document updated"); 
            }); 
            done(err, user); 
        }); 
    }); 
}, 
function(user, done) { 
    MongoClient.connect(url, function(err, db){  
        var dbo = db.db("Your db name goes here"); 
        var Username=""; 
        var password=""; 
        dbo.collection('Accountsettings').find().toArray(function(err,result){ 
            if (err) throw err; 
            Username=result[0].UserName; 
            password=result[0].Password; 
        }) 
    }) 
    var smtpTransport = nodemailer.createTransport({ 
        service: 'SendGrid', 
        auth: { 
            user: Username, 
            pass: password 
        } 
    }); 
    var mailOptions = { 
        to: user.Email, 
        from: '[email protected]', 
        subject: 'Your password has been changed', 
        text: 'Hello,\n\n' + 
            'This is a confirmation that the password for your account ' + user.Email + ' has just been changed.\n' 
    }; 
    smtpTransport.sendMail(mailOptions, function(err) { 
        res.json({status : 'success', message : 'Success! Your password has been changed.'}); 
        done(err); 
    }); 

], function(err) { 
if (err) return err; 
}); 
}

Hope this code will help someone who really needs  it. Thank you.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in