How to improve Client Side DataTable performance in C# ASP.NET MVC Project?

In our test environment, it takes about 55 seconds to load approximately 5,500 records. We are using the following DataTable script:

    <script>
        $(document).ready(function() {
            $("#DataTable").DataTable({
                stateSave: true,
                stateSaveCallback: function(settings, data) {
                    localStorage.setItem(`DataTables_${settings.sInstance}`, JSON.stringify(data));
                },
                stateLoadCallback: function(settings) {
                    return JSON.parse(localStorage.getItem(`DataTables_${settings.sInstance}`));
                },
                stateDuration: 0,
                searching: true,
                columnDefs: [
                    {
                        orderable: false,
                        searchable: false,
                        targets: @ViewBag.NoSort
                    }
                ],
                order: [[@ViewBag.InitSort, "desc"]]
            });

            $(".dataTables_length").addClass("form-inline pb-2");

            $(".dataTables_length select").addClass("mx-1");

            $(".dataTables_filter").addClass("form-inline float-right pb-2");

            $(".dataTables_paginate").addClass("float-right");

        });
    </script>

Not sure if ~5,500 records call for a server side DataTable script.

How can this DataTable script be updated to improve response time/performance?

Compare Javascript Object field with another Object field

I have two Objects one of them has the Store Name and the other object has the Price for an item along with the Store ID on both objects. Such as;

obj1 = [
    {id: 1,name: "Store1"},
    {id: 2,name: "Store2"},
    {id: 3,name: "Store3"}
  ];

obj2= [
{ id: 1, price: 100 },
{ id: 2, price: 200 },
{ id: 3, price: 300 }
];

What I want to achieve is that compare obj1 id with obj2 id if they are the same get the price and the store name from the same id. What is the best way to achieve this? I have been trying to use Array.map or filter but can’t really make it work. Thank you!

Catching statements ignore errors of catch statements

I’m working on an authentication system for my React app. For this I made a hook that will fetch the user if a cookie is present. Unfortunately, I cannot catch the 400 error in any way.. I tried .catch((e) => ()) and regular try{} catch{}.

Here’s the function that fetches the user from the session key:

const getUserBySession = async (sessionKey) => {
  const loginResponse = await fetch("http://localhost:5000/user/getbysession", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      sessionKey,
    }),
  }).catch((error) => console.log("invalid session"));
  const loginResponseJson = await loginResponse.json();
  if (loginResponse.status !== 200 || loginResponseJson.error) return;

  return { ...loginResponse };
};

For some reason it keeps just showing the 400 error in red in the console without catching it, meaning that it completely skips all the code below the fetch statement, which really shouldn’t happen…

I’m calling this function in my hook like:

const useAuthentication = () => {
  const [userToken, setUserToken] = useCookie("token");
  const [user, setUser] = useState();

  useEffect(() => {
    if (!user && userToken) {
      console.log("found user token");
      getUserBySession(userToken).then((fetchedUser) => {
        if (fetchedUser) setUser(fetchedUser);
        else setUserToken(undefined);
      });
    }
  }, []);

  const setUserAndSession = (user) => {
    setUserToken(user.session);
    setUser(user);
  };

  return [user, setUserAndSession];
};

This all keeps resulting in an ugly 400 console error that references the line with fetch in it:
enter image description here

If someone knows any solution or other debugging steps I could take, please let me know. Thanks in advance.

Display data from db on HTML using Node.js

I am trying to get a webpage to display data from my database and display it on a html page in a table and be able to scroll down on the table by rendering it in ejs. I based my code from this site https://www.tutsmake.com/node-js-fetch-and-display-data-from-mysql-database-in-html-list/

i’m not really sure what I’m doing wrong, the db is connecting just fine, and I have the ejs file in my views folder. I’m guessing the issue is coming from the ejs file but I’m not sure. I’ve just started coding again so this is basically all new to me.

when I go to localhost:3000/test I’m getting a 404 error and when I look at the terminal it says GET/TEST 404 20.377ms -1153, I think I might be pulling to much data at once since the there are 75 rows for this, I’ve tried to limit the amount of rows but it still wont load the page and for some reason this code can’t even find my ejs file.

From what I’ve read online there are a million different ways to do this and I don’t know where to start to get this working. I’m using mssql as my database and using visual studio to build everything.

this is my server.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressValidator = require('express-validator');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');

var sql = require("mssql/msnodesqlv8");
var connection = require('./lib/db');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
   secret: '123456cat',
   resave: false,
   saveUninitialized: true,
   cookie: { maxAge: 60000 }
}))

