How to Use Take and Skip Function in MVC - linq

I want to Load Data and skip previous data which already append in the view using skip and take count in mvc.Here is my View where i am getting data
var skipCount = 5;
var takeCount = 5;
function loadMore() {
$(window).bind('scroll', bindScroll);
itemCount = takeCount;
skipCount += takeCount;
setTimeout(function () {
getFeed();
},100);
}
function bindScroll() {
if ($(window).scrollLeft() + $(window).width() > $('.tile-area').width() - 130) {
$(window).unbind('scroll');
loadMore();
}
}
function getFeed() {
$.ajax({
type: "Post",
url: "/PlanetFeed/PlanetfeedPartial",
dataType: "html",
data: { id: planetFeedOwnerId, filterType: filterType, taggedItemGraphId: taggedItemGraphId, itemCount: takeCount, SkipCount: skipCount }, //"feedGraphId=10696",
success: function (data) {
if (data === null) {
} else {
$('.tile-area-title').html("");
var div = $('.planetFeed:last');
div.after(data);
skipCount += takeCount + 1;
}
});
}
And Here is My Controller Where I am Passing Parameter
public ActionResult PlanetfeedPartial(Guid id, string filterType, Guid taggedItemGraphId, int itemCount, int SkipCount)
{
var planetfeedsOrder = from p in db.PlanetFeeds
where p.CurrentState != 1
join s in searchTag on p.PlanetFeedGraphId equals s.SecondaryTaggedGraphItemId
join g in db.Graphs on p.PlanetFeedItemGraphId equals g.GraphID
join u in db.UserInfos on p.PlanetFeedPosterId equals u.UserInfoID
orderby p.PostDate descending
select new PlanetFeedViewModel
{
Username = u.FirstName + " " + u.LastName,
isRootFeed = p.isRootFeed,
PostDate = p.PostDate,
CommentCount = g.CountResponses,
CountPositiveReactions = g.CountPositiveReactions,
CountNegativeReactions = g.CountNegativeReactions,
ItemID = g.ItemID,
UserLevel = u.UserLevel,
CurrentState = p.CurrentState,
Address = g.Address
};
return PartialView("_PlanetfeedPartial", planetfeedsOrder.OrderByDescending(p => p.PostDate).Skip(SkipCount).Take(itemCount).ToList());
}
I am not getting proper Data and every time when i am loading data in scroll getting different data not in a proper sequence and all data not loading

var planetfeedsOrder = (from p in db.PlanetFeeds
where p.CurrentState != 1
join s in searchTag on p.PlanetFeedGraphId equals s.SecondaryTaggedGraphItemId
join g in db.Graphs on p.PlanetFeedItemGraphId equals g.GraphID
join u in db.UserInfos on p.PlanetFeedPosterId equals u.UserInfoID
orderby p.PostDate descending
select new PlanetFeedViewModel
{
Username = u.FirstName + " " + u.LastName,
isRootFeed = p.isRootFeed,
PostDate = p.PostDate,
CommentCount = g.CountResponses,
CountPositiveReactions = g.CountPositiveReactions,
CountNegativeReactions = g.CountNegativeReactions,
ItemID = g.ItemID,
UserLevel = u.UserLevel,
CurrentState = p.CurrentState,
Address = g.Address
}).orderby(o=>o.id).skip(100);
skip One hundred then shows your data and create order by any id or string that you want sequence data.

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).

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) {

Json result returned as a file in Internet Explorer?

net MVC application, in which I have multiple charts. On these charts, I have applied filters and by clicking each filter, I do an ajax call which returns the result in Json and then applies to the charts.
Now its working perfectly in Firefox and Chrome, but in Internet Explorer - Ajax call is always unsuccessful. I tried hitting the web api url directly through my browser and the issue it seems is, the result json was being returned as a file to be downloaded.
This is my ajax code :
function getIssueResolvedGraphdata(control, departCode, departName) {
$.ajax(
{
type: "GET",
url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (myData) {
var resolvedStartDate = myData.data.IssueResolvedStartDate;
var issueData = myData.data.IssueData;
var resolveData = myData.data.ResolvedData;
//converting issueData into integer array...
var issue = issueData.replace("[", "");
var issue1 = issue.replace("]", "");
var issue2 = issue1.split(",");
for (var i = 0; i < issue2.length; i++) { issue2[i] = parseInt(issue2[i]); }
//converting resolvedData into integer array
var resolve = resolveData.replace("[", "");
var resolve1 = resolve.replace("]", "");
var resolve2 = resolve1.split(",");
for (var j = 0; j < resolve2.length; j++) { resolve2[j] = parseInt(resolve2[j]); }
//getting max value from array...
var issueMaxVal = Math.max.apply(null, issue2);
var resolveMaxVal = Math.max.apply(null, resolve2);
//Eliminating leading zeros in issue array
var removeIndex = 0;
var myDate;
var newDate;
var arrayLength;
if (issueMaxVal != 0) {
arrayLength = issue2.length;
for (var i = 0; i < arrayLength; i++) {
if (issue2[0] == 0) {
issue2.splice(0, 1);
removeIndex = i;
} else {
break;
}
}
//Getting days count of current month
var monthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
var monthEnd = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1);
var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
var monthDays = 0;
if (monthLength == 28) {
monthDays = removeIndex;
}
else if (monthLength == 30) {
monthDays = removeIndex + 1;
}
else if (monthLength == 31 || monthLength == 29) {
monthDays = removeIndex + 2;
}
//matching the resultant issue array with resolve array & setting start date
var iDate = resolvedStartDate;
var tDate = '';
for (var i = 0; i < iDate.length; i++) {
if (iDate[i] == ',') {
tDate += '/';
}
else {
tDate += iDate[i];
}
}
if (removeIndex != 0) {
resolve2.splice(0, (removeIndex + 1));
var myDate = new Date(tDate);
myDate.setDate(myDate.getDate() + monthDays);
newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
} else {
var myDate = new Date(tDate);
newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
}
} else {
alert("Empty");
}
//updating chart here...
var chart = $('#performance-cart').highcharts();
chart.series[0].update({
pointStart: newDate,
data: issue2
});
chart.series[1].update({
pointStart: newDate,
data: resolve2
});
if (issueMaxVal > resolveMaxVal) {
chart.yAxis[0].setExtremes(0, issueMaxVal);
} else {
chart.yAxis[0].setExtremes(0, resolveMaxVal);
}
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
} });}
Code from web api controller :
[HttpGet]
[CrossDomainActionFilter]
public Response<GraphIssueResolvedWrapper> GetQueryIssueResolvedData(string deptCode)
{
Response<GraphIssueResolvedWrapper> objResponse = new Response<GraphIssueResolvedWrapper>();
GraphIssueResolvedWrapper objGraphIssueResolvedWrapper = new GraphIssueResolvedWrapper();
try
{
....code.....
objResponse.isSuccess = true;
objResponse.errorDetail = string.Empty;
objResponse.data = objGraphIssueResolvedWrapper;
}
catch (Exception ex)
{
objResponse.isSuccess = false;
objResponse.errorDetail = ex.Message.ToString();
objResponse.data = null;
}
return objResponse;
}
Reponse Class :
public class Response<T>
{
public bool isSuccess { get; set; }
public string errorDetail { get; set; }
public T data { get; set; }
}
I am stuck at this for hours now. Any help will be appreciated.
I have solved my problem by using the following code : ( I guess it needed CORS support)
function isIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE");
if (msie > 0)
return true;
return false;
}
Then in document.ready function of my binding script :
$(document).ready(function () {
if (isIE())
$.support.cors = true;
});
Note : it still download Json stream as a file but now my AJAX call is successful upon each hit.
You've missed contentType: 'text/html' which is pretty important for IE7-8:
$.ajax(
{
type: "GET",
url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
dataType: "json",
contentType: 'text/html'
crossDomain: true,
async: true,
cache: false,
success: function (myData) {
var result = JSON.parse(myData);
///...code...
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
To make it works in IE7-8 you also need to be sure that you've writing Conrent-Type Header into your response on server side. Add this line right before return statement;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html; charset=iso-8859-1");
And in code probably you will need to parse result in success method by using JSON.parse(myData);

retrieve data from c# linq object to json to html

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);
}
},

Resources