Tuesday, November 17, 2020

Connecting Your Eclipse Project to Github

 

OK so I have a relatively complex Java and MySQL database project that was developed in Eclipse EE using Tomcat. I want to now make it available on GitHub. So how do I do that?

Here is a really great YouTube tutorial that shows exactly how to set up your project to get it ready to commit to GitHub, as well as how to add the proper configurations to your project so that pushing stuff to and pulling stuff from the GitHub repository goes smoothly:

https://www.youtube.com/watch?v=HuhJ22oHyfc

  1. So, start with a completed project in Eclipse.
  2. Make sure you have Git for Windows installed, and of course a GitHub account.
  3. First thing you do is creates a local repository on his own machine.
  4. Right click on project > Team > Share Project... and this opens the Configure Git Repository dialogue
  5.  On the Configure Git Repository dialogue, click the Create button... this opens the Create a New Git Repository dialogue
  6. Now, in the Create a New Git Repository dialogue there is a 'Repository directory' field
  7. The value of the 'Repository directory' field defaults to 'C:\<whatever your path is>\git\repository'
  8. Change that to 'C:\<whatever your path is>\git\Local<your project's name>'
  9. Click Finish on the New Git Repository dialogue and then click Finish again on the Configure Git Repository dialogue. (Eclipse will have now moved your repository into a different location)
  10. Now, you need to enable some Git stuff on your project.
  11.  Go to Window > Perspective > Customize Perspective ... this opens the Customize Perspective dialogue
  12. On the the Customize Perspective dialogue, click the Action Set Availability tab.
  13. On the Action Set Availability tab, select all the Git options, then click Apply and Close. 
  14. Now you will see at the top that you have a Git menu, as well as some new Git buttons in the tool bar.
  15. Next, select Window > Show View > Other ... this opens the Show View dialogue.
  16. In the Show View dialogue, expand Git. In the Git drop-down, control-click 'Git Repositories' and 'Git Staging.'
  17. While still in the Show View dialogue, expand Team and control-click 'History.'
  18.  Now, all three of those views are open in the bottom of the Eclipse IDE.
  19. Now, to commit the project for the first time to GitHub, right-click on your project > Team > Commit ... this updates the Git Staging view at the bottom of the IDE
  20. In the Git Staging view at the bottom of the IDE, click the double arrows (the ones that when you hover over them say 'Add all files including non-selected ones to the index')
  21. This moves all your project files from the Unstaged to the Staged box. 
  22. In the Commit Message box, type 'Initial commit.' Remember, this is all gonna be public so keep it PG.
  23. DO NOT click the Commit and Push Now button. Instead, start out by clicking the Commit button.
  24. Now, click on the GitHub Repositories view.
  25.  Right-click on the repo that appears in the GitHub Repositories view > Show In > History 
  26.  This is the point where you should go online to your GitHub account and create a new repository for this project. 
  27. Leave it Public and DO NOT select any of the Initialize Repository options. Instead, just click Create Repository.
  28. On the GitHub 'Quick Setup' page, copy the url to your repo (it will look something like 'https://GitHub.com/olddognewtrix123/ContactManager.git')
  29. Now you need to do a little more work on your project so that when you finally do the initial commit to GitHub, things will go smoothly.
  30. So, back on the GitHub Repositories view, expand your repo, right-click Remotes and select Create Remote - this opens the New Remote dialogue.  
  31. On the New Remote dialogue, leave everything at default and click OK - this opens the Configure push for remote dialogue.     
  32. On the Configure push for remote dialogue, click the Change button - this opens the Source Git Repository dialogue.
  33. The Source Git Repository dialogue should already have your GitHub URI selected.
  34. The URI field should have something that looks like 'https://GitHub.com/olddognewtrix123/ContactManager.git'
  35. The Host field should have something that looks like 'GitHub.com'
  36. The Repository path field should have something that looks like '/olddognewtrix123/ContactManager.git'
  37.  On Source Git Repository dialogue, type in your GitHub username and password, then click Finish.
  38.  Back on the Configure push for remote dialogue, click the Advanced button ... this opens the Push Ref Specifications dialogue. 
  39.  On the Push Ref Specifications dialogue, drop down Source ref and select 'master[breanch],' then click Add Spec.
  40.  On the Push Ref Specifications dialogue, select the 'Save specifications and origin configuration' box, then click Finish.
  41.  Back on the New Remote dialogue, click Save. 
  42. Now, click the 'Push current branch to upstream' button on the toolbar in the IDE (it is the one with the up-arrow)
  43. The machine thinks for a bit, then opens the Pushed to LocalContactManager - origin doalogue.
  44.  On the Pushed to LocalContactManager - origin doalogue, just click Close.
  45. Go back to the repository on your GitHub account. Hit F5 and you will see a folder for the initial commit of your project. 
  46. Now, that's all set up to push stuff to GitHub. But what if you want to pull stuff (like if you decide down the road to have collaborators making changes to the GitHub repository)?
  47. Back on the GitHub Repositories view, expand origin then right click on the fetch configuration (the one with the down-arrow next to it) and click Fetch Configuration ... this opens the Configure fetch for remote origin dialogue. 
  48. On the Configure fetch for remote origin dialogue, click Advanced, select 'master [branch],' Add Spec, Finish and then Save.


  


       

