Long polling: Max Pool size reached - mysql

I'm using long polling in my website to check for any new data in MySQL database and then updating the ui,
actually if the website is up for longer than +- one hour the website just broke up by giving the following error:
500 {"Message":"error connecting: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.","StackTrace":" at MySql.Data.MySqlClient.MySqlPool.GetConnection()\r\n at MySql.Data.MySqlClient.MySqlConnection.Open()\r\n at VisualReservation._Default.getSale() in C:\\Users\\imytyuk\\Documents\\Visual Studio 2017\\Projects\\VisualReservation\\VisualReservation\\Default.aspx.vb:line 109","ExceptionType":"MySql.Data.MySqlClient.MySqlException"}
So it seems that there are too many connections to the database and it just get broken..
Actually the error is thrown by the following method that is called from long polling
function getTavoli(data_tavoli, salaSelect, pooling) {
$.ajax({
type: "POST",
url: "Default.aspx/SetTavoli",
data: JSON.stringify({ data: moment(data_tavoli).format('YYYY-MM-DD') }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var ingiorno = $('#ingiorno').val();
var fngiorno = $('#fngiorno').val();
var insera = $('#insera').val();
var fnsera = $('#fnsera').val();
ingiorno = ingiorno.split(":")[0];
fngiorno = fngiorno.split(":")[0];
insera = insera.split(":")[0];
fnsera = fnsera.split(":")[0];
if ($('#titleTurni').attr('data-turno') == "giorno") {
Range = ingiorno * 4
Fine = (fngiorno * 4) + 1;
orainizio = ingiorno;
orafine = fngiorno;
} else {
Range = insera * 4
Fine = (fnsera * 4) + 1;
orainizio = insera;
orafine = fnsera;
}
data = r.d;
data = $.parseJSON(data);
if (pooling) {
if (JSON.stringify(data) === prevData) {
return;
} else {
recreateTabs();
prevData = JSON.stringify(data);
}
}
$('#listBodyMobile').empty();
$('#bodyGiorno').empty();
$('#bodySera').empty();
getInfo(data_tavoli);
$.each(data, function (i, item) {
// doing all stuff with items
});
});
},
error: function (xhr, status, errorThrow) {
console.log(xhr.status + " " + xhr.responseText);
}
});
}
The polling is called in the following way
poolingTav = setInterval(() => {
getTavoli(new Date($("#day").attr('data-giorno')), $("#titleSale").attr('data-numsala'), true);
}, 50000)
While the SetTavoli in the server side looks like the following
<WebMethod()>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Shared Function SetTavoli(ByVal data As String) As String
Dim con As MySqlConnection = New MySqlConnection
con.ConnectionString = "CONNSTRING"
DeleteSTB(con)
Dim strSql As String = "QUERY"
Dim dtb As New DataTable
con.Open()
Dim sqlCmd As New MySqlCommand(strSql, con)
Dim sqlDad As New MySqlDataAdapter(sqlCmd)
sqlDad.Fill(dtb)
con.Dispose()
dtb.Columns(0).ColumnName = "data"
dtb.Columns(1).ColumnName = "orain"
dtb.Columns(2).ColumnName = "oraout"
dtb.Columns(3).ColumnName = "numtav"
dtb.Columns(4).ColumnName = "numcop"
dtb.Columns(5).ColumnName = "email"
dtb.Columns(6).ColumnName = "tel"
dtb.Columns(7).ColumnName = "note"
dtb.Columns(8).ColumnName = "nome"
dtb.Columns(9).ColumnName = "id"
dtb.Columns(10).ColumnName = "stato"
Return Json(dtb)
End Function
So i was wondering what i'm doing wrong and how i could fix that issue still by using long polling...
To the website there will be connected lot of users with their own account and will be accessing their own databases..

Related

ajax and select element dropdown

