Saturday, May 16, 2020

Node.JS rest api Tutorials


Install appropriate node version from here : 
https://nodejs.org/en/download/

All these commands must be run on command prompt after npm package 
installation.
generate an empty npm project without going through an interactive 
process.
npm init -y

install required (driver) packages
npm i express mysql body-parser cors 

install nodemon, it is a tool that helps by automatically restarting 
the node 
application when file changes in the directory are detected
npm i -g nodemon




//First create a folder (lers say "nodejs-rest-api")
// and then create a file in that folder called "app.js" 
//and you should add this code :

var express = require("express");
var app = express();
// mysql driver
var mysql = require("mysql");
// parser to parse POST body content
var bodyParser = require("body-parser");
// this is the port where your application will run (eg: localhost:9800)
var port = 9800;

// create connection object for database
let connection = mysql.createConnection({
    host: "localhost",
    user: "user",
    password: "password",
    database: "somedatabase",
});

app.use(bodyParser.json()); // so it can support JSON-encoded bodies
app.use(
    bodyParser.urlencoded({
        // so it can support URL-encoded bodies
        extended: true,
    })
);

// this will connect MySQL
connection.connect();

// this will create a get request with route "localhost:9800/"
// req -> request
// res -> response
app.get("/", (req, res) => {
    res.send("Application started");
});

// this will create a get request with route "localhost:9800/coaches"
app.get("/coaches", (req, res) => {
    connection.query("SELECT * FROM coachmain;", (err, result) => {
        if (err) {
            console.log(err);
            res.json({ error: true });
        } else {
            console.log(result);
            res.json(result);
        }
    });
});

// this will create a delete request with route "localhost:9800/deleteCoach"
/*
delete body should be something like this :
    {
        "coachId": 1
    }
*/
app.delete("/deleteCoach", function (req, res) {
    // get data from forms and add to the table called coachmain
    var coachId = parseInt(req.body.coachId);
    var queryString =
        `DELETE FROM  coachmain 
           where coachId =
                '` +
        coachId +
        `'`;
    connection.query(queryString, function (err, result) {
        if (err) {
            // handle error and notify user
            res.status(400).send(err);
        } else {
            // success message here. if you forget this, 
            // the request will wait till timeout
            res.status(201).send(req.body);
        }
    });
});

// this will create a post request with route "localhost:9800/deleteCoach"
/*
post body should be something like this :
    {
        "name": "full name",
        "coachId": 1,
        "season": 2
    }
*/
app.post("/newCoach", function (req, res) {
    // get data from forms and add to the table called user..
    var name = req.body.name;
    var coachId = parseInt(req.body.coachId);
    var season = parseInt(req.body.season);
    var queryString =
        `INSERT INTO coachmain 
            (
                name, coachId, season
            )
            VALUES
            (
                '` +
        name +
        `','` +
        coachId +
        `','` +
        season +
        `'
            )`;
    connection.query(queryString, function (err, result) {
        if (err) {
            // handle error and notify user
            res.status(400).send(err);
        } else {
            // success message here. if you forget this, 
            // the request will wait till timeout
            res.status(201).send(req.body);
        }
    });
});

// application will listen to this port
app.listen(port, (err) => {
    console.log("running on :" + port);
});

Tuesday, May 12, 2020

Create Software Inventories

# read all child keys (*) from all four locations and do not emit # errors if one of these keys does not exist Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKCU:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' -ErrorAction Ignore | # list only items with the DisplayName Where-Object DisplayName | # show these registry values per item Select-Object -Property DisplayName, DisplayVersion, UninstallString, InstallDate | # sort by DisplayName Sort-Object -Property DisplayName

taken from :

https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/create-software-inventories

Monday, January 27, 2020

Tuesday, September 24, 2019

various sql utility t-sql

-- content of store procedure 
sp_helptext 'dbo.proc_name'

-- which store procedure ran and when
 SELECT DB_NAME(database_id)
    ,OBJECT_NAME(object_id,database_id)
    ,cached_time
    ,last_execution_time
    ,execution_count
