I have a data with following structure. I am using Entity Framework.
Id fileName date status
---------------------------------------------
1 file1 12-05-2016 11:30 fail
2 file1 12-05-2016 11:35 success
3 file2 13-05-2016 12:01 success
4 file2 13-05-2016 12.02 fail
5 file1 13-05-2016 success
6 file3 13-05-2016 fail
I want result like this
fileName 12-05-2016 13-05-2016
------------------------------------------
file1 success sucess
file2 fail
file3 fail
Criteria - Search the data between two dates and all dates file status should be displayed in above way. For the same day same file's two entries exist, then latest status will be displayed.
I am using code first approach to get data.
this is my code at repo
IQueryable<FileData> filedata=this.context.FileData;
I created a pivot table based on Svek code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
FileStatus filestatus = new FileStatus();
filestatus.Load();
DataTable pivot = filestatus.PivotTable();
}
}
public class FileStatus
{
public static List<FileStatus> filedata = new List<FileStatus>();
public int? Id { get; set; }
public string filename { get; set; }
public DateTime date { get; set; }
public string status { get; set; }
public void Load()
{
filedata = new List<FileStatus>()
{
new FileStatus(){ Id = 1, filename = "file1", date = new DateTime(2016,05,12,11,30,00), status = "fail"},
new FileStatus(){ Id = 2, filename = "file1", date = new DateTime(2016,05,12,11,35,00), status = "success"},
new FileStatus(){ Id = 3, filename = "file2", date = new DateTime(2016,05,13,12,01,00), status = "success"},
new FileStatus(){ Id = 4, filename = "file2", date = new DateTime(2016,05,13,12,02,00), status = "fail"},
new FileStatus(){ Id = 5, filename = "file1", date = new DateTime(2016,05,13,12,30,00), status = "success"},
new FileStatus(){ Id = 6, filename = "file3", date = new DateTime(2016,05,13,12,31,00), status = "fail"}
};
}
public DataTable PivotTable()
{
DataTable pivot = new DataTable();
DateTime[] uniqueDates = filedata.Select(x => x.date.Date).Distinct().OrderBy(x => x).ToArray();
pivot.Columns.Add("filename", typeof(string));
foreach (DateTime date in uniqueDates)
{
pivot.Columns.Add(date.ToString("MM-dd-yyyy"), typeof(string));
}
var groups = filedata.GroupBy(x => x.filename).ToList();
foreach (var group in groups)
{
DataRow newRow = pivot.Rows.Add();
newRow["filename"] = group.Key;
foreach (FileStatus filestatus in group)
{
newRow[filestatus.date.ToString("MM-dd-yyyy")] = filestatus.status;
}
}
return pivot;
}
}
}
First of all, you have to pay me for that, hahaha, all the example is wrong (repeats, year 1016¿?, hour with . instead of :, and without hour), I check you has written quickly...so:
declare #cols nvarchar(max)
declare #query nvarchar(max)
CREATE TABLE [dbo].[Table_1](
[id] [int] NULL,
[filename] [nvarchar](50) NULL,
[date] [datetime] NULL,
[status] [nvarchar](50) NULL
) ON [PRIMARY]
insert into table_1
values
(1 ,'file1' ,'12-05-2016 11:30:00.000' ,'fail'),
(2 ,'file1' ,'12-05-2016 11:35:00.000' ,'success'),
(3 ,'file2' ,'13-05-2016 12:01:00.000' ,'success'),
(3 ,'file2' ,'13-05-2016 12:02:00.000' ,'fail'),
(4 ,'file1' ,'13-05-2016 12:03:00.000' ,'success'),
(5 ,'file3' ,'13-05-2016 12:04:00.000' ,'fail')
select t2.filename,dat, status
into #temp1
FROM
(select filename, cast([date] as date) as dat, max([date]) as maxdat
from table_1
group by filename, cast([date] as date)
) t1
INNER JOIN
table_1 t2
on t1.filename = t2.filename
and t2.[date] = t1.maxdat
and cast(t2.date as date) = t1.dat
--select * from #temp1
--after that you want pivot by date and max status for example¿?
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(convert(CHAR(10), datelist, 120))
from
(
select distinct cast(dat as date) as datelist from #temp1
)t1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
--select #cols
set #query =
('select filename, ' + #cols + '
from #temp1
pivot (
max(status)
for dat in (' + #cols + ')
)p
')
print #query
exec(#query)
Hope this help you! $$
Based on your question, here is an example class that would work
public class FileStatus
{
public int? Id { get; set; }
public string Filename { get; set; }
public DateTime Date { get; set; }
public string Status { get; set; }
}
Here is a working sample that would get you the result you want, so that you can pass it onto your report template:
var filedata= new List<FileStatus>()
{
new FileStatus(){ Id = 1, Filename = "file1", Date = new DateTime(2016,05,12,11,30,00), Status = "fail"},
new FileStatus(){ Id = 2, Filename = "file1", Date = new DateTime(2016,05,12,11,35,00), Status = "success"},
new FileStatus(){ Id = 3, Filename = "file2", Date = new DateTime(2016,05,13,12,01,00), Status = "success"},
new FileStatus(){ Id = 4, Filename = "file2", Date = new DateTime(2016,05,13,12,02,00), Status = "fail"},
new FileStatus(){ Id = 5, Filename = "file1", Date = new DateTime(2016,05,13,12,30,00), Status = "success"},
new FileStatus(){ Id = 6, Filename = "file3", Date = new DateTime(2016,05,13,12,31,00), Status = "fail"}
};
//remove the above and replace it with your own:
//IQueryable<FileData> filedata = this.context.FileData;
var result = filedata.GroupBy(c => new { c.Filename, c.Date.Date }).Select(c => new
{
Row = c.Key.Filename,
Column = c.Key.Date,
Value = filedata.FirstOrDefault(co => co.Id == c.Max(max => max.Id)).Status
}).OrderBy(c => c.Row).OrderBy(c => c.Column);
Related
My use case is, I have a List of orders that I need to post to external API.
but the conditions are that, I can post 5 order in one post call of API.
and these 5 orders have to be of same store and of deliveryWindows should be either morning or afternoon for all 5 orders.
I have written the below code but I am not happy with that, Can anyone Kindly help to refactor the below logic.
I have used 3 for loops to Loop through Deliverywindow and also for stores and for all the orders in the store.
Is there better approach/async Looping of the below/ having separate method calls.
Any suggestion is really helpful!
using MoreLinq;
using System;
using System.Collections.Generic;
using System.Linq;
static void Main(string[] args)
{
//In real time I will have 1000's of orders for one store and deliveryWindow (Morning)
var allOrders = GetProductOrders();
string[] deliveryWindows = new[] { "Morning", "AfterNoon" };
//Looping for Morning & Afternoon
foreach (var deliveryWindow in deliveryWindows)
{
//Getting Morning order in first run and afternoon order in second run
var OrderForWindow = allOrders.Where(x => x.DeliveryWindow.Equals(deliveryWindow));
//Getting All Unique Store (Will have StoreA, StoreB, etc)
List<string> Stores = OrderForWindow.Select(x => x.StoreName).Distinct().ToList();
foreach (var Store in Stores)
{
//Store releated order for that windown (morning/afternoon)
var StoreOrders = OrderForWindow.Where(order => order.StoreName.Equals(Store)).ToList();
//taking 10 items from StoreOrders
//Batch will pick 5 items at once
foreach (var orders in StoreOrders.Batch(5))
{
//storeOrder will have list of 5 order which all have same delivery window
//Post External call
}
}
}
}
public static List<ProductOrder> GetProductOrders()
{
List<ProductOrder> productOrder = new List<ProductOrder>()
{
new ProductOrder(){ ID = 1, DeliveryWindow ="Morning", StoreName = "StoreA", customerDetails = "Cust1"},
new ProductOrder(){ ID = 2, DeliveryWindow ="Morning", StoreName = "StoreA",customerDetails = "Cust2"},
new ProductOrder(){ ID = 3, DeliveryWindow ="Morning", StoreName = "StoreA",customerDetails = "Cust3"},
new ProductOrder(){ ID = 4, DeliveryWindow ="AfterNoon", StoreName = "StoreA",customerDetails = "Cust4"},
new ProductOrder(){ ID = 5, DeliveryWindow ="AfterNoon", StoreName = "StoreA",customerDetails = "Cust5"},
new ProductOrder(){ ID = 6, DeliveryWindow ="Morning", StoreName = "StoreB",customerDetails = "Cust6"},
new ProductOrder(){ ID = 7, DeliveryWindow ="Morning", StoreName = "StoreB",customerDetails = "Cust7"},
new ProductOrder(){ ID = 8, DeliveryWindow ="AfterNoon", StoreName = "StoreB",customerDetails = "Cust8"},
new ProductOrder(){ ID = 9, DeliveryWindow ="AfterNoon", StoreName = "StoreB",customerDetails = "Cust9"},
new ProductOrder(){ ID = 10, DeliveryWindow ="AfterNoon", StoreName = "StoreC",customerDetails = "Cust10"},
};
return productOrder;
}
}
public class ProductOrder
{
public int ID { set; get; }
public string StoreName { set;get;}
public string DeliveryWindow { set; get; }
public string customerDetails { set; get; }
public string ProductDetails { set; get; }
}
As pointed out, this post is a great resource to help you understand how to group against multiple keys.
Here's what that would look like in your case:
var allOrders = GetProductOrders();
var groupedOrders = from order in allOrders
// We group using an anonymous object
// that contains the properties we're interested in
group order by new
{
order.StoreName,
order.DeliveryWindow
};
// Access is straightforward:
foreach (var orderGroup in groupedOrders)
{
Console.WriteLine($"Group {orderGroup.Key.StoreName} {orderGroup.Key.DeliveryWindow}");
// The group is a list itself, so you can apply
// your Batch LINQ extension
foreach (var order in orderGroup)
{
Console.WriteLine(order.ID);
}
}
I am trying to generate a list result through linq.
I would like to have a result as a list with unique folder id with 0th item as folder_name, 1st Item as a list with one or more projects having fields project_id,name and description.
I have written following query:
Folders is basically model with format as folderid, name, List projects where Project Model has project_id, name and description
from the following records:
Models
public class FolderModel
{
public int folder_id { get; set; }
public string folder_name { get; set; }
public List<ProjectModel> projects{ get; set; }
}
public class ProjectModel
{
public int project_id { get; set; }
public string project_name { get; set; }
public string project_description { get; set; }
}
public class ResultModel
{
public List<FolderModel> folders { get; set; }
}
Result Data
List<FolderModel, List<ProjectModel>> result = new List<FolderModel, List<ProjectModel>>();
List<ProjectModel> projectList1 = new List<>();
ProjectModel projectModel1 = new ProjectModel();
projectModel1.project_name = "F1P1";
projectModel1.project_description = "F1P1";
projectList1.add(projectModel1);
List<ProjectModel> projectList2 = new List<>();
ProjectModel projectModel21 = new ProjectModel();
projectModel21.project_name = "F2P1";
projectModel21.project_description = "F2P1";
projectList2.add(projectModel21);
ProjectModel projectModel22 = new ProjectModel();
projectModel22.project_name = "F2P2";
projectModel22.project_description = "F2P2";
projectList2.add(projectModel22);
List<ProjectModel> projectList3 = new List<>();
ProjectModel projectModel3 = new ProjectModel();
projectModel3.project_name = "F3P1";
projectModel3.project_description = "F1P3";
projectList3.add(projectModel3);
ResultModel resultModel = new resultModel();
resultModel.(new FolderModel { folder_id: 1,folder-name: "F1" }, projectList1);
FolderModel folderModel1 = new FolderModel();
folderModel1.folder_id = 1
folderModel1.folder_name = "F1"
folderModel1.projects = projectList1
FolderModel folderModel2 = new FolderModel();
folderModel2.folder_id = 2
folderModel2.folder_name = "F2"
folderModel2.projects = projectList2
FolderModel folderModel3 = new FolderModel();
folderModel3.folder_id = 3
folderModel3.folder_name = "F3"
folderModel3.projects = projectList3
ResultModel resultModel = new ResultModel();
List<FolderModel> folderList = new List<>();
folderList.add(folderModel1);
folderList.add(folderModel2);
folderList.add(folderModel3);
resultModel.folders = folderList
SQL Data
folder_id | folder_name | project_id | project_name | project_description
1 F1 11 F1P1 F1P1
2 F2 21 F2P1 F2P1
2 F2 22 F2P2 F2P2
3 F3 31 F3P1 F3P1
4 F4 41 F4P1 F4P1
5 F5 51 F5P1 F5P1
This is what I have tried
var result = resultModel.folders.GroupBy(x => new { x.folder_id }).ToList();
I am sure that after group by I have to select name but not sure how can I generate project into a list and add it to main folder id. Can someone please guide on this.
You can query like this:
var result =
resultModel
.folders
.GroupBy(x => new { x.folder_id })
.Select(s => new
{
folder_id = s.Key,
folder_name = s.First().folder_name
})
.ToList();
It seems to me that you're looking for this:
var folders = new []
{
new { folder_id = 1, folder_name = "F1", project_id = 11, project_name = "F1P1", project_description = "F1P1" },
new { folder_id = 2, folder_name = "F2", project_id = 21, project_name = "F2P1", project_description = "F2P1" },
new { folder_id = 2, folder_name = "F2", project_id = 22, project_name = "F2P2", project_description = "F2P2" },
new { folder_id = 3, folder_name = "F3", project_id = 31, project_name = "F3P1", project_description = "F3P1" },
new { folder_id = 4, folder_name = "F4", project_id = 41, project_name = "F4P1", project_description = "F4P1" },
new { folder_id = 5, folder_name = "F5", project_id = 51, project_name = "F5P1", project_description = "F5P1" },
};
List<FolderModel> result =
folders
.GroupBy(
x => new { x.folder_id, x.folder_name },
x => new { x.project_id, x.project_name, x.project_description })
.Select(x => new FolderModel()
{
folder_id = x.Key.folder_id,
folder_name = x.Key.folder_name,
projects = x.Select(y => new ProjectModel()
{
project_id = y.project_id,
project_name = y.project_name,
project_description = y.project_description,
}).ToList(),
})
.ToList();
I am having 2 reports and combining them into a list. some of the item has null values.when i do sorting, it moves null values at the last.
Here is the sample program
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Report> reports = new List<Report>();
Report[] report1 = {
new Report{Id=10001,Date=null},
new Report{Id=10001,Date=null},
new Report{Id=10001,Date=Convert.ToDateTime("01/01/2017")}};
Report[] report2 = {
new Report{Id=10002,Date=null},
new Report{Id=10002,Date=null},
new Report{Id=10002,Date=Convert.ToDateTime("03/01/2017")}};
Report[] report3 = {
new Report{Id=10003,Date=null},
new Report{Id=10003,Date=null},
new Report{Id=10003,Date=Convert.ToDateTime("05/01/2017")}};
Report[] report4 = {
new Report{Id=10004,Date=null},
new Report{Id=10004,Date=null},
new Report{Id=10004,Date=Convert.ToDateTime("07/01/2017")}};
reports.AddRange(report1);
reports.AddRange(report2);
reports.AddRange(report3);
reports.AddRange(report4);
var report5 = new List<Report>()
{
new Report{Id=null,Date=Convert.ToDateTime("02/01/2017")},
new Report{Id=null,Date=Convert.ToDateTime("04/01/2017")},
new Report{Id=null,Date=Convert.ToDateTime("06/01/2017")},
};
reports.AddRange(report5);
foreach (var report in reports.OrderByDescending(x => x.Date))
{
Console.WriteLine("ID = " + report.Id + " " + "Date = " + report.Date);
}
Console.ReadKey();
}
}
class Report
{
public int? Id { get; set; }
public DateTime? Date { get; set; }
}
}
Sorting should be made based on the date and should not skip/move the null values of report list. Output should be as follows.
ID = 10004 Date =
ID = 10004 Date =
ID = 10004 Date = 07/01/2017
ID = Date = 06/01/2017
ID = 10003 Date =
ID = 10003 Date =
ID = 10003 Date = 05/01/2017
ID = Date = 04/01/2017
ID = 10002 Date =
ID = 10002 Date =
ID = 10002 Date = 03/01/2017
ID = Date = 02/01/2017
ID = 10001 Date =
ID = 10001 Date =
ID = 10001 Date = 01/01/2017
So, if I understood your answer correctly, you want to order by the ID's of the reports, and then the dates.
Change this:
foreach (var report in reports.OrderByDescending(x => x.Date))
{
Console.WriteLine("ID = " + report.Id + " " + "Date = " + report.Date);
}
to this:
foreach (var report in reports.OrderByDescending(x => x.Id).ThenBy(x => x.Date))
{
Console.WriteLine("ID = " + report.Id + " " + "Date = " + report.Date);
}
The latter sorts the reports by their ID, then by their date.
If I understood correctly, you want to order by Date first, and if Date is null, use ID for ordering. In this case, you need custom Report comparer.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Report> reports = new List<Report>();
Report[] report1 =
{
new Report {Id = 10001, Date = null},
new Report {Id = 10001, Date = null},
new Report {Id = 10001, Date = Convert.ToDateTime("01/01/2017")}
};
Report[] report2 =
{
new Report {Id = 10002, Date = null},
new Report {Id = 10002, Date = null},
new Report {Id = 10002, Date = Convert.ToDateTime("03/01/2017")}
};
Report[] report3 =
{
new Report {Id = 10003, Date = null},
new Report {Id = 10003, Date = null},
new Report {Id = 10003, Date = Convert.ToDateTime("05/01/2017")}
};
Report[] report4 =
{
new Report {Id = 10004, Date = null},
new Report {Id = 10004, Date = null},
new Report {Id = 10004, Date = Convert.ToDateTime("07/01/2017")}
};
reports.AddRange(report1);
reports.AddRange(report2);
reports.AddRange(report3);
reports.AddRange(report4);
var report5 = new List<Report>()
{
new Report {Id = null, Date = Convert.ToDateTime("02/01/2017")},
new Report {Id = null, Date = Convert.ToDateTime("04/01/2017")},
new Report {Id = null, Date = Convert.ToDateTime("06/01/2017")},
};
reports.AddRange(report5);
foreach (var report in reports.OrderByDescending(x => x, new ReportComparer()))
{
Console.WriteLine("ID = " + report.Id + " " + "Date = " + report.Date);
}
Console.ReadKey();
}
class ReportComparer: IComparer<Report>
{
public int Compare(Report x, Report y)
{
// write your ordering rules here
if (x.Date.HasValue && y.Date.HasValue)
{
return x.Date.Value.CompareTo(y.Date.Value);
}
return x.Id.Value.CompareTo(y.Id.Value);
}
}
class Report
{
public int? Id { get; set; }
public DateTime? Date { get; set; }
}
}
}
I would recommend not using linq for this.
I would create your own sort function.
Something like a bubble sort simple bubble sort
Where you can change the condition for swapping the elements.
You can do as assign you null Date with DateTime.MaxValue then order your list and reassign DateTime.MaxValue with null
var reportlist = reports.OrderBy(n => n.Date = n.Date == null ? n.Date = DateTime.MaxValue : n.Date).Select(n=>n = new Report() {Date= n.Date == DateTime.MaxValue ? n.Date = null : n.Date, Id=n.Id }).ToList();
foreach (var report in reportlist)
{
Console.WriteLine("ID = " + report.Id + " " + "Date = " + report.Date);
}
I want to get ResourceNames on the base of Id in EntityFramework but it is giving error: "LINQ to Entities does not recognize the method 'System.String GetResourceNameById(Int32)' method, and this method cannot be translated into a store expression."
Following ismy code.
public string GetResourceNameById(int Id)
{
return _DBContex.Employees.Where(x => x.Id == Id).FirstOrDefault().FirstName;
}
public CygnusInternalResponseViewModel GetAllTimeEntriesForGrid(int start = 0, int perPage = -1, string sortColumn = "", string sortDirection = "")
{
List<TimeEntryViewModel> te = new List<TimeEntryViewModel>();
te = (from jb in _DBContex.TimeEntries
select new TimeEntryViewModel
{
Id = jb.Id,
ResourceId = (int)jb.ResourceId,
TicketId = (int)jb.TicketId,
WorkType = (WorkTypeCatalog)jb.WorkType,
HoursWorked = (float)jb.HoursWorked,
Status = (TimeEntryStatusCatalog)jb.Status,
Role = (RoleCatalog)jb.Role,
StartTime = (TimeSpan)jb.StartTime,
EndTime = (TimeSpan)jb.EndTime,
SummaryNotes = jb.SummaryNotes,
InternalNotes = jb.InternalNotes,
Contract = (DateTime)jb.Contract,
Date = (DateTime)jb.Date,
ResourceName = GetResourceNameById((int)jb.ResourceId) // ERRORR Line
}).ToList();
You might need to create in memory representation of your database table.
public CygnusInternalResponseViewModel GetAllTimeEntriesForGrid(int start = 0, int perPage = -1, string sortColumn = "", string sortDirection = "")
{
List<TimeEntryViewModel> te = new List<TimeEntryViewModel>();
var query=_DBContex.TimeEntries.ToList();//create in-memory representation
te = (from jb in query
select new TimeEntryViewModel
{
Id = jb.Id,
ResourceId = (int)jb.ResourceId,
TicketId = (int)jb.TicketId,
WorkType = (WorkTypeCatalog)jb.WorkType,
HoursWorked = (float)jb.HoursWorked,
Status = (TimeEntryStatusCatalog)jb.Status,
Role = (RoleCatalog)jb.Role,
StartTime = (TimeSpan)jb.StartTime,
EndTime = (TimeSpan)jb.EndTime,
SummaryNotes = jb.SummaryNotes,
InternalNotes = jb.InternalNotes,
Contract = (DateTime)jb.Contract,
Date = (DateTime)jb.Date,
ResourceName = GetResourceNameById((int)jb.ResourceId)
}).ToList();
te = (from jb in _DBContex.TimeEntries
select new TimeEntryViewModel
{
Id = jb.Id,
ResourceId = (int)jb.ResourceId,
TicketId = (int)jb.TicketId,
WorkType = (WorkTypeCatalog)jb.WorkType,
HoursWorked = (float)jb.HoursWorked,
Status = (TimeEntryStatusCatalog)jb.Status,
Role = (RoleCatalog)jb.Role,
StartTime = (TimeSpan)jb.StartTime,
EndTime = (TimeSpan)jb.EndTime,
SummaryNotes = jb.SummaryNotes,
InternalNotes = jb.InternalNotes,
Contract = (DateTime)jb.Contract,
Date = (DateTime)jb.Date
}).ToList();
te.Foreach(t=>t.ResourceName = GetResourceNameById((int)t.ResourceId);
First you get the records then you set the ResourceName
You can call ToList() method before your SELECT and then call your function.
I have an SQL server with the following layout
Table ( id int
title varchar(40),
start Date(),
end Date(),
allDay bool,
username varchar(40)
);
I have gotten the following code from this blog to create a JSON object from the data I wish to use, however his data is stored differently. How do I create the same object, extracted from my database?
I am guessing I need to make the file a .cshtml file rather than a .js file and use this :
#{
var db = Database.Open("events");
var selectQueryString = "SELECT * FROM events";
}
#foreach(var row in db.Query(selectQueryString)){ }
But how do I adapt this code to produce the same JSON object?
Here is the relevant code from the blog, my attempt is below :
public JsonResult GetEvents(double start, double end)
{
var userName = Session["UserName"] as string;
if(string.IsNullOrEmpty(userName))
{
return null;
}
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var rep = Resolver.Resolve<IEventRepository>();
var events = rep.ListEventsForUser(userName,fromDate,toDate);
var eventList = from e in events
select new {
id = e.Id,
title = e.Title,
start = e.FromDate.ToString("s"),
end = e.ToDate.ToString("s"),
allDay = false
};
var rows = eventList.ToArray();
return Json(rows,JsonRequestBehavior.AllowGet);
}
Edit :
I am now working with the following .cshtml code for the GetEvents command, but it will not work. Does anybody have any ideas ?
#{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
var fromDate = origin.AddSeconds((Request["start"]));
var toDate = origin.AddSeconds(Request["end"]);
var db = Database.Open("events");
var result = db.Query("SELECT * FROM events");
var data = result.Select(x => new
{
id = x.id,
title = x.title,
start = x.start.ToString("s"),
end = x.end.ToString("s"),
allDay = false
}).ToArray();
Json.Write(data, Response.Output);
Response.ContentType = "application/json";
}
There are no controllers and actions in WebMatrix WebPages. You need to write a separate .cshtml page that will query the database and serve the JSON to the response:
#{
var db = Database.Open("events");
var result = db.Query("SELECT * FROM events");
var data = result.Select(x => new
{
id = x.id,
title = x.title,
start = x.start.ToString("s"),
end = x.end.ToString("s"),
allDay = false
}).ToArray();
Json.Write(data, Response.Output);
Response.ContentType = "application/json";
}
and then in another page in which you want to display the calendar you could configure it:
$(document).ready(function() {
$('#calendar').fullCalendar({
theme: true,
header: {
left: '',
center: '',
right: ''
},
defaultView: 'agendaDay',
editable: false,
events: '/events.cshtml'
});
});
UPDATE: Here's an example of how you could use parametrized queries:
#{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
var fromDate = origin.AddSeconds(int.Parse(Request["start"]));
var toDate = origin.AddSeconds(int.Parse(Request["end"]));
var db = Database.Open("events");
var sql = "SELECT * FROM events WHERE start >= #0 AND end <= #1";
var result = db.Query(sql, fromDate, toDate);
var data = result.Select(x => new
{
id = x.id,
title = x.title,
start = x.start.ToString("s"),
end = x.end.ToString("s"),
allDay = false
}).ToArray();
Json.Write(data, Response.Output);
Response.ContentType = "application/json";
}
Now you could query the page like this: /events.cshtml?start=5&end=10
DECLARE #listCol VARCHAR(2000)
DECLARE #query VARCHAR(4000)
SELECT #listCol = STUFF(( SELECT distinct '], [' + [PSize]
FROM Pattern
FOR
XML PATH('')
), 1, 2, '') + ']'
SET #query = 'SELECT * FROM
(SELECT PColour as Colour_Size_Matrix, PSize, PCode
FROM Pattern
) src
PIVOT (Count(PCode) FOR PSize
IN (' + #listCol + ')) AS pvt'
EXECUTE ( #query )
I want the result of this query as JSON