Generating a JSON outcome from a SQL server database

My SQL server has the following table layout:

Table (    id int,
           title varchar(40),
           start Date(),
           end Date(),
           allDay bool,
           username varchar(40)
      );

I found some code on this blog to create a JSON object from my data, but it doesn't match how my data is stored. How can I create a similar object based on my database structure?

I think I need to convert the file to a .cshtml instead of a .js and use this code snippet:

@{
    var db = Database.Open("events"); 
    var selectQueryString = "SELECT * FROM events";
}

 @foreach(var row in db.Query(selectQueryString)){ }

But I'm not sure how to modify this code to generate the same JSON object.

Here is the relevant code from the blog, along with my attempt 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 trying to work with the following .cshtml code for the GetEvents command, however it seems to be failing. Any suggestions?

   @{ 
        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";
    }

Answer №1

In WebMatrix WebPages, there is no need for controllers and actions. Instead, you can create a separate .cshtml page to fetch data from the database and serve it as JSON 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";
}

Then, in another page where you want to display the calendar, you can configure it like this:

$(document).ready(function() {             
    $('#calendar').fullCalendar({ 
        theme: true, 
        header: { 
            left: '', 
            center: '', 
            right: '' 
      }, 
        defaultView: 'agendaDay', 
        editable: false, 
        events: '/events.cshtml' 
    }); 
});

UPDATE: Here's an example showcasing how parametrized queries can be used:

@{

    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";
}

You can now query the page using parameters like this:

/events.cshtml?start=5&end=10

Answer №2

DECLARE @listColumn VARCHAR(2000)
DECLARE @sqlQuery VARCHAR(4000)

SELECT  @listColumn = STUFF(( SELECT distinct  '], [' + [PSize]
                           FROM     Pattern
                         FOR
                           XML PATH('')
                         ), 1, 2, '') + ']'


SET @sqlQuery = 'SELECT * FROM
      (SELECT PColour as Colour_Size_Matrix, PSize, PCode
            FROM Pattern
            ) source
PIVOT (Count(PCode) FOR PSize
IN (' + @listColumn + ')) AS pivotTable'

EXECUTE ( @sqlQuery )

I need the output of this query in JSON format

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I eliminate unwanted zombie events in Vue JS?

How do you get rid of a zombie event? When navigating back and forth, the events run multiple times. MainApp.vue <template> <input type="button" @click.prevent="handleClick()" value="Click Me"> </template> <script> export defa ...

What is the best way to stretch the background image across both the footer and navbar for my app?

Here is the code snippet I am currently working with: <template> <v-app> <AppBar></AppBar> <v-main> <router-view></router-view> </v-main> <Footer></Footer> ...

Steps for implementing a reset button in a JavaScript slot machine game

I need assistance with implementing a reset button for my slot machine game prototype written in JS. I attempted to create a playAgain function to restart the game by calling the main game function, but it's not working as expected. Do I need to pass ...

What advantages come from selectively importing a single function from a Node.js package on the backend, rather than importing the entire package?

Consider a scenario where I only require the ObjectId function from the mongoose package in my file. Are there any advantages (in terms of CPU usage, memory consumption, speed, etc.) to importing just that specific function instead of the entire mongoose ...

Filtering out section boxes does not eliminate empty spaces

Link to Fiddle I've run into a bit of a roadblock while trying to filter my section box for a project I'm currently working on. The issue I'm facing is that instead of collapsing the first section box to display only the filtered options, i ...

I encounter an error message stating "Cannot read property 'push' of undefined" when trying to add an item to a property within an interface

I have a model defined like this : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode[]; } export interface TrackMode { trackNumber: number; ...

Encountering issues with SignInWithRedirect feature's functionality

Whenever I attempt to SignInWithRedirect in my React project, I am redirected to a Google site where I only see a blue progress bar at the top before quickly being redirected back to my website. My intention is to be shown my Google sign-in options, but it ...

Error encountered: jquery form validation fails to register changes

I am currently developing a calculator-like code where users will submit a form multiple times, and I need to save the result of calculations only if there are changes in the form. For instance, when a user clicks the "Calculate" button for the first time, ...

The status is currently not defined when attempting to retrieve JSON data and display it on individual pages for each piece of data

I have written some code where I am trying to display the attributes of a selected product from my product page based on its ID. For example, when a product is clicked, it should redirect to a URL like /#/product/2 and display all the attributes of the pro ...

Performing numerous asynchronous MongoDB queries in Node.js

Is there a better way to write multiple queries in succession? For example: Space.findOne({ _id: id }, function(err, space) { User.findOne({ user_id: userid }, function(err, user) { res.json({ space: space, user: user}); }); }); It can g ...

Attempting to provide varying values causes If/Else to become unresponsive

I've implemented a function that scans a file for a specific term and then outputs the entire line as a JSON object. Strangely, when I include an else statement in the logic, an error occurs: _http_outgoing.js:335 throw new Error('Can\& ...

Start by creating a set of vertices and triangles to be utilized by the vertex shader

After experimenting with vertexshaderart.com, I'm eager to apply what I've learned on a different website. While I have experience using shaders in the past, some effects achieved on the site require access to vertices, lines, and triangles. Pass ...

SQL query is not producing any results

Hello, I am having trouble running the query below as it is not returning anything. I just want to retrieve the job description for the selected job type from my jobs table. Any assistance would be highly appreciated as I have been struggling with this fo ...

Tips for concealing a particular button that shares the same class designation

Is there a way to create a function in vanilla JavaScript that can hide a specific button? <button class"btn">button 1 </button> <button class"btn">button 2 </button> <button class"btn">button 3 </button> Specifically, ...

SQL limit is not functioning as expected: how should the syntax be correctly written?

I have a quick query, and I apologize if it seems too basic. Currently, I am establishing a connection to a remote database with the following code: import pyodbc import pandas as pd import numpy as np cnxn = pyodbc.connect('DSN=MYDSN') After ...

Is it possible for an ul to be displayed beneath a white section within an li

I am working on a JQuery carousel that is displaying correctly, but I want to make a small adjustment to the content: <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-1 jcarousel-item-1-horizontal" style="float: left; list-style: none ...

Component not being returned by function following form submission in React

After spending a few weeks diving into React, I decided to create a react app that presents a form. The goal is for the user to input information and generate a madlib sentence upon submission. However, I am facing an issue where the GenerateMadlib compone ...

Issue encountered while attempting to retrieve data from a local json file due to Cross-Origin Resource Sharing

I'm attempting to fetch and display the contents of a JSON file on a webpage, but I'm encountering this error message: Access to XMLHttpRequest at 'file:///C:/Users/bobal/Documents/htmlTry/myData.json' from origin 'null' has ...

Tips for incorporating a page route with an HTML extension in Next.js

I'm facing a challenge in converting a non-Next.js page to Next.js while maintaining my SEO ranking. To preserve the route structure with HTML extensions and enhance visual appeal, I have outlined the folder structure below: Unfortunately, when acces ...

Troubleshooting a cross-origin resource sharing problem in Express.js

I've set up Express as the backend for my client application, but I keep encountering an issue when trying to make a request to the GET /urls endpoint. The error message I receive is: Access to fetch at 'http://localhost:5000/urls' from orig ...