Saturday, February 8, 2020

Uploading Files to Google Drive without Authorization using HTML Form and convert to spread sheet

function doPost(e) {
  var data = Utilities.base64Decode(e.parameters.data);
  var blob = Utilities.newBlob(data, e.parameters.mimetype, e.parameters.filename);
  var file =DriveApp.createFile(blob);
  convertExceltoGoogleSpreadsheet(e.parameters.filename);
  var output = HtmlService.createHtmlOutput( JSON.stringify(file) +"<b>Done!</b>");
  output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
  return output;
  // return ContentService.createTextOutput("Done.") <--- Here, an error occurred.
}

function convertExceltoGoogleSpreadsheet(fileName) {
  try {
    fileName = fileName || "microsoft-excel.xlsx";
    var excelFile = DriveApp.getFilesByName(fileName).next();
    var fileId = excelFile.getId();
    var folderId = Drive.Files.get(fileId).parents[0].id;
    var blob = excelFile.getBlob();
    var resource = {
      title: excelFile.getName(),
      mimeType: MimeType.GOOGLE_SHEETS,
      parents: [{id: folderId}],
    };
    file = Drive.Files.insert(resource, blob, {"convert": true });
 
  } catch (f) {
    Logger.log(f.toString());
  }

}




<!DOCTYPE html>
<html>

<head>
    <title>Sample script for uploading file to Google Drive without authorization</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.js"></script>
</head>

<body>
 
    <form action="https://script.google.com/macros/s/##/exec" id="form" method="post">
        Upload a file
        <div id="data"></div>
        <input name="file" id="uploadfile" type="file">
        <input id="submit" type="submit">
    </form>
    <script>
    $('#uploadfile').on("change", function() {
        var file = this.files[0];
        var fr = new FileReader();
        fr.fileName = file.name;
        fr.onload = function(e) {
            e.target.result
            html = '<input type="hidden" name="data" value="' + e.target.result.replace(/^.*,/, '') + '" >';
            html += '<input type="hidden" name="mimetype" value="' + e.target.result.match(/^.*(?=;)/)[0] + '" >';
            html += '<input type="hidden" name="filename" value="' + e.target.fileName + '" >';
            $("#data").empty().append(html);
        }
        debugger;
        fr.readAsDataURL(file);
    });
    </script>
</body>

</html>




Note: This will require enabling advanced Drive service from within Google Apps Script - Menu > Resources > Advanced Google Services AND Menu > Resources > Advanced Google Services > Drive API and Admin Directory API









Wednesday, March 6, 2019

Wake on Lan

using System;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.IO;
using System.Collections;
using System.Text;
using Newtonsoft.Json;
using Microsoft.VisualBasic;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using System.Globalization;
using System.Net.Sockets;


public class WOLUdpClient : UdpClient
{
    // *********************************************************************
    /// <summary>
    /// Initializes a new instance of <see cref="WOLUdpClient"/>.
    /// </summary>
    public WOLUdpClient()
        : base()
    {
    }

    // *********************************************************************
    /// <summary>
    /// Sets up the UDP client to broadcast packets.
    /// </summary>
    /// <returns><see langword="true"/> if the UDP client is set in
    /// broadcast mode.</returns>
    public bool IsClientInBrodcastMode()
    {
        bool broadcast = false;
        if (this.Active)
        {
            try
            {
                this.Client.SetSocketOption(SocketOptionLevel.Socket,
                     SocketOptionName.Broadcast, 0);
                broadcast = true;
            }
            catch
            {
                broadcast = false;
            }
        }
        return broadcast;
    }
}

 private String GetClientMac(string IPAddress)
    {
        /* There is a good chance that the server does not have an "arp" record for a given IP address, */
        /* so to create an arp entry we first send a ping to the IP Address*/
        string mac = string.Empty;

        try
        {
            //Sending ping:
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = "ping";
            psi.CreateNoWindow = true;
            psi.RedirectStandardInput = false;
            psi.RedirectStandardOutput = false;
            psi.Arguments = IPAddress;
            psi.UseShellExecute = false;

            Process process = Process.Start(psi);
            process.WaitForExit();

            //Now run arp command:
            psi = new ProcessStartInfo();
            psi.FileName = "arp";
            psi.CreateNoWindow = false;
            psi.RedirectStandardInput = false;
            psi.RedirectStandardOutput = true;
            psi.Arguments = "-a " + IPAddress;
            psi.UseShellExecute = false;

            process = Process.Start(psi);
            string arpInfo = string.Empty;
            while (!process.StandardOutput.EndOfStream)
            {
                arpInfo += process.StandardOutput.ReadLine();
            }

            process.WaitForExit();

            //Remove all white space from ARP result:
            arpInfo = arpInfo.Replace(" ", "");
            //Strip MAC from ARP result
            mac = arpInfo.Substring((arpInfo.IndexOf(IPAddress) + IPAddress.Length), 17);
        }
        catch (Exception)
        {
            //Error code here....
        }

        return mac.ToUpper();
    }


 private static string Wakeup(string macAddress)
    {
        try
        {
            WOLUdpClient client = new WOLUdpClient();
            client.Connect(
            new IPAddress(0xffffffff),    //255.255.255.255  i.e broadcast
            0x2fff); // port = 12287
            if (client.IsClientInBrodcastMode())
            {
                int byteCount = 0;
                byte[] bytes = new byte[102];
                for (int trailer = 0; trailer < 6; trailer++)
                {
                    bytes[byteCount++] = 0xFF;
                }
                for (int macPackets = 0; macPackets < 16; macPackets++)
                {
                    int i = 0;
                    for (int macBytes = 0; macBytes < 6; macBytes++)
                    {
                        bytes[byteCount++] =
                        byte.Parse(macAddress.Substring(i, 2),
                        NumberStyles.HexNumber);
                        i += 2;
                    }
                }

                int returnValue = client.Send(bytes, byteCount);
                return (returnValue + " bytes sent to " + macAddress +
                 Environment.NewLine + "Check if it's woken up. If not, try again!" +
                 Environment.NewLine);
            }

            else
            {
                return ("Remote client could not be set in broadcast mode!");
            }
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }

string MAC = "00-00-0000-0000".Replace("-", "");
 Wakeup(MAC);

Merge 2 Json

How to merge 2 json in javascript

Here is a sample of json merge

var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };

// Merge defaults and options, without modifying defaults
var settings = $.extend( {}, defaults, options );