Technology and More

MySQL Connection String for ASP.NET

Posted by: David Hill on

Here is an example MySQL connection string for ASP.NET:

<add name="data" connectionString="Server=localhost; Database=world;Uid=myUserId;Pwd='PaSsWoRd'" providerName="MySql.Data.MySqlClient" />

To use the connection string properly, a reference must be added to the project for the MySQL Data connector assembly. A search for "MySql.Data.dll" in the \Windows folder turned up several locations:

C:\Windows\Microsoft.NET\assembly\GACMSIL\MySql.Data\v4.08.0.20.0__c5687fc88969c44d\MySql.Data.dll

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\PrivateAssemblies\MySql.Data.dll

(note: this dev environment uses Microsoft Visual Studio 2019 Community Edition)

and if MySQL is installed in the development environment, a connector can be found here:

C:\Program Files (x86)\MySQL\Connector NET 8.0\Assemblies\v4.5.2\MySql.Data.dll

GREP

Posted by: David Hill on

Here is a brief example of how to use grep in a jQuery script to filter JSON data based on complex (or not) criteria.

This example gets JSON from a test api, prints out the list of names returned. Then, below the horizontal rule, filters the names for any which have "C" as the first letter. Then it prints those.

Here's the html:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="crossorigin="anonymous"></script>
    <title></title>
</head>
<body>
    <h1>Website</h1>
    <div id="results"></div>
    <hr />
    <div id="grep"></div>

    <script src="index.js"></script>
</body>
</html>

Here's the jQuery:

$(function () {
            var url = "https://jsonplaceholder.typicode.com/users";
            url += "?callback=?";
            $.getJSON(url, function(data) {
                var output = "";
                $.each(data, function (i, obj) {
                    output += "<p>" + obj.name + "</p>";
                });
                $("#results").append(output);

                var grepResult = $.grep(data, function (element, index) {
                  return element.name.substr(0,1) == "C" ;
                  });

                var grepOutput = "";
                $.each(grepResult, function( index, value ) {
                  grepOutput += "<p>" + value.name + "</p>";
                  });
                $("#grep").append(grepOutput);
            });
        });

Hope this helps.

Repl.it

Posted by: David Hill on