hello guys please i have an issue with ajax i have this function that fetch data from jsp but when i add a new data to the database and call the function again it duplicates the data unless i refresh the page which i don't want users to do
<script>
search1();
function search1(){
$.ajax({
type:"GET",
url:"drop.jsp",
dataType:'JSON',
data:{"title":'title'},
success:function(data){
console.log(data);
for(var i = 0; i< data.length; i++){
$('#title').append($("<option/>",
{
text: data[i].area,
}));
}
},
error(err){
alert("error")
}
});
}
</script>
it fetch's data as i want but when i call that same function with another function it duplicate the dropdown data the second function is below
<script>
function title2(){
$.ajax({
type:"POST",
url:"drop.jsp",
data:{"title1":$("#title1").val()},
success:function(msg){
var obj = JSON.parse(msg);
search1();
},
error(err){
alertify.error('Error');
}
})
}
</script>
and the jsp code is
String title = request.getParameter("title");
String marital = request.getParameter("marital");
String minis = request.getParameter("minis");
String occu = request.getParameter("occu");
String job = request.getParameter("job");
String bs = request.getParameter("bs");
String class1 = request.getParameter("class1");
String course = request.getParameter("course");
JSONArray list =new JSONArray();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/cop","root","root");
Statement st = con.createStatement();
if(title != null){
String sql = "Select * from title";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
JSONObject obj = new JSONObject();
String area = rs.getString("title");
obj.put("area", area);
list.add(obj);
}
out.println(list.toJSONString());
out.flush();
}
and the output is in the image
the output

trying to upload Image in mvc web api project using jquery ajax only

