How to create Polygon in JS with google API in asp.net? - javascript

I have a small program that saves my addresses with bookmarks, all that data is saved in a SQL server database, what I want to do is through Javascrip, create a polygon, I have tried the google documentation, but I can't understand and it generates an error, this is done in windows form of asp.net.
enter image description here
This would be the script to make the various Markers that I have, now I don't know how I could add a polygon with color
<script>
//Variable global para trabajar con el MAPA
let map;
//Funcion para inicializar el mapa con un centro definido
function initMap(lat, long) {
map = new google.maps.Map(document.getElementById("ModalMapPreview"), {
center: { lat: lat, lng: long },
zoom: 15,
});
}
//Funcion encargada de ejecutarse una vez termine la carga de la pagina
$(document).ready(function () {
(function ($) {
//Función para convertir Tabla de datos en JSON
var convertTableToJson = function () {
//Se inicializa un arreglo para almacenar los regisros
var rows = [];
//Recorre cada una de las filas de la tabla gvUbicaciones o gridview
$('table#gvUbicaciones tr').each(function (i, n) {
//Se asigna fila para incertarala en arreglo
var $row = $(n);
//condición para omitir primera fila - encabezado
if (i !== 0) {
//Se incerta registro en arreglo tipado
rows.push({
idubi: $row.find('td:eq(1)').text(),
Ubicacion: $row.find('td:eq(2)').text(),
Lat: $row.find('td:eq(3)').text(),
Long: $row.find('td:eq(4)').text()
});
}
});
return rows;
};
//Función para crear los marcadores
$(function () {
//Obtenemos arreglo de registros
var markers = convertTableToJson();
//Validamos que existan registros para crear marcadores, de lo contrario inicializamos mapa sin marcadores
if (markers[0]) {
//Inicializamos mapa y centramos en el primer marcador del arreglo
// initMap(parseFloat(markers[0].Lat), parseFloat(markers[0].Long));
//initMap(parseFloat(-17.783851), parseFloat(-63.182580));
initMap(parseFloat($("#txtLat").val()), parseFloat($("#txtLong").val()));
//Recorremos la lista de marcadores y los establecemos en el mapa
$.each(markers, function (key, val) {
//Se crea un objeto con las propiedades latitud y longitud para establecerlo en la configuración del marcador
const myLatLng = { lat: parseFloat(val.Lat), lng: parseFloat(val.Long) };
//Se crea marcador con el API de google y se establece en el mapa
var marker = new google.maps.Marker({
map,
position: myLatLng,
draggable: true,
title: val.Ubicacion
});
//Plantilla para ventana de información del marcador
const contentString =
'<div id="content">' +
'<h4 >' + val.Ubicacion + '</h4>' +
'<div id="bodyContent">' +
"<p><b>idubi: </b>" + val.idubi + "<br/>" +
"<b>Ubicacion: </b>" + val.Ubicacion + "<br/>" +
"<b>Latitud: </b>" + val.Lat + "<br/>" +
"<b>Longitud: </b>" + val.Long +
"</p>" +
"</div>" +
"</div>";
//Se crea ventana de información del marcador con el API de google
const infowindow = new google.maps.InfoWindow({
content: contentString,
});
//Se establece evento para que cada vez que se haga click en el marcador se muestre la ventana de información
marker.addListener("click", () => {
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'dragend', function (evt) {
$("#txtLat").val(evt.latLng.lat().toFixed(6));
$("#txtLong").val(evt.latLng.lng().toFixed(6));
map.panTo(evt.latLng);
});
});
} else {
//Se inicializa mapa cuando no hay registros
initMap(parseFloat(-17.783851), parseFloat(-63.182580));
}
});
})(jQuery);
});

Related

Leaflet: resize bindPopup

How can I change the size of the bindPopup since when opening the web from a mobile phone it is very large, in the image that shows a lot of space is left below, is there any way to reduce that size?
search the internet but there are no results almost everything is from the bookmarks
This is part of the code I use to display this information:
const updateMap = () => {
const Buslocation =
"https:xxxxxxxxxxxxx" + gtebi;
fetch(Buslocation)
.then((res) => res.json())
.then((data) => {
//si existe el marcador removerlo para no tener marcadores duplicados
if (bus_marker) {
map.removeLayer(bus_marker);
}
//asignar valores que se usaran ingresar el marcador
const latitud = data.latitud;
const longitud = data.longitud;
//asignar valores que se usaran mas adelate para definir el popup
const destino = data.destino;
const origen = data.origen;
const patente = data.patente;
//animacion para dirigirse al punto donde se encuentra el bus
map.flyTo([latitud, longitud], 12);
//crear marcador
bus_marker = L.marker([latitud, longitud], {
icon: busicon,
})
.addTo(map)
.bindPopup(
"<strong><h3>El bus esta aquí</h3></strong>" +
"<h5>Origen: " +
"<strong>" +
origen +
"</strong>" +
"</h5>" +
"<h5>Destino: " +
"<strong>" +
destino +
"</strong>" +
"</h5>" +
"<h5>Patente: " +
"<strong>" +
patente +
"</strong>" +
"</h5>"
)
.update();
});
//definir el tiempo de actualizacion del marcador(bus)
setTimeout(updateMap, 180000);
};
I searched the internet but I only get options for the map markers.
or if I can remove the bindPopup somehow, because if I don't use it, the white bar is left next to it.

Call an url with parameters from jquery in mvc

I want to open a new url, pasing parameters using jquery, this is the way that im doing it,
$('#BtnPrintFlujo').click(function(e) {
var url = '#Url.Action("BillingxCashier", "Reports",new {area="Configurations" })';
url += "/opParam=" + $("#Users option:selected").val() +
"&fromDate=" + $('#FromDate').val() +
"&toDate=" + $('#ToDate').val();
var win = window.open(url);
if (win) {
win.focus();
} else {
alert("Porfavor, debes permitir que se abran las ventanas emergentes o el reporte no va a salir :'( ");
}
});
but, it said this error
Request.Path dangerous on the client (&).
$('#BtnPrintFlujo').click(function(e) {
var url = '#Url.Action("BillingxCashier", "Reports",new {area="Configurations" })';
url += "?opParam=" + $("#Users option:selected").val() +
"&fromDate=" + $('#FromDate').val() +
"&toDate=" + $('#ToDate').val();
var win = window.open(url);
if (win) {
win.focus();
} else {
alert("Porfavor, debes permitir que se abran las ventanas emergentes o el reporte no va a salir :'( ");
}
});
you missed an question mark before first parameter,
url += "?opParam=" + $("#Users option:selected").val() +
try this

Request.QueryString don´t receive values

Good morning everyone,
I have a system which needs send a e-mail with some variables that I have in my JS. The code, at begin, looks fine to me, but the Request.QueryString returns me nothing. I am trying to receive data from the URL with Request.Url.ToString() and that show me all the url sended by the JS, which means the JS is sending, but the Request.QueryString can´t read the values.
Can someone please help me with this?
Below I show the code.
<script type="text/javascript">
var nomeCarinha;
$(document).on("click", "[id*=lnkView]", function () {
$("#nome").html($(this).closest("tr").find("td.sDisplayName").text());
$("#Product").html($(this).closest("tr").find(".Produto").text());
$("#IP").html($(this).closest("tr").find("td.sNetworkAddress").text());
$("#DC").html($(this).closest("tr").find("td.dc").text());
$("#comentario").html($(this).closest("tr").find("td.sComment").text());
$("#inicio").html($(this).closest("tr").find("td.inicio").text());
$("#mensagem").html($(this).closest("tr").find(".mensagem").text());
$("#monitor").html($(this).closest("tr").find("td.sMonitorTypeName").text());
$("#dialog").dialog({
width: 1000,
title: "Detalhes para TP",
buttons: {
Email: function (nome) {
var width = 150;
var height = 250;
var left = 99;
var top = 99;
var nome = $(this).find("#nome").text();
var produto = $(this).find("#product").text();
var ip = $(this).find("#IP").text();
var dc = $(this).find("#DC").text();
var comentario = $(this).find("#comentario").text();
var inicio = $(this).find("#inicio").text();
var mensagem = $(this).find("#mensagem").text();
var monitor = $(this).find("#monitor").text();
var janeleira = window.open("outlookPrimeiro.aspx?nomeDevice="+nome+"&nomeIp"+ip+"&nomeDc="+dc+"&nomeComentario="+comentario+"&nomeInicio="+inicio+"&nomeMonitor="+monitor, 'janela', 'width=' + width + ', height=' + height + ', top=' + top + ', left=' + left + ', scrollbars=yes, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no, setTimeout=1000');
// Rescrever no outlookprimeiro.aspx para tirar os + no lugar de espaço da URL
},
Ok: function () {
$(this).dialog('close');
}
},
modal: true
});
return false;
});
function blinker() {
$('.blink').fadeOut(500);
$('.blink').fadeIn(500);
}
setInterval(blinker, 1000); //Runs every second
And the receive:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//NECESSÁRIO PARA USAR MARSHALL
using System.Runtime.InteropServices;
//NECESSARIO PARA USAR O OUTLOOK
using aqueleLance = Microsoft.Office.Interop.Outlook;
using OutlookApp = Microsoft.Office.Interop.Outlook.Application;
using testeUsingPrimeiro = Microsoft.Office.Interop.Outlook._AutoFormatRule;
using testeUsingSegundo = Microsoft.Office.Interop.Outlook._AutoFormatRules;
using testeUsingTerceiro = Microsoft.Office.Interop.Outlook.AutoFormatRule;
using testeUsingQuarto = Microsoft.Office.Interop.Outlook.AutoFormatRules;
public partial class outlookPrimeiro : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String nomeDevice = Request.Url.ToString();
//String nomeProduto = "TESTE";
String nomeIp = Request.QueryString["ip"];
String nomeDc = Request.QueryString["dc"];
String nomeComentario = Request.QueryString["comentario"];
String nomeInicio = Request.QueryString["inicio"];
String nomeMonitor = Request.QueryString["monitor"];
//DEFINICICOES DE DADOS DO E-MAIL A SER ENVIADO
String paraEmail = "noc#email.com.br";
String copiaEmail = "mateus#email.com.br";
//String copiaOculta = "";
String assuntoEmail = "Usando Outlook 2013
String corpo = "<html><body><div style='width:95%;text-align: center;background-color: black'><table style='width: 100%;text-align: center'><tr style='background-color:#5B2E90'><td style='color: white'>Prioridade</td><td style='color: white'>Acionamento</td><td style='color: white'>KBN</td><td style='color: white'>Device</td><td style='color: white'>IP</td><td style='color: white'>DC</td><td style='color: white'>WUG</td><td style='color: white'>Diretorio</td><td style='color: white'>Monitor</td><td style='color: white'>Comentario</td><td style='color: white'>Tempo Down</td><td style='color: white'>Inicio</td><td style='color: white'>TP</td></tr><tr><td style='color: orange'>Prioridade</td><td style='color: orange'>Acionamento</td><td style='color: orange'>KBN</td><td style='color: orange'>" + nomeDevice + "</td><td style='color: orange'>" + nomeIp + "</td><td style='color: orange'>" + nomeDc + "</td><td style='color: orange'>WUG</td><td style='color: orange'>Diretorio</td><td style='color: orange'>" + nomeMonitor + "</td><td style='color: orange'>COMENTARIO</td><td style='color: orange'>Tempo Down</td><td style='color: orange'>" + nomeInicio + "</td><td style='color: orange'>TP</td></tr></table></div></body></html>";
//CRIA NOVO APP USANDO Microsoft.Office.Interop.Outlook.Application
OutlookApp appDoOutlook = new OutlookApp();
//CRIA E-MAIL
aqueleLance.MailItem itemDoMail = appDoOutlook.CreateItem(aqueleLance.OlItemType.olMailItem) as aqueleLance.MailItem;
//QUAL CONTA VAI ENVIAR? NECESSÁRIO TER A CONTA NA MÁQUINA
string nomeDaConta = "noc#linx.com.br";
//CRIA SESSÃO
aqueleLance.NameSpace sessao = itemDoMail.Session;
//PEGA CONTAS PRESENTES NA MÁQUINA
aqueleLance.Accounts contaAccounts = sessao.Accounts;
//FOR 1 ATÉ FINAL DO NÚMERO DE CONTAS
for (int i = 1; i <= contaAccounts.Count; i++)
{
//aqueleLance.Account contaAccount RECEBE O VALOR DO FOR
aqueleLance.Account contaAccount = contaAccounts[i];
//SE A CONTA EXISTE, ELE VAI ENVIAR
//(COMPARAÇÃO FEITA EM LOWER CASE
if (contaAccount.DisplayName.ToLower() == nomeDaConta.ToLower())
{
//COMANDO PARA ENVIAR USANDO A CONTA XXXXX
itemDoMail.SendUsingAccount = contaAccount;
//LIBERA VARIAVEL
Marshal.ReleaseComObject(contaAccount);
//PARA O COMANDO
break;
}
}
//PARA QUEM ENVIA O E-MAIL
itemDoMail.To = paraEmail;
//ENVIAR COM COPIA PARA
itemDoMail.CC = copiaEmail;
//COPIA OCULTA
//itemDoMail.BCC = copiaOculta;
//ASSUNTO DO EMAIL
itemDoMail.Subject = assuntoEmail;
//CORPO DO EMAIL EM HTML
itemDoMail.HTMLBody = corpo;
//"<html><body>Enviado pelo <strong>Outlook</strong> 2013<br/> Teste do envio com CC e BCC.<br/><br/></body></html>"
//IMPORTANCIA DO EMAIL
itemDoMail.Importance = aqueleLance.OlImportance.olImportanceHigh;
//ENVIA O EMAIL
//NÃO É POSSÍVEL VER ANTES DE ENVIAR SEM HABILITAR O DISPLAY ABAIXO
//itemDoMail.Send();
//HABILITE ISSO PARA VER A MENSAGEM ANTES DE ENVIAR
//PRECISA TIRAR O SEND ACIMA
itemDoMail.Display(false);
//LIBERA CONTAS
Marshal.ReleaseComObject(contaAccounts);
//LIBERA SESSÃO
Marshal.ReleaseComObject(sessao);
}
}
You're not using the same keys for your values:
"nomeDevice="+nome+"&nomeIp="+ip+"&nomeDc="+dc+"&nomeComentario="+comentario+"&nomeInicio="+inicio+"&nomeMonitor="+monitor
So you should also read these in the C# code:
String nomeIp = Request.QueryString["nomeIp"];
String nomeDc = Request.QueryString["nomeDc"];
String nomeComentario = Request.QueryString["nomeComentario"];
String nomeInicio = Request.QueryString["nomeInicio"];
String nomeMonitor = Request.QueryString["nomeMonitor"];
Also note that you should absolutely escape the content on the JavaScript side using encodeURIComponent(), otherwise your users can make the request fail by having for instance a & in the comentario... e.g.:
"outlookPrimeiro.aspx"+
"?nomeDevice="+encodeURIComponent(nome)+
"&nomeIp="+encodeURIComponent(ip)+
"&nomeDc="+encodeURIComponent(dc)+
"&nomeComentario="+encodeURIComponent(comentario)+
"&nomeInicio="+encodeURIComponent(inicio)+
"&nomeMonitor="+encodeURIComponent(monitor)
Try To change:
String nomeIp = Request.QueryString["ip"];
To
String nomeIp = Request.QueryString["nomeIp"]
and so on...
also, there's small typo. +"&nomeIp"+ip+ should be +"&nomeIp="+ip+

