How to upload file into box.com - ruby-on-rails

i am working on file upload into box.com but i am stuck there. i used Net::HTTP for that and i need the help of regarding this library.
my main code which interact to box.com is
module BoxApi
class FileOperation < Base
attr_reader :upload_path
def initialize
super
#upload_path = "https://upload.box.com/api/2.0/files/content"
end
#here filder_id args denote folder inside upload file and file args hold the content of file which are uploaded by file_field
def upload(folder_id, file)
boundary = "AaB03x"
body = []
body << "--#{boundary}\r\n"
body << "Content-Disposition: form-data; name='filename'; filename=#{file.original_filename}\r\n"
body << "Content-Type: text/plain\r\n\r\n"
body << file
body << "--#{boundary}\r\n"
body << "Content-Disposition: form-data; name='parent_id'"
body << "\r\n"
body << folder_id
body << "\r\n--#{boundary}--\r\n"
https_post(URI.parse("#{upload_path}"), body, boundary)
# `curl "Authorization: Bearer MlaNbyAefUWrawZEqGkDKvq9foCmQ0lL" -F filename=#./public/404.html -F parent_id='#{folder_id}' #{upload_path}`
rescue => ex
p "Exception caught (1) ==> #{ex}"
end
private
def https_post(uri, body, boundary)
http = https_setting(uri)
request = Net::HTTP::Post.new(uri.request_uri)
# request.body = JSON.parse(body)
request.body = body.join
request["Content-Type"] = "multipart/form-data, boundary=#{boundary}"
request["Authorization"] = "Bearer #{box_token.token}"
http.request(request)
rescue => ex
p "Exception caught (2) ==> #{ex}"
end
def https_setting(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http
end
end
end

Here's my Powershell code which uses System.Net.HttpWebRequest
param(
$FileRequestID ,
$FileToUpload
)
$BoxDomain = "yourenterprise.ent.box.com"
$URL = "https://$($BoxDomain)/app-api/file-request-web/public/file-request?urlId=$($FileRequestID)"
$resultsRaw = Invoke-WebRequest -Uri $URL -Method GET -UseBasicParsing
$resultsJson = ConvertFrom-Json $resultsRaw.Content
$boxFileRequestId = $resultsJson.id
$boxFolderId = $resultsJson.folder.id
$fileInfo = [System.IO.FileInfo]$FileToUpload
$ProcessStartDateTime = Get-Date
$ProgressName = "$($fileInfo.Name) Upload Progress"
$requestContent = "{`"fileRequestURL`":`"$($FileRequestID)`",`"formVersionId`":`"303881722`",`"values`":{`"element-0`":{`"type`":`"files`",`"data`":[{`"local_path`":`"$($fileInfo.Name)`",`"size`":$($fileInfo.Length)}]},`"folder`":{`"type`":`"folder`",`"id`":`"$($boxFolderId)`"}}}"
$UploadFormResponse = Invoke-WebRequest -Uri "https://$($BoxDomain)/app-api/file-request-web/public/form-response" -Method POST -ContentType "application/json;charset=UTF-8" -Body $requestContent -UseBasicParsing
$UploadFormResponseJson = ConvertFrom-Json $UploadFormResponse.Content
$requestContent = "{`"name`":`"$($fileInfo.Name)`",`"parent`":{`"id`":`"$($boxFolderId)`"},`"size`":$($fileInfo.Length)}"
$OptionsResponse = Invoke-WebRequest -Uri "https://$($BoxDomain)/api/2.1/files/content" -Method OPTIONS -Body $requestContent -Headers #{ Authorization = "Bearer $($UploadFormResponseJson.uploadToken)";} -UseBasicParsing
$OptionsResponseJson = ConvertFrom-Json $OptionsResponse.Content
$UploadURL = $OptionsResponseJson.upload_url
$boundary = "---------------------------" +[System.DateTime]::Now.Ticks.ToString("x");
$boundarybytes = [System.Text.Encoding]::ASCII.GetBytes("`r`n--" + $boundary + "`r`n");
$wr = [System.Net.HttpWebRequest]([System.Net.WebRequest]::Create($UploadURL));
$wr.ContentType = "multipart/form-data; boundary=" + $boundary;
$wr.Method = "POST";
$wr.KeepAlive = $true;
$wr.PreAuthenticate = $true
$wr.Headers.Add("Authorization", "Bearer $($UploadFormResponseJson.uploadToken)")
$wr.AllowWriteStreamBuffering = $false
$wr.SendChunked = $true
$rs = $wr.GetRequestStream();
#Write attributes
$rs.Write($boundarybytes, 0, $boundarybytes.Length);
$formAttributes = "Content-Disposition: form-data; name=`"attributes`"`r`n`r`n{`"name`":`"$($fileInfo.Name)`",`"parent`":{`"id`":`"$($boxFolderId)`"},`"content_modified_at`":`"$($fileInfo.LastWriteTimeUtc.ToString("yyyy-MM-ddTHH:mm:ssZ"))`"}"
$formAttributesBytes = [System.Text.Encoding]::UTF8.GetBytes($formAttributes)
$rs.Write($formAttributesBytes, 0, $formAttributesBytes.Length)
#Write File
$rs.Write($boundarybytes, 0, $boundarybytes.Length);
$formFile = "Content-Disposition: form-data; name=`"file`"; filename=`"$($fileInfo.Name)`"`r`nContent-Type: application/octet-stream`r`n`r`n"
$formFileBytes = [System.Text.Encoding]::UTF8.GetBytes($formFile)
$rs.Write($formFileBytes, 0, $formFileBytes.Length)
[System.IO.FileStream]$fileStream = [System.IO.File]::Open($fileInfo.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
$buffer = [System.Byte[]]::new(1048576)
$bytesRead = 0;
$totalBytesRead = 0
$totalBytesToRead = $fileInfo.Length
while (($bytesRead = $fileStream.Read($buffer, 0, $buffer.Length)) -ne 0) {
$rs.Write($buffer, 0, $bytesRead);
$rs.Flush()
$totalBytesRead += $bytesRead
$SecondsElapsed = ((Get-Date) - $ProcessStartDateTime).TotalSeconds
$SecondsRemaining = ($SecondsElapsed / ($totalBytesRead / $totalBytesToRead)) - $SecondsElapsed
Write-Progress -Activity $ProgressName -PercentComplete (($totalBytesRead/$($totalBytesToRead)) * 100) -CurrentOperation "$("{0:N2}" -f ((($totalBytesRead/$($totalBytesToRead)) * 100),2))% Complete" -SecondsRemaining $SecondsRemaining
}
$fileStream.Close();
$trailerBytes = [System.Text.Encoding]::ASCII.GetBytes("`r`n--" + $boundary + "`r`n");
$rs.Write($trailerBytes, 0, $trailerBytes.Length);
$rs.Close();
#Done writing File
$wresp = $wr.GetResponse();
$wresp.StatusCode
$stream2 = $wresp.GetResponseStream();
$reader2 = New-Object -TypeName System.IO.StreamReader -ArgumentList $stream2
$response = ConvertFrom-Json ($reader2.ReadToEnd())
#$response

This is a translation of the code by #NitrusCS into Bash.
It took a while and it's not identical, but it works.
#!/bin/bash
#CONSTANTS
BoxDomain="yourenterprise.ent.box.com"
formVersionId="1576913797"
#FUNCTIONS
function getdate() {
date "+%A, %B %d, %Y %I:%M:%S %p" | sed 's/am$/AM/g' | sed 's/pm$/PM/g'
}
function datetimeinticks() {
printf '%x\n' $(echo $(($(($(date '+%s') - $(date -d "0001-01-01T00:00:00.0000000 +0200" '+%s'))) * 10000000 + $((10#$(date '+%N')/100)) )))
}
#ARGUMENTS
FileRequestID="$1"
FileToUpload="$2"
FileName=$(basename $FileToUpload)
FileLength=$(stat --printf="%s" "$FileToUpload")
#MAIN CODE
URL="https://$BoxDomain/app-api/file-request-web/public/file-request?urlId=$FileRequestID"
echo -n "[$FileName] Preparing for upload: 0%"
resultsRaw=$(curl -s -X GET "$URL")
echo "$resultsRaw" > ${FileName}_errors.log
echo -en "\r[$FileName] Preparing for upload: 33%"
boxFolderId=$(echo $resultsRaw | jq ".folder" | jq ".id")
ProcessStartDateTime=$(getdate)
requestContent="{\"fileRequestURL\": \"$FileRequestID\",\"formVersionId\": \"$formVersionId\",\"values\":{\"element-0\":{\"type\":\"files\",\"data\":[{\"local_path\":\"$FileName\",\"size\":$FileLength}]},\"folder\":{\"type\":\"folder\",\"id\":$boxFolderId}}}"
UploadFormResponse=$(curl -s "https://$BoxDomain/app-api/file-request-web/public/form-response" -X POST -H "content-type: application/json;charset=UTF-8" -d "$requestContent")
echo "$UploadFormResponse" >> ${FileName}_errors.log
echo -en "\r[$FileName] Preparing for upload: 67%"
uploadToken=$(echo $UploadFormResponse | jq ".uploadToken" | sed 's/^\"//g' | sed 's/\"$//g')
requestContent="{\"name\":\"$FileName\",\"parent\":{\"id\":$boxFolderId},\"size\":$FileLength}"
OptionsResponse=$(curl -s "https://$BoxDomain/api/2.1/files/content" -X OPTIONS -H "Authorization: Bearer $uploadToken" -d "$requestContent")
echo "$OptionsResponse" >> ${FileName}_errors.log
echo -e "\r[$FileName] Preparing for upload: 100% ... "
UploadURL=$(echo $OptionsResponse | jq ".upload_url" | sed 's/^\"//g' | sed 's/\"$//g')
boundary="---------------------------$(datetimeinticks)"
LastWriteTimeUtc=$(date -u -d "$(stat --printf=%y "$FileToUpload")" '+%Y-%m-%dT%H:%M:%SZ')
boundarystring="$(echo -en "\r\n--" ; echo -n $boundary ; echo -en "\r\n" ; echo .)"
boundarystring=${boundarystring%.}
rs="${FileName}_requestdata.http"
touch $rs
echo -n "$boundarystring" > $rs
formAttributes="$(echo -en "Content-Disposition: form-data; name=\"attributes\"\r\n\r\n{\"name\":\"$FileName\",\"parent\":{\"id\":$boxFolderId},\"content_modified_at\":\"$LastWriteTimeUtc\"}" ; echo .)"
formAttributes=${formAttributes%.}
echo -n "$formAttributes" >> $rs
echo -n "$boundarystring" >> $rs
formFile="$(echo -en "Content-Disposition: form-data; name=\"file\"; filename=\"$FileName\"\r\nContent-Type: application/octet-stream\r\n\r\n" ; echo .)"
formFile=${formFile%.}
echo -n "$formFile" >> $rs
echo -n "[$FileName] Preparing the file to upload..."
cat "$FileToUpload" >> $rs
trailerstring="$(echo -en "\r\n--" ; echo -n $boundary ; echo -en "--\r\n" ; echo .)"
trailerstring=${trailerstring%.}
echo -n "$trailerstring" >> $rs
echo "[$FileName] Uploading:"
response=$(curl -X POST -H "content-type: multipart/form-data; boundary=$boundary" -H "Authorization: Bearer $uploadToken" --data-binary #$rs "$UploadURL")
echo "$response" >> ${FileName}_errors.log
echo $response | grep -q '"type":"file"' && { echo "[$FileName] Upload complete" ; rm ${FileName}_errors.log ; rm $rs ; }
echo $response | grep -q '"type":"file"' || echo "[$FileName] Upload failed: See file ${FileName}_errors.log for details."

Another translation of #NitrusCS into Python3 using the requests library. I was inspired by the bash code of #Kubuntuer82.
I'll include the gist here:
import datetime
import requests
import urllib
import os.path
import sys
import json
#
# Given a "File Request URL" and a local file, this program uploads to a box folder.
#
class BoxUploader(object) :
def __init__(self, requestURL) :
self.request_url = requestURL
o = urllib.parse.urlparse(requestURL)
self.boxDomain = o.hostname
self.fileRequestId = os.path.basename(o.path)
self.initialUrl = 'https://' + self.boxDomain + '/app-api/file-request-web/public/file-request?urlId=' + self.fileRequestId
self.formResponseUrl = 'https://' + self.boxDomain + '/app-api/file-request-web/public/form-response'
self.optionsUrl = 'https://' + self.boxDomain + '/api/2.1/files/content'
def upload_file(self, fname) :
#
# Initial call to the "get" url
#
rfc3339_format='%Y-%m-%dT%H:%M:%S%z'
response = requests.get(self.initialUrl)
jsonResponse = response.json()
basename = os.path.basename(fname)
local_timezone= datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
modifiedTime = datetime.datetime.fromtimestamp(os.path.getmtime(fname), tz=local_timezone)
#
# Submit a form response to get an upload token
#
boxFileRequestId = jsonResponse['id']
boxFolderId = jsonResponse['folder']['id']
formVersionId = jsonResponse['form']['versionId']
fileLength = os.path.getsize(fname)
print("Form Version ID: " + formVersionId)
requestContent = { "fileRequestURL" : self.fileRequestId,
"formVersionId" : formVersionId,
"values" : {"element-0" : { "type":"files", "data":[ {"local_path":fname, "size":fileLength}] },
"folder" : {"type" : "folder", "id": boxFolderId}}}
uploadFormResponse = requests.post(self.formResponseUrl, json=requestContent)
uploadFormResponseJson = uploadFormResponse.json()
#
# Make a call to the options url to get the actual url to
# upload the file to.
#
uploadToken = uploadFormResponseJson['uploadToken']
headers = { "Authorization" : "Bearer " + uploadToken }
requestContent = { "name" : fname,
"parent": { "id" : boxFolderId },
"size": fileLength}
optionsResponse = requests.options(self.optionsUrl, headers=headers, json=requestContent)
optionsResponseJson = optionsResponse.json()
# Upload the file.
upload_url = optionsResponseJson['upload_url']
form_attributes = { 'name' : fname,
'parent': {"id": boxFolderId},
'content_modified_at' : modifiedTime.strftime(rfc3339_format) }
files={ 'attributes' : (None, json.dumps(form_attributes), 'application/json', {'Content-Disposition':'form-data'}),
'file' : (fname, open(fname, 'rb')) }
#upload_request = requests.Request('POST', upload_url, headers=headers, files=files).prepare()
#print(upload_request.headers)
#print(upload_request.body)
uploadResponse = requests.post(upload_url, headers=headers, files=files)
print(json.dumps(uploadResponse.json(), indent=2))
def main(requestUrl, file) :
uploader = BoxUploader(requestUrl)
uploader.upload_file(file)
if __name__ == '__main__' :
url = sys.argv[1]
file = sys.argv[2]
main(url, file)

Related

Convert http_archive to repository_rule

I'm trying to convert a binary fetching from http_archive:
def purescript_toolchain():
http_archive(
name = "purs",
urls = ["https://github.com/purescript/purescript/releases/download/v0.14.7/linux64.tar.gz"],
sha256 = "cae16a0017c63fd83e029ca5a01cb9fc02cacdbd805b1d2b248f9bb3c3ea926d",
strip_prefix = strip_"purescript",
build_file_content = """exports_files(["purs"])""",
)
To a repository rule based approach:
def _purescript_toolchain_impl(repository_ctx):
repository_ctx.download_and_extract(
url = "https://github.com/purescript/purescript/releases/download/v0.14.7/linux64.tar.gz",
sha256 = "cae16a0017c63fd83e029ca5a01cb9fc02cacdbd805b1d2b248f9bb3c3ea926d",
stripPrefix = "purescript",
)
repository_ctx.file(
"BUILD.bazel",
content = """exports_files(["purs"])""",
)
_purescript_toolchain = repository_rule(
_purescript_toolchain_impl,
configure = True,
environ = ["PATH"],
)
def purescript_toolchain():
_purescript_toolchain(name = "purs")
It seems to work, but when I try to call other functions:
run_template = """
#!/usr/bin/env bash
set -o errexit
node -e "require('./{target_path}/{entry_module}/index.js').{entry_function}({entry_params})"
"""
def _purescript_compile(ctx):
srcs = ctx.files.srcs + ctx.files.deps
target = ctx.actions.declare_file(ctx.outputs.target.basename)
purs = ctx.executable.purs
flags = " ".join(ctx.attr.compiler_flags)
bazel_ps_deps = []
for d in ctx.attr.deps:
for f in d.files.to_list():
if f.basename == "target_srcs":
bazel_ps_deps = [f.path + "/**/*.purs"] + bazel_ps_deps
compileCmd = "\n".join(
[ "set -o errexit"
, """mkdir "$2" """
, """ "$1" compile """ + flags + """ --output "$2" "${#:3}" """
]
)
ctx.actions.run_shell(
tools = srcs + [purs],
outputs = [target],
command = compileCmd,
arguments = [purs.path, target.path] +
[src.path for src in srcs if src.extension == "purs"] +
bazel_ps_deps,
)
cpSrcsCmd = "\n".join(
[ "set -o errexit"
, """mkdir -p "$1" """
, """cp "${#:2}" "$1" """
]
)
target_srcs = ctx.actions.declare_file(ctx.outputs.target_srcs.basename)
ctx.actions.run_shell(
inputs = ctx.files.srcs,
outputs = [target_srcs],
command = cpSrcsCmd,
arguments = [target_srcs.path] + [src.path for src in ctx.files.srcs],
)
return target
def _purescript_tar(ctx):
target = _purescript_compile(ctx)
tar = ctx.actions.declare_file(ctx.outputs.tar.basename)
ctx.actions.run_shell(
inputs = [target],
outputs = [tar],
command = """
set -o errexit
tar --create --file "$1" --directory "$2" .
""",
arguments = [tar.path, target.path],
)
def _purescript_app(ctx):
target = _purescript_compile(ctx)
entry_params = ",".join([
'\\"{entry}\\"'.format(entry=e) for e in ctx.attr.entry_parameters
])
script = ctx.actions.declare_file(ctx.label.name)
script_content = run_template.format(
target_path = target.short_path,
entry_module = getattr(ctx.attr, "entry_module"),
entry_function = getattr(ctx.attr, "entry_function"),
entry_params = entry_params,
)
ctx.actions.write(script, script_content, is_executable = True)
runfiles = ctx.runfiles(files = [target])
return [DefaultInfo(executable = script, runfiles = runfiles)]
purescript_app = rule(
implementation = _purescript_app,
attrs = {
"srcs": attr.label_list(
allow_files = True,
),
"deps": attr.label_list(
default = [],
),
"purs": attr.label(
allow_single_file = True,
executable = True,
cfg = "host",
default = "#purs",
),
"compiler_flags": attr.string_list(
default = []
),
"entry_module": attr.string(
default = "Main",
),
"entry_function": attr.string(
default = "main",
),
"entry_parameters": attr.string_list(
default = [],
),
},
outputs = {
"target": "target",
"target_srcs": "target_srcs",
},
executable = True,
)
Called via:
purescript_app(
name = "ui",
visibility = ["//visibility:public"],
srcs = glob(["src/**/*.purs"]),
)
However, with this new version I get this error:
DEBUG: Repository io_bazel_rules_purescript instantiated at:
.../WORKSPACE:66:13: in <toplevel>
Repository rule http_archive defined at:
~/.cache/bazel/_bazel_black/b6b6a2b95964967dc5a9c8dec827e874/external/bazel_tools/tools/build_defs/repo/http.bzl:336:31: in <toplevel>
INFO: Analyzed target //webui:ui (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
ERROR: .../webui/BUILD.bazel:16:15: Action webui/target failed: (Exit 127): bash failed: error executing command /nix/store/4nmqxajzaf60yjribkgvj5j54x9yvr1r-bash-5.1-p12/bin/bash -c 'set -o errexit
mkdir "$2"
"$1" compile --output "$2" "${#:3}" ' '' external/purs/purs bazel-out/k8-fastbuild/bin/webui/target ... (remaining 98 argument(s) skipped)
Use --sandbox_debug to see verbose messages from the sandbox
: line 3: external/purs/purs: No such file or directory
Target //webui:ui failed to build
Which is surprising since the file exist in the directory (external/purs/purs).
Is their anything to add in the new version?

Azure DevOps Update Refs - Delete Branch via API

implemented a function to delete a branch on the azure devops:
function Remove-RemoteBranch {
param (
[Parameter(Mandatory = $true)]
[String]
$CollectionUri,
[Parameter(Mandatory = $true)]
[String]
$TeamProject,
[Parameter(Mandatory = $true)]
[String]
$Repository,
[Parameter(Mandatory = $true)]
[string]
$BranchName,
[Parameter(Mandatory = $true)]
[string]
$BranchID,
[Parameter(Mandatory = $true)]
[String]$AccessToken
)
#create PAT in B64 format"
$B64_PAT = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AccessToken)"))
#Header for Authorization
$header = #{Authorization = 'Basic ' + $B64_PAT }
$body = ConvertTo-Json (
#{
name = $BranchName;
oldObjectId = $BranchID;
newObjectId = "0000000000000000000000000000000000000000";
})
$response = (Invoke-RestMethod -Method Post `
-Uri "$($CollectionUri)/$($TeamProject)/_apis/git/repositories/$($Repository)/refs/?api-version=4.1" `
-Body $body `
-ContentType "application/json" `
-Headers $header `
-UseBasicParsing)
if ($response.StatusCode -notmatch "200") {
throw "Statuscode from RestRequest is $($Response.status)"
}
}
I couldnt find a solution to my issue yet. I get the error "Value cannot be null.\r\nParameter name: refUpdates" if I send a request to the server. I couldn't find any advices in the MS docu. May be some of you folks have an idea.
Thank you in advance.
Edit:
I have found the answer. The body has to look like this:
$body = ConvertTo-Json (
#(
#{
name = $BranchName;
oldObjectId = $BranchID;
newObjectId = "0000000000000000000000000000000000000000";
}
)
)
I had the same issue and found my $body didn't have square brackets around it as per the docs
[
{
name = $BranchName;
oldObjectId = $BranchID;
newObjectId = "0000000000000000000000000000000000000000";
}
]

Ruby HTTPS Post issue

I have two codes (variable info masked intentionally), the first one I receive the response with 200 code return, but second one I get 403 forbidden, any idea?
def get_token()
http = Net::HTTP.new(server, 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl?
#path(a.k.a) ->www.mysite.com/some_POST_handling_script.rb'
path = '/rest/fastlogin/v1.0?app_key=' + app_key + '&username=%2B' + username + '&format=json'
puts path
headers = {'Content-Type'=> 'application/x-www-form-urlencoded', 'Authorization' => password }
resp, data = http.post(path, data, headers)
puts 'Code = ' + resp.code
puts 'Message = ' + resp.message
resp.each {|key, val| puts key + ' = ' + val}
puts data
puts JSON.parse(resp.body)["access_token"]
result = {}
result["code"] = resp.code
result["token"] = JSON.parse(resp.body)["access_token"]
print result
return result
end
def get_token1()
path = '/rest/fastlogin/v1.0?app_key=' + app_key + '&username=%2B' + username + '&format=json'
uri = URI.parse('https://' + server + path)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl?
req = Net::HTTP::Post.new(uri.path)
req["Authorization"] = password
puts uri.host
puts uri.path
puts uri.port
resp,data = http.request(req)
print resp
end
I think this is authentication issue. Credentials which you provide are wrong. That's why 403 forbidden error is occurring.

Check for new files in multiple folders, Report that new file does or does not exist

I am a 2 day newbie with Powershell 2.0. I have searched and come this far, but I am stuck with what to do further. Please bear with me I tried to search!
Task: Create a PS file that searches subfolders in a folder. Each folder contains a site backup file. I need to know if a new file was created and report if the file was or was not created.
The PS file needs to do the following:
Check a folder
If new files exists say "ok" else "not OK"
Do this for 28 folders creating 28 statements
dump write-output to common function (email)
use data from email in the body of an email.
Problems:
One search goes OK, when I add another I get false answers. I suspect this has something to do with using the same variables over and over.
I'm still a bit lost on how to get a carriage return to work in the body of the email. Everything goes on one continuous line.
I am suspecting I have unneeded statements in my creation. The file is bits and pieces of answers I have found here. I am having trouble putting it together properly for my needs. Guidance would be greatly appreciated.
#Site #1
$fullPath = "\\10.10.1.5\working\$folder"
$folder1= "test1"
$numdays = 0
$numhours = 10
$nummins = 0
$site = "site 1"
function Verify1($path, $days, $hours, $mins)
{$files = #(get-childitem $path -include *.* -recurse | where {($_.LastWriteTime -gt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins)) -and ($_.psIsContainer -eq $false)})
if ($files -ne $NULL)
{$file = $files
write-host ("The backup File for " + $site + " was backed up successfully!!")}
else {write-host ("The backup File for " + $site + " WAS NOT backed up successfully!!")}}
Verify1 $fullPath $numdays $numhours $nummins
#Site #2
$fullPath = "\\10.10.1.5\working\$folder"
$folder2= "test2"
$numdays2 = 0
$numhours2 = 10
$nummins2 = 0
$site = "site 2"
function Verify2($path, $days, $hours, $mins)
{$files = #(get-childitem $path -include *.* -recurse | where {($_.LastWriteTime -gt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins)) -and ($_.psIsContainer -eq $false)})
if ($files -ne $NULL)
{$file = $files
write-host ("The backup File for " + $site + " was backed up successfully!!")}
else {write-host ("The backup File for " + $site + " WAS NOT backed up successfully!!")}}
Verify2 $fullPath2 $numdays $numhours $nummins
function email {
process { Write-Host $_ }
}
#verify1 | email
#verify2 | email
$date = (Get-Date).ToString('MM/dd/yyyy')
$EmailFrom = "email#gmail.com"
$EmailTo = "email#gmail.com"
$Subject = ("Daily Database Report for " + $date)
[string]$body = ""
foreach ($email in $emails) {$body = $body + "`r`n"}
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("user", "password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Problem 1
Issue looks likes coming from the variables carrying the same name.
If you look at site 2, it has full path looking at $folder which does not exist in either config blocks.
Something like
#Config Block
#Folders
$folder1= "test1"
$folder2= "test2"
#Remote Paths
$fullPath1 = "\\10.10.1.5\working\$folder1"
$fullPath2 = "\\10.10.1.5\working\$folder2"
#Site Names
$site1 = "Site 1"
$site2 = "Site 2"
#Time Difference
$numdays = 0
$numhours = 10
$nummins = 0
#Function
function VerifySite($Path, $Site, $Days, $Hours, $Mins)
{$files = #(get-childitem $path -include *.* -recurse | where {($_.LastWriteTime -gt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins)) -and ($_.psIsContainer -eq $false)})
if ($files -ne $NULL)
{$file = $files
write-host ("The backup File for " + $site + " was backed up successfully!!")}
else {write-host ("The backup File for " + $site + " WAS NOT backed up successfully!!")}}
VerifySite $fullPath1 $Site1 $numdays $numhours $nummins
VerifySite $fullPath2 $Site2 $numdays $numhours $nummins
might archive the desired results. Cleaned up the configuration so it can be read easier and removed the second verify function as it wasn't required.
Had a chance to revist this and look at problem 2.
Problem 2.
Email body.
I reworked it a bit to produce a log file. I then built the email body from the logfile and finally removed the logfile
#Config Block
#Folders
$folder1= "test1"
$folder2= "test2"
$folder3= "test3"
$folder4= "test4"
$folder5= "test5"
#Remote Paths
$fullPath1 = "\\10.10.1.5\working\$folder1"
$fullPath2 = "\\10.10.1.5\working\$folder2"
$fullPath3 = "\\10.10.1.5\working\$folder3"
$fullPath4 = "\\10.10.1.5\working\$folder4"
$fullPath5 = "\\10.10.1.5\working\$folder5"
#Site Names
$site1 = "Site 1"
$site2 = "Site 2"
$site3 = "Site 3"
$site4 = "Site 4"
$site5 = "Site 5"
#Time Difference
#Days
$numdays1 = 0
$numdays2 = 1
#Hours
$numhours1 = 10
$numhours2 = 15
#Mins
$nummins1 = 0
$nummins2 = 0
#Dates
$date = (Get-Date).ToString('MM/dd/yyyy')
$Logdate = (Get-Date).ToString('MMddyyyy')
#logs
$logFile = "D:\Log_$Logdate.txt"
#Email
$EmailFrom = "email#gmail.com"
$EmailTo = "email#gmail.com"
$Subject = ("Daily Database Report for " + $date)
#Function
function VerifySite($Path, $Site, $Days, $Hours, $Mins)
{$files = #(get-childitem $path -include *.* -recurse | where {($_.LastWriteTime -gt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins)) -and ($_.psIsContainer -eq $false)})
if ($files -ne $NULL)
{$file = $files
write-output ($Date + " The backup File for " + $site + " was backed up successfully!!") | Out-File $logFile -Append }
else {write-output ($Date + " The backup File for " + $site + " WAS NOT backed up successfully!!") | Out-File $logFile -Append}}
#Commands
VerifySite $fullPath1 $Site1 $numdays2 $numhours1 $nummins1
VerifySite $fullPath2 $Site2 $numdays1 $numhours2 $nummins2
VerifySite $fullPath3 $Site3 $numdays1 $numhours1 $nummins1
VerifySite $fullPath4 $Site4 $numdays1 $numhours2 $nummins1
VerifySite $fullPath5 $Site5 $numdays2 $numhours1 $nummins2
[string]$body = ""
$logs = Get-Content $logFile
foreach ($log in $logs )
{
$body = $body + $log + "`r`n"
}
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("user", "password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
#Cleanup if required.
remove-item $logFile
You should get $body returning something like
11/02/2015 The backup File for Site 1 WAS NOT backed up successfully!!
11/02/2015 The backup File for Site 2 was backed up successfully!!
Also reworked the variables a bit to show how it can be expanded.

How to post XML data via a proxy in Ruby?

I would like to run the following command in ruby on rails via a proxy:
curl --request POST http://200.206.38.24:8580/my_server_path/
--data-binary #test01.xml
--header "Content-type: Application/vnd.vizrt.payload+xml;type=element"
And so far I have:
PROXY_URL = 'proxy.mydomain.com'
PROXY_PORT = 3128
PROXY_USER = 'user'
PROXY_PASSWORD = 'pass'
MSE_HOST = '200.206.38.24'
MSE_PORT = 8580
MSE_PATH = '/my_server_path/'
xml_file = '<?xml version="1.0" encoding="utf-8"?><etc... />'
Net::HTTP::Proxy(PROXY_URL, PROXY_PORT, PROXY_USER, PROXY_PASSWORD).start(MSE_HOST, MSE_PORT) do |http|
response = http.post(MSE_PATH, xml_file, {"Content-type" => "Application/vnd.vizrt.payload+xml;type=element"})
end
Thanks in advance for any help.
According to tests, it works fine.
The response from http.post can be accessed via the body method. Eg: response.body

Resources