app.use(flash());
app.use(expressValidator());

app.use('/', indexRouter);
app.use('/index', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
   next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
   // set locals, only providing error in development
   res.locals.message = err.message;
   res.locals.error = req.app.get('env') === 'development' ? err : {};
   // render the error page
   res.status(err.status || 500);
   res.render('error');
});
module.exports = app;

this is my dbaCon.js

const sql = require("mssql/msnodesqlv8");

var conn = new sql.ConnectionPool({
    server: 'DESKTOP-BA7Q2HM',
    port: 1433,
    driver: 'msnodesqlv8',
    database: "tempdb",
    domain: 'DNAME',
    requestTimeout: 3600000,
    options: {
        trustedConnection: true,
        enableArtithAbort: true
    },
    debug: true,
    parseJSON: true
});

conn.connect(function (err) {
    if (err) throw err;
    console.log('Database is connected successfully!');
});
module.exports = conn;

this is my users.js

var express = require('express');
var router = express.Router();
var connection = require('../dbaCon.js');


/* GET home page. */
router.get('/', function (req, res, next) {

    connection.query('SELECT id, status, type, Date, Review * FROM [dba].[table] ', function (err, rows) {

        if (err) {
            req.flash('error', err);
            res.render('index', { page_title: "test - Node.js", data: '' });
        } else {

            res.render('index', { page_title: "test - Node.js", data: rows });
        }

    });
});

module.exports = router;

this is my index.ejs file

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Display Active Loan info to Client</title>
</head>
<body>
    <% if (messages.error) { %>
    <p style="color:red"><%- messages.error %></p>
    <% } %>
    <% if (messages.success) { %>
    <p class="alert alert-success mt-4"><%- messages.success %></p>
    <% } %>
    <br>
    <table class="table">
        <thead>
            <tr>
                <th scope="col">id</th>
                <th scope="col">status</th>
                <th scope="col">type</th>
                <th scope="col">date</th>
                <th scope="col">review</th>

            </tr>
        </thead>
        <tbody>
            <% if(data.length){
            for(var i = 0; i< data.length; i++) {%>
            <tr>
                <th scope="row"><%= (i+1) %></th>
                <td><%= data[i].id%></td>
                <td><%= data[i].status%></td>
                <td><%= data[i].type%></td>
                <td><%= data[i].date%></td>
                <td><%= data[i].review%></td>
            </tr>
            <% }
            }else{ %>
            <tr>
                <td colspan="3">No Data Availed</td>
            </tr>
            <% } %>
        </tbody>
    </table>
</body>
</html>

Angular way of doing javascript getById code

I’m working on a migration project from AngularJS to Angular8

where I came across this code

// get the pattern from SVG document and set the stroke color
 var patternElt = $scope.svgDocument.find("#striped");
 patternElt.css("fill", color);
 // apply the striped class to the element
 element.css("fill", "url(#striped)");
 $(zoneClassSelector, element).css("fill", "url(#striped)");

what the above code does is when an element is clicked, it gets a pattern element from an svg file (below) and adds a fill color to it, and then applies it on the clicked DOM element :

<defs>
    <pattern id="striped" 
        width="8" height="8" 
        patternUnits="userSpaceOnUse"
        patternTransform="rotate(45)">
        <rect width="4" height="8" transform="translate(0,0)"></rect>
    </pattern>
</defs>

In my case in Typescript code I have the following

click($event: MouseEvent) {

let clickedEl = $event.target;
// check if clicked element is not an svg element 
if (clickedEl instanceof SVGPolygonElement || clickedEl instanceof SVGPathElement || clickedEl instanceof SVGGElement) {
  this.renderer.setAttribute(clickedEl, "style", "fill:url(#striped);");
}

}

Note: the SVG file is loaded with its path (no SVG xml in the component view to reference)

How could I get the striped pattern element using Typscript to add a fill color to it before pass it to the renderer setAttribute

React Router v2.7 to v6 onEnter Migration

I am trying to migrate an application running on router v3, using the onEnter attribute for route after auth.