Saturday, October 10, 2020

How to Get a Java servlet running how to get Tomcat working get a backend java servlet working that you can deploy on AWS

How to Get a Java servlet running how to get Tomcat working get a backend java servlet working that you can deploy on AWS

 


Before you can post a java web app to AWS via Elastic Beanstalk, you gotta be able to get a working java app running on your own machine.


 Spend ONE HOUR going through steps below and after that you should have a pretty good map in your head of what's what with Java servlets. 


BRIEF RAMBLE


 Whenever I need to learn something very complex, at first I create a handful of what I call "vignettes." If you are a painter, before you create a huge complex painting, you will first prepare yourself by creating a whole bunch of smaller paintings. These smaller paintings are done with no real fear of failure. They are usually left incomplete with only part of the canvas covered in paint. They are done just to get a working mastery of the different components that will support the overall finished project. These smaller paintings are called vignettes. I apply the same principle for coding projects, especially when I am learning some new technology or framework for the first time. 


 My overall goal is to start writing Java web applications and hosting them on AWS. What follows is one of the vignettes I started out with to begin learning this.


ADDITIONAL RESOURCES


But first, here are the blogs and YouTube vids that really helped me begin to understand how to do this:


https://www.c-sharpcorner.com/UploadFile/fd0172/how-to-configure-and-install-apache-tomcat-server-in-windows/


https://www.youtube.com/watch?v=qImCqaxuhgQ 


http://www.ides01.com/2020/05/26/javaweb-error-the-superclassjavax-servlet-http-httpservlet-was-not-found-on-the-java-build-path/ 


 


 SPEND ONE HOUR GOING THROUGH THESE STEPS:

The surest problem you will encounter in this whole process is that Eclipse just never gets hooked up properly to Tomcat. This means you have to spend some time carefully getting everything downloaded and installed correctly....

1. Clear out delete and uninstall all previous versions of jdk, jre, tomcat, eclipse, whatever. CLEAR OUT EVERYTHING FROM ALL PREVIOUS ATTEMPTS – you don’t want any confusing junk left behind while you are doing the stuff below

2. Delete all variables and paths to JDK or JRE in your Environmental Variables - again the object here is to avoid confusion in the near future

3. Go to the Oracle Install page:  https://www.oracle.com/java/technologies/javase-jdk11-downloads.html

    a. Download BOTH the Windows X64 installer and the Windows X64 Compressed Archive

    b. Go to the folder where the installer is (most likely the Downloads folder) and run the exe

    c. Go to C:\Program Files\Java\jdk-11.0.8 and make sure there are folders and files in there (bin, conf, etc.)

    d. Go to Environmental Variables

    e. Create a variable called JAVA_HOME and point it at C:\Program Files\Java\jdk-11.0.8

    f. Add an element to path C:\Program Files\Java\jdk-11.0.8\bin

    g. OK and save everything in Environmental Variables

    h. Go to the command prompt and verify you have done everything correctly:

        "Microsoft Windows [Version 10.0.18363.1082]

        (c) 2019 Microsoft Corporation. All rights reserved.

        C:\Users\-redacted->set JAVA_HOME

        JAVA_HOME=C:\Program Files\Java\jdk-11.0.8

        C:\Users\-redacted->java -version

        java version "11.0.8" 2020-07-14 LTS

        Java(TM) SE Runtime Environment 18.9 (build 11.0.8+10-LTS)

        Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.8+10-LTS, mixed mode)"

