Inject git branch name into HTML page - html

I work on an ASP.NET MVC web project, and we're developing several features concurrently. Each feature is on its own branch, and to test the site we publish it to a staging area.
However, after it's published I often forget from which branch we published.
Is there any way to inject the git branch name into the HTML somewhere, so the page will display <span>feature/coolNewFeature1</span> or <span>develop</span> as a reminder for which codebase is currently on the staging area?

Go to Project Properties and add a "pre-build event command line" script like:
git.exe rev-parse --abbrev-ref HEAD > "$(ProjectDir)\Resources\BuildInfo.txt"
Build the project, mark the "BuildInfo.txt" file as an Embedded Resource
In your footer cshtml, add code like:
#{
var buildInfo = Cache["buildInfo"];
if (buildInfo == null)
{
using (var r = new StreamReader(typeof(HomeController).Assembly
.GetManifestResourceStream("My.Module.Web.Resources.BuildInfo.txt")))
{
buildInfo = Cache["buildInfo"] = r.ReadToEnd();
}
}
}
#buildInfo

I am not super comfortable with ASP .NET but I can think of the following sequence of steps (I assume that you will select a git branch, compile and then deploy - and there is a script that possibly is automating this):
Create a small Javascript file (e.g. version.js) that declares
var version_branch = "<your-branch>";
Run a shell script (or it's equivalent on your platform)
$ t=$(git branch | grep "*" | cut -d' ' -f2) && echo "var version = '"$t"';" > /path/to/js/file
Include this in the Javascript files you are serving - like you might be doing for other Javascript. Remember to include a <script> tag for this file on your main template page.
When the page loads you can use jquery to inject this text in the footer as the accepted answer on this question suggests - Using CSS to insert text.
Hope this helps!

Related

Populate word document from html form

I am new to web development and need your help to figure out how to use the form in HTML and use the data to populate the said field in a word document. Any advice on how to approach this problem is highly appreciated. It would really help if you could post a live example for the below. Please,do let me know if any further explanation is required.
As a new developer, I want to advise you that you are getting into some challenging territory here and many of the solutions might require some heavy experience with programming and MS Word. In this forum, there are many options you can try, but from what I gather you will need to learn about macros.
The second option you could try are some services that will do this for you for a fee. Here are two options. Check out Formstack or Jotform
If you use this type of service, you would create a form action within your html code that will merge the data from the form into the Microsoft Word Document using merge tags.
The third option you can try is using Javascript within the form to populate the Word Document. The code would look more like this:
function Export2Word(element, filename = ''){
var preHtml = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
var postHtml = "</body></html>";
var html = preHtml+document.getElementById(element).innerHTML+postHtml;
var blob = new Blob(['\ufeff', html], {
type: 'application/msword'
});
// Specify link url
var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);
// Specify file name
filename = filename?filename+'.doc':'document.doc';
// Create download link element
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob ){
navigator.msSaveOrOpenBlob(blob, filename);
}else{
// Create a link to the file
downloadLink.href = url;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
document.body.removeChild(downloadLink);
}
Export HTML Table Data to Excel using JavaScript
HTML Content:
Wrap the HTML content in a container you want to export to MS Word document (.doc).
<div id="exportContent">
<!-- Your content here -->
</div>
Last option would be using PHP, and I recommend watching this video by CodexWorld and reviewing the post that goes along with it here. This is a challenging concept, so I would encourage you to take your time.
Hopefully this will help and best of luck.
Well, I don't know how to exactly do that, I am also a beginner like you. What seems to help you might be connecting your form with Google Sheets. The Google Spread Sheet will store all data submitted via your form. You can then use this data wherever you want.
There is an open source project for this task, you can do that by following the steps stated here: https://github.com/dwyl/learn-to-send-email-via-google-script-html-no-server
You can see it in action here: https://nisootech.vercel.app/#contact-me
There are two parts in your application
Enabling user to input the values in frontend. Which you can build using any frontend technology stack eg: HTML and Plain Javascript(Required for calling the Services), React JS, Angular etc.
Backend Service which will basically does the heavy work
Receiving the input from user.
Creating Word file using any libraries such as
Generate word files using Apache POI ,
Using Node.js to generate dynamic word document using Database value
Downloading the file after its completely generated using the values supplied by user.
download a file from Spring boot rest service
how to download file in react js
For the Backend service you can use technologies like Java and Springboot, Python, Node Js etc.
Building Restful webservices using spring
Use Technology in which you are more comfortable and start building. These Links and documentation you can use to start from basic.
Suggest you to breakdown your problems focus on each specific areas and do the development as per your smaller problems and integrate them later.

What's the lightest way to add the smallest amount of dynamics to a static HTML site?

