Google Sheet Connection to SQL Server - javascript

I am hoping that someone can help me with this connection issue, I am trying to connect a Google Sheet to a SQL Server 2014 database and pull the data via a View.
Below is a piece of code that I have taken from the :-
https://learn.microsoft.com/en-us/sql/connect/jdbc/connection-url-sample
import java.sql.*;
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;user=UserName;password=*****";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT TOP 10 * FROM Person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
I have amended the connection string with the relevant SQL connection username and password but I am getting the following error :-
Missing ; before statement. (line 1, file "Code")Dismiss
I am very new to this so please if possible keep the answers as simple as possible.
Thanks PD
After some time I cut down the original code and it looks a lot more like what I am after but still having some connection issues, can anyone see what the error might be
// Read up to 1000 rows of data from the table and log them.
function readFromTable() {
var conn = Jdbc.getConnection("jdbc:sqlserver://IP ADDRESS:1433;databaseName=name;user=user;password=password");
var start = new Date();
var stmt = conn.createStatement();
stmt.setMaxRows(1000);
var results = stmt.executeQuery('SELECT * FROM table');
var numCols = results.getMetaData().getColumnCount();
while (results.next()) {
var rowString = '';
for (var col = 0; col < numCols; col++) {
rowString += results.getString(col + 1) + '\t';
}
Logger.log(rowString)
}
results.close();
stmt.close();
var end = new Date();
Logger.log('Time elapsed: %sms', end - start);
}

Related

Detect the end of download stream on browser with jquery function