4. Download Tomcat 8 from https://tomcat.apache.org/download-80.cgi

    a. Click the 64-bit Windows zip (pgp, sha512)

    b. Extract the files directly to C drive (for example, the path to \bin should just end up being C:\apache-tomcat-8.5.58\bin

    c. Open the configuration file "web.xml" in the Tomcat "conf" folder (edit with plain old Notepad so as not to introduce any formatting).

    d. Enable the directory listing by changing "listings" from "false" to "true" for the "default" servlet.

    e. Open the Tomcat "server.xml" file and make sure the default port is set to 8080

    '<Connector port="8080" protocol="HTTP/1.1"'

5. Test the Tomcat server installation by going into the bin folder and clicking the startup.bat file then point your browser at "http://localhost:8080" - the default Apache Tomcat page should appear

6. Turn the server off by going into the bin folder and clicking the shutdown.bat file (At this point if you hit F5 on the tomcat page on your browser, the browser will return "unable to connect")

7. Download Eclipse Java EE IDE - make sure it is the "Eclipse IDE for Enterprise Java Developers"

    a. Download the zip file and extract it directly to the C drive (for example, the path to the configuration folder should be "C:\eclipse\configuration")

Now, you gotta make sure everything is working.  The best way to do that is by creating and running a simple servlet...

1. Run Eclipse by going into the, right-clicking on Eclipse.exe, and clicking "Run as Administrator"

2. Go ahead and click Launch for whatever Workspace that Eclipse suggests

3. Close the Welcome tab that appears by default on Eclipse and make sure you can see the "Project Explorer" on the left

4. Now its time to connect Eclipse and Tomcat. In Eclipse, click on Window -> Preferences; in Preferences, expand the Server list

5. Click on Runtime Environments then click the Add button - a list of Apache Tomcat servers

should be available

6. Select the server you want (this should be Tomcat 8.5 if you are following this guide)

7. Click the Next button

8. On the next page, click Browse and select the tomcat folder on your C drive

9. Click Finish then Apply and Close

    So at this point Tomcat is hooked up with Eclipse. For example, Eclipse will start and stop Tomcat         for you when in the future you want to run one of your applications.

10. Now, click File -> New -> Dynamic Web Project

11. In Project Name just type "Test00" - leave everything else on that page at its default and clcikc Next

12. Don't change anything on the next page where it says "Source folders on build path" - just click Next

13. On the next page, check the box that says "Generate web.xml deployment descriptor" then click Finish

14. After several moments, the dialogue will close and you will see "Test00" over on the left in the Project Explorer

15. Now let's go ahead and create a servlet. Expand the Java Resources folder and you will see the src folder

16. Right-click on the src folder, then click New -> Servlet

17. In the Create Servlet dialogue, enter "testservlet" into the Class name field

18. Delete the text in the Superclass field - we don't need it for now

19. Click next - in the URL mapping field where it says "/testservlet" change it to say "/welcome" then click Next

20. Don't click anything on the next page - just click Finish

21. OK now Eclipse has open the "testservlet.java" file you just created

20. Here's where it gets a little tricky: Highlight everything below "public class testservlet implements Servlet {" and replace it just with  a "}"

21. Click on the red 'X' that appears to the left of "public class testservlet implements Servlet" and double-click on the "Add unimplemented methods" option

22. Your code should now look like this (NOTE update the two methods Init and Service by adding some writeline commands!):


   import java.io.IOException;

  import javax.servlet.Servlet;

  import javax.servlet.ServletConfig;

  import javax.servlet.ServletException;

  import javax.servlet.ServletRequest;

  import javax.servlet.ServletResponse;

  import javax.servlet.annotation.WebServlet;

  /**

   * Servlet implementation class testservlet

   */

  @WebServlet("/welcome")

  public class testservlet implements Servlet {

                @Override

                public void destroy() {

                                // TODO Auto-generated method stub

                 }

                @Override

                public ServletConfig getServletConfig() {

                                // TODO Auto-generated method stub

                                return null;

                }

                @Override

                public String getServletInfo() {

                                // TODO Auto-generated method stub

                                return null;

                }

                @Override

                public void init(ServletConfig arg0) throws ServletException {

                                // TODO Auto-generated method stub

                                System.out.println("This is printed from Init");

                }

                @Override

                public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {

                                // TODO Auto-generated method stub

                                System.out.println("This is printed from Service");

                }

  }



23. You now have to update web.xml with the servlet for this to work. In the Project Explorer under Web Content -> WEB Inf -> lib  click on the web.xml file

24. When the web.xml file opens, down at the bottom click the Source tab

25. It starts out looking like this:


  <?xml version="1.0" encoding="UTF-8"?>

  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

    <display-name>Test00</display-name>

    <welcome-file-list>

      <welcome-file>index.html</welcome-file>

      <welcome-file>index.htm</welcome-file>

      <welcome-file>index.jsp</welcome-file>

      <welcome-file>default.html</welcome-file>

      <welcome-file>default.htm</welcome-file>

      <welcome-file>default.jsp</welcome-file>

    </welcome-file-list>

  </web-app>


 26. Change it to look like this:

  <?xml version="1.0" encoding="UTF-8"?>

  <element>

  <servlet>

  <servlet-name>whatever</servlet-name>

  <servlet-class>testservlet</servlet-class>

  </servlet>

  <servlet-mapping>

  <servlet-name>whatever</servlet-name>

  <url-patter>/welcome</url-patter>

  </servlet-mapping>

  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

    <display-name>Test00</display-name>

    <welcome-file-list>

      <welcome-file>index.html</welcome-file>

      <welcome-file>index.htm</welcome-file>

      <welcome-file>index.jsp</welcome-file>

      <welcome-file>default.html</welcome-file>

      <welcome-file>default.htm</welcome-file>

      <welcome-file>default.jsp</welcome-file>

    </welcome-file-list>

  </web-app>

  </element>

27. OK that's it. Right-click on Test00 in the Project Explorer and click Run As -> 1 Run on Server

28. On the Run on Server dialogue, just click Next

29. On the Add and Remove dialogue, just click Finish

30. This will fire up Tomcat and a browser session will start up right inside of Eclipse.

31. It will not look like much but if you change the url from "http://localhost:8080/Test00/" to "http://localhost:8080/Test00/welcome" then hit the refresh button, you will see output in the Console tab (by that I mean the Console tab down at the bottom of Eclipse over to the right of Snippets)

32. In Console you now should see "This is printed from Init    This is printed from Service"

33. If you keep hitting the refresh button, you will see new lines of "This is printed from Service" appear


That's it!  You got a java servlet working!  Now, lets get a little more complicated....


  1.  Hit the red button in Eclipse to stop Tomcat running. 
  2. Click File -> New -> Dynamic Web Project
  3. In Project Name just type "Test01" - leave everything else on that page at its default and click Next
  4. Don't change anything on the next page where it says "Source folders on build path" - just click Next
  5. On the next page, check the box that says "Generate web.xml deployment descriptor" then click Finish
  6. After several moments, the dialogue will close and you will see "Test01" over on the left in the Project Explorer
  7. Right-click on src folder (in the Java Resources folder) and click New -> servlet
  8. In Class name type "samplepage"; change NOTHING else and click Next, Next, Finish
  9. Your samplepage.java file should look like this:

  import java.io.IOException;

  import javax.servlet.ServletException;

  import javax.servlet.annotation.WebServlet;

  import javax.servlet.http.HttpServlet;

  import javax.servlet.http.HttpServletRequest;

  import javax.servlet.http.HttpServletResponse;

  /**

   * Servlet implementation class samplepage

   */

  @WebServlet("/samplepage")

public class samplepage extends HttpServlet {

                private static final long serialVersionUID = 1L;

    /**

     * @see HttpServlet#HttpServlet()

     */

    public samplepage() {

        super();

        // TODO Auto-generated constructor stub

    }

                /**

                 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

                 */

                protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                                // TODO Auto-generated method stub

                                response.getWriter().append("Served at: ").append(request.getContextPath());

                }

                /**

                 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

                 */

                protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                                // TODO Auto-generated method stub

                                doGet(request, response);

                }

  }