I have a personal website that's all static html.
It works perfectly for my needs, except for one tiny thing.
I want to dynamically change a single word on a single page: the name of the current map for a game server I'm running.
I can easily run a cron job to dump the name of the map into a file in the site's html directory, call it mapname.txt. This file contains a single line of text, the name of the map.
How would I update, say, game.html to include this map name?
I would very strongly prefer to not pull in some massive framework, or something like php or javascript to accomplish this.
I want the lightest weight solution possible. Using sed is an option, although definitely a hacky one. What's the tiniest step up from static html?
If you say "dynamically", do you mean:
If the information changes ...
A) the user should see it after they have re-loaded the page?
B) the page should update without the need to reload?
For A, you can use PHP (or any other language your server supports) to read the data from the file and print it into the web page. This will happen on server side.
For B, you can use JS that queries the file and updates the HTML. This will happen on client side.
To change text there are a few way though only two appropriate methods.
First is using textContent:
document.getElementById('example').textContent = 'some example text';
Secondly is the older nodeValue however it's a bit more tricky since you have to specify the exact textNode (e.g. .firstChild):
document.getElementById('example').firstChild.nodevalue = 'some example text';
You're 100% on the mark about not using frameworks or libraries, almost everything exists without the suck.
I'm not going to test this though this is a very stripped down version of my ajax function from my web platform. Some people might scream about the Fetch API however the syntax is an absolute mess. I recommend figuring out how to standardize this function so you can use it for everything instead of making copies of the code for every instance. Mine supports both GET and POST requests.
function ajax(method, url, param_id_container_pos, id_container)
{
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.timeout = 8000;
xhr.open(method,url,true);
xhr.send(null);
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
{
if (xhr.getResponseHeader('content-type'))
{
var type = xhr.getResponseHeader('content-type').split('/')[1];
if (type.indexOf(';') >- 1) {type = type.split(';')[0];}
}
else {var type = 'xml';}//Best guess for now.
console.log(type,xhr);
console.log(xhr.responseText);
//console.log(type,xhr.responseXML);
//document.getElementById('example').textContent = xhr.responseText;
}
}
}
You're also going to have to ensure that the url is set to an absolute path. I use path variable in my platform (see my profile for the link, wildly clean and organized code).
There are plenty of ways to make this function reusable and I highly recommend doing that. For now use the last non-curley-bracket line to update your line of text.

URL API parser alternative for Google Scripts

The javascript used by Google Scripts does not include the URI API library for parsing URLs. It also does not support complex (perl-like backwards looking) regular expressions. As far as I know you can't import public libraries. This makes it hard, verbose and unreliable to parse out URL elements.
However it does support web calls through URLFetchApp and the REST API. Is there a parsing server out in the internet that hosts the URI API, which can be called by URLFetchApp or using the built in REST API? I can not find one easily. Other solutions welcome.
I have a working solution only for US based URLs. International URLs break my regEx. I prefer using a robust solution not dependent on regEx.
If you want to know the problem dealing with....
I need to compare two URLs and see if the 2nd url is a on a subdomain, or directory or same as the home page.
function scoreURL (urlOne,urlTwo){
let regexSubdomain = /(?:http[s]?:\/\/)?([^\/\s]+)(\/.*)?/;
var urlOneArray = urlOne.split(regexSubdomain);
var urlTwoArray = urlTwo.split(regexSubdomain);
var subdomainOne = urlOneArray[1].replace(new RegExp('www.','i'),'')
var subdomainTwo = urlTwoArray[1].replace(new RegExp('www.','i'),'')
// return -1 if landing page is on sub domais, 0 if landing page is separate page , 1 if landing page is home page
if (subdomainOne === subdomainTwo) {
if (urlOneArray[2] === urlTwoArray[2])
{return (1);} else {return(0);}
} else return (-1);
}
The basic URL api links to a polyfill core-js module.
The URL polyfill uses multiple require statements that are not directly supported in apps script.
You can manually copy paste all required files from the parent directory and remove all required dependencies OR
Use webpack in your local nodejs to transpile the polyfill
install webpack and corejs
mkdir webpack
cd webpack
npm init -y
npm install webpack webpack-cli --save-dev
npm install --save core-js#3.18.3
src/index.js:
import 'core-js/web/url'
Bundle with webpack
npx webpack
Copy the resulting bundled js(in dist/main.js) to a file(url.gs) in apps script.
You'll now be able to use URL, URLSearchParams in global scope.

Using includeData Tag with nunjucks templating

