retrieve data from c# linq object to json to html - asp.net-mvc-3

Retrieve code from json.
C#code:-
var collection = getsortcat.Select(x => new
{
idterm = x.IDTerm,
mvo = x.MVO,
pic = x.Pic,
said = x.SAid,
termactive = x.TermActive,
vid = x.Vid,
fvo = x.FVO,
eterm = x.ETerm,
edef = x.EDef,
buse = x.BUse,
bterm = x.BTerm,
idcat = x.TermCat,
items = x.TermCategory1.IDCat,
catname = x.TermCategory1.TermCategory1
});
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(collection);
return Json(output, JsonRequestBehavior.AllowGet);
Javascript Code:-
success: function (e) {
var txt = "'{ data :" + e + "}'";
var obj = eval("(" + txt + ")");
$('#pdata').append(obj.data[0]);
},
Not getting output. Please give me solution how to retrieve data from c# linq object to json to html?

First fix your controller action to get rid of any JavaScriptSerializers and manual plumbing code. Directly return the collection to the Json result:
var collection = getsortcat.Select(x => new
{
idterm = x.IDTerm,
mvo = x.MVO,
pic = x.Pic,
said = x.SAid,
termactive = x.TermActive,
vid = x.Vid,
fvo = x.FVO,
eterm = x.ETerm,
edef = x.EDef,
buse = x.BUse,
bterm = x.BTerm,
idcat = x.TermCat,
items = x.TermCategory1.IDCat,
catname = x.TermCategory1.TermCategory1
});
return Json(collection, JsonRequestBehavior.AllowGet);
Now inside the success callback the e parameter already represents an array of objects that were parsed. You don't need to call any eval. Directly access the elements (by index) and then the properties:
success: function (e) {
var txt = e[0].mvo;
},
you could also loop through the elements:
success: function (e) {
for (var i = 0; i < e.length; i++) {
var element = e[i];
alert(element.idterm);
}
},

Related

How to upload a image to Google Drive Shared folder and get its sharable URL?