10. Do Run As and make sure the server fires up as expected

11. Now, go back to the servlet and add "import java.io.PrintWriter;"

12. Update the doGet method as follows:

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                                PrintWriter out = response.getWriter();

        out.println("Hello World!");

        response.setContentType("text/html");

        PrintWriter out1 = response.getWriter();

        // send HTML page to client

        out1.println("<html>");

        out1.println("<head><title>A Test Servlet</title></head>");

        out1.println("<body>");

        out1.println("<h1>Test</h1>");

        out1.println("<p>This page is not from an HTML file. Rather, it is from a servlet!</p>");

        out1.println("<form><textarea id=\"w3review\" name=\"w3review\" rows=\"4\" cols=\"50\">\r\n"

        + "This form is not from an HTML file. Servlets can injsct HTML for working forms too!\r\n"

        + "</textarea></form>");

        out1.println("</body></html>");

                }

13. Save, then go back to the Eclipse browser tab and extend the url to this: http://localhost:8080/Test01/samplepage

14. Give it a second to update then hit the refresh button on the Eclipse browser. You should now see this:

  Hello World! 


  Test

 

  This page is not from an HTML file. Rather, it is from a servlet!


  This form is not from an HTML file. Servlets can injsct HTML for working forms too!


 15. Go ahead and stop the server at this point. You are ready to create your WAR file. The WAR file is the "bridge", if you will, between you creating a working java servlet app on your own computer and getting your work to appear on a web page generated by AWS.