I am using the automated workflow with gulp to build html and css from nunjucks templates based on this: https://github.com/uxmoon/automate-workflow
And I now want to include json data stored in files to access them in my components. There is a plugin called "includeData" that should do the trick:
https://github.com/VincentLeung/nunjucks-includeData
I tried to include this into the process, but it does not work.
What I did so far:
I added a file called "nunjucks-includedata.js" into the tasks folder where the gulp tasks are located.
var nunjucks = require('nunjucks'),
includeData = require('nunjucks-includeData'),
gulpnunjucks = require('gulp-nunjucks');
var templates = 'app/templates'; //Set this as the folder that contains your nunjuck files
var env = new nunjucks.Environment(new nunjucks.FileSystemLoader(templates));
includeData.install(env);
gulp.task('pages', function() {
// Gets .html files. see file layout at bottom
return gulp.src([templates + '/*.html', templates + '/**/*.html'])
// Renders template with nunjucks and marked
.pipe(gulpnunjucks.compile("", {env: env}))
// output files in dist folder
.pipe(gulp.dest(dist))
});
But it does not work. I get an error when starting gulp, that the tag "includeData" is not recognized.
There is of course something missing but I have no idea what it is and I also did not find anything useful when searching the internet.
Hopefully someone is already using the includeData plugin sucessfully in his build process and can tell me what I have to change in the configuration.
Thank you very much in advance for any help!
best regards,
Thomas
At first you must check that extension installed
// test.json
{"name": "Bill"}
// your-app.js
...
includeData.install(env);
var res = res.renderString('{% includeData "test.json" %} {{name}}');
console.log(res); // Bill
This extension don't work on Node 5.x, because require destructuring assignment (see node_modules\nunjucks-includeData\index.js, line 78). Perhaps, you must update your Node.

Last Modified Date of a file on a web site

Is there a way to get the Last-Modified-Date of a file on a Web Site?
i.e. Here is an example file I have out there:
http://www.ymcadetroit.org/atf/cf/%7B2101903E-A11A-4532-A64D-9D823368A605%7D/Birmingham_Youth_Sports_Parent_Manual.pdf
Go to the website you want to know about, wait for it to fully load, then go to the address bar and write this:
javascript:alert(document.lastModified)
You'll get a popup that says when it was last modified.
The HTTP intends the Last-Modified header field to declare the last modification date. But the server needs to know that date.
On static files whose content is sent directly to the client and not interpreted otherwise by the server (e.g. .html, .css, .js) it uses the last modified date of that file. But on files that generated content dynamically (PHP, Python, etc.) the script needs to specify that information itself. But unfortunatly many scripts don’t to that.
So if a Last-Modified header field is present, you can use that information. But if not, you cannot determin the last modification date.
Here is some C# code to do it:
public DateTime GetLastModifyTime(string url)
{
WebRequest request = WebRequest.Create(url);
request.Credentials = CredentialCache.DefaultNetworkCredentials;
request.Method = "HEAD";
using (WebResponse response = request.GetResponse())
{
string lastModifyString = response.Headers.Get("Last-Modified");
DateTime remoteTime;
if (DateTime.TryParse(lastModifyString, out remoteTime))
{
return remoteTime;
}
return DateTime.MinValue;
}
}
I realize this question is 4 years old, but a search of the web proved that satisfactory answers remain rare. Peter's answer is part of the solution. When I had the same problem to solve, that got me started. But the rest of the solution...
As he said, the web server must be configured to send the last-modified date ... so how do you configure the web server?
Assuming you have the necessary level of control, you first need to enable server side includes. There are several ways to do this - one of which is the "xbithack". A good reference is http://httpd.apache.org/docs/current/howto/ssi.html.
Assuming you've done this, you need to set the execute bit on any html file that needs to have server-side includes parsed. This can be done at the command line of a UNIX-like system: chmod u+x file.html or on the Mac using get-info (command-I) on the file.
This leaves the snippet to actually put in your file, which looks like this:
This document last modified <!--#flastmod file="index.html" -->
Since I found many, many recommendations that didn't include this, and simply used the javascript document.lastModified, I suspect that some servers give you what you want with the javascript version, whereas some (including the one hosting our stuff) don't.
To obtain the last modified date from client side, you can access the HTML DOM using the lastModified property using JavaScript.
The lastModified property grabs the information from the head portion sent with all web requests. The value can be manually set by developers on the web-server side of things so it may not reflect the actual last modified date of the file responsible for delivering the content.
Example
<!DOCTYPE html>
<html>
<body>
<b>document.lastModified : </b>
<script>document.write( document.lastModified );</script>
</body>
</html>
The specific command in JavaScript that retrieves this is document.lastModified and can easily be converted into a Date object as follows :
var x = new Date(document.lastModified);
More information can be found on the site I used as a reference w3 schools : HTML DOM lastModified Property
I believe the web server must be configured to send the last-modified date in an HTTP-header, this is certainly one way. Check out section 14.29 Last-Modified of this document:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
You can do the following to get Last-Modified:
https://superuser.com/a/991895
Using curl:
curl -s -v -X HEAD http://foo.com/bar/baz.pdf 2>&1 | grep '^< Last-Modified:'
Using wget:
wget --server-response --spider http://example.com/bar/example.pdf 2>&1 | grep -i Last-Modified
With just plain HTML, no you cannot.
You can with PHP, or ASP, or any other server side language.
I'm not an expert in headers, but believe you are looking for this:
There is a way to check the date when a file was modified:
View HTTP headers in Google Chrome?
Check in there (Chrome's Developer Tools / Network / Selected File / Headers) the "If-Modified-Since" variable.
Until now this has helped me to achieve what you are asking, get a file's modification date.
In php:
print getlastmod();
print gmdate('D, d M Y H:i:s', getlastmod());