JOIN query using SignalR and SqlDependency in ASP.NET Core

In my project, I use SignalR and SqlDependency. There is no problem when I use a normal SELECT query or a parameterized query. But when I create a query with JOIN, I get an error.

Repository,

    public List<ResultNotificationDto> ListNotification(int id)
    {
        var notificationDtos = new List<ResultNotificationDto>();

        using (var connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string query = "SELECT N.LogID, U.Name + ' ' + U.Surname AS SenderUserID, N.RecordID, N.Timestamp, N.Description, N.Title, N.NotificationIcon FROM Notification N INNER JOIN AspNetUsers U ON N.SenderUserID = U.Id WHERE N.Status = 0 AND N.ReceiverUserID = @receiverUserID";
            var cmd = new SqlCommand(query, connection);
            cmd.Parameters.AddWithValue("@receiverUserID", id);
            var dependency = new SqlDependency(cmd);
            dependency.OnChange += new OnChangeEventHandler(dbChangeNotification);
            var reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                var notificationDto = new ResultNotificationDto
                {
                    LogID = Convert.ToInt32(reader["LogID"]),
                    SenderUserID = reader["SenderUserID"].ToString(),
                    Action = reader["Action"].ToString(),
                    TableName = reader["TableName"].ToString(),
                    RecordID = Convert.ToInt32(reader["RecordID"]),
                    Timestamp = Convert.ToDateTime(reader["Timestamp"]),
                    Description = reader["Description"].ToString(),
                    Title = reader["Title"].ToString(),
                    NotificationIcon = reader["NotificationIcon"].ToString(),
                };
                notificationDtos.Add(notificationDto);
            }
        }
        return notificationDtos;
    }

    private void dbChangeNotification(object sender, SqlNotificationEventArgs e)
    {
        _hubContext.Clients.All.SendAsync("ReceiveNotification");
    }

Index.cshtml,

<script>
    $(document).ready(() => {
        let connection = new signalR.HubConnectionBuilder().withUrl("/appHub").build();
        connection.start();

        connection.on("ReceiveNotification", function () {
            loadData()
        });

        loadData();

        function loadData() {
            $.ajax({
                type: "Get",
                url: "/Home/GetIndex",
                success: function (value) {
                    $("#tableExpense tbody").empty();

                    var tablerow;
                    $.each(value, (index, item) => {
                        tablerow = $("<tr/>");
                        tablerow.append(`<td><a class="fw-semibold text-primary">#${item.logID}</a></td>`)
                        tablerow.append(`<td>${item.senderUserID}</td>`)
                        tablerow.append(`<td>${item.action}</td>`)
                        tablerow.append(`<td>${item.tableName}</td>`)
                        tablerow.append(`<td>${item.recordID}</td>`);
                        tablerow.append(`<td>${item.timeStamp}</td>`);
                        tablerow.append(`<td>${item.description}</td>`);
                        tablerow.append(`<td>${item.title}</td>`);
                        tablerow.append(`<td>${item.notificationIcon}</td>`);
                        $("#tableExpense").append(tablerow);
                    })
                },
                error: function (xhr, status, error) {
                }
            })
        }
    });
</script>

HomeController.cs,

[HttpGet]
public async Task<IActionResult> GetIndex()
{
    var findUser = await _userManager.FindByNameAsync(User.Identity.Name);
    int id = findUser.Id;
    return Ok(_notificationDal.ListNotification(id));
}

GET https://localhost:7243/Home/GetIndex 500 (Internal Server Error)

I get this error in the console.

ERR_TOO_MANY_REDIRECTS with Next.js on Vercel and Custom Domain on Cloudflare

I’m experiencing an issue with setting up my Next.js project hosted on Vercel with a custom domain managed through Cloudflare. Despite configuring the DNS and SSL settings correctly, I keep running into a net::ERR_TOO_MANY_REDIRECTS error when I try to access my site at www.example.io.

Here’s what my setup looks like:

  • Domain: www.example.io
  • Hosting: Vercel
  • DNS: Cloudflare