16. Right-click on Test01 and click Export. Create the WAR file with the WAR Export wizard and just save it to a folder somewhere.

Log on to your AWS console, go to Elastic Beanstalk, click the Create Application button, follow the wizard, and import the WAR file from your machine when prompted. Once the AWS service is running and the web page it generates is running in your browser, extend the browser with "/samplepage" to see the HTML that the servlet is producing. 

Friday, April 17, 2020

Your First (rudimentary) PWA in Seven Steps


Introduction, audience, and scope

This is a very, very basic tutorial. I will refrain from even calling it ‘bare-bones’ because that skeleton would be missing the metacarpals and a femur, so to speak.

The goal, or use case, is simply to get the app to pass the PWA audit in Chrome and make the app downloadable to a user’s machine, should the user decide they are better off using an offline version of the application.

To begin with, you should already have written and fully debugged a dirt-simple, front-end only HTML/JavaScript app that does not require any external resources (it does not connect to an API for data, for example).

To see the example I used, go to here .

Besides some basic HTML and JavaScript, some introductory knowledge of service workers is a prerequisite for this tutorial. PWA is where you will really start of suffer from and then master service workers. If you are absolutely new to service workers, stop here and go do one or two tutorials that are focused just on service workers. Then come back.

Please note that I am using a Windows 10 machine and the Chrome browser for all of this. If you are following the steps of this tutorial and getting different results, first check to see if the issue may be that you are using a different setup.

Make your app visible to Chrome

I am using Chrome’s Audit feature to get started on the PWA version of the app (Audit comes with Chrome - just open Chrome and hit F12 to see the dev tools; Audits is one of the tabs across the top). In order for Audit to see your app, and then later for service workers to function properly, your app has to be in a HTTP/HTTPS document. You cannot just be running your app on local host. There’s probably half a dozen better ways to go about meeting this requirements, but what I did to accomplish this was just to host my app on GitHUB pages.

(For more of a nuts and bolts guide to actually setting up a GitHub Pages website manually without all the bells and whistles, go to my earlier post).

NOTE: If you opt for GitHub pages, always use full reference paths as opposed to partial paths. Absolutely make sure to name the main file “index.html” or GitHub Pages won’t work in your browser.

Audit your app and clean up failures

Once you have reached the point where you can view your app the in Chrome web browser as a HTTP/HTTPS doc, you are ready to run an audit in Chrome and figure out where to go from here.
Click F12 and that will open the Chrome dev tools. Up at the top where it says “Elements,” “Console,” “Sources,” etc,. click on the “Audit” tab. On the “Audit” tab, click the “Generate report” button.

There will probably be lotsa red telling you how miserably your site fails to meet basic industry standards.