I have implemented a function in an .NET application to download a large number of files using a stream with an undefined initial length.
I need to capture, on the browser, when the stream ends to show an alert to the user but I have difficulty understanding how to solve or which workaround to use.
This is my function:
private void OutputStreamZipped(Page page)
{
page.Response.ContentType = "application/zip";
page.Response.AddHeader("content-disposition", "attachment" + ";filename=" + "myFileName.zip");
page.Response.AddHeader("Accept-Ranges", "bytes");
page.Response.AddHeader("Expires", "0");
page.Response.AddHeader("Pragma", "cache");
page.Response.AddHeader("Cache-Control", "private");
page.Response.Buffer = false;
page.Response.BufferOutput = false;
byte[] buffer = new byte[2 * 1024 * 1024];
try
{
using (ZipOutputStream zipOutputStream = new ZipOutputStream(Response.OutputStream))
{
zipOutputStream.SetLevel(3);
DirectoryInfo DI = new DirectoryInfo(#"C:\myFolder");
foreach (var i in DI.GetFiles())
{
Stream fs = File.OpenRead(i.FullName);
ZipEntry zipEntry = new ZipEntry(ZipEntry.CleanName(i.Name));
zipEntry.Size = fs.Length;
zipOutputStream.PutNextEntry(zipEntry);
int count = fs.Read(buffer, 0, buffer.Length);
while (count > 0)
{
zipOutputStream.Write(buffer, 0, count);
count = fs.Read(buffer, 0, buffer.Length);
if (!Response.IsClientConnected)
{
break;
}
Response.Flush();
}
fs.Close();
}
zipOutputStream.Close();
}
Response.Flush();
page.Response.SuppressContent = true;
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception)
{
throw;
}
}
Thanks to anyone who can give me a tip

I want to print to pdf file in javascript, where outputstream and pdfwriter

I am trying to create a PDF from a server-side controller (report) (ireport) with ajax (and so on), and try to return the data to pdfwriter, servletoutputstream, and httpservletresponse. (I do not know exactly what I'm doing, but I'm doing it this way).
The original purpose was to send a server-side pdf file to the client, find the printer and print without a preview window.
Among them, I wrote 'application / pdf' on the server side and 'datetype: text' on the client side ajax (there is an error if I do not use ajax datatype: text)
If you print the results to the console, they will only be listed as unknown code.
Currently I am trying to put it into an iframe frame.
Question!
1. What should I do to use the text string sent to server -> client as pdf or script code?
(I have already asked you two weeks ago)
2. How do I send a pdf to server -> client? I would like to apply it to the screen by expressing it directly in code instead of downloading it. To print out.
ENG)>
// I used ajax only, because I dont know any other way
$.ajax({
url : "url",
data : JSON.stringify(data),
dataType : "text",
type: "POST",
contentType: 'application/json; charset=utf-8',
async : false,
success: function(result){
// I want to view PDF contents and directly print to PDF.
}
})
public Params createIbExItemLabelReport(HttpServletRequest resq, HttpSession session, Params inParams, HttpServletResponse resp) throws Exception{
Params outParams = ParamsFactory.createParams(inParams);
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Expires", "0");
List<DataRow> list = new ArrayList<DataRow>();
String reportCd = "15";
String fileName = "ibExItemLabel"+reportCd+"Report";
String nullJpgFile = "";
int flag = 0;
int nullCheck = 0;
for(DataRow dr : inParams.getDataTable("dt_data")){
String imgName = "c:\\WMS\\LABEL\\FIAC021_" +reportCd + ".jpg";
File f = new File(imgName);
if (!f.isFile()) {
flag = 1;
if(nullCheck != 0){
nullJpgFile += ", ";
}
nullJpgFile += "FIAC021";
nullCheck++;
continue;
}
String bacodeCd = "FIAC02120180416001";
dr.setParam("imgName", imgName);
dr.setParam("bacodeCd", bacodeCd);
list.add(dr);
}
if(flag == 1){
outParams.setParam("ERROR_FILE", "제품코드 ["+nullJpgFile+"]의 라벨 사이즈" + reportCd + "인 파일이 존재하지않습니다.");
return outParams;
}
String appPath = session.getServletContext().getRealPath("/");
String pdfPath = null;
List<DataRow> list2 = new ArrayList<DataRow>();
for(int i = 0; i < list.size(); i++){
for(int j = 0; j < list.get(i).getInt("printQty"); j++){
list2.add(list.get(i));
}
}
Report report = new Report();
pdfPath = report.reportToPdf(session, list2, fileName);
outParams.setParam("fileName", pdfPath);
System.out.println("Found! FileName is ' : "+ pdfPath);
pdfPath = appPath + pdfPath;
pdfPath = pdfPath.replace("//", "/");
ServletOutputStream servletOutput = resp.getOutputStream();
PdfWriter pdfWriter = null;
StringBuffer pdfJs = null;
ByteArrayOutputStream pdfOutput = null;
InputStream pdfInput = null;
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
pdfOutput = convertPDFToByteArrayOutputStream(pdfPath);
int printCopy = 1;
if (printCopy == 0) {
printCopy = 1;
}
if (printCopy > 1) {
PdfCopyFields pdfPrintCopy = new PdfCopyFields(pdfOutput);
for (int i = 0; i < printCopy; i++) {
pdfPrintCopy.addDocument(new PdfReader(outputToInputStream(pdfOutput)));
}
pdfPrintCopy.close();
}
pdfInput = outputToInputStream(pdfOutput);
pdfReader = new PdfReader(pdfInput);
pdfStamper = new PdfStamper(pdfReader, servletOutput);
pdfWriter = pdfStamper.getWriter();
String printerNm = "SINDOH D410 Series PCL";
pdfWriter.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar | PdfWriter.HideWindowUI);
pdfJs = new StringBuffer();
pdfJs.append("var param=this.getPrintParams();\r");
pdfJs.append("param.printerName=\"").append(printerNm).append("\";\r");
pdfJs.append("param.interactive=param.constants.interactionLevel.silent;\r");
pdfJs.append("param.pageHandling=param.constants.handling.shrink;\r");
pdfJs.append("this.print(param);\r");
pdfJs.append("this.closeDoc();");
pdfWriter.addJavaScript(pdfJs.toString(), false);
servletOutput.flush();
Log.debug("servletOutput " );
if (pdfInput != null) {
try {
pdfInput.close();
} catch (Exception e) {
}
pdfInput = null;
}
if (pdfOutput != null) {
try {
pdfOutput.close();
} catch (Exception e) {
}
pdfOutput = null;
}
if (pdfReader != null) {
pdfReader.close();
pdfReader = null;
}
pdfWriter = null;
try {
if (pdfStamper != null) {
pdfStamper.close();
pdfStamper = null;
}
} catch (Exception e) {
}
resp.setHeader("Content-Disposition", "inline; filename="+pdfPath);
resp.setHeader("Content-Type", "application/pdf; charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
Log.debug("before outParams " );
return outParams;
}
private InputStream outputToInputStream(ByteArrayOutputStream source) {
return new ByteArrayInputStream(source.toByteArray());
}
private static ByteArrayOutputStream convertPDFToByteArrayOutputStream(String FilePath) {
InputStream inputStream = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
inputStream = new FileInputStream(new File(FilePath));
byte[] buffer = new byte[1024];
baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return baos;
}
please answer my question

How to scan open port of client machine using local IP address in C# in MVC?