FROM sys.dm_exec_procedure_stats order by last_execution_time DESC

-- search for stored proc which contains text you are searching for
SELECT ROUTINE_NAME, ROUTINE_DEFINITION
    FROM INFORMATION_SCHEMA.ROUTINES 
    WHERE ROUTINE_DEFINITION  LIKE '%your search text%' 
    AND ROUTINE_TYPE='PROCEDURE'


-- find tables in database which matches our criteria
DECLARE @SelectCol1     nvarchar(60)
insert into @tblNames (name)
SELECT name FROM sys.databases
where name like '0r'
How to enable cdc : record keeping in database 
use master go select [name], database_id, is_cdc_enabled from sys.databases go  use [databasename] go exec sys.sp_cdc_enable_db go
 select * from [dbname].[dbo].[tblMain]

--  ALTER TABLE [dbname].[dbo].[tblMain] ADD [colName] bigint; --add column

Tuesday, July 7, 2015

KMP algorithm

IndexOf Implementation :-

public static int[] FailureFunction(string p)
        {
            int[] F = new int[p.Length];
            F[0] = 0;
            int i = 1, j = 0;
            while (i < F.Length)
            {
                if (p[i] == p[j])
                {
                    F[i] = j + 1;
                    i++;
                    j++;
                }
                else if (j > 0)
                {
                    j = F[j - 1];
                }
                else
                {
                    F[i] = 0;
                    j++;
                }
            }
            return F;
        }

        public static int KMP(string s, string p)
        {
            int[] F = FailureFunction(p);
            int i = 0, j = 0;
            while (i < s.Length)
            {
                if (s[i] == p[j])
                {
                    if (j == p.Length-1)
                    {
                        return i - j;//match
                    }
                    else
                    {
                        i++; j++;
                    }
                }
                else
                {
                    if (j > 0)
                    {
                        j = F[j - 1];
                    }
                    else
                    {
                        i++;
                    }
                }

            }
            return -1;
        }

Wednesday, March 25, 2015

test remote powershell console is working or not Test-PsRemoting from Lee Holmes

I dont own the post, I dont have any legal rights just a pointer and a replication from the original post. The original post belongs to Mr. Lee Holmes. If someone tells me to pull the post down, I will. I am just reposting this article.

URL :-
http://www.leeholmes.com/blog/2009/11/20/testing-for-powershell-remoting-test-psremoting/

Testing for PowerShell Remoting: Test-PsRemoting

When you’re writing a script that depends on PowerShell Remoting, it’s often helpful to know that the remoting channel is open and will support the activities of your script.
PowerShell has a Test-WSMan command, but that only verifies that a WSMan connection is possible. There are other scenarios you could be impacted by:
  • Not having permission on the remote machine
  • Misconfiguration of the PowerShell endpoint
  • Corrupted installation
  • (etc)
As you dig deeper, you realize that the only way to really test the viability of the remoting channel is to just do something on it, and verify that you got the results you expected to. Since the implementation was so simple, we didn’t write a cmdlet for it. In retrospect, the concept is more difficult than the implementation, so we probably should have written it anyways. Here’s an example function that tests the remoting connection to a specific machine.
function Test-PsRemoting 
{ 
    param( 
        [Parameter(Mandatory = $true)] 
        $computername 
    ) 
    
    try 
    { 
        $errorActionPreference = "Stop" 
        $result = Invoke-Command -ComputerName $computername { 1 } 
    } 
    catch 
    { 
        Write-Verbose $_ 
        return $false 
    } 
    
    ## I’ve never seen this happen, but if you want to be 
    ## thorough…. 
    if($result -ne 1) 
    { 
        Write-Verbose "Remoting to $computerName returned an unexpected result." 
        return $false 
    } 
    
    $true    
}

source: http://www.leeholmes.com/blog/2009/11/20/testing-for-powershell-remoting-test-psremoting/

Node.JS rest api Tutorials