At this point you could easily ignore the components of the Audit that do not have to do directly with PWA and just move on. But loose ends drive me batty so I cleaned them up. Just google each statement and patch up your HTML accordingly.

Add a manifest.json file

PWA requires a ‘manifest.json’ file in the root directory. You have to title the manifest ‘manifest.json’ and save it as a .json file.

The manifest you are starting out with in this tutorial is very minimal. Other more advanced tutorials will show you how to do more with the manifest and more with logos. For now we are just keeping things dirt-simple.

Your manifest should look like this (fill in what you want for ‘name,’ ‘short_name,’ and the colors):

  {
  "name": "<the name of your app>",
  "short_name": "<the name of your app>",",
  "icons": [
    {
      "src": “images/192_icon.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "images/512_icon.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": "https://<username>.github.io/index.html",
  "display": "standalone",
  "background_color": "<the color you want>",
  "theme_color": "<the color you want>"
}

In a typical PWA, there are actually more than just the two icon/icon sizes used. But these two – 192 px and 512 px - are the bare minimum to get a PWA up and running, and this is a bare-minimum tutorial. In fact, I just went out and googled “free test icons,” one for 192 pix and one for 512 px. I copied and pasted them to good ol’ Paint, saved them as jpegs, then uploaded them to a ‘images’ folder in the root directory of the GitHub page. 

Create an offline version of the app

Just create a copy of the index.html file in the root directory. Title this new file ‘offlineApp.html.’
In a full PWA application, something that is beyond the scope of this tutorial, the offline version of the app is part of what allows PWA to turn your app into something that can seamlessly transition between an online and an off-line experience. It's a big deal. But given the very limited scope of this tutorial, just create and rename the copy of index.html for now. Consider it a stub where the future offline version of the app will go when you know more about PWA.

Create the Service Worker

Now, create the service-worker.js file in the root directory. Here is my code for my service-worker.js file:

  const myCache = 'static-cache';
  const pageToCache = [ '/offlineApp.html' ];

  self.addEventListener('install', function(event) {
    event.waitUntil(
      caches.open(myCache)
      .then(function(cache) {
        return cache.addAll(pageToCache);
      })
    );
  });

  self.addEventListener('fetch', function(event) {
    event.respondWith(
      caches.match(event.request)
      .then(function(response) {
        return response || fetchAndCache(event.request);
      })
    );
  });

  function fetchAndCache(url) {
    return fetch(url)
    .then(function(response) {
      // check for valid response
      if (!response.ok) {
        throw Error(response.statusText);
      }
     return caches.open(myCache)
      .then(function(cache) {
        cache.put(url, response.clone());
        return response;
      });
    })
    .catch(function(error) {
      console.log('Request failed:', error);
      // offline 404 page really needs  go here but I have not bothered yet
    });
  }

Reference service-worker.js and manifest.json in index.html

Our goal, again, is a very limited one. We just want to use PWA to let the user download the app from the page where the app is hosted.

Add the following to the header section of your HTML:

  <link rel=”manifest” href=”https://< username>.github.io/manifest.json” />

NOTE: Always use ‘https’ in your links and not ‘http,’ otherwise you will create what is known as a cross-origin error. This is because GitHub resources always use the secure ‘https’ protocol.

Go to your index.html page and add a <script></script> section. Add the following code:

  if ('serviceWorker' in navigator) {
   window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js')
     .then((reg) => {
      console.log('Service worker registered.', reg);
     });
    });
  }

Test

That’s pretty much it. If you run your app in your Chrome browser, check out the three vertical dots icon. There should now be an option to install a stand-alone version of your app. Congrats – you’ve got your first PWA up and running!

Troubleshooting

App not working on other browsers?

Not all browsers support the web app manifest the same way Chrome does. But you want your app to work on all browsers if possible. Try updating your meta-tags in index.html to help out other browsers. Add the following to the header section of your index.html file:
  <meta name = “apple-mobile-web-app-title” content=”myApp” >
  <meta name = “apple-mobile-web-app-status-bar-style” content=”blue” >
  <meta name = “apple-mobile-web-app-title” content=”myApp” >

 


Follow these steps to create a GitHub Pages website without having to download anything

