Connecting Unity with SQL server - android

He everyone I have problem with connect to sql server in android type phone i will summit code that code is working in windows application but when i build to android its give error I need and hope to help me for solve this issue thank u
This is Error when I build to android apk:
and this is code the which is working in windowns app:
#pragma strict
import System;
import System.Data;
import System.Data.SqlClient;
var dbcon : IDbConnection;
var connectionString : String;
function Start () {
connectionString = "Server=dbdatabase.mssql.somee.com; Database=dbdatabase;User ID=dbdatabase_SQLLogin_1; Password=1j8uc1yyja";
}
function Update () {
}
var user :String="";
var pas :String="";
function OnGUI()
{
GUI.Label(new Rect(150, 130, 100, 100), "Name :");
GUI.Label(new Rect(150, 160, 120, 120), "Pass :");
user = GUI.TextField(new Rect(200, 130, 100, 20), user);
pas=GUI.TextField(new Rect(200,160,100,20),pas);
if (GUI.Button(Rect(200,190,100,50),"Login"))
{
dbcon = new SqlConnection(connectionString);
dbcon.Open();
var dbcmd : IDbCommand = dbcon.CreateCommand();
var cmdSql : String = "SELECT name FROM setting WHERE name='"+user+"' and pass='"+pas+"'";
dbcmd.CommandText = cmdSql;
var reader : IDataReader = dbcmd.ExecuteReader();
while(reader .Read()) {
var nm : String = reader ["name"].ToString();
print ("OK "+nm);
}
reader .Close();
reader = null;
dbcon.Close();
dbcon = null;
}
}

Related

How to convert incoming excel file to JSON in Ionic 6

I am using xlsx library to convert input excel file into JSON and it works fine but when I test on android it won't trigger reader.onload function. Please suggest to me what's the correct library to use for android or what to need to change
const reader: FileReader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = (e: any) => {
console.log(e)
const binarystr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(binarystr, { type: 'binary' });
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
const data = XLSX.utils.sheet_to_json(ws);
console.log(data);
this.fileData = data;
};
It doesn't print console.log(e), I've tried try-catch to catch the error but it didn't catch the error as well. Please let me know what's the issue and which library is best for Android as well as IOS
I solved it. Please see the code below, hope it will help someone
incomingfile(event){
this.file= event.target.files[0];
this.readXLSX(this.file);
}
readXLSX(file){
let fileReader = this.getFileReader(file);
fileReader.onload = (e: any) => {
/* create workbook */
const binarystr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(binarystr, { type: 'binary' });
/* selected the first sheet */
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
/* save data */
const data = XLSX.utils.sheet_to_json(ws); // to get 2d array pass 2nd parameter as object {header: 1}
console.log(data); // Data will be logged in array format containing objects
this.zone.run(() => {
this.fileData = data;
});
};
}
getFileReader(file): FileReader {
const fileReader = new FileReader();
fileReader.readAsBinaryString(file);
const zoneOriginalInstance = (fileReader as any)["__zone_symbol__originalInstance"];
return zoneOriginalInstance || fileReader;
}

Xamarin Forms upload image Laravel POST Request failed

