Creating a JSON result from SQL server database - c#

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

Related

xunit testing to see if a specific value is there in the list

I am writing x-unit testing.
I want to check if list contains the newly added value.
I tried the below code but i am not getting the result
_record.Add(new PortfolioCompanyLinkModel { Id = 3, PortfolioCompanyId = 1, URL = "www.historiclreports2.com", LinkName = "Historical Reports", ToBeDeleted = false, IsExternalLink = false, LinkId = 1 });
_record.Add(new PortfolioCompanyLinkModel { Id = 4, PortfolioCompanyId = 1, URL = "www.SalesForce.com", LinkName = "SalesForce", ToBeDeleted = false, IsExternalLink = false, LinkId = 2 });
var repo = new PortfolioCompanyLinkRepository(dbContext, obj.HttpContextAccessor);
var update = await repo.GetOne(2);
_record.Add(new PortfolioCompanyLinkModel { Id = update.Id, PortfolioCompanyId = update.PortfolioCompanyId, URL = "www.historiclreportstest.com", LinkName = update.Link.Name, ToBeDeleted = false, IsExternalLink = true, LinkId = update.LinkId });
var delete = await repo.GetOne(1);
_record.Add(new PortfolioCompanyLinkModel { Id = delete.Id, PortfolioCompanyId = delete.PortfolioCompanyId, URL = delete.URL, LinkName = delete.Link.Name, ToBeDeleted = true, IsExternalLink = delete.Link.IsExternalLink, LinkId = delete.LinkId });
await repo.AddUpdateDelete(_record);
await repo.SaveAsync();
var actual = await repo.GetAll();
Assert.Collection(actual, item => Assert.Contains("www.historiclreports2.com", item.URL));
How do i check if actual has www.historiclreports2.com as URL ?
In order to do this, you want to single out the record you desire to assert on. This can be done multiple ways, but the way I have do this is always as follows:
var recordInQuestion = actual.Where(x => x.URL
.Equals("www.historiclreports2.com"))
.SingleOrDefault();
Assert.NotNull(recordInQuestion);
Other options are:
Assert.Single(actual.Where(x => x.URL.Equals("www.historiclreports2.com")));
Assert.True(actual.Any(x => x.URL.Equals("www.historiclreports2.com")))
Using the first option with the SingleOrDefault() in which the record is assigned to a variable allows you to easily perform multiple asserts on that object's data.

Using output parameters when calling stored procedures with AsyncPoco

I'm executing a SQL Server stored procedure which returns a single output parameter using AsyncPoco:
CREATE PROCEDURE [dbo].[GenerateId]
(#RETVAL VARCHAR(12) OUTPUT)
AS
DECLARE #pkgID VARCHAR(12)
BEGIN
SELECT #pkgID = 'ABC' + '000'
SELECT #RETVAL = #pkgID
END
GO
Here's how I'm calling it:
var spOutput = new SqlParameter("#RETVAL", System.Data.SqlDbType.VarChar)
{
Direction = System.Data.ParameterDirection.Output,
Size = 12,
};
var sql = $";EXEC [dbo].[GenerateId] #0 OUTPUT";
var response = await _dbAdapter.FetchAsync<dynamic>(sql, new object[] { spOutput });
return (string)spOutput.Value;
This is the error I get:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Object.GetType()
at AsyncPoco.Database.FormatCommand(String sql, Object[] args) in C:\Aldenteware\AsyncPoco\code\AsyncPoco\Database.cs:line 2279
I figured it out:
var spOutput = new SqlParameter("#RETVAL", System.Data.SqlDbType.VarChar)
{
Direction = System.Data.ParameterDirection.Output,
Size = 12,
};
var sql = $";EXEC [dbo].[GenerateId] ##RETVAL = #0 OUTPUT";
var sqlClass = new Sql();
var s = sqlClass.Append(sql, spOutput);
var response = await _dbAdapter.ExecuteAsync(s);
return (string)spOutput.Value;

How to query multiple result in specify value in dapper

I want return all records when data.Task = 0 in this query. how to do it?
var data = SqlConn.ConnectSQL().Query("Select TicketNo, PickName From TaxiTicket Where DriverID = #ID AND Status = #State",
new { ID = find.Account, State = data.Task });
var data = SqlConn.ConnectSQL().Query("Select TicketNo, PickName From TaxiTicket
Where DriverID = #ID AND (Status = case #State when 0 then Status else #state end)",
new { ID = find.Account, State = data.Task });
this only addresses your point of question, how you prepare and pass parameters is another issue. you seem to have some weird assignment using same data variable.

Using List<int> in Url.Action Method

i am writing code for search page and i have to pass some filters to the action and depending on those input I have to generate hyper links, hence i am using Url.Action function to generate links.
below is my code
#Url.Action("Index","Search",new SkillKindleWeb.ViewModels.Search.SearchRawInput()
{
CategoryIds = Model.Request.CategoryIds,
SubCategoryIds = Model.Request.SubCategoryIds,
StartDate = Model.Request.StartDate,
EndDate = Model.Request.EndDate,
StartPrice = Model.Request.StartPrice,
LocationGroupIds = Model.Request.LocationGroupIds,
LocationIds = Model.Request.LocationIds,
EndPrice = Model.Request.EndPrice,
City = Model.Request.City,
PageNo = 1,
SearchQuery = Model.Request.SearchQuery,
Segment1 = Model.Request.Segment1,
Segment2 = Model.Request.Segment2,
TargetAge = Model.Request.TargetAge
})
and it is generating url like this
http://someDomain.com/ncr/classes?CategoryIds=System.Collections.Generic.List%601%5BSystem.Int32%5D&StartDate=03%2F30%2F2013%2000%3A00%3A00&StartPrice=0&EndPrice=140000&PageNo=2
My expected Url was
http://SomeDomain.com/ncr/classes?CategoryIds=9&StartDate=3/30/2013&StartPrice=0&EndPrice=140000
What about converting it to string representation yourself like that:
#Url.Action("Index","Search",new SkillKindleWeb.ViewModels.Search.SearchRawInput()
{
CategoryIds = string.Join(",", Model.Request.CategoryIds),
SubCategoryIds = string.Join(",", Model.Request.SubCategoryIds),
StartDate = Model.Request.StartDate.ToShortDateString(),
EndDate = Model.Request.EndDate.ToShortDateString(),
StartPrice = Model.Request.StartPrice,
LocationGroupIds = Model.Request.LocationGroupIds,
LocationIds = Model.Request.LocationIds,
EndPrice = Model.Request.EndPrice,
City = Model.Request.City,
PageNo = 1,
SearchQuery = Model.Request.SearchQuery,
Segment1 = Model.Request.Segment1,
Segment2 = Model.Request.Segment2,
TargetAge = Model.Request.TargetAge
})
That is what a viewmodel should be for. That you convert and format all the values you need in the way the view expects it.
Notice that I added a ToShortDateString() to your dates as well, since it seems you are not interested in the time part.