One of our coder/developer friends turned us on to repl.it (https://repl.it).

Repl.it is an online application that makes it easy to develop, learn, try, and share. (No, Geek Methods doen't have any connection to repl.it - unless you count having a free account - then, yes.)

It supports a huge number of languages and it's fun!

Repl.it gets its name from REPL, the Read–eval–print loop from the old LISP days of interactive computer programming. But if you think the repl.it is old-school or out-dated, think again. It's hugely helpful and a great way to try out logic and coding paradigms.

ASP.NET IsLoggedIn Method

Posted by: David Hill on

So far, this is the best way I've found for a web to check if the user is currently logged in.

bool isLoggedIn = (System.Web.HttpContext.Current.User != null) && (System.Web.HttpContext.Current.User.Identity.IsAuthenticated); 

It is also worth noting that the System.Web.HttpContext.Current.User object has many properties that can come in handy when working with authenticated members.

jQuery Global Functions

Posted by: David Hill on

Here's how we use jQuery functions in a separate file:

// globalFunctions.js
// this should be included FIRST
// place this in the script where you want to use these functions:
// <script src="/scripts/globalFunctions.js"></script>

$(function () {

    function getBozo() {
        return "bozo";
    }

    function getUrlParameterByName(name) {
        // url = current url
        var url = window.location.href;
        var value = getParameterByName(url, name);
        return value;
    }

    function getParameterByName(url, name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(url);

        if (results == null) {
            return "";
        }
        else {
            return decodeURIComponent(results[1].replace(/\+/g, " "));
        }
    }

    // all functions must be listed
    window.getValue = getBozo;
    window.getUrlParameterByName = getUrlParameterByName;
    window.getParameterByName = getParameterByName;
})

Getting Started with Node.js

Posted by: David Hill on

For those who want to jump into learning Node.js with a minimum of noise, here is one way to approach it:

Note: This is easy on a Linux machine. (I used Ubuntu v. 16.04 LTS.)

First Install NVM

Note: you may need to install curl if it is not already installed. If you do, in a terminal window, type

sudo apt-get install curl

Then

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.5/install.sh | bash

Restart terminal, then check version with this:

nvm --version

Install Node

nvm install 6.11.4

(When installing a Node.js instance, nvm will also install a compatible npm version.)

Other commands: (from: https://www.sitepoint.com/quick-tip-multiple-versions-node-nvm/)

To check which npm version:

npm -v

To check which node versions are available

nvm ls-remote

Install the latest Node.js version

nvm install node

Uninstall any instance

nvm uninstall 4.8.4

Switch to node ver 4.8.4

nvm use 4.8.4

Switch to latest Node.js version

nvm use node

Check which versions you have installed

nvm ls

Create a custom alias

nvm alias awesome-version 4.8.4

use the alias version

nvm use awesome-version

Delete an alias

nvm unalias awesome-version

Simple node

Start node

node

Send text to the console

console.log('Aggie & Dave');

Exit node

process.exit()

or

.exit

or

Ctrl+C [enter] 

Express

Open terminal

  mkdir myApp
  cd myApp
  npm init  (entry point: app.js)
  npm install express --save   (creates all necessary files)

Very simple app

Create a file called app.js

var express = require('express');
var app = express();
app.get("/", function(req, res) {
 res.send("<h1>Home Page</h1>");
});
var server = app.listen(3000, function(){
console.log("Listening on port 3000");
});

In the terminal window, enter the following command to run the Node app (which launches the server):

node app.js

Open a browser. Navigate to: http://localhost:3000

App with multiple routes

var express = require('express');
var app = express();
app.get('/', function(req, res) {
  res.send('<h1>Home</h1>');
});
app.get('/aggie', function(req, res) {
  res.send('<h1>Aggie the dog!</h1>');
});
app.get('/julie', function(req, res) {
  res.send('<h1>Julie is great.</h1>');
});
var server = app.listen(3000, function() {
  console.log('Listening on port 3000');
});

Open a browser. Navigate to: http://localhost:3000

A Few Helpers

Posted by: David Hill on

Here are just a few of the "helpers" I frequently include in web applications to make life easier.

StringListFromDelimitedString

public static List<string> StringListFromDelimitedString(string commaDelimitedString, string delimiter = ",")
{
            List<string> rtnVal = new List<string>();
            if (commaDelimitedString != null)
            {
                rtnVal = commaDelimitedString.Split(new[] { delimiter },
                StringSplitOptions.RemoveEmptyEntries).Select(b => b.Trim()).ToList();
            }
            return rtnVal;
}

IntListFromCommaDelimitedString

public static List<int> IntListFromCommaDelimitedString(string commaDelimitedString)
{
    List<int> rtnVal = new List<int>();
    if (!string.IsNullOrWhiteSpace(commaDelimitedString))
    {
        List<string> stringList = StringListFromCommaDelimitedString(commaDelimitedString);
        foreach (var value in stringList)
        {
            int intValue = 0;
            bool parse = int.TryParse(value, out intValue);
            if (parse)
            {
                rtnVal.Add(intValue);
            }
        }
    }
    return rtnVal;
}

CommaDelimitedStringFromStringList

public static string CommaDelimitedStringFromStringList(List<string> stringList, bool spaceAfterComma = false)
{
    string rtnVal = "";
    string delimiter = !spaceAfterComma ? "," : ", ";

    stringList.RemoveAll(o => String.IsNullOrWhiteSpace(o));
    rtnVal = string.Join(delimiter, stringList);
    return rtnVal;
}

StringFromQueryString

public static string stringFromQueryString(string queryString, string defaultValue = "")
{
    string rtrnVal = defaultValue;
    HttpRequest request = HttpContext.Current.Request;
    if (request.QueryString[queryString] != null)
    {
        string queryStringValue = request.QueryString[queryString];
        rtrnVal = queryStringValue;
    }
    return rtrnVal;
}

GetRootPath

public static string GetRootPath()
{
    return HttpContext.Current.Server.MapPath("~");
}

FileExists

public static bool FileExists(string fileName)
{
    // note: all paths should start with a character and end with a "/"

    bool rtnVal = false;
    string rootPath = HttpContext.Current.Server.MapPath("~");
    string fileSpec = string.Format("{0}{1}", rootPath, fileName);
    if (File.Exists(fileSpec))
    {
        rtnVal = true;
    }
    return rtnVal;
}

jQuery To Warn If Leaving a Page With Unsaved Form Data

Posted by: David Hill on

Here is a bit of jQuery script to warn the user if they want to leave the page but have changed data in a form without saving.

// this warns user when trying to leave page with unsaved data
var warnOnLeavingUnsavedData = true;
var dataChanged = false;

$('form').on('keyup change', 'input, select, textarea', function () {
    formChange();
});

function formChange()
{
    dataChanged = true;
    $('form').submit(function () { dataChanged = false; });
}

$(window).bind('beforeunload', function () {
    if (warnOnLeavingUnsavedData) {
        if (dataChanged) {
            return;
        }
    }
});

jQuery getJson JSONP Example

Posted by: David Hill on

Most browsers have a policy that does not allow JSON to be returned from a server in another domain. This "cross-domain" policy make it impossible to receive ordinary JSON from a different server than the one requesting it.

Enter JSONP. It gets its name from (JSON with Padding) because the JSON response object is returned from the server as if it were an argument to a callback function.

jQuery handles JSONP processing and is very easy to work with in this regard.

Here is a simple web page that includes JSONP processing using jQuery:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <script type="text/javascript" src="/scripts/jquery-3.2.1.min.js"></script>
    <title></title>
</head>
<body>
    <h1>Website</h1>
    <div id="results"></div>

    <script>
        $(function () {
            var url = "https://jsonplaceholder.typicode.com/users";
            url += "?callback=?";
            $.getJSON(url, function(data) {
                var output = "";
                $.each(data, function (i, obj) {
                    output += "<p>" + obj.name + "</p>";
                });
                $("#results").append(output);
            });
        });
    </script>

</body>
</html>

This uses a call to the website jsonplaceholder.typicode.com which exists for the sole purpose of testing json/ajax calls.

Take an ASP.NET Web Application Offline

Posted by: David Hill on

It's easy to take an ASP.NET web application offline without going through IIS.

Simply add a file called "app_offline.htm" to the root of the application. It will automatically disconnect from IIS and databases.

It will display the contents of the app_offline.htm file instead.

You're welcome.