If I upload over Insomnia an image to my Laravel application everything is ok and I get following log
[2020-03-04 05:26:39] local.DEBUG: array (
'image' =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => 'Screenshot_1583210368.png',
'mimeType' => 'image/png',
'error' => 0,
'hashName' => NULL,
)),
)
But if I upload an image on android emulator the log file in Laravel looks like (1000+ lines) :
�"#�G����ޠ��U��H��I�G"Ĉ`.SB^G
This is my Xamarin Function :
public async Task<string> uploadImage(Stream stream)
{
using (var client = new HttpClient())
{
var content = new MultipartFormDataContent();
content.Add(new StreamContent(stream),"image");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", (Application.Current.Properties["access_token"].ToString()));
var result = await client.PostAsync("https://example.com/api/upload/image", content);
return "";
}
}
Example of uploading a image to server side in Xamarin:
private MediaFile _image;
// code here to assign image to _image
var content = new MultipartFormDataContent();
content.Add(new StreamContent(_image.GetStream()), "\"file\"", $"\"{_image.Path}\"");
var httpClient = new System.Net.Http.HttpClient();
var url = "http://upload.here.io/folder/subdir";
var responseMsg = await httpClient.PostAsync(url, content);
var remotePath = await responseMsg.Content.ReadAsStringAsync();

Fetching Data in Google SpreadSheets

I have a problem with this reference From this Site Using Google SpreadSheet as Database. the problem is that. the Android Application cannot fetch the data in a google spreadsheet. The Application can successfully run but couldn't find data in the Spreadsheet.
I Already Updated the codes from the android studio because of the old version used codes. I just copy and paste it and change some of it.
Codes Below:
The Script Link to fetch the Data :
https://script.google.com/macros/s/AKfycbwZJCWoQ7dpC5KwyRM9JYsjCjymQUspAfPmniOApD_CSEoc-LdP/exec?id=16O_OfgKxASgqa2WWQKePJI1jnJMTdb4OyXbUJU6kWH0&sheet=Sheet1
Link of the SpreadSheet :
https://docs.google.com/spreadsheets/d/16O_OfgKxASgqa2WWQKePJI1jnJMTdb4OyXbUJU6kWH0/edit#gid=0
This is the App Script that Fetches the data:
you can also see the app script codes here : App Script Codes.
function doGet(request) {
var output = ContentService.createTextOutput(),
data = {},
id = request.parameters.id,
sheet = request.parameters.sheet,
ss = SpreadsheetApp.openById(id);
data.records = readData_(ss, sheet);
var callback = request.parameters.callback;
if (callback === undefined) {
output.setContent(JSON.stringify(data));
} else {
output.setContent(callback + "(" + JSON.stringify(data) + ")");
}
output.setMimeType(ContentService.MimeType.JSON);
return output;
}
function readData_(ss, sheetname, properties) {
if (typeof properties == "undefined") {
properties = getHeaderRow_(ss, sheetname);
properties = properties.map(function(p) { return p.replace(/\s+/g, '_'); });
}
var rows = getDataRows_(ss, sheetname),
data = [];
for (var r = 0, l = rows.length; r < l; r++) {
var row = rows[r],
record = {};
for (var p in properties) {
record[properties[p]] = row[p];
}
data.push(record);
}
return data;
}
function getDataRows_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
}
function getHeaderRow_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0];
}
More Codes From the Link Above or click here for not scrolling back.

Broken image being displayed when using the image path returned from cordovacapture captureimage

I have tried various solutions: $cordovaCapture, $cordovaCamera(DATA_URL can display the picture, but i want file_URI to do the same).
here is my code snippet:
$scope.addImage = function() {
var options = {limit: 1};
$cordovaCapture.captureImage(options).then(function(imageData) {
console.log(imageData);
// var jsonobj=angular.toJson(imageData);
$scope.profile.image = imageData[0];
console.log(angular.toJson(imageData));
console.log($scope.profile.image.localURL);//the path to upload
document.getElementById('myImage').src = "'"+$scope.profile.image.localURL+"'";//have already tried without the quottes
/* window.plugins.Base64.encodeFile($scope.profile.image.localURL,function(base64){ // Encode URI to Base64 needed for contacts plugin
$scope.profile.image.preview = base64;
console.log($scope.profile.image.preview);
});*/
// Success! Image data is here
}, function(err) {
});
i even tried whitelisting certainties in the module as in :
.config( [
'$compileProvider',
function( $compileProvider )
{
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|file|content|blob|cdvfile):|data:image\//);
}
])
It didn't help either. I am testing the project in both device and emulator. I even tried base64 encoding the file from the path. Nothing works as to display the recently taken picture. The path that i retrieve is like this:
cdvfile://localhost/persistent/DCIM/Camera/123123123.jpg
Instead of using file_URI to upload the image. I used data_URL,converted the image to blob and used the cordova-file-transfer plugin to upload the file to the server. In that way, i could use the base64 encoded image on the html side as well as upload at the same time.
$scope.captureImage = function() {
navigator.camera.getPicture(cameraSuccess, cameraError, {
destinationType: Camera.DestinationType.DATA_URL,
correctOrientation: true
});
}
var cameraSuccess = function(imageData) {
$scope.profileImageSource = imageData;
$scope.changeImage = function(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 512;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, {
type: contentType
});
}
$scope.picture = $scope.changeImage(imageData, 'image/png');
$scope.$digest();
}
HTML:
<img ng-src="data:image/gif;base64,{{profileImageSource}}">

How to upload FILE_URI using Google Drive API: Insert File

On Android, I'm trying to upload the output from Cordova/Phonegap getPicture() using Google Drive API: Insert File. Is there a way to do this using the FILE_URI instead of DATA_URL (base64)?
I tried Camera.DestinationType.DATA_URL first, but it didn't return Base64 data like it was supposed to, it just returned the same thing as FILE_URI. So now I'm trying to figure out how to pass FILE_URI to Google Drive Insert File (which takes Base64). Is there a way to convert FILE_URI to Base64?
Cordova code:
navigator.camera.getPicture(onSuccess, onFail,
{ quality: 50, destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
// need to do something like this:
var fileData = ConvertToBase64(imageURI);
insertFile(fileData);
}
Google Drive code:
/**
* Insert new file.
*
* #param {File} fileData File object to read data from.
* #param {Function} callback Function to call when the request is complete.
*/
function insertFile(fileData, callback) {
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var reader = new FileReader();
reader.readAsBinaryString(fileData);
reader.onload = function(e) {
var contentType = fileData.type || 'application/octet-stream';
var metadata = {
'title': fileData.fileName,
'mimeType': contentType
};
var base64Data = btoa(reader.result);
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files',
'method': 'POST',
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody});
if (!callback) {
callback = function(file) {
console.log(file)
};
}
request.execute(callback);
}
}
I realize this is a bit old - but it now looks like you can use a FileReader in phoneGap.
I haven't tested this yet, but something like this should also work, without the canvas hack.
[EDIT - tested and revised the code below. works for me :D ]
var cfn = function(x) { console.log(x) };
var cameraOps = { quality: 50, destinationType: Camera.DestinationType.FILE_URI };
navigator.camera.getPicture(function(imagePath) {
window.resolveLocalFileSystemURL(imagePath, function(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("read success!!!");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
}, cfn);
}, cfn);
}, cfn);
Yes you can....
Specify Destination Type as FILE_URI itself and in imagedata you will be getting the images file uri place it in a image tag and then place it inside HTML5 canvas and canvas has one method called toDataURL where you will be able to get the base64 of the corresponding image.
function onSuccess(imageData)
{
var $img = $('<img/>');
$img.attr('src', imageData);
$img.css({position: 'absolute', left: '0px', top: '-999999em', maxWidth: 'none', width: 'auto', height: 'auto'});
$img.bind('load', function()
{
var canvas = document.createElement("canvas");
canvas.width = $img.width();
canvas.height = $img.height();
var ctx = canvas.getContext('2d');
ctx.drawImage($img[0], 0, 0);
var dataUri = canvas.toDataURL('image/png');
});
$img.bind('error', function()
{
console.log('Couldnt convert photo to data URI');
});
}
Thanks to Arun for pointing me in the right direction. I ended up using this javascript function, which was based off http://jsfiddle.net/jasdeepkhalsa/L5HmW/
function getBase64Image(imgElem) {
// imgElem must be on the same server otherwise a cross-origin error will be thrown "SECURITY_ERR: DOM Exception 18"
var canvas = document.createElement("canvas");
canvas.width = imgElem.clientWidth;
canvas.height = imgElem.clientHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(imgElem, 0, 0);
var dataURL = canvas.toDataURL("image/jpeg");
dataURL = dataURL.replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
return dataURL;
}

Categories

Resources