C# SQL Statement transformed TO LINQ how can i translate this statement to a working linq

I am having trouble with this I have 3 Data tables i use over and over again which are cached I would like to write a LINQ statement which would do the following is this possible?
T-SQL VERSION:
SELECT P.[CID],P.[AID]
,B.[AID], B.[Data], B.[Status], B.[Language]
FROM MY_TABLE_1 P
JOIN
(
SELECT A.[AID], A.[Data], A.[Status], A.[Language] FROM MY_TABLE_2 A
UNION ALL
SELECT B.[AID], B.[Data], B.[Status], B.[Language] FROM MY_TABLE_3 B
) B on P.[AID] = B.[AID]
WHERE B.[Language] = 'EN' OR B.[Language] = 'ANY' AND B.STATUS = 1 AND B.[Language] = 'EN' OR B.[Language] = 'ANY' AND B.STATUS = 1
Then i would like it to create a result set of the following
Results:
|CID|AID|DATA|STATUS|LANGUAGE
Try this:
from p in Context.MyTable1
join b in Contact.MyTable2.Concat(Contact.MyTable3)
on p.aid equals b.aid
where b.Language == "EN" || b.Language == "ANY"
where b.Status == 1
select new
{
p.CID,
p.AID,
b.Data,
b.Status,
b.Language
};
Don't do it this way.
Your two options
Create a view which represents your Union statement (Table2 and Table3)
Create a relationship on the DBML between Table1 and the new view on the AID column.
Do a SelectMany to get your required return result.
or (and preferred)
Create a stored procedure that accepts the language / status (assuming they are parameters) and returns this data set. This will be the most efficient method.
You are doing database work in your business logic! Use the database for what it was intended.
Make sure you reference System.Data.DataSetExtensions, and use the AsEnumerable() method to use LINQ to DataSets.
var myTable1 = new [] {
new { CID = "123", AID = 345, Data = 32323, Status = 1, Language = "EN"},
new { CID = "231", AID = 123, Data = 11525, Status = 2, Language = "EN"},
new { CID = "729", AID = 513, Data = 15121, Status = 1, Language = "ANY"},
new { CID = "231", AID = 123, Data = 54421, Status = 2, Language = "EN"}}
.ToDataTable().AsEnumerable();
var myTable2 = new [] {
new { CID = "512", AID = 513, Data = 32323, Status = 1, Language = "ANY"},
new { CID = "444", AID = 123, Data = 11525, Status = 2, Language = "BLAH"},
new { CID = "222", AID = 333, Data = 15121, Status = 1, Language = "ANY"},
new { CID = "111", AID = 345, Data = 54421, Status = 2, Language = "EN"}}
.ToDataTable().AsEnumerable();
var myTable3 = new [] {
new { CID = "888", AID = 123, Data = 32323, Status = 2, Language = "EN"},
new { CID = "494", AID = 333, Data = 11525, Status = 1, Language = "FR"},
new { CID = "202", AID = 513, Data = 15121, Status = 1, Language = "EN"},
new { CID = "101", AID = 345, Data = 54421, Status = 2, Language = "ANY"}}
.ToDataTable().AsEnumerable();
var q = from p in myTable1
join b in myTable2.Union(myTable3) on p.Field<int>("AID") equals b.Field<int>("AID")
where (b.Field<string>("Language") == "EN" || b.Field<string>("Language") == "ANY") && b.Field<int>("Status") == 1
select new
{
CID = p.Field<string>("CID"),
B_AID = p.Field<int>("AID"),
P_AID = b.Field<int>("AID"),
Data = b.Field<int>("Data"),
Status = b.Field<int>("Status"),
Language = b.Field<string>("Language")
};
var table = q.ToDataTable();
I used an extension method you can find here to test this, it's pretty useful if you are doing a lot of LINQ over DataTables.

Categories