How to format string and number in google script

I'm trying to send mail to a list of people with some important data that i need to be in the e-mail formatted as bold. I tried to use the string.setBold() but it says that the function does not exist. By the way the email is something like this:
var emailBody = "¡Hola " + name + "!" +
"\n\nTe informamos que tienen un pago pendiente por " +
acobrar + " con el equipo " + equipo + " en Liga Siete" +
". Segun nuestros registros han realizado los siguientes pagos" +
pagos + "\n\nTe recordamos que con la tarifa " + tarifa +
" deben cancelar un total de " + apagar +
" y que la garantía no se considera como abono. Recuerda que esta cuota debe ser pagada antes del " +
deadline +
" o quedaran inhabilitados de jugar o incluso perder el cupo."
Where the variable name, equipo, tarifa and apagar must be in bold.
How can I accomplish this?

Is it possible to peform a Windows Explorer search using JavaScript for a HTA?

This is the code that I have been working on that doesn't work. I want it to perform the search and look into a folder called "info" in the same directory.
<html>
<head>
<title>Application Executer</title>
<HTA:APPLICATION ID="oMyApp"
APPLICATIONNAME="Application Executer"
WINDOWSTATE="normal">
<script type="text/javascript" language="javascript">
function RunFile() {
WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("explorer.exe search-ms://query=somethinginapdf", 1, false);
}
</script>
</head>
<body>
<input type="button" value="Windows Search" onclick="RunFile();"/>
</body>
</html>
give it a try with this vbscript :
'**********************************************************************************
'Description du script VBS : Rechercher dans le contenu des fichiers de type texte
'**********************************************************************************
'En balayant les fichiers de type "fichiers texte" (fichiers ".txt",".htm",".asp",".php",".rtf",".html",".htm",".hta",".xml",".csv",".vbs" etc...),
'de les ouvrir les uns après les autres pour en extraire la portion de texte contenant le mot recherché.
'Le petit moteur peut toutefois rendre service pour explorer (en local) de petits sites Intranet (sans indexation préalable des pages).
'Code Original ==> http://jacxl.free.fr/cours_xl/vbs/moteur_rech.vbs
'***************************************************************************************************************************************************************
'- Mise à jour par Hackoo en 19/12/2013
'- Ajout d'une fonction pour parcourir le dossier à traiter par la fonction BrowseForFolder afin de rendre le script plus convivial et facile à manipuler
'- le résultat de la recherche est dans un fichier de type HTA au lieu dans un fichier de type HTML crée dans le dossier temporaire
'- Ajout de la fonction Explore() intégré dans le HTA pour explorer chaque fichier à part dans l'explorateur Windows
'- Ajout de la fonction HtmlEscape()
'***************************************************************************************************************************************************************
'- Mise à jour par Hackoo en 07/03/2014
'- Ajout d'une barre d'attente en HTA lors de la recherche pour faire patienter l'utilisateur
'***************************************************************************************************************************************************************
On Error Resume Next
Dim ws,Titre,MsgTitre,MsgAttente,oExec,Temp,Copyright,Size
dim tabl()
dim tablold()
redim tabl(1)
tabl(0)="jetpack"
num=1
nbtot=0
nboct=0
nbssrep=0
Copyright = "(Version modifié © Hackoo)"
Titre = "Recherche dans le contenu des fichiers de type texte " & Copyright
Set fs = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject("wscript.Shell")
Temp = ws.ExpandEnvironmentStrings("%Temp%")
'choix du répertoire
nomrep = Parcourir_Dossier()
'choix du mot recherché
mot_cherch=inputbox("Taper le mot pour effectuer la recherche ?",Titre,"Wscript")
MsgTitre = "Recherche dans le contenu des fichiers de type texte " & Copyright
MsgAttente = "Veuillez patienter.la recherche du mot <FONT COLOR='yellow'><B>" & DblQuote(mot_cherch) & "</B></FONT> est en cours..."
If mot_cherch = "" Then WScript.Quit
'traiter le cas où nomrep est un disque ou un nom non valide
'if not fs.folderexists(nomrep) then 'or ucase(fs.getdrivename(nomrep))=ucase(replace(nomrep,"\","")) then
' MsgBox "nom de répertoire non valide"
' wscript.quit
'end if
tabl(1)=nomrep
'créer le fichier texte et l'ouvrir en appending
Dim tempFolder : Set tempFolder = fs.GetSpecialFolder(2)
Dim tempfile : tempFile = tempFolder & "\liste_fichiers.hta"
'msgbox tempFile
fichresult = tempFile
Set nouv_fich = fs.OpenTextFile(fichresult,2,true,-1)
nouv_fich.close
Set nouv_fich = fs.OpenTextFile(fichresult,8,false,-1)
Call CreateProgressBar(MsgTitre,MsgAttente)'Creation de barre de progression
Call LancerProgressBar()'Lancement de la barre de progression
StartTime = Timer 'Debut du Compteur Timer
nouv_fich.writeline("<html><title>"&Titre&"</title><HTA:APPLICATION SCROLL=""yes"" WINDOWSTATE=""Maximize""icon=""verifier.exe"">"&_
"<meta content=""text/html; charset=UTF-8"" http-equiv=""content-type"">"&_
"<body text=white bgcolor=#1234568><style type='text/css'>"&_
"a:link {color: #F19105;}"&_
"a:visited {color: #F19105;}"&_
"a:active {color: #F19105;}"&_
"a:hover {color: #FF9900;background-color: rgb(255, 255, 255);}"&_
"</style>")
nouv_fich.writeline "<SCRIPT LANGUAGE=""VBScript"">"
nouv_fich.writeline "Function Explore(filename)"
nouv_fich.writeline "Set ws=CreateObject(""wscript.Shell"")"
nouv_fich.writeline "ws.run ""Explorer /n,/select,""&filename&"""""
nouv_fich.writeline "End Function"
nouv_fich.writeline "</script>"
'boucler sur les niveaux jusqu'à ce qu'il n'y ait
'plus de sous répertoires dans le niveau
do while num>0 '------------------------------------
'recopie tabl
redim tablold(ubound(tabl))
for n=0 to ubound(tabl)
tablold(n)=tabl(n)
next
'réinitialiser tabl
redim tabl(0)
tabl(0)="zaza"
'explorer le ss répertoire
for n=1 to ubound(tablold)
expl(tablold(n)) 'ajoute ds le tableau tabl les ss rep de tablold(n)
next
loop '----------------------------------------------
nouv_fich.writeline("</BODY></HTML>")
nouv_fich.close
Call FermerProgressBar()'Fermeture de barre de progression
DurationTime = FormatNumber(Timer - StartTime, 0) & " seconds." 'La duree de l'execution du script
Set Dossier = fs.getfolder(nomrep)
SizeKo = Round(FormatNumber(Dossier.Size)/(1024),2) & " Ko" 'Taille en Ko avec 2 chiffres apres la Virgule
SizeMo = Round(FormatNumber(Dossier.Size)/(1048576),2) & " Mo" 'Taille en Mo avec 2 chiffres apres la Virgule
SizeGo = Round(FormatNumber(Dossier.Size)/(1073741824),2) & " Go" 'Taille en Go avec 2 chiffres apres la Virgule
If Dossier.size < 1024 Then
Size = Dossier.size & " Octets"
elseif Dossier.size < 1048576 Then
Size = SizeKo
elseif Dossier.size < 1073741824 Then
Size = SizeMo
else
Size = SizeGo
end If
set nouv_fich=nothing
If Err <> 0 Then
'MsgBox Err.Number & VbCrLF & Err.Description,16,MsgTitre
On Error GoTo 0
End if
'nboct2= int(fs.getfolder(nomrep).size/1024/1024)
set fs=nothing
'afficher le résultat dans un Popup
Ws.Popup "La recherche est terminée en "& DurationTime & " !"& vbCr &_
"Recherche effectuée dans " & vbCrLF & nbtot & " fichiers pour " & Size & " dans " & DblQuote(nomrep) &_
" et ses " & nbssrep & " sous-répertoires (total " & Size & ")","6",MsgTitre,64
Set sh = CreateObject("WScript.Shell")
sh.run "explorer " & fichresult
set sh=nothing
'*************************************************************************
Function Parcourir_Dossier()
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Veuillez choisir un dossier pour la recherche " & Copyright,1,"c:\Programs")
If objFolder Is Nothing Then
Wscript.Quit
End If
NomDossier = objFolder.title
Parcourir_Dossier = objFolder.self.path
end Function
'*************************************************************************
sub expl(nomfich)
'ajoute dans le tableau tabl() tous les sous répertoires de nomfich
'et ajoute dans le fichier nouv_fich les noms des fichiers et leurs caractéristiques
Set rep=fs.getFolder(nomfich)
num=ubound(tabl)
'parcourir les sous répertoires de nomfich
for each ssrep in rep.subfolders
num=num+1
redim preserve tabl(num)
tabl(num)= ssrep.path
nbssrep=nbssrep+1
next
'parcourir les fichiers de nomfich
for each fich in rep.files
nbtot=nbtot+1
nboct=nboct+fich.size
'**********************************************************************************************************************************************************************************************
'chercher dans le fichier (vous pouvez commenter cette ligne si vous voulez juste afficher les fichiers qui contient seulement le mot à rechercher)
'nouv_fich.writeline fich.path & "<br><FONT COLOR=""yellow""><B>(" & int(fich.size/1024) & " ko, créé " & fich.DateCreated & ", acc " & fich.DateLastAccessed & ")</B></FONT><br>"
'**********************************************************************************************************************************************************************************************
Dim Ext
'ici dans ce tableau vous pouvez ajouter d'autres extensions de type texte
Ext = Array(".txt",".asp",".php",".rtf",".html",".htm",".hta",".xml",".csv",".vbs",".js",".css",".ini",".inf")
For i=LBound(Ext) To UBound(Ext)
if instr(lcase(fich.name),Ext(i)) > 0 Then
Set fich_sce = fs.OpenTextFile(fich.path,1,false,-2)
txtlu=fich_sce.readall
txtlu = HtmlEscape(txtlu)
fich_sce.close
'txtlu=tt(txtlu)
pos=instr(lcase(txtlu),lcase(mot_cherch))
if pos>0 then
nouv_fich.writeline ("<HR><A href=""#"" OnClick='Explore("""& fich.Path & """)'>" & fich.Path & "</A>")
do while pos>0
nbav=50
if pos-1<nbav then nbav=pos-1
nbapr=50
if len(txtlu)-pos-len(mot_cherch)+1<nbapr then nbapr=len(txtlu)-pos-len(mot_cherch)+1
txx= tt(mid(txtlu,pos-nbav,nbav)) & "<FONT COLOR='Yellow'><B>" & tt(mid(txtlu,pos,len(mot_cherch))) & "</B></FONT>" & mid(txtlu,pos+len(mot_cherch),nbapr)
if nbav=50 then txx="..." & txx
if nbapr=50 then txx=txx & "..."
txx="<BR> " & txx
nouv_fich.writeline txx
txtlu=right(txtlu,len(txtlu)-pos+1-len(mot_cherch))
pos=instr(lcase(txtlu),lcase(mot_cherch))
loop
end if
end if
next
next
set rep=nothing
end sub
'*************************************************************************
function tt(txte)
tt=txte
tt=replace(tt,"<","<")
tt=replace(tt,">",">")
end function
'*************************************************************************
Function HtmlEscape(strRawData)
'http://alexandre.alapetite.fr/doc-alex/alx_special.html
Dim strHtmlEscape
strHtmlEscape = strRawData
strHtmlEscape = Replace(strHtmlEscape, "&", "&")
strHtmlEscape = Replace(strHtmlEscape, "<", "<")
strHtmlEscape = Replace(strHtmlEscape, ">", ">")
strHtmlEscape = Replace(strHtmlEscape, """", """)
strHtmlEscape = Replace(strHtmlEscape, "à", "à")
strHtmlEscape = Replace(strHtmlEscape, "è", "è")
strHtmlEscape = Replace(strHtmlEscape, "é", "é")
strHtmlEscape = Replace(strHtmlEscape, "©", "©")
strHtmlEscape = Replace(strHtmlEscape, "ê", "ê")
'strHtmlEscape = Replace(strHtmlEscape, vbCrLf, "<br>")
'strHtmlEscape = Replace(strHtmlEscape, vbCr, "<br>")
'strHtmlEscape = Replace(strHtmlEscape, vbLf, "<br>")
'strHtmlEscape = Replace(strHtmlEscape, vbTab, " ")
'strHtmlEscape = Replace(strHtmlEscape, " ", " ")
HtmlEscape = strHtmlEscape
End Function
'****************************************************************************************************
Sub CreateProgressBar(Titre,MsgAttente)
Dim ws,fso,f,f2,ts,ts2,Ligne,i,fread,LireTout,NbLigneTotal,Temp,PathOutPutHTML,fhta,oExec
Set ws = CreateObject("wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Temp = WS.ExpandEnvironmentStrings("%Temp%")
PathOutPutHTML = Temp & "\Barre.hta"
Set fhta = fso.OpenTextFile(PathOutPutHTML,2,True)
fhta.WriteLine "<HTML>"
fhta.WriteLine "<HEAD>"
fhta.WriteLine "<Title> " & Titre & "</Title>"
fhta.WriteLine "<HTA:APPLICATION"
fhta.WriteLine "ICON = ""magnify.exe"" "
fhta.WriteLine "BORDER=""THIN"" "
fhta.WriteLine "INNERBORDER=""NO"" "
fhta.WriteLine "MAXIMIZEBUTTON=""NO"" "
fhta.WriteLine "MINIMIZEBUTTON=""NO"" "
fhta.WriteLine "SCROLL=""NO"" "
fhta.WriteLine "SYSMENU=""NO"" "
fhta.WriteLine "SELECTION=""NO"" "
fhta.WriteLine "SINGLEINSTANCE=""YES"">"
fhta.WriteLine "</HEAD>"
fhta.WriteLine "<BODY text=""white""><CENTER><DIV><SPAN ID=""ProgressBar""></SPAN>"
fhta.WriteLine "<span><marquee DIRECTION=""LEFT"" SCROLLAMOUNT=""3"" BEHAVIOR=ALTERNATE><font face=""Comic sans MS"">" & MsgAttente &"</font></marquee></span></DIV></CENTER></BODY></HTML>"
fhta.WriteLine "<SCRIPT LANGUAGE=""VBScript""> "
fhta.WriteLine "Set ws = CreateObject(""wscript.Shell"")"
fhta.WriteLine "Temp = WS.ExpandEnvironmentStrings(""%Temp%"")"
fhta.WriteLine "Sub window_onload()"
fhta.WriteLine " CenterWindow 480,90"
fhta.WriteLine " Self.document.bgColor = ""1234568"" "
fhta.WriteLine " End Sub"
fhta.WriteLine " Sub CenterWindow(x,y)"
fhta.WriteLine " Dim iLeft,itop"
fhta.WriteLine " window.resizeTo x,y"
fhta.WriteLine " iLeft = window.screen.availWidth/2 - x/2"
fhta.WriteLine " itop = window.screen.availHeight/2 - y/2"
fhta.WriteLine " window.moveTo ileft,itop"
fhta.WriteLine "End Sub"
fhta.WriteLine "</script>"
fhta.close
End Sub
'**********************************************************************************************
Sub LancerProgressBar()
Set oExec = Ws.Exec("mshta.exe " & Temp & "\Barre.hta")
End Sub
'**********************************************************************************************
Sub FermerProgressBar()
oExec.Terminate
End Sub
'**********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************
While it isn't exactly what you've asked for, depending on your needs it may give you a usable result.
Go ahead and look at the code for the format of the cfg parameter.
var fileFinder = function (cfg) {
"use strict";
var debugMessages = false,
found = {};
function FileFinderException(value) {
var that = this;
this.value = value;
this.message = "fileFinder config error";
this.toString = function () {
return [that.value, that.message].join(" ");
};
}
if (cfg.Folder === undefined) {
throw new FileFinderException("Path Undefined");
}
if (cfg.filePattern === undefined) {
cfg.filePattern = ".*";
}
if (cfg.dirPattern === undefined) {
cfg.dirPattern = ".*";
}
if (cfg.directorySeparator === undefined) {
cfg.directorySeparator = "\\";
}
cfg.includeFiles = !!cfg.includeFiles;
cfg.includeFolders = !!cfg.includeFolders;
found.messages = [];
found.files = cfg.includeFiles ? [] : null;
found.folders = cfg.includeFolders ? [] : null;
function walkDirectoryTree(folder, folder_name) {
var subfolders = folder.SubFolders,
en,
subfolder;
function walkDirectoryFilter(items, re_pattern, list) {
var e = new Enumerator(items),
item;
while (!e.atEnd()) {
item = e.item();
if (item.name.match(re_pattern)) {
if (debugMessages) {
found.messages.push(item.name);
}
if (list) {
list.push(folder_name + cfg.directorySeparator + item.name);
}
}
e.moveNext();
}
}
if (debugMessages) {
found.messages.push("Files in " + folder_name + " matching '" + cfg.filePattern + "':");
}
walkDirectoryFilter(folder.files, cfg.filePattern, found.files);
if (debugMessages) {
found.messages.push("Folders in " + folder_name + " matching '" + cfg.dirPattern + "':");
}
walkDirectoryFilter(subfolders, cfg.dirPattern, found.folders);
en = new Enumerator(subfolders);
while (!en.atEnd()) {
subfolder = en.item();
walkDirectoryTree(subfolder, folder_name + cfg.directorySeparator + subfolder.name);
en.moveNext();
}
}
<html>
<head>
<title>Application Executer</title>
<HTA:APPLICATION ID="oMyApp"
APPLICATIONNAME="Application Executer"
WINDOWSTATE="normal">
<script type="text/javascript" language="javascript">
function RunFile() {
WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("explorer.exe \"search-ms://query=something\"", 1, false);
}
</script>
</head>
<body>
<input type="button" value="Windows Search" onclick="RunFile();"/>
</body>
</html>

Categories