I am trying to upload Image but upon running my application my Image parameter is passing null, and I don't know why it is not picking up the file I attached
but in my browser console when I check my image file object that if it is attached or not, it shows that it does attach
but in my controller its passing null
my ajax code where I am passing the image file object,
$('.empOfficialDetails').click(function (ev) {
ev.preventDefault();
var data = new Object();
data.UserName = $('#username').val();
data.UPassword = $('#userpass').val();
data.OfficialEmailAddress = $('#officialemail').val();
data.Departments = $('#departments :selected').text();
data.Designation = $('#designation :selected').text();
data.RoleID = $('#role').val();
data.Role = $('#role :selected').text();
data.ReportToID = $('#reportToID').val();
data.ReportTo = $('#reportTo :selected').text();
data.JoiningDate = $('#joindate').val();
data.IsAdmin = $('#isAdmin :selected').val() ? 1 : 0;
data.IsActive = $('#isActive :selected').val() ? 1 : 0;
data.IsPermanent = $('#isPermanent :selected').val() ? 1 : 0;
data.DateofPermanancy = $('#permanantdate').val();
data.HiredbyReference = $('#hiredbyRef :selected').val() ? 1 : 0;
data.HiredbyReferenceName = $('#refePersonName').val();
data.BasicSalary = $('#basicSalary').val();
data.CurrentPicURL = $('.picture')[0].files; //this is my image file object
//data.EmpID = $('.HiddenID').val();
if (data.UserName && data.UPassword && data.OfficialEmailAddress && data.Departments && data.Designation && data.Role && data.IsAdmin && data.IsPermanent) {
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(data),
enctype: 'multipart/form-data',
beforeSend: function () {
$("#dvRoomsLoader").show();
},
complete: function () {
$("#dvRoomsLoader").hide();
},
success: function (data) {
var ID = parseInt(data);
if (ID > 0) {
//var id = data;
$(".HiddenID").val(data);
//var id = $(".HiddenID").val();
$('#official').css('display', 'block');
$('#official').html("Employees Official details added successfully...!");
$('#official').fadeOut(25000);
$("#dvRoomsLoader").show();
$('.empOfficialDetails').html("Update <i class='fa fa-angle-right rotate-icon'></i>");
}
else {
$('#official').find("alert alert-success").addClass("alert alert-danger").remove("alert alert-success");
}
},
error: function (ex) {
alert("There was an error while submitting employee data");
alert('Error' + ex.responseXML);
alert('Error' + ex.responseText);
alert('Error' + ex.responseJSON);
alert('Error' + ex.readyState);
alert('Error' + ex.statusText);
}
});
}
return false;
});
but in controller on running the code it passes null
public void EmployeeImage(HttpPostedFileBase file)
{
var allowedExtensions = new[] { ".Jpg", ".png", ".jpg", "jpeg" };
var fileName = Path.GetFileName(file.FileName);
var ext = Path.GetExtension(file.FileName); //getting the extension(ex-.jpg)
byte[] bytes;
using (BinaryReader br = new BinaryReader(file.InputStream))
{
bytes = br.ReadBytes(file.ContentLength);
}
if (allowedExtensions.Contains(ext)) //check what type of extension
{
string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension
string myfile = name + "_" + ext; //appending the name with id
var path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/assets/img/profiles/employeeImages"), myfile); // store the file inside ~/project folder(Img)
file.SaveAs(path);
}
}
public int Emp_OfficialDetails(Employee emp)
{
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AmanraHRMS"].ConnectionString);
var con = DB.getDatabaseConnection();
SqlCommand com = new SqlCommand("sp_InsEmpOfficialDetails", con);
com.CommandType = CommandType.StoredProcedure;
#region Employee Official Details Insert Code block
com.Parameters.AddWithValue("#UserName", emp.UserName);
com.Parameters.AddWithValue("#pass", emp.UPassword);
com.Parameters.AddWithValue("#OfficialEmailAddress", emp.OfficialEmailAddress);
com.Parameters.AddWithValue("#Department", emp.Departments);
com.Parameters.AddWithValue("#Role", emp.Role);
com.Parameters.AddWithValue("#IsAdmin", Convert.ToBoolean(emp.IsAdmin));
com.Parameters.AddWithValue("#Designation", emp.Designation);
com.Parameters.AddWithValue("#ReportToID", emp.ReportToID);
com.Parameters.AddWithValue("#ReportTo", emp.ReportTo);
com.Parameters.AddWithValue("#JoiningDate", Convert.ToDateTime(emp.JoiningDate));
com.Parameters.AddWithValue("#IsPermanent", Convert.ToBoolean(emp.IsPermanent));
com.Parameters.AddWithValue("#DateofPermanancy", Convert.ToDateTime(emp.DateofPermanancy));
com.Parameters.AddWithValue("#IsActive", Convert.ToBoolean(emp.IsActive));
com.Parameters.AddWithValue("#HiredbyReference", Convert.ToBoolean(emp.HiredbyReference));
com.Parameters.AddWithValue("#HiredbyReferenceName", emp.HiredbyReferenceName);
com.Parameters.AddWithValue("#BasicSalary", emp.BasicSalary);
com.Parameters.AddWithValue("#CurrentPicURL", emp.CurrentPicURL);
#endregion
var file = emp.CurrentPicURL;
EmployeeImage(file);
var ID = com.ExecuteScalar();
com.Clone();
return Convert.ToInt32(ID);
}
and in my model class my Image datatype is as
public HttpPostedFileBase CurrentPicURL { get; set; }
I have no Idea what I am doing wrong If anyone who knows about this, your help is highly appreciated my friend
You can't use JSON.stringify to upload a file via AJAX. You need to use the FormData class.
Sending files using a FormData object | MDN
const data = new FormData();
data.append("UserName", $('#username').val());
data.append("UPassword", $('#userpass').val());
...
const file = $('.picture')[0].files[0];
data.append("CurrentPicURL", file, file.name);
...
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
data: data,
processData: false,
contentType: false,
beforeSend: function () {
...
NB: Unless you need to support Internet Explorer, you might want to use the Fetch API instead of AJAX. This can be much simpler, particularly when combined with async and await.

I cannot get the file with short-lived URL (downloadUrl) from Google Drive API

I have problem on getting files from downloadUrl provided from Google Drive API v2.
Here is the screenshot.
I have tried several websites and it still occurs. How can I fix it? Or is it a problem from Google?
20200312 Edit:
I am using Javascript for Google File Picker and it returns JSON for the picked file. Then I use Classic ASP to get the file to server and save.
Here is the code
Front-end
function initGooglePicker() {
var picker = new FilePicker({
apiKey: API_KEY,
clientId: CLIENT_ID,
buttonEl: document.getElementById('btnGoogleDrive'),
onSelect: function(file, access_token) {
var path, ext, filename;
if (file.downloadUrl) {
path = file.downloadUrl;
filename = file.title;
ext = filename.split('.').pop().toLowerCase();
}
else if (file.exportLinks) {
if (file['exportLinks']['application/pdf']) {
path = file['exportLinks']['application/pdf'] + "&exportFormat=pdf" ;
ext = "pdf";
filename = file.title + "." + ext;
}
}
$('#access_token').val(access_token);
},
onCancel: function() {}
});
}
Back-end
Function UploadGoogleDriveFile(fromPath, toPath, accessToken)
Dim retVal
retVal = "0"
Dim objXML
Set objXML = Server.CreateObject("MSXML2.ServerXMLHTTP")
objXML.Open "GET", fromPath, False
objXml.SetRequestHeader "Authorization", "Bearer " & accessToken
objXML.Send
If objXML.readystate = 4 Then
Response.Write(objXML.status & "<br>")
Response.Write(objXML.responseBody)
Response.End
End If
If objXML.readystate = 4 And objXML.status = 200 Then
If Len(objXML.responseText) > acct_cv_file_size Then
retVal = "2"
Else
CreateFolderBeforeUpload(toPath)
Set objStream = Server.createobject("Adodb.Stream")
objStream.Type = 1
objStream.Open
objStream.Write objXML.responseBody
objStream.SaveToFile toPath, 2
objStream.Close
Set objStream = Nothing
retVal = "1"
End If
End If
Set objXML = Nothing
UploadGoogleDriveFile = retVal
End Function
If you want to download a file using the Drive API V2 and setting the access token in the header, you have to do it by calling this url:
https://www.googleapis.com/drive/v2/files/[file-Id]?alt=media
As it's told in the Response section in the Files: get endpoint. It's really important the url parameter alt=media in order to make it work.
I've used this code before (works for me), which I found on Issue Tracker, in that way you can have another approach, too.
//fileurl - https://www.googleapis.com/drive/v2/files/[file-Id]?alt=media
//accessToken - client's accessToken
//filepath - location to store the downloaded file
public void downloadGdriveFileThroughWebRequest(string fileurl, string filepath, string accessToken)
{
HttpWebRequest rq = (HttpWebRequest)WebRequest.Create(fileurl);
rq.Method = "GET";
rq.PreAuthenticate = true;
rq.Headers.Add("Authorization", "Bearer " + accessToken);
try {
HttpWebResponse resp = (HttpWebResponse)rq.GetResponse();
using (Stream output = File.OpenWrite(filepath))
{
using (Stream s = resp.GetResponseStream())
{
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
reader.ReadLine();
Console.WriteLine(reader.ReadToEnd());
}
}
}

ASPNET LocalStorage Json Deserialization

I work on an application in online mode / disconnected and an example found on the book HTML5 Programming for ASPNET developers .
I use the ASPNET technologies MVC5 .
I have an error when I deserialize Data in my controller:
public JsonResult SaveResults()
{
string jsonData = string.Empty;
using (StreamReader sr = new StreamReader(Request.InputStream))
{
jsonData = sr.ReadToEnd();
}
Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);
SurveyDbEntities db = new SurveyDbEntities();
User usr = new User();
usr.FirstName = data["FirstName"];
usr.LastName = data["LastName"];
usr.Email = data["Email"];
db.Users.AddObject(usr);
db.SaveChanges();
string userEmail = data["Email"];
int usrId = (from item in db.Users
where item.Email == userEmail
select item.UserID).SingleOrDefault();
data.Remove("FirstName");
data.Remove("LastName");
data.Remove("Email");
foreach (string str in data.Keys)
{
int choiceId = int.Parse(str);
int questionId = int.Parse(data[str]);
Result result = new Result();
result.QuestionID = questionId;
result.ChoiceID = choiceId;
result.UserID = usrId;
db.Results.AddObject(result);
}
db.SaveChanges();
return Json("success");
}
This line shows the error
Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);
My jsonData ( Quote problem ? ) :
{"Email":"test#aol.fr","FirstName":"test","LastName":"test","container":"<div data-questions-questionid="1" class="paddedDiv">Which programming language do you use?<br><input type="checkbox" data-choices-questionid="1" data-choices-choiceid="1"><span>C#</span><br><input type="checkbox" data-choices-questionid="1" data-choices-choiceid="2"><span>VB.NET</span><br><input type="checkbox" data-choices-questionid="1" data-choices-choiceid="3"><span>PHP</span></div><div data-questions-questionid="2" class="paddedDiv">Which of the following browsers do you use while developing websites?<br><input type="checkbox" data-choices-questionid="2" data-choices-choiceid="4"><span>IE9</span><br><input type="checkbox" data-choices-questionid="2" data-choices-choiceid="5"><span>Firefox</span><br><input type="checkbox" data-choices-questionid="2" data-choices-choiceid="6"><span>Chrome</span></div><div data-questions-questionid="3" class="paddedDiv">Which of the following tools do you use?<br><input type="checkbox" data-choices-questionid="3" data-choices-choiceid="7"><span>Visual Studio</span><br><input type="checkbox" data-choices-questionid="3" data-choices-choiceid="8"><span>Web Matrix</span><br><input type="checkbox" data-choices-questionid="3" data-choices-choiceid="9"><span>Expression Web</span></div>"}
Then error :
{"After parsing a value an unexpected character was encountered: 1. Path 'container', line 1, position 105."}
Any idea where is the problem ?
Javascript SubmitData
function SubmitData(event) {
var data = '';
for (var i = 0; i < storage.length; i++) {
var key = storage.key(i);
var value = storage[key];
var pair = '"' + key + '":"' + value + '"';
data = data + pair + ",";
}
if (data.charAt(data.length - 1) == ',') {
data = data.substring(0, data.length - 1)
}
data = '{' + data + '}';
$.ajax({
type: "POST",
url: "/Home/SaveResults",
contentType: "application/json; charset=utf-8",
data: data,
dataType: "json",
success: function(results){
alert('Results saved!');
window.localStorage.clear();
},
error: function (err) {
alert(err.status + " - " + err.statusText);
}
})
}
Have a look at your JSON data:
"container":"<div data-questions-questionid="1
the value of property 'container' ends right before the '1'
So yes.. it's an encoding error even I don't know if there are other issues as well.