Step one is that you need craft and debug an HTML file locally on your own machine. Nothing fancy here – just open a text editor like NotePad and get rolling. An example of just such an app is here. You can use that if you want, but I would suggest you do this with your own code so you have the satisfaction of seeing your own creation as a web page anyone can access.

 Step two is that you store the file in a folder on your machine and rename it “index.html.” If it is any other name, it will not work on GitHub Pages.

Step three is make sure you have an account on GitHub. As of writing, this is totally free and requires no special software on your machine to get an account and manipulate GitHub right in your browser (stuff like Git that you have to download onto your machine can be learned later and are not necessary for this tutorial).

 Step four is create a repository on your GitHub account. Your webpage is basically just going to be a repository on your GitHub account. Just navigate to your GitHub account and click to create a new repository (aka “repo”). Just make sure the repo name is your GitHub user name plus “github.io” when you name it. My user name is olddognewtrix123, so when I made a repo that is supposed to actually be a webpage, I went on to my GitHub account, and clicked to create a new repo. When I was prompted to name the repo, I called it “olddognewtrix123.github.io.” If you do not name your repo correctly, all you will have created is just another GitHub repository. Which is great, but you won’t be able to hit it from your browser like a web page. So follow the exact naming convention. Leave the “Public” radio button selected. You can leave the “Initialize with ReadMe” checkbox unselected – it is not necessary. Now click the green Create Repo button.

 Step five is to click the Upload File button on the repository’s page. Select your index.html file from the folder on your machine and complete the upload. Fill out the comment fields and click the green Commit Changes button. You can repeat step three for any other files that your index.html file needs to run, like if you have a separate style sheet.

 Step six is super important and not a lot of tutorials mention it: you gotta make sure index.html has a ref tag, it is using the absolute path and not the relative path. So, click on the index.html file on the GitHub repository page. Once it is open you will see your HTML. Click the icon in the top right that looks like a pen to begin editing. Change any relative paths in your HTML to the absolute paths for the GitHub repository. So, if your HTML has
       <a href="/otherpage.html"/>
 you need to change it to 
    <a href="https://olddognewtrix123.github.io/otherpage.html"/>

Then of course commit your changes.

Step seven is simple – you wait. Sometimes it can take up to thirty minutes for your changes to show up on GitHub pages. After thirty minutes, plug the name of your repo (<yourusername>.github.io) into your browser. hit Enter, and bask in the glory of your new web page.

Sunday, April 15, 2018

Net Ninja's React JS tutorial in c9.io - skipping webpack by using create-react-app

OK, many are the quirks in c9.io and many many are the quirks in configuring webpacket.

At this point I just want to improve how react itself works and not get bogged down in figgerin out webpacket (I will do that later, however).

So what I did was go through the first page or two of this tutorial: http://www.react.express/environment and am just figuring out how to do the Net Ninja tutorial on top of the template you get when you use create-react-app

The flavors of react are a little different bu I believe that will save me a lot of time.

First I got the create-react-app up and running just fine in the browser.

So going forward I am just tacking the Net Ninja components onto the existing app.

So for example the react app gives you

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
   import registerServiceWorker from './registerServiceWorker';

     ReactDOM.render(<App />, document.getElementById('root'));
     registerServiceWorker();

and 


    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './App.css';

    class App extends Component {
     render() {
         <header className="App-header">
              <img src={logo} className="App-logo" alt="logo" />
              <h1 className="App-title">Welcome to React</h1>
             </header>
            <p className="App-intro">
              To get started, KLJHKJLHKJ dit <code>src/App.js</code> and save to reload.
             </p>
        );
      }   
    }

    export default App;

So, for the very first component Net Ninja has us build, I just changed App to 

    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './App.css';

    class App extends Component {
     render() {
         return (
          <div className="App">
           <h1>hellooooooooo</h1>
          </div>
        );
      }   

    }

    export default App;


Now, if I wanted to in turn add a child component to App I can just do this:



    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './App.css';
    import Howdy from './Howdy';

    class App extends Component {
     render() {
         return (
          <div className="App">
           <h1>hellooooooooo</h1>
           <Howdy />
          </div>
        );
      }   

    }

    export default App;


and here is the 'Howdy' component:

    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './App.css';

    class Howdy extends Component {
     render() {
         return (
          <div className="App">
           <h1>howdy howdy howdy howdy howdy!</h1>
          </div>
        );
      }   
    }

    export default Howdy;