onEnter function in YAMain.jsx

    static onEnter(store) {
        return (nextState, replaceState, callback) => {

            // Check if the user is logged in and allowed to make requests before letting them proceed
            store.dispatch({
                type: IS_LOGGED_IN,
                onLoggedIn: () => {
                    store.dispatch({
                        type: GET_SELECTED_LOCATION_AND_CLASSROOM,
                        onSuccess: callback,
                        onFailure: () => {

                            // Get all of the required information from the store
                            const profile = getProfile(store.getState());
                            const selectedClassroom = getSelectedClassroom(store.getState());
                            const selectedLocation = getSelectedLocation(store.getState());

                            // No location has been selected by an admin, go to the locations page
                            if (profile.get('accessLevel') !== 'E' && !selectedLocation.get('id')) {

                                // Return early if this is the page we are going to
                                if (nextState.location.pathname.startsWith('/location')) {
                                    return callback();
                                }

                                replaceState('/location');
                                return callback();
                            }

                            // No classroom has been selected by a user, go to the classrooms page
                            if (!selectedClassroom.get('id')) {

                                // Return early if this is the page we are going to
                                if (nextState.location.pathname.startsWith('/classroom')) {
                                    return callback();
                                }

                                replaceState('/classroom');
                                return callback();
                            }

                            return callback();
                        }
                    });
                },
                onNotLoggedIn: () => {
                    replaceState('/login');
                    callback();
                },
                onFailure: (error) => {
                    if (isTimeGateError(error)) {
                        replaceState('/locked');
                        callback();
                    }
                }
            });
        };

render function in YARouter.jsx, both classes extend component.

    render() {
        return (
            <BrowserRouter>
                <Routes>
                    {/* Handles the main logic and renders all but one of the pages */}
                    <Route
                        exact path="/"
                        element={<YAMain/>
                        }
                        onEnter={YAMain.onEnter(this.props.store)}
                    >
                        <Route path="/" element={YADashboard}/>

                        {/* Locations page displays the available list of locations */}
                        <Route
                            path="location"
                            element={YALocations}
                        />

                        {/* Classrooms page displays the available list of classrooms */}
                        <Route
                            path="classroom"
                            element={YAClassrooms}
                        />

this is not the entirety of the routing but should be enough to give you an idea of what’s going on.

This is what I have now, I have tried a number of things suggested on various places. I’m trying to understand how I can either make this work so I can move on and work on this and make it proper later, OR make it proper now and fix this issue.

How can I go about ensuring proper redirection for user authentication, I’ve spent 2 days at work trying to figure anything out and am completely stuck.

Thanks.

wait for a function inside if statment

Hi I am kinda new to js and its hard for me to understand that code can execute before the code before him finished, so here is my problem:

I have a function that logs in a user to a server based on the provided email and password (the server pard works) and I want to wait for the function to return a bool value:

    if (logInUser(userToLogin)){
        // do something if succes
        console.log("loged in")
    }else{
        // do something if not login
        console.log("not logged in")
    }

here is the function:
this function sends a post request to an API and based on the response return true or false

const logInUser = (user) => {
fetch("/api/login", { method: "POST", body: JSON.stringify(user)})
.then(data => {
    console.log(data.status)
    if (data.status === 201){
       return true;
    }else if(data.status === 401){
        alert("check email and password and try again");
        return false;
    }else{
        alert("unknown error try again");
        return false;
    };
});

};

so no matter what I send it will console.log(“not logged in”) although the login process was a success:

when I send the correct email and password

as u can see the response was 201, the user logged in but the console log “not logged in”.

when I enter random velues

here is the response I get when I give a random email and value the log also happens before I get the response.

so how can I make the if statements wait for the “logInUser: function to finish

I tried adding await like so:

  if (await logInUser(userToLogin)){
        // do something if succes
        console.log("loged in")
    }else{
        // do something if not login
        console.log("not logged in")
    } here

but it’s not working.

How do I make background Image on each division row from URL

I need to display different background URL on each row base on the item in MySQL. I use php mySQL fetch array to get the item name and background URL. So far, I was able to get the URL background and display in row by using CSS, but every time I choose different item all division row get’s overwritten by this new background. This result to have duplicate background.
I have attached of sample image where the background image of division row got overwritten and duplicate image.

[Duplicate Row Background][1] [1]: https://i.stack.imgur.com/qxLOI.png

Snippet of Php fetch array to echo the division and the CSS id of Background Image.

<style>
.blocks {
  display:table-row;
  
}
.block {
  display:table-cell;
  height:100px; 
}

#background-container { 
  display:table;
  width:100%;
  border-collapse:collapse;
  background: url(<?php echo  $bgurl; ?>) center;
   -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
</style>
while ($row = mysqli_fetch_array($query)) 
                    {
                        $pro_id = $row['pro_id'];
                        
                                $sql1 = "SELECT * FROM products WHERE product_id = '$pro_id' ";
                                $query1 = mysqli_query($conn , $sql1);
                                while ($row1 = mysqli_fetch_array($query1)) 
                                {

                                    $id = $row1['product_id'];
                                    $name = $row1['product_title'];
                                    $element = $row1['product_price'];
                                    $faction = $row1['product_description'];
                                    $picture = $row1['product_image'];
                                    $class = $row1['product_keywords'];
                                    $rarity = $row1['sales'];
                                    $bgurl = $row1['bgurl'];
                               
                            

                                echo 
                                '
                                
                                   <div class="container" id ="background-container">
                                
                                    <div class="row pt-2 pb-1" style="border-top: .5px  solid grey; border-bottom: .5px  solid grey;" >
                                    <div class="col-4" >
                                        <p class="squad1-title" >'.$bgurl.'</p>
                                    </div>
                                    <div class="col-7">
                

                                        
                                    </div>
                                    
                                    <div class="remove" >
                                        <i class="fa fa-minus-square removeitem" style="padding center" data-proid="'.$id.'" title="Remove"> </i>
                                    </div>
                                    </div>
                                   </div>
                                ';
                                }
                    }

getting the size of img using javascript without the table part [closed]

hi so I’ve been working on some code.

<!DOCTYPE html>
<html>
    <body>
<table>
    <tr>
        <th id="th">
        </th>
    </tr>
</table>
            <img
            id="photo"
            src="../img/2.jpeg"
             width="30%" height="30%" 
            />
<script>
    var th = document.getElementById('th');
    alert(th.clientHeight);
    </script>
    <script>
    var img = document.getElementById('photo'); 
    var width=img.clientHeight;
    var height=img.clientHeight;
    alert(width+"--"+height);
        </script>
    </body>
</html>

the strange thing is, it works unless I remove the table part. Even the alert is enough.
does anybody have an idea what causes this?
and how to solve it?

How to read xlsx files in Mirth

I am new to mirth and trying to see if anyone is knowledgeable on how mirth handles excel files.

Right now, My mirth channel works great with zip files, csv, and txt files but not xlsx. When it encounters an xlsx file it errors out.

[2022-02-08 09:37:00,037]  ERROR  (com.mirth.connect.donkey.server.channel.Channel:1288): Error processing message in channel xlsx (5447c43e-7aee-4ade-9460-d490edef7f04).
com.mirth.connect.donkey.server.channel.ChannelException: 
    at com.mirth.connect.donkey.server.channel.Channel.dispatchRawMessage(Channel.java:1243)
    at com.mirth.connect.donkey.server.channel.SourceConnector.dispatchRawMessage(SourceConnector.java:192)
    at com.mirth.connect.donkey.server.channel.SourceConnector.dispatchRawMessage(SourceConnector.java:170)
    at com.mirth.connect.connectors.file.FileReceiver.processFile(FileReceiver.java:418)
    at com.mirth.connect.connectors.file.FileReceiver.processFiles(FileReceiver.java:328)
    at com.mirth.connect.connectors.file.FileReceiver.poll(FileReceiver.java:239)
    at com.mirth.connect.donkey.server.channel.PollConnectorJob.execute(PollConnectorJob.java:49)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)Caused by: com.mirth.connect.donkey.server.data.DonkeyDaoException: org.postgresql.util.PSQLException: ERROR: invalid byte sequence for encoding "UTF8": 0x00
    at com.mirth.connect.donkey.server.data.jdbc.JdbcDao.insertContent(JdbcDao.java:287)
    at com.mirth.connect.donkey.server.data.jdbc.JdbcDao.insertMessageContent(JdbcDao.java:199)
    at com.mirth.connect.donkey.server.data.buffered.BufferedDao.executeTasks(BufferedDao.java:110)
    at com.mirth.connect.donkey.server.data.buffered.BufferedDao.commit(BufferedDao.java:85)
    at com.mirth.connect.donkey.server.data.buffered.BufferedDao.commit(BufferedDao.java:72)
    at com.mirth.connect.donkey.server.channel.Channel.dispatchRawMessage(Channel.java:1215)
    ... 8 moreCaused by: org.postgresql.util.PSQLException: ERROR: invalid byte sequence for encoding "UTF8": 0x00
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2455)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2155)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:288)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:430)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:356)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:168)
    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:135)
    at com.mirth.connect.donkey.server.data.jdbc.JdbcDao.insertContent(JdbcDao.java:284)
    ... 13 more ```

Value is concatenated instead of added using DevExpress controls

I’m new to using DevExpress controls and Javascript and would like to enter a value into 2 textboxes and for the result to be returned in the 3rd textbox. Code below:

         function sum() {
             var num1 = +txtValue1.GetValue();
             var num2 = +txtValue2.GetValue();
             var result = parseInt(txtValue1.GetValue) + parseInt(txtValue2.GetValue);             
         } 
        </script>
        <style type="text/css">
        #form1 {
            align-content: center;
            display: block;
            height: 288px;
            margin-top: 0px;
        }
    </style>
    <title></title>
</head>
<body>
    
    <form id="form1" runat="server">
    
         <div>
            Toms Test Form</div>
            
             <br />  
                <dx:ASPxLabel ID="lblValue1" ClientInstanceName="lblValue_1" runat="server" Text="Value 1:" ></dx:ASPxLabel> <br />
                <dx:ASPxTextBox ID="txtValue1" runat="server" Width="180px" Height="5px"> 
                    <ValidationSettings ValidationGroup="vgtxtValue1">
                        <RequiredField IsRequired="True" ErrorText="You must enter a value" />
                 </ValidationSettings>  
                </dx:ASPxTextBox>
                <dx:ASPxLabel ID="lblValue2" ClientInstanceName="lblValue2" runat="server" Text="Value 2:"></dx:ASPxLabel>
                <dx:ASPxTextBox ID="txtValue2" runat="server" Width="180px" Height="5px">
                    <ValidationSettings ValidationGroup="vgtxtValue2">
                     <RequiredField IsRequired="True" ErrorText="You must enter a value"/>
                    </ValidationSettings>
                </dx:ASPxTextBox> 
                <dx:ASPxLabel ID="lblTotal" runat="server" Text="Value Total:" ></dx:ASPxLabel>
                <dx:ASPxTextBox ID="txtTotal" runat="server" Width="180px" Height="5px" readonly="true"></dx:ASPxTextBox> <br />
                <dx:ASPxButton  ID="btnTotal" runat="server" Text="Calculate Total" >
                    <ClientSideEvents Click="sum"/></dx:ASPxButton>          
         <div />```