how to pagination JSONResult in MVC with ajax url data loading?

I have a problem in pagination with a json result data in MVC.
Below code is my ajax data loading:
jQuery.ajax({
url: "/Products/Search",
type: "POST",
dataType: "json",
success: function (data) {
displayData(data);
},
error: function (errdata, errdata1, errdata2) { $('#ProductList').html("Error in connect to server" + errdata.responseText); }
and my controller JsonResult is below:
public JsonResult List()
{
tbl = db.tblProducts;
return Json(tbl, JsonRequestBehavior.AllowGet);
}
I can recive data from above ajax data loading successfully, but I can't pagination it.
Please help me.
Thank you.
There is no code for Pagination,Do you want to do client side pagination or server side
Thinking your devloping an ASP.Net MVC application
Server side pagnation : You can load the specific number of records alone.
Using Skip and Take functionlitys
public JsonResult GetOrders(int pagesize, int pagenum)
{
var query = Request.QueryString;
var dbResult = db.Database.SqlQuery<Order>(this.BuildQuery(query));
var orders = from order in dbResult
select new Order
{
ShippedDate = order.ShippedDate,
ShipName = order.ShipName,
ShipAddress = order.ShipAddress,
ShipCity = order.ShipCity,
ShipCountry = order.ShipCountry
};
var total = dbResult.Count();
orders = orders.Skip(pagesize * pagenum).Take(pagesize);
var result = new
{
TotalRows = total,
Rows = orders
};
return Json(result, JsonRequestBehavior.AllowGet);
}
Client side pagination : Load the entire records to your view from there implement pagination
Sample code : http://jsfiddle.net/rniemeyer/5xr2x/
Database db = new Database();
public int PageSize = 5;
public int VisiblePageCount = 5;
public JsonResult Search(int page = 1)
{
var model = new ModelName();
var tbl = db.tblProducts;
var renderedScheduleItems =(tbl.Skip((page - 1) * PageSize)
.Take(PageSize)
.ToList());
model.Products = renderedScheduleItems;
model.PagingDetail = new PagingDetail()
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = items.Count,
VisiblePageCount = VisiblePageCount
};
return Json(model, JsonRequestBehavior.AllowGet);
}