NOTICE THE FOLLOWING:

The App component can use the Howdy component because the App component contains

     import Howdy from './Howdy';

And the Index component can use the App component because the Index component contains

    import App from './App';

Monday, April 2, 2018

Learning to Code Over 40

I did not get super-serious about learning to code until I myself was in the 40+ set.

Allow me to share with you some hard-won wisdom:

1. DO NOT BE A HELP VAMPIRE

Don't know what a "help vampire" is? Google it. For at least the first year that you are learning this stuff, there are absolutely no questions or conundrums you will encounter that have not already been solved and documented in at least eight places. Unless you are trying to learn some brand spankin' new language or framework that just came out last year, the answers are already there somewhere for you to google. Do NOT add to the pile of stupid, poorly researched questions that have already been answered. You will only serve to discourage those who are willing to provide their time and talent to places like stackoverflow. Ultimately, you are shooting yourself in the foot. Train yourself to dig in and research the crap out of every corner of the internet when you encounter a sticky problem - apparently that is what real developers do. Welcome to the new normal.

2. DO NOT CODE ALONE

OK, obviously you are going to have to code all by yourself to get through the first few dozen tutorials in order to get a baseline understanding (unless you are starting down this road with a coding buddy, which I wish to heck I had!). What I mean, however, is that there is going to be a point where your mind has been expanded by this stuff, and you are champing at the bit to do more than just tutorials. It is a really, really bad idea to continue on all alone at this point. What you are going to end up doing is spend months reinventing the wheel to create nothing but irrelevant, low quality crap. If I sound bitter it is because I myself have wasted several months getting all wrapped up in projects I dreamed up and planned on my own, while all that time and energy could have gone to working with other people and learning the proper things like what good design actually is, what quality code actually is, and how things like Github work. Don't waste your time. Hook up with an opensource project when you are ready to actually start building new stuff.

3. IF IT DIDN'T HAPPEN ON GITHUB, IT DIDN'T HAPPEN

Most likely, the first five questions of any tech interview that you might go to sometime down the road are going to be questions about Github. Github is where your work will be expected to be stored. Github is how the quality of your code will be assessed. If you don't know Github, you don't know squat. If your code is not on Github, nobody is going to bother looking. Again, learn to code as part of a group of remote devs; this will force you to become very github-capable.

Thursday, March 15, 2018

Visual Studio 2012 Coded UI Test for Crystal Reports are too slow - how to speed them up

OK I have been getting really discouraged writing coded UI tests to test the output of Crystal Reports.

Seriously it was taking over seven minutes for one test to run. Ridiculous.

So I took a step back and asked what is the original problem. What do I the human tester actually need and do when manually testing one of these reports?

I decided to set formatting aside. Important, but for my particular needs I could indeed relegate that to other tests or even to manual testing.  The most important thing for me was to test the content of the Crystal report output to make sure what was coming from the database was correct. The other important thing was to run the multiple data exports, which manually involved clicking buttons, waiting, clicking more buttons, dozens of times over.

So the answer so far is to divide, focus, and conquer.

I put the button pushing into entirely separate tests. Now I can just run those UI tests and the machine does all the button pushing for me while I do something that really requires the attention of an actual person.

Back to the content: I just want to make sure the content is correct.

Remember how in your mapWhatever.cs code you've got lines of code that look like

     var something = rpt.UIWEbblahbalh.UIBobjidyaddayadda.somethingsomethingFrame...InnerText

?

That's called threading. Threading is what is going to kill your efficiency with this tool and with theses tests. Threading takes a looong time for some reason. YOU ONLY WANT TO THREAD ONCE IF YOU CAN HELP IT. My problem was I was threading multiple times, slowing my test way down.

So I just figured out how to thread once and get all the content of the report into a single long string (this will vary depending on how your page was built). Then, for the assertion I did StringAssert.Contains(<bigString>, <smallString>)

<bigString> is the big long string of content.

<smallString> is the value I need to make sure appears in the content.

Test takes less than two minutes now. Still slow, but in the acceptable range, because I have to do this same test dozens of time every time we update and have to do general regression testing. Better to have the machine do it.