currently I have a working Arduino App that takes a picture, uploads it to a Goggle Drive folder (already made public) and stores some related data on a Google Sheet including the image file name.
But I need to access this data and image from a web app running somewhere else.
The image name "filename.jpg" will not work as part of an URL.
In my current solution two scripts are used:
The first successfully transfers the image.
The second adds a line to the Google Sheet with all the necessary parameters but at this stage all I have is the filename.jpg.
I need to add something to the this second script to get filename.jpg's URL so it can be stored along with the related data on the Google Sheet.
If I could merge the functionality of both scripts in one it would do the job as the transfer script has access to the file ID but I really need help on this one.
Image transfer script:
function doPost(e) {
var myFoldername = e.parameter.myFoldername;
var myFile = e.parameter.myFile;
var myFilename = e.parameter.myFilename;
//var myFilename = Utilities.formatDate(new Date(), "GMT", "yyyyMMddHHmmss")+"-"+e.parameter.myFilename;
var myToken = e.parameter.myToken;
var contentType = myFile.substring(myFile.indexOf(":")+1, myFile.indexOf(";"));
var data = myFile.substring(myFile.indexOf(",")+1);
data = Utilities.base64Decode(data);
var blob = Utilities.newBlob(data, contentType, myFilename);
// Save a captured image to Google Drive.
var folder, folders = DriveApp.getFoldersByName(myFoldername);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(myFoldername);
}
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + myFilename);
var imageID = file.getUrl().substring(file.getUrl().indexOf("/d/")+3,file.getUrl().indexOf("view")-1);
var imageUrl = "https://drive.google.com/uc?authuser=0&id="+imageID;
// Send a link message to Line Notify.
var res = "Line Notify: ";
try {
var url = 'https://notify-api.line.me/api/notify';
var response = UrlFetchApp.fetch(url, {
'headers': {
'Authorization': 'Bearer ' + myToken,
},
'method': 'post',
'payload': {
'message': imageUrl
}
});
res += response.getContentText();
} catch(error) {
res += error;
}
return ContentService.createTextOutput(myFoldername+"/"+myFilename+"\n"+imageUrl+"\n"+res);
}
Google Sheet Script:
var timeZone = "UTC"; //get yours at https://www.timeanddate.com/time/zones/
var dateTimeFormat = "dd/MM/yyyy HH:mm";
var enableSendingEmails = true;
var emailAddress = ""; // comma separate for several emails
// 'bob#example.com';
// 'bob#example.com,admin#example.com';
function doGet(e) {
var result = 'Ok'; // default result
if (e.parameter == 'undefined') {
result = 'No Parameters';
} else {
var alarm= e.parameter.alarm;
if (typeof alarm != 'undefined') {
sendEmail("alarm text:" + stripQuotes(alarm));
return ContentService.createTextOutput(result);
}
var sheet = getSpreadSheet();
var lastRow = sheet.getLastRow();
var newRow = 1;
if (lastRow > 0) {
var lastVal = sheet.getRange(lastRow, 1).getValue();
//if there was no info for (sentEmailIfUnitIsOutForMinutes) checkIfDead() function will append row with 'dead' text
// so checking do we need to override it
if (lastVal == 'dead')
newRow = lastRow; //to overwrite "dead" value
else
newRow = lastRow + 1;
}
var rowData = [];
var namesOfParams=[];
for (var param in parseQuery(e.queryString))
namesOfParams.push(param);
// namesOfParams=namesOfParams.reverse();
//creatating headers if first row
if (newRow == 1) {
rowData[0] = "Date";
var i = 1;
for (var i=0; i<namesOfParams.length;i++ ) {
rowData[i+1] = namesOfParams[i];
}
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
rowData = [];
newRow++;
}
rowData[0] = Utilities.formatDate(new Date(), timeZone, dateTimeFormat);
for (var i=0; i<namesOfParams.length;i++ ) {
var value = stripQuotes(e.parameter[namesOfParams[i]]);
rowData[i+1] = value;
}
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
// Return result of operation
return ContentService.createTextOutput(result);
}
// Remove leading and trailing single or double quotes
function stripQuotes(value) {
return value.replace(/^["']|['"]$/g, "");
}
function parseQuery(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
function sendEmail(message) {
if (!enableSendingEmails)
return;
var subject = 'Something wrong with your esp';
MailApp.sendEmail(emailAddress, subject, message);
}
function getSpreadSheet() {
return SpreadsheetApp.getActiveSheet();
}
Assistance welcome.
Thanks
Paulo
Problem solved with the following script:
var timeZone = "GMT";
var dateTimeFormat = "dd/MM/yyyy HH:mm:ss";
var logSpreadSheetId = "1W1ypQEkfKNFSqhtfgbjbjFgzHO8LDaTv6mNWTP9h4M8";
// logSpreadSheetId is to be copied from the sheet's URL as follows: https://docs.google.com/spreadsheets/d/1W1ypQEkfKNFSqhtfgbjbjFgzHO8LDaTv6mNWTP9h4M8/edit#gid=0
function doPost(e) {
var myFoldername = e.parameter.myFoldername;
var myFile = e.parameter.myFile;
//var myFilename = e.parameter.myFilename;
//var myFilename = Utilities.formatDate(new Date(), timeZone, "ddMMyyyyHHmmss")+"-"+e.parameter.myFilename;
var myFilename = Utilities.formatDate(new Date(), timeZone, "ddMMyyyyHHmmss")+".jpg";
var myToken = e.parameter.myToken;
var contentType = myFile.substring(myFile.indexOf(":")+1, myFile.indexOf(";"));
var data = myFile.substring(myFile.indexOf(",")+1);
data = Utilities.base64Decode(data);
var blob = Utilities.newBlob(data, contentType, myFilename);
// Save a captured image to Google Drive.
var folder, folders = DriveApp.getFoldersByName(myFoldername);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(myFoldername);
}
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + myFilename);
var imageID = file.getUrl().substring(file.getUrl().indexOf("/d/")+3,file.getUrl().indexOf("view")-1);
var imageUrl = "https://drive.google.com/uc?authuser=0&id="+imageID;
addLog(myFilename,imageUrl);
return ContentService.createTextOutput(myFoldername+"/"+myFilename+"\n"+imageUrl+"\n"); //+res);
}
function addLog(myFilename,imageUrl) {
var spr = SpreadsheetApp.openById(logSpreadSheetId);
var sheet = spr.getSheets()[0];
var data = sheet.getDataRange().getValues();
var pos = sheet.getLastRow();
var rowData = [];
if(!pos>0){
pos = 1;
rowData[0] = "Date";
rowData[1] = "Image";
rowData[2] = "URL";
var newRange = sheet.getRange(pos, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
pos = pos +1;
rowData = [];
rowData[0] = Utilities.formatDate(new Date(), timeZone, dateTimeFormat);
rowData[1] = myFilename;
rowData[2] = imageUrl;
var newRange = sheet.getRange(pos, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
Also, for simplicity, the sheet and the script now sit on independent files as the script can refer to the sheet using its ID as in: var logSpreadSheetId = "1W1ypQEkfKNFSqhtfgbjbjFgzHO8LDaTv6mNWTP9h4M8"; (Please used the ID of your own sheet).

How do I access every index of a specific Array inside an AJAX object

I'm calling an ajax for giphy, with this code:
$.ajax({
url: queryURL,
method: "GET"
}). then(function(response) {
console.log(response);
when I look at the console log there's an object with the first property being data. Each index of data is another object, inside this object are two properties i'm trying to pull, rating and url. I want to be able to list the rating and url not just of a specific index, but every index in that data array. What would be the best way to do that? Currently I've tried a for loop
for (var i = 0; i<response.data.length;i++){
var dataIndex = response.data[i];
}
then <creating a variable something like>
var imgURL = response.data[dataIndex].url
but its not working.
Here's the entire code
function displayTopicGif() {
var topic = $(this).attr("data-name");
// query url
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + topic + "&limit=20&rating=r&api_key=";
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response);
// for loop to create a variable for the index of the objects data
for (var i = 0; i < response.data.length; i++) {
var dataIndex = response.data[i];
}
// where the gif's will be dumped
var topicDiv = $("<div class='topic'>");
// rating of gif
var rating = response.data[0].rating;
console.log(rating);
// Creating an element to have the rating displayed
var pOne = $("<p>").text("Rating: " + rating);
// add to the rating element
topicDiv.append(pOne);
// retrieve the IMG of the gif
var imgURL = response.data[0].url;
var image = $("<img>").attr("src", imgURL);
topicDiv.append(image);
// put gif into topic-view div
$("#topic-view").prepend(topicDiv);
});
}
You can check that something is an object using $.isPlainObject and then read through its properties via:
for (key in object) {
var value = object[key];
//log
}
Or you can get the keys using Object.getOwnPropertyNames();. See this sample excerpt from MDN:
const object1 = {
a: 1,
b: 2,
c: 3
};
console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["a", "b", "c"]

In my mvc full calendar, events are not getting displayed

I am facing a problem in rendering events from a SQL Server database. All events are getting fetched using this code but not getting displayed in my calendar, so can anyone please help me?
.cshtml code:
events: function(start, end, callback) {
debugger;
var startdate=start.format('DD-MM-YYYY HH:mm'),
enddate=end.format('DD-MM-YYYY HH:mm'),
params={'start_time':startdate,'end_time':enddate};
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllEvents","Base")',
success: function (data) {
alert("hello");
}
});
}
,
my controller code:
public static List<Task_has_UsersModel> LoadAllTasks(double start, double end)
{
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var sql = "SELECT * from task_has_users";
var data = Database.Open("DefaultConnection").Query(sql);
List<Task_has_UsersModel> result = new List<Task_has_UsersModel>();
foreach (var item in data)
{
Task_has_UsersModel model = new Task_has_UsersModel();
model.Task_Id = Convert.ToInt32(item.Task_Id);
model.Project_Id = Convert.ToInt32(item.Project_Id);
model.start_time = item.start_time;
model.end_time = item.end_time;
result.Add(model);
}
return result;
}
[HttpPost]
public JsonResult GetAllEvents(double start, double end)
{
var ApptListForDate = LoadAllTasks(start,end);
var eventList = from e in ApptListForDate
select new
{
id=e.Task_Id,
name=e.Project_Id,
start=e.start_time.ToString(),
end=e.end_time.ToString(),
allDay=false,
color = "#008000",
//allDay=false,
className= "label-important" ,
};
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
private static DateTime ConvertFromUnixTimestamp(double timestamp)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
}
I have tried with (double start,double end ) still my events are not getting displayed in calendar
Finally after 3 days of hard work , i have done this.... No need to write anything in events , just call a function , it will automatically appends the date range and all you are done................... thanks
.cshtml code:
events:'GetAllEvents',
eventLimit: 50,
editable: true,
droppable: true,
// timeFormat: 'hh:mm-h:mma ',
timeFormat: 'hh:mma ',
displayEventEnd : true,
my controller code:
public static List<Task_has_UsersModel> LoadAllTasks(string start, string end,string uname)
{
UsersContext db = new UsersContext();
var uid = (from i in db.UserProfiles
where i.UserName == uname
select i.UserId).FirstOrDefault();
int userId = Convert.ToInt32(uid);
// var culture = System.Globalization.CultureInfo.CurrentCulture;
var sql = "SELECT * from task_has_users where UserId = " + userId;
var data = Database.Open("DefaultConnection").Query(sql);
List<Task_has_UsersModel> result = new List<Task_has_UsersModel>();
foreach (var item in data)
{
Task_has_UsersModel model = new Task_has_UsersModel();
model.Task_Id = Convert.ToInt32(item.Task_Id);
model.Project_Id = Convert.ToInt32(item.ProjectId);
// model.start_time = Convert.ToDateTime(item.start_time);
model.start_time = (item.start_time).ToString("yyyy-MM-dd HH-mm-ss");
model.end_time = (item.end_time).ToString("yyyy-MM-dd HH-mm-ss");
model.title = item.title;
result.Add(model);
}
return result;
}
[HttpGet]
public JsonResult GetAllEvents(string start, string end)
{
string uname = (Session["UserName"]).ToString();
var ApptListForDate = LoadAllTasks(start,end,uname);
var eventList = from e in ApptListForDate
select new
{
id=e.Task_Id,
title=e.title,
start=e.start_time,
end=e.end_time,
allDay=false,
color = "#008000",
//allDay=false,
className= "label-important" ,
};
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
finally done

httpRequest inside for loop sets same value for all records

I want to build and return an array of objects from CloudCode based on a query and the result of a httpRequest done for each record.
The problem with the following (example) is that it adds the same value for all "element" objects for all records. From testing I know that the variables "outside" the promises.push(Parse.Cloud.httpRequest(.. (e.g. "countryName") are unique.
What am I missing here?
Thanks!
Parse.Cloud.define("search3", function(request, response) {
var rs = [];
var promises = [];
// Query CountryTemp class
var query = new Parse.Query('CountryTemp');
query.limit(1000);
query.exists("Country");
query.include("Country");
query.greaterThan('Month11', 25);
query.find().then(function(results) {
for (var i = 0; i < results.length; ++i) {
var element = {};
var result = results[i];
var country = result.get("Country");
var countryID = country.id;
var countryName = country.get("Name");
var temp = result.get("Month11");
promises.push(Parse.Cloud.httpRequest({
url: 'http://www.google.com'
}).then(function(httpResponse){
element.id = countryID;
element.countryName = countryName;
element.temp = result.get("Month11");
element.httpresponse = httpResponse.text.substr(0, 50);
rs.push(element);
}));
}
return Parse.Promise.when(promises);
}).then(function() {
response.success(rs);
}, function() {
response.error('error');
});
});
Found the problem, Using underscore "_each" instead of "for" fixed it:
var _ = require('underscore');
..
_.each(results, function(result) {

I want to use Loading Image on laoding partial view MVC 4?

my issue is my partial view has a grid which has large data which takes time...now i want to use loading image like beforesend only to load my partial view...
my master data loaded quickly but my detail data in partial view takes time
here its my ajax ...
$.ajax({
url: '#Url.Action("get_Laptop_Detail_By_PO", "ChangeLaptopStage")',
data: { PO_Number: PO_Number },
beforeSend: function () {
$('.loader').show();
$('.main_area').addClass("disable_main_area");
},
success: function (data) {
var Qty = data.ItemQuantity
var Po_ID = data.PO_ID
$("#Total_laptop_Qty").val(Qty)
$("#PO_ID").val(Po_ID)
///This statement fetch my detail data in partial view ...i want to load this statement on loading image
$("#LaptopDetail").load('#(Url.Action("Laptop_detail_By_PO", "ChangeLaptopStage", null, Request.Url.Scheme))?PO_Number=' + PO_Number);
},
});
<div id="LaptopDetail">
</div>
This is my controller where partial view calls
[HttpGet]
public ActionResult Laptop_detail_By_PO(string PO_Number, ChangeLaptop_Stage REC)
{
Cls_Lot Lot_cls = new Cls_Lot();
List<LapTopDetail> LaptopDetail = new List<LapTopDetail>();
ds = new DataSet();
dt = new DataTable();
dt2 = new DataTable();
if (PO_Number != null)
{
ds = Lot_cls.getLaptopDetail_By_PO(22, PO_Number);
dt = ds.Tables[1];
foreach (DataRow drData in dt.Rows)
{
LaptopDetail.Add(new LapTopDetail
{
//RowNumber = Convert.ToInt32(drData["RowNumber"]),
PO_Dtl_ID = Convert.ToInt32(drData["ID"]),
PO_mstr_ID = Convert.ToInt32(drData["LapTop_Master_ID"]),
WareHouseStatus = drData["WareHouseStatus"].ToString(),
GulfITBarcode = drData["GulfITBarcode"].ToString(),
Item_Orgainal_srNO = drData["Item_Orgainal_srNO"].ToString(),
Category = drData["Category"].ToString(),
Make_Brand = drData["Make_Brand"].ToString(),
Series = drData["Series"].ToString(),
ModelNO = drData["ModelNO"].ToString(),
Color = drData["Color"].ToString(),
Processor_Brand = drData["Processor_Brand"].ToString(),
Processor_Type = drData["Processor_Type"].ToString(),
Processor = drData["Processor"].ToString(),
Speed_GHZ = drData["Speed_GHZ"].ToString(),
Memmory_MB = drData["Memmory_MB"].ToString(),
Memmory_Type = drData["Memmory_Type"].ToString(),
LCD_Screen_Size_inchs = drData["LCD_Screen_Size_inchs"].ToString(),
Touch_Screen = drData["Touch_Screen"].ToString(),
LCD_Teatures = drData["LCD_Teatures"].ToString(),
HDD_1_GB = drData["HDD_1_GB"].ToString(),
HDD_1_Type = drData["HDD_1_Type"].ToString(),
HDD_2_GB = drData["HDD_2_GB"].ToString(),
HDD_2_Type = drData["HDD_2_Type"].ToString(),
Graphic_Card_Name = drData["Graphic_Card_Name"].ToString(),
Graphic_Card_Memory_MB = drData["Graphic_Card_Memory_MB"].ToString(),
Camera = drData["Camera"].ToString(),
Camera_MegaPixel = drData["Camera_MegaPixel"].ToString(),
Lan = drData["Lan"].ToString(),
Wifi = drData["Wifi"].ToString(),
Bluetooth = drData["Bluetooth"].ToString(),
NFC = drData["NFC"].ToString(),
OpticalDriver = drData["OpticalDriver"].ToString(),
OpticalDriver_Type = drData["OpticalDriver_Type"].ToString(),
USB_Ports_Qty = drData["USB_Ports_Qty"].ToString(),
SD_Card_Reader = drData["SD_Card_Reader"].ToString(),
Stylus_Pen = drData["Stylus_Pen"].ToString(),
Finger_Printer_Reader = drData["Finger_Printer_Reader"].ToString(),
HDMI = drData["HDMI"].ToString(),
VGA = drData["VGA"].ToString(),
Display_Port = drData["Display_Port"].ToString(),
Thunderbolt = drData["Thunderbolt"].ToString(),
Audio_Port_Mic = drData["Audio_Port_Mic"].ToString(),
Audio_Port_Sound = drData["Audio_Port_Sound"].ToString(),
Speakers = drData["Speakers"].ToString(),
Battery = drData["Battery"].ToString(),
Ext_Adapter = drData["Ext_Adapter"].ToString(),
Other_1 = drData["Other_1"].ToString(),
Other_2 = drData["Other_2"].ToString(),
Other_3 = drData["Other_3"].ToString(),
Other_4 = drData["Other_4"].ToString(),
});
}
REC.Laptop_Detail = LaptopDetail;
return PartialView("Laptop_detail", REC);
}
else
{
return PartialView("P_Error");
}
}
Please help me
Use it on global $(document).ajaxStart and $(document).ajaxComplete events to attach it globally for all the request. There is an option called global in $.ajax which when set to false will not take global events into consideration.
$(document).ajaxStart(function(){
$('.loader').toggle();
$('.main_area').toggleClass("disable_main_area");
}).ajaxComplete(function(){
$('.loader').toggle();
$('.main_area').toggleClass("disable_main_area");
});
As I said this will attach it to all ajax request and if you want it not appear for all the ajax requests then add that global:false in each ajax request like on below:
$.ajax({
...
global:false,
...
});
For more global events visit - Global Events
Now if you want to attach it to only particular .load you can try as below:
$('.loader').show(); //show it before calling load
$("#LaptopDetail").load('#(Url.Action("Laptop_detail_By_PO", "ChangeLaptopStage", null, Request.Url.Scheme))?PO_Number=' + PO_Number), function() {
$('.loader').hide(); //hide once load completes
});

Resources