I am developing a web application in MVC. When user log in to website I am getting local IP address of user. But now what I want to do is scan list of open ports of client local machine.
Is there any way to implement this in JavaScript or jQuery or C# in MVC?
public void btnPing_Click(object sender, EventArgs e)
{
try
{
int intCount = 0;
int maxip = 0;
richTmp.Clear();
string strIP = null;
string machineName = string.Empty;
List<string> strListIp = new List<string>();
List<string> txtBuffrFile = new List<string>();
BufferdIp = new List<string>();
for (int i = 1; i <= 30; i++)
{
System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
lstDetails.Items.Add("System Found: " + maxip);
System.Net.NetworkInformation.PingReply rep = p.Send("192.168.1." + i,500);
if (rep.Status == System.Net.NetworkInformation.IPStatus.Success)
{
intCount++;
lstDetails.Items.Clear();
lstDetails.Items.Add("Loading...Total(" + maxip+")");
strIP = rep.Address.ToString();
machineName = GetMachineNameFromIPAddress(strIP);
if (machineName == string.Empty || machineName == null)
{
strListIp.Add(strIP + ":-" + "Offline");
BufferdIp.Add("0");
}
else
{
strListIp.Add(strIP + ":-" + machineName+"(Online)");
BufferdIp.Add(strIP);
txtBuffrFile.Add(strIP);
maxip++;
}
}
}
lstDetails.Items.Clear();
foreach (var IDAddres in strListIp)
{
lstDetails.Items.Add(IDAddres);
}
for (int i = 0; i != txtBuffrFile.Count;i++ )
{
richTmp.Text += txtBuffrFile.ElementAt(i) + "\n";
}
if (MessageBox.Show("Do you want to Save This Search", "Save Dialog", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == (DialogResult.Yes))
{
if(File.Exists (path))
File.Delete(path);
FileStream stream = File.Create(path);
stream.Close();
File.WriteAllText(path, richTmp.Text, Encoding.UTF8);
}
btnConnct.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I use this to ping in my LAN area but problem is this works only when you know IP pattern and Range :(

How to convert datatable to json string in c#

Its work perfect when data in the datatable is small i.e 10 columns and 300 rows. But when the amount of data in datatable is large it did not work.
Here is my code
[WebMethod]
public static string getData()
{
string _cs = "";
string _query = "";
OleDbConnection _conn = new OleDbConnection();
OleDbCommand _cmd = new OleDbCommand();
OleDbDataAdapter _da = new OleDbDataAdapter();
DataTable _dt = new DataTable();
try
{
_cs = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _path + ";Extended Properties= \"Excel 8.0;HDR=Yes;IMEX=1\";";
//_query = "SELECT * FROM [3123121288$A1:L290]"; work perfect
_query = "SELECT * FROM [3123121288$]"; //did not work
_conn.ConnectionString = _cs;
_cmd.Connection = _conn;
_cmd.CommandText = _query;
_da.SelectCommand = _cmd;
_da.Fill(_dt);
}
catch (Exception ex)
{ }
return JsonConvert.SerializeObject(_dt);
}

The SmartSource Data collector JavaScript Tag, could be inserted from Java?

I'm totally new in Webtrends, I have read that The SmartSource Data collector JavaScript Tag, could be inserted from Java or HTML. does anyone know how to inser it from Java, I found the below class, is this class does the job? please provide some samples. Thanks in advance
public class DC {
public DC() {
super();
}
public String post_url(String connUrl, Map<String, String> bodyref) {
String response = "";
String responseCode = "";
try {
HttpURLConnection conn = null;
// construct data
String data = "";
Iterator<String> i = bodyref.keySet().iterator();
boolean ampersand = false;
while (i.hasNext()) {
if (ampersand) {
data += "&";
} else {
ampersand = true;
}
String b = i.next();
data += b + "=" + bodyref.get(b);
}
System.out.println();
System.out.println("[Request]");
System.out.println("(Url)");
System.out.println(connUrl);
System.out.println("(Body)");
System.out.println(data);
// send data
URL url = new URL(connUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
try {
// get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response += line;
response += "\n";
}
rd.close();
} catch (IOException e1) {
if (conn != null) {
// get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String line;
while ((line = rd.readLine()) != null) {
response += line;
response += "\n";
}
}
}
System.out.println();
System.out.println("[Response]");
System.out.println("(Status)");
System.out.printf("%s %s\n", conn.getResponseCode(), conn.getResponseMessage());
System.out.println("(Message)");
System.out.println(conn.getResponseMessage());
System.out.println("(Body)");
System.out.println(response);
System.out.flush();
wr.close();
} catch (Exception e) {
System.out.println();
System.out.println("[Response]");
System.out.println("(Status)");
System.out.println(e.toString());
System.out.println("(Message)");
System.out.println(e.getMessage());
System.out.flush();
}
return response;
}
public static void main(String[] args) {
DC dc = new DC();
// customer-specific DCSID
String dcsid = "dcslbiart00000gwngvpqkrcn_2u3z";
// base portion of DC API url
String base_url = "http://dc.webtrends.com/v1/" + dcsid;
// post body
Map<String, String> body1 = new HashMap();
// post query string
String querystring = "";
// compose urls
String id_url = base_url + "/ids.svc" + querystring;
String event_url = base_url + "/events.svc" + querystring;
// get visitor identifier
String id = dc.post_url(id_url, body1);
// post body
Map<String, String> body = new HashMap();
// initialize post body
body.put("dcsuri", "/MyJavaTest");
body.put("dcssip", "localhost");
body.put("WT.ti", "MyJavaTest");
body.put("WT.co_f", id);
body.put("dcsverbose", "true");
// submit event data
dc.post_url(event_url, body);
}

Categories

Resources