I have created a CNAME record in Cloudflare’s DNS settings like this:

  • Type: CNAME
  • Name: www
  • Content: cname.vercel-dns.com
  • Proxy status: DNS only
  • TTL: Auto

Additionally, I’ve set Cloudflare’s SSL/TLS encryption mode to “Full”.

Has anyone encountered this issue before, and can you suggest any solutions or further troubleshooting steps I can take?

Thank you in advance for your help!

video incrusted in a modal window outbounds the limits of container

First of all, sorry if im english is not good. Im reading this forum for years ago, and now, is the first time that i need your help guys, please, consider help me, because im not an expert of front-end.

I have a web, with a datatable with movementst. This movements have a button to open a modal window, and is here where i have the problem.

I spent a lot of days, hours, nigths… with this problem, and im sure that is a silly thing, but im so bad with frontend.

when the modal opens two videos from different angles of movements beggining to play (i change this videos for other standard and public). This is OK.

But when i want to zoom with wheel mouse event, and i want to drag the video zoomed, it can be outside of the container, and i want that the video stays in the container.

I attach a jsfiddle with the case:

(https://jsfiddle.net/pililagorda/y4v7z2c0/2/)

Could you help me please?

Thanks in advance
Sorry for the inconveniences
Kind regards

But when i want to zoom with wheel mouse event, and i want to drag the video zoomed, it can be outside of the container, and i want that the video stays in the container.

Framer Motion exit animation with useAnimate() and useEffect() not working

I’m trying to implement exit animation with the new way using useAnimate hook and useEffect but for some reason its not firing up.

Here’s my code inside the useEffect function:

  const [scope, animate] = useAnimate();
  const [isPresent, safeToRemove] = usePresence();

  useEffect(() => {
    if (isPresent) {
      const enterAnimation = async () => {
        await animate([
          [
            "#title",
            { opacity: [0, 1], y: [-20, 0] },
            { duration: 0.5, delay: stagger(0.2) },
          ],
          [
            "#text",
            { opacity: [0, 1], y: [-20, 0] },
            { duration: 0.5, delay: stagger(0.2) },
          ],
        ]);
      };
      enterAnimation();
    } else {
      const exitAnimation = async () => {
        await animate(
          "#title",
          { opacity: [1, 0], y: [0, 20] },
          { duration: 0.5 },
        );
        safeToRemove();
        console.log("exited");
      };
      exitAnimation();
    }
  }, [selectedTab]);

… and here’s my codesandbox so you can see the markup, how i use <AnimatePresence> and anything else.

Any help would be appreciated!

Cannot read properties of undefined (reading ‘createElement’) on wp.element.createElement

I’m developing a WordPress plugin using ReactJS and I have these two files:

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from "./App";

document.addEventListener("DOMContentLoaded", function() {
    let container = document.getElementById("mcw-first");

    if (typeof container !== 'undefined' && container !== null) {
        ReactDOM.render(<App />, container);
    }
});

And App.js:

function App() {
    return (
      <div>Test div</div>
    );
  }
  
  export default App;

But the console of my browser outputs this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'createElement')
    at HTMLDocument.eval (index.js:23:46)

enter image description here

I’m using webpack to compile all the files into a single JavaScript file.

What is going on? I’ve seen other people with the same error but their problem was that they used import { React } from 'react' instead of the correct form import React from 'react' as I do…

Also where does come from wp.element? I’m pretty sure it’s some WordPress thing but why is it compiled in there in the React index.js file?

MongoDB aggregation query of subdocument in an array

I am working on a stats dashboard for a meditations application, and I’m having trouble constructing a MongoDB query to retrieve the most listened meditations based on user progress. The relevant collections are users and meditations.

A user document in the users collection looks like this:

{"_id": {"$oid": "627b519f73b2bd3375f5a7a5"}, "userProgress": {"meditationsPracticed": [{"timestamp": "11.5.2022, 9:03:34", "id": "5ef2ff0af1a23752be00651f"}, {"timestamp": "11.5.2022, 12:46:03", "id": "5eca520c10fe0480d350c9a4"}, /* more meditations */]}}

And a meditation document in the meditations collection looks like this:

{"_id": {"$oid": "5eca520c10fe0480d350c9ac"}, "name": "Sleep Well", "duration": {"$numberInt": "250"}}

I want to create a query that retrieves the most listened meditations based on the id values in the meditationsPracticed array within the userProgress field of the user document.

Any help with constructing this MongoDB query would be greatly appreciated. Thank you!

I tried multiple queries with $unwind and $lookup with no success

How can i fix this page wich appears before my website is loading?

Image showing the website loading first what seems to be the html then the styleWebsite fully loaded : [Page before fully loaded] (https://i.stack.imgur.com/cfvpw.png) ; Nice Page inspected ; Page with a problem inspected

I use wordpress and divi and there is a page with only urls that loads before all the esthetic content loads, my** cls suddenly increased on pagespeed insights** :

The website : Website with problem

I searched for everything and didn’t find nothing, now i tried to export my website in a sub domain of another hosting and the problem is fixed there but its the same files in dont understand any of it right now. Please help me.

So you can see here the website that I exported into a personal subdomain and we can see that there is no issue :

[domelex.snowblind-webmaster.fr]((https://domelex.snowblind-webmaster.fr) ;

Moreover, i noticed that when i inspect the pages, the head is built differently.

I don’t know what to do… I know that recently i did many changes like going from php 7.4 to 8.2, Updating the wordpress and deactivated W3 Total Cache because of a blank page of the death and finally deactivated the .htaccess file.

This error happens only with the homepage and I tried many lines of codes in order to load the css normaly but nothing.

Please help me guys

MongoDB/Mongoose: Unable to update array field in user document

I have an API endpoint

PATCH http://localhost:3000/api/v1/addToFavoriteCollection

 try {
    const user = await UsersCollections.findById(id);
    const { favourites } = user;
    // user.favourites.push({ resourceCollection, resourceName });
    // await user.save();

    //
    res.status(200).json({
      message: 'Added to favorites!',
      user
    });

and in postman i have:

{
    "message": "Added to favorites!",
    "user": {
        "type": "flashcard",
        "_id": "655cee1bce26ab5b90584157",
        "role": "user",
        "name": "gogo2",
        "email": "[email protected]",
        "password": "$2a$12$ZjP6i2PqRzsuPt8V2pTM.uBC.qZA2C/EiAVFTCwdzTlLyfrrO08/6",
        "__v": 0,
        "favourites": [
            "Regex",
            "Data structures"
        ]
    }
}

but i want to have access to favourites, so:

const { favourites } = user;

and

 res.status(200).json({
          message: 'Added to favorites!',
          favourites 
        });

but then in postman:

{
    "message": "Added to favorites!"
}

It is because of:

 const user = await UsersCollections.findById(id)

If i add lean()

  const user = await UsersCollections.findById(id).lean()

in postman it works:

{
    "message": "Added to favorites!",
    "favourites": [
        "Regex",
        "Data structures"
    ]
}

But if I use lean() i cant save to the database, since save() is a mongoDB/ mongoose method and lean converts MongoDB object to Javascript Object, and than i cant save it to the collection.

Why i cant have access to favourites using const user = await UsersCollections.findById(id) without using lean() and the not be able to save it?

Console says: cant push on undefined..

i tried others methods:

 try {
 
    const updatedUser = await UsersCollections.findByIdAndUpdate(
      id,
      { favourites: 'protocols' }, //
      { new: true }
    );

but still didnt work

Cookies Not Saving in Browser – React & Node.js

I’m a beginner in React and Node.js and currently experimenting with cookies for my server. My issue is that while the server sends JWT cookies during the login request, they aren’t visible in the browser’s “Application > Cookies” section. This prevents me from using them for JWT verification and logout functionality.

Expected Behavior:

Upon login, the server should send JWT cookies to the browser, and they should be visible in the browser’s “Application > Cookies” section. These cookies are crucial for verifying the JWT access and refresh tokens, as well as for the logout request.

Actual Behavior:

Despite the server sending the cookies in the response (see attached log excerpt), they are not visible in the browser’s cookie section. This behavior persists across different browsers, even after troubleshooting steps like clearing cache, disabling extensions, and verifying cookie settings.

as you see i console log the response and the cookies is there:
Log Excerpt:

referer: 'http://mydomain.local:3000/',
      'accept-encoding': 'gzip, deflate, br',
      'accept-language': 'en-US,en;q=0.9'
    },
    [Symbol(kHeadersCount)]: 32,
    [Symbol(kTrailers)]: null,
    [Symbol(kTrailersCount)]: 0
  },
  _sent100: false,
  _expect_continue: false,
  _maxRequestsPerSocket: 0,
  locals: [Object: null prototype] {},
  [Symbol(kCapture)]: false,
  [Symbol(kBytesWritten)]: 0,
  [Symbol(kNeedDrain)]: false,
  [Symbol(corked)]: 0,
  [Symbol(kOutHeaders)]: [Object: null prototype] {
    'x-powered-by': [ 'X-Powered-By', 'Express' ],
    'access-control-allow-credentials': [ 'Access-Control-Allow-Credentials', 'true' ],
    'access-control-allow-origin': [ 'Access-Control-Allow-Origin', 'http://mydomain.local:3000' ],
    vary: [ 'Vary', 'Origin' ],
    'set-cookie': [
      'Set-Cookie',
      'jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6eyJ1c2VybmFtZSI6Im1lbW9tZW1vIiwicCI6ImhvdyJ9LCJpYXQiOjE3MDIyMDkyNTIsImV4cCI6MTcwMjI5NTY1Mn0.7uMEK_DNIHaoad4x_Svo0EHzMI4Bkw6Hv9Duo7ISXyM; Max-Age=86400; Path=/; Expires=Mon, 11 Dec 2023 11:54:12 GMT; HttpOnly; SameSite=None'
    ]
  },
  [Symbol(errored)]: null,
  [Symbol(kHighWaterMark)]: 16384,
  [Symbol(kRejectNonStandardBodyWrites)]: false,
  [Symbol(kUniqueHeaders)]: null

this my line that i set the cookies in loginController.js:

res.cookie('jwt', refreshToken, { httpOnly: true, sameSite: 'none', maxAge: 24 * 60 * 60 * 1000 });

I’ve already tried the following troubleshooting steps:

Disabled third-party cookies.

Verified the cookie path.

Cleared browser cache and cookies.

Disabled privacy extensions.

Checked Opera’s cookie management settings.

Tested in other browsers.

Any insights or suggestions would be greatly appreciated. I’m open to providing more information about my code or the issue itself.

Thank you for your time and assistance!

Development environment: React & Node.js

Browser: Opera (issue persists in other browsers)


How to safely POST HTML to database?

In a Laravel project, for a form that POST data, I have a <textarea> HTML tag that use a classic editor from CKEditor (source: https://ckeditor.com/ckeditor-5/online-builder/).

For now, when it POST a text through this field, it send HTML to the database and my view renders HTML with the text between tags.

If I remove the CKEditor, the form works fine and I don’t have the HTML tags so we can say that the tags appears within the CKEditor config.

Here’s how I use CKEditor for now:

<script src="{{asset('ckeditor5/build/ckeditor.js')}}"></script>
<script>
   ClassicEditor
       .create( document.querySelector( '#description' ) )
       .catch( error => {
           console.error( error );
       } );
</script>

Where #description is the id for the <textarea> I’m using. I would like to be able to configure more deeply the CKEditor.

I tried to only get the text from it with innerText but the CKEditor is supposed to know when a text is bold or italic. It appears I need to register HTML in database and my feature isn’t working properly if I sanitise the input.

How to create a dynamic divs and fit them in a fixed sized container

I have api which send me data of divs that has to be created, we will refer them as pages
each page as a size that A0,A1,A2,A3,A4,A5,A6 and user created, eg. “200*100” also it has some more data called has areas for each page and each area has width,height,x as left, y as top

**I want to create this pages using divs and fit them in fixed size container which has height and width in vh **

NOTE: size of the page can vary and it has to scale up or down and need to fit in the fixed page-container

here is example data and im using reactjs
data = [
{
“orientation”: “Portrait”,
“size”: “200*100”,
“areas”: [
{
“name”: “test”,
“width”: “190.0”,
“x”: “9.0”,
“y”: “9.0”,
“id”: “FAR.1”,
“type”: “green”,
“height”: “276.0”,
“xonRight”: “0.0”
},
{
“name”: “test”,
“width”: “190.0”,
“x”: “18.0”,
“y”: “18.0”,
“id”: “FAR.1”,
“type”: “blue”,
“height”: “276.0”,
“xonRight”: “0.0”
}
],
}]

I want to create divs based on data provided and they should fit in fixed size div

Listen for new network request in JavsScript

I want to fire an event when there is a new network request. I have overwritten the fetch by following code,

        window.fetch = new Proxy(window.fetch, {
            apply(actualFetch, that, args) {
                const result = Reflect.apply(actualFetch, that, args);

                result.then(() => {
                    if (args.some(i => {
                        return (
                            typeof i === 'string' &&
                            (i?.includes('/example')
                        )
                    })) {
                        console.log('hello')
                    }
                });

                return result;
            }
        });

It works only when I make a new request using fetch but when I make an axios request from different script file (compiled react) it doesn’t fire any event. Any idea?

Excel split task in js/node.js

let excelBot = new Excel.bot();

        let file_path = "C:\Users\FeatSystems\Desktop\Excel_Split_Task.xlsx";
        let rslt = await excelBot.init({ visible: true });
        rslt = await excelBot.open(file_path);
        rslt = await excelBot.readRange("A2:A331");

        const data = rslt.data;
        const batchSize = 25;

        let currentBatch = [];
        let repeatedGroups = [];

        for (let i = 0; i < data.length; i++) {
            const value = data[i];

            if (!currentBatch.includes(value)) {
                if (currentBatch.length + 1 <= batchSize) {
                    currentBatch.push(value);
                } else {
                    const newFilePath = `C:\Users\FeatSystems\Desktop\Split_Task_${Math.floor(i / batchSize) + 1}.xlsx`;
                    await excelBot.create(newFilePath);

                    await excelBot.fillRange(`A2:A${currentBatch.length + 1}`, currentBatch);

                    currentBatch = [value];
                }
            } else {
                currentBatch.push(value);

                if (currentBatch.length > 1 && i === data.length - 1) {
                    repeatedGroups.push(currentBatch);
                }
            }

            if (i === data.length - 1) {
                const newFilePath = `C:\Users\FeatSystems\Desktop\Split_Task_${Math.floor(i / batchSize) + 1}.xlsx`;
                await excelBot.create(newFilePath);

                await excelBot.fillRange(`A2:A${currentBatch.length + 1}`, currentBatch);
            }
        }

        for (let j = 0; j < repeatedGroups.length; j++) {
            const repeatedGroup = repeatedGroups[j];
            const newFilePath = `C:\Users\FeatSystems\Desktop\Repeated_Group_${j + 1}.xlsx`;
            await excelBot.create(newFilePath);
            await excelBot.fillRange(`A2:A${repeatedGroup.length + 1}`, repeatedGroup);

# } with these code 14 excels are getting created with a threshold of 25 data in each now for filling 25 data in each excel code is splitting repeated data i want if 1 data is repeating 13 times then those 13 data should be in one excel and dor filling threshold it will take other value which are not repeating

I have tried chatgpt but no luck

How do I pause audio in React

I have a simple toggle audio function, and the audio.play() works fine but not audio.pause()

import track from "../assets/haydn3.wav";

const AudioPlayer = () => {
 const [isPlaying, setIsPlaying] = useState(false);
  const audio = new Audio(track);

  const handleTogglePlay = () => {
    if (!isPlaying) {
      audio.play();
      setIsPlaying(!isPlaying);
    } else {
      audio.pause();
      console.log("pause");
      setIsPlaying(!isPlaying);
    }
  };

I wrote an even simpler function and that also wouldn’t work. Any known issues with .pause()?

const pause = () => {
    audio.pause();
  };