Sprite tile detection issue

A little new to JS so I apologize if my code looks… rudimentary… but I’m trying to code a platformer completely from scratch. I started this project with very little JS knowledge and have made quite some progress since. I just finished coding hitbox detection, however buggy it may currently be, and it works pretty well. I still have to work out some kinks and only the bottom two anchors have been actually coded but I ran into an issue that haven’t been able to find a definitive answer to.

Code
https://pastebin.com/C8xPtCv1

Line 724:

 if (tile3 == "D27" || tile3 == "D28" || tile3 == "D29" || tile3 == "D30" || tile4 == "D27" || tile4 == "D28" || tile4 == "D29" || tile4 == "D30" || tile3 == "H36" || tile3 == "H37" || tile3 == "H38" || tile3 == "H39" || tile4 == "H36" || tile4 == "H37" || tile4 == "H38" || tile4 == "H39" || tile3 == "L30" || tile3 == "L31" || tile3 == "L32" || tile3 == "L33" || tile4 == "L30" || tile4 == "L31" || tile4 == "L32" || tile4 == "L33" || tile3 == "L20" || tile3 == "L21" || tile3 == "L22" || tile3 == "L23" || tile4 == "L20" || tile4 == "L21" || tile4 == "L22" || tile4 == "L23") {

On line 724 I have coded a basic detection system that allows the sprite to interact with 4 platforms. The issue; its extremely tedious, and if I plan on coding multiple scenes all on a 48×27 tile canvas this is not a great way to go about it. My initial thinking for tile detection was arrays but in my fruitless attempts at trying to figure them out I failed. I’m looking for a way to assign each anchor to each tiles state. Currently the way to do that is the test if the anchor is inside the tile. eg. (tile3 == “D27 || tile4 ==”D27”) writing this code for EVERY tile however, is not the way I want to write this code, not to mention the sprite has 2 more anchors i need to code for head collision. I want to write these conditionals in a more efficient way but i have no idea how.

Rounding the corners of an SVG

I’m using a package that generates a rectangular Treemap with this structure:

  • svg (wrapper with width=100% and height=100%)
    • svg (the outer rectangle of the Treemap, also width=100% and height=100%)
      • g (one for each Treemap node)
        • rect
        • clipPath
        • text

enter image description here
I need to round the four corners of the entire Treemap (not the rx ry of each rect within).

Is it possible to do that by creating a clipPath either as a child of the wrapper or the inner svg that defines a rounded rectangle? If so, can it expose whatever the background color is behind the svg?