I am getting document.ready event hitting twice. console logging shows one from xxx.js, and another from xxx.js?v=somenumber [closed]

I am getting document.ready event hitting twice. console logging shows one from xxx.js, and another from xxx.js?v=somenumber

We were using edge, but we also saw the same “hitting twice” behavior in chrome. Edge is the one that showed us the two different versions of xxx.js , which were also in the source tab of the developer tools in Edge.

In the bundleconfig.cs file we had zzz.js including xxx.js, and once we removed this the two-document-ready hits behavior went away, and the source tab showed only one version of xxx.js (the one with the ?v=somenumber added).

Why were there two versions of xxx.js, and why were they both somehow active at the same time (both throwing the document.ready event)?

ASP .NET 6. Hosted on Azure. GetAllVehicles() Ajax call works in Visual Studio 2022 but errors out on Azure

<script type="text/javascript">
    $(document).ready(function () {
        $('#vehiclesTable').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "@Url.Action("GetAllVehicles", "Vehicles")",
                "type": "GET",
                "error": function (xhr, error, thrown) {
                    console.log("Error: ", xhr.responseText);
                }
            },
            "columns": [
                { "data": "customerName" },
                { "data": "year" },
                { "data": "make" },
                { "data": "model" },
                { "data": "trim" },
                { "data": "engineSize" },
                { "data": "transmission" },
                { "data": "transmissionType" },
                { "data": "mileage" },
                {
                    "data": "id",
                    "render": function (data, type, row) {
                        return `<a href="/Vehicles/Details/${data}" class="btn btn-info">Details</a>
                                        <a href="/Vehicles/Edit/${data}" class="btn btn-warning">Edit</a>
                                        <a href="/Vehicles/Delete/${data}" class="btn btn-danger">Delete</a>`;
                    },
                    "orderable": false
                }
            ],
            "order": [[0, "asc"]]
        });
    });
</script> 

<- script in index.html 

 [HttpGet]
 public async Task<IActionResult> GetAllVehicles()
 {
     var draw = HttpContext.Request.Query["draw"].FirstOrDefault();
     var start = Request.Query["start"].FirstOrDefault();
     var length = Request.Query["length"].FirstOrDefault();
     var sortColumn = Request.Query["columns[" + Request.Query["order[0][column]"].FirstOrDefault() + "][data]"].FirstOrDefault();
     var sortColumnDirection = Request.Query["order[0][dir]"].FirstOrDefault();
     var searchValue = Request.Query["search[value]"].FirstOrDefault();
     int pageSize = length != null ? Convert.ToInt32(length) : 0;
     int skip = start != null ? Convert.ToInt32(start) : 0;
     int recordsTotal = 0;

     // Fetch all data
     var vehiclesData = _context.Vehicles
      .Include(j => j.Customer)
      .Select(j => new
      {
          j.Id,
          CustomerName = j.Customer.FirstName + " " + j.Customer.LastName,
          j.Year,
          j.Make,
          j.Model,
          j.Trim,
          j.EngineSize,
          j.Transmission,
          j.TransmissionType,
          j.Mileage

      });

     // Search
     if (!string.IsNullOrEmpty(searchValue))
     {
         vehiclesData = vehiclesData.Where(j =>
      j.CustomerName.Contains(searchValue) ||
      j.Year.ToString().Contains(searchValue) ||
      j.Make.Contains(searchValue) ||
      j.Model.Contains(searchValue) ||
      j.Trim.Contains(searchValue) ||
      j.EngineSize.Contains(searchValue) ||
      j.Transmission.Contains(searchValue) ||
      j.TransmissionType.Contains(searchValue) ||
      j.Mileage.Contains(searchValue)
  );

     }

     // Sorting
     if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))
     {
         var sortExpression = $"{sortColumn} {sortColumnDirection}";
         vehiclesData = vehiclesData.OrderBy(sortExpression);
     }

     // Total number of rows count 
     recordsTotal = vehiclesData.Count();

     // Paging 
     var data = vehiclesData.Skip(skip).Take(pageSize).ToList();

     // Returning Json Data
     var jsonData = new
     {
         draw = draw,
         recordsFiltered = recordsTotal,
         recordsTotal = recordsTotal,
         data = data.Select(v => new
         {
             customerName = v.CustomerName,
             year = v.Year,
             make = v.Make,
             model = v.Model,
             trim = v.Trim,
             engineSize = v.EngineSize,
             transmission = v.Transmission,
             transmissionType = v.TransmissionType,
             mileage = v.Mileage,
             id = v.Id
         })
     };


     return Ok(jsonData);
 }

<- VehiclesController GetAllVehicles()

Again this works great when I run it locally. It just breaks when I push it to Azure.

I tried different calls, routing and every change worked locally but broke when pushed over to Azure. I have another controller with an almost identical call just different data and that ones works perfectly.

In Javascript can you create a bi-directional map?

I’m trying to figure out the best (simplest?) way to create maps for all of the properties of an object of objects. For example:

const customerData = {
  customer1: {
    region: "south",
    market: "education",
    salesRep: "Bob"
  },
  customer2: {
    region: "north",
    market: "commerical",
    salesRep: "Nancy"
  }, ...
}

In my real world example, each customer has about 10 properties, each with a single primitive data type. I want to take and convert that to objects/maps that I can use to look up all the customers that have, say region == "north".

const regions = {
  north: ["customer2", ...],
  south: ["customer1", ...]
}
// OR
const regions = {
  north: [customerData["customer2"], ...],
  south: [customerData["customer1"], ...]
}

And doing that for all of the properties.
(If I weren’t storing these in Redux and using the Redux toolkit, I would probably do the latter, but it prefers not deeply nesting the data, so will probably go with the former.)
I can easily write the forEach/for of loops to create these objects.

But my real question is: Is there some higher level construct for this?

This seems like this would be a not uncommon thing, but I can’t think of a way of doing it without just spinning through the list of all customers and manually creating the Objects/Maps for each property.
I guess I could probably convert the customerData to an array and use .filter(), but this seems heavy (there are over 2000 customers).

Awaiting dynamic import makes JS application exit without any error

I’m writing some code that should load all modules inside a folder.

for (let path of controllerPaths) {
    path = path.replaceAll("\", "/"); // Replace windows path backslashes

    const controller: ApiController = (await import(`file:///${path}`))?.default; // Application exits without any error

    // ...
}

Wrapping the code in a try/catch block doesn’t change the result as the application still exits.

I’m sure the path is correct and exists. The path is absolute.

Error calling Office.context.mailbox.item.body.getTypeAsync when reading an Outlook message

I’m creating my first Outlook Web Add-in app. When I’m calling Office.context.mailbox.item.body.getTypeAsync when viewing an email in Outlook, I get the error message “Uncaught
TypeError: Office.context.mailbox.item.body.getTypeAsync is not a function”:

(function () {
    Office.onReady(function () {
        Office.context.mailbox.item.body.getTypeAsync((typeResult) => {
            if (typeResult.status === Office.AsyncResultStatus.Succeeded) {
                const coercionType = typeResult.value;

                Office.context.mailbox.item.body.getAsync(coercionType, (getResult) => {
                    if (getResult.status === Office.AsyncResultStatus.Succeeded) {
                        // Do something with getResult.value - message body content.
                    }
                    else {
                        console.log(getResult.error.message);
                    }
                });
            }
            else {
                console.log(typeResult.error.message);
            }
        });
    });
})();

If I separate out the code and call Office.context.mailbox.item.body.getAsync with a hard coded coercion type (Office.CoercionType.Html or Office.CoercionType.Text), getAsync works as expected. But getTypeAsync is not available on Office.context.mailbox.item.body as a function, with getAsync being the sole function on Office.context.mailbox.item.body when reading the message in Outlook web and inspecting using dev tools. This seems unusual, as other functions should be available on Office.context.mailbox.item.body as indicated by the Office.js documentation.

What could be causing the problem, and how do I fix it so that I can call getTypeAsync correctly? I am using the live Office.js framework from Microsoft, so that should include all of the latest functionality. Is it likely to be an issue with the manifest file, or an issue of getting the Office.js framework from Microsoft?

Here is part of the header in my MessageRead.html base file with reference to my JavaScript files, including the Office.js framework:

<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
<script src="MessageRead.js" type="module"></script>

Can someone explain why this piece of code only return status 400? [closed]

Help me please

 async updateCategory(req) {
  const {id} = req.params;
  try {
    let category = await Category.findByPk(id);


    if (!req.body || !req.body.name || !req.body.slug || (req.body.use_in_menu != undefined && req.body.use_in_menu != null)) {
      return {
        status: 400,
        message: "Dados invalidos."
      }
    }

    if (!category) {
      return {
        status: 404,
        message: "Categoria não encontrada."
      }
    }

    await category.update(req.body)
    return {
      status: 204,
      message: ""
    }
  } catch (error) {
    return {
      status: 500,
      message: "Erro do servidor"
    }
  }
}

Is expected to return message 204 when i send a new payload, but it only return “400 invalid data”.

i am using createBrowserRouter i got Cannot destructure property ‘basename’ of ‘react__WEBPACK_IMPORTED_MODULE_0__.useContext(…)’ as it is null

i got this error in react = index.tsx:963 Uncaught TypeError: Cannot destructure property ‘basename’ of ‘react__WEBPACK_IMPORTED_MODULE_0__.useContext(…)’ as it is null.

In the code below, I am trying to pass the query entered by the user in the search bar from the header component to another component using props, as shown below.

in head.js i have this code

<Link to="/results">
          < SearchVideo results={searchResult} loading={loading} />
        </Link>

this is my app.js

const appRouter = createBrowserRouter([{
  path: "/",
  element: <Body />,
  children: [
    {
      path: "/",
      element: <MainContainer />,
    },
    {
      path: "watch",
      element: <WatchPage />,
    },
    {
      path: "results",
      element: <SearchVideo />,
    },
  ],
}]);

function App() {
  return (  
    <Provider store={store}>
      <div className="bg-black ">
        <Head />
        <RouterProvider router={appRouter}/>
      </div>
    </Provider>
  );
}

export default App;

this is my index.js

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App />
);

i have one reactapp which have bug so want solution

Fabric.js – How do I scale canvas to screen size and save full size image from the canvas

I’m using Fabric.js 5.3.1 in a website where users can upload a photo and mark them up. Everything seems to be working however when I set the uploaded image to the background of the canvas and scale it to fit the screen, then save that image, the image is the same size as its scaled dimensions. Meaning if I upload a 1920×1080 image, set it to the canvas’ background image, then scale the canvas down to screen size (say 600×337.5) then save the image using canvas.toDataUrl() my saved image is 600×337.5.

This is how I set the canvas’ background image:

setCanvasBackground: function (imgUrl) {
    let bgImg = new Image();
    bgImg.onload = function () {
        origBgWidth = bgImg.width; // global variable
        origBgHeight = bgImg.height; // global variable

        canvas.setDimensions({
            width: bgImg.width,
            height: bgImg.height
        });

        canvas.setBackgroundImage(imgUrl, function () {
            canvas.requestRenderAll();
            canvas.clearContext(canvas.contextTop);
            canvas.setZoom(1);

            undo_history.push(JSON.stringify(canvas)); // global variable
        });
    }

    bgImg.src = imgUrl;
}

Then I scale the canvas to screen dimensions like so:

resizeCanvas: function (areaWidth, areaHeight) {

    let canvasWidth = canvas.getWidth();
    let canvasHeight = canvas.getHeight();

    const wRatio = areaWidth / canvasWidth;
    const hRatio = areaHeight / canvasHeight;
    const scale = Math.min(wRatio, hRatio);

    const newWidth = canvasWidth * scale;
    const newHeight = canvasHeight * scale;
    const zoom = canvas.getZoom() * scale;

    canvas.setDimensions({ width: newWidth, height: newHeight });
    canvas.setZoom(zoom);
    canvas.requestRenderAll();
}

Finally, I save the image by converting it to a blob and uploading:

getImageBlobFromCanvas: function () {
    // I have to set the original dimensions and zoom level for it to save full size
    canvas.setDimensions({
        width: origBgWidth,
        height: origBgHeight
    });
    canvas.setZoom(1);

    let imageData = canvas.toDataURL({ format: "png" });
    return convertBase64ToBlob(imageData);
}

Is there a way to more efficiently scale and save the canvas image without having to store the original dimensions and reset them back before calling canvas.toDataUrl()? I want to scale the canvas for a responsive design but when uploading the image, it needs to be its original size. Using canvas.setDimensions() and canvas.setZoom() just before saving seems hacky.

How to use Web Sockets in my Book Store proj [closed]

This is my CSharp prog, this project is about a Book Store but I attached screenshot of the serverside only.
screenshot of my classes
I want to add web sockets to my project, I dont even know how to start.
https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket?view=net-8.0
I tried to look at this but cant understand how to begin.

In addition,I created a chat that I want to add to it socket funcion to pull from the server detailes and display it inside the chat.
I hope someone can guide me throgh it and help!
Thank you!
Dan

Issue with FormSubmission [duplicate]

I have the following code which does the form submission and everything works well, until i have a textarea with tinymce attached to it, it does not send any data to the server, not sure what is wrong

ig i use normal textarea the data is sent and saved in the database, but only seems to be a trouble with the editor based textarea

var formSubmission = document.getElementById('formSubmission'); 

if(formSubmission) {
  $("#formSubmission").validate({
    errorPlacement: function(error, element) {
      error.appendTo(element.parent());
    },
    highlight: function(element) {
      $(element).addClass("error");
    },
    unhighlight: function(element) {
      $(element).removeClass("error");
    },
    submitHandler: function(form) { 
      var $form    = $(form),
          formData = new FormData(),
          params   = $form.serializeArray();

        var filesInput = $form.find('[name="uploadfile"]');
        if (filesInput.length > 0 && filesInput[0].files.length > 0) {
            var files = filesInput[0].files;
            $.each(files, function(i, file) {
                formData.append('uploadedFiles', file);
            });
        }

        $.each(params, function(i, val) {
            formData.append(val.name, val.value);
        });

        // Block UI and show processing message
        $.blockUI({ 
            message: '<h3>Please wait, we are running some background processes to make it work...</h3>',
            css: { 
                border: 'none', 
                padding: '15px', 
                backgroundColor: '#000', 
                '-webkit-border-radius': '10px', 
                '-moz-border-radius': '10px', 
                opacity: .5, 
                color: '#fff' 
            } 
        });
        $.ajax({
          url:'process.cfm?action=' + $('#formSubmission').attr('data-post'),
          data: formData,
          mimeType: "multipart/form-data",
          contentType: false,
          processData: false,
          type:'POST',
          dataType: 'json',
          success: function(data) {
            // Unblock UI
            $.unblockUI();
            var json = data;
            if((json.SUCCESS === true) || (json.valid === true) || (json.sucess === true)) {
              showAlert(json.message, 'success', 1);
            } else {
              showAlert(json.message, 'error');
            }
          },
          error: function(textStatus, errorThrown) {
            // Unblock UI
            $.unblockUI();

            showAlert('An error occurred during the operation: ' + textStatus, 'error');
          }
        });
        return false;
    }
  });
}

How to decode Google CloudEvent data?

I have a Google Cloud Function that is triggered when a document is written in my Firestore.

functions.cloudEvent('onItemCreate', async (cloudEvent: functions.CloudEvent<any>) => {
    console.log("cloudEvent.data", typeof cloudEvent.data, cloudEvent.data)
    const decodedData = cloudEvent.data.toString('utf8');
    console.log("Decoded Data:", decodedData);
}

// > cloudEvent.data object <Buffer 0a 9e 03 0a 7f 70 72 6f 6a 65 63 74 73 2f 65 69 6e 73 6b 35 67 2d 69 6d 2d 64 65 76 2f 64 61 74 61 62 61 73 65 73 2f 66 69 72 65 73 74 6f 72 65 2d 69 ... 367 more bytes>
// > Decoded Data: 
// �
// oprojects/my-project-id/databases/firestore/my-firestore/documents/items/Rfhg7PU9Rb1i55VNPzxH   
// a�a��������"��������

How do I correctly decode the data as there are some weird characters with my current approach?

Getting ‘token’ undefined in api.js when registering a user through the front end

Undefined token, or token is null at api.js, none of the console.logs are triggered. so unsure how to troubleshoot at this point. chatGPT no help.

api.js

import { fetchBaseQuery, createApi } from "@reduxjs/toolkit/query/react";

export const api = createApi({
  reducerPath: "api",
  baseQuery: fetchBaseQuery({
    // baseUrl: "https://capstonebackend-0wah.onrender.com/",
    baseUrl: "http://localhost:3000",
    tagTypes: ["User"],

    prepareHeaders: (headers, { getState }) => {
      const token = getState().register.token || getState().login.token;
      const sessionToken = window.sessionStorage.getItem("Token", token);
      if (token || sessionToken) {
        headers.set("authorization", `Bearer ${token || sessionToken}`);
      }
    },
  }),
  endpoints: () => ({}),
});

registerSlice.js

import { createSlice } from "@reduxjs/toolkit";
import { api } from "../../app/api";

const registerApi = api.injectEndpoints({
  endpoints: (builder) => ({
    register: builder.mutation({
      query: (credentials) => ({
        url: "/register",
        method: "POST",
        body: credentials,
        responseHandler: (response) => response.text(),
      }),
      invalidateTags: ["User"],
    }),
  }),
});

const registerSlice = createSlice({
  name: "register",
  initialState: {
    user: {},
    token: null,
  },
  reducers: {
    setUser: (state, action) => {
      console.log("Setting user in login:", action.payload);
      state.user = action.payload;
    },
  },

  extraReducers: (builder) => {
    builder.addMatcher(
      registerApi.endpoints.register.matchFulfilled,
      (state, { payload }) => {
        console.log(payload);
        const temp = JSON.parse(payload);
        console.log(temp);
        state.token = temp.token;
        // state.user = temp;
        // state.id = temp.id;
        // window.sessionStorage.setItem("Token", temp.token);
        // window.sessionStorage.setItem("User", temp.id);
      }
    );
  },
});

export default registerSlice.reducer;

export const { useRegisterMutation } = registerApi;

export const {  setUser } = registerSlice.actions;


Whenever I submit a registerUser request through the frontend it is getting token undefined. I put breakpoints in and found it is undefined in the api.js. It doesn’t seem like it is even triggering the registerSlice. Tested the backend in Postman and it can register a user and get a token just fine. How can I fix this to get the token to be passed correctly?

How do I get my inline editing Vue component to update the value after editing?

I’m working on a simple inline editing component for a project, and have it mostly working, except that once the edit happens, the bound variable doesn’t update the way I’d like it.

The basic approach is that I have a table cell that just has the variable text, and then on double-click I swap in an input field populated with the text value.

Why is the computedCellValue not getting the updated value of the input when it gets edited?

<script setup>
    import { defineProps, ref, computed, nextTick } from 'vue';

    const props = defineProps([
        "cellValue",
        "prefix",
        "postfix"
    ]);

    const isEditing = ref(false);
    const inputField = ref(null);
    const computedCellValue = computed(() => props.cellValue);

    function toggleEditOn() {
        isEditing.value = true;

        nextTick(function () {
            inputField.value.focus();
            inputField.value.select();
        });
    }

    function toggleEditOff() {
        isEditing.value = false;
    }
</script>

<template>
    <td class="w-64 mx-1" @dblclick="toggleEditOn()" v-show="isEditing == false">
        {{ props.prefix }}{{ computedCellValue }}{{ props.postfix }}
    </td>
    <td class="w-64 mx-1" v-show="isEditing == true">
        {{ props.prefix }}<input class="w-64 bg-slate-400 p-1 text-white" ref="inputField" type="text" :value="computedCellValue"  @blur="toggleEditOff()" @focus="focused" @keyup.enter="toggleEditOff()">{{ props.postfix }}
    </td>
</template>

How to Query Multiple Media Items by MyAnimeList IDs Using Anilist’s GraphQL API?

I’m working with a Anilist’s GraphQL API where the Media query supports fetching media by a single ID. The schema for the Media query looks like this:

query Media($idMal: Int!) {
  Media(idMal: $idMal) {
    ...media
  }
}

// idMal = [21, 166531]

However, I need to fetch multiple media items at once using an array of MyAnimeList (MAL) IDs. The API does not provide a query that allows fetching multiple items by an array of IDs in a single request.

I expected to efficiently fetch multiple media items using a single request or a more streamlined approach than making multiple separate requests.

Any help or suggestions would be greatly appreciated!

Registering Javascript file Blazor

I have a scenario where I want to register a javascript file insidemy blazor appplication.

Any suggestion how we can fix this issue. Any help is appreciated.

Thank you in advance.

I have placed the file as shown in the below image
enter image description here

I have used the script tag inside one of the razor component as shown below.
enter image description here

But I am getting the below error when I am using script tag to register Javascript.
enter image description here

While using JSRuntime am not getting any error by the javascript is not executing and is also not present while checking the page source.

I have also tried to place the script tag in the App.Razor a file where _blazor.web.js file is present. Again not getting the error but the JS file is not executing but it is present while viewing the page source.

If I remove the _blazor.web.js then the javascript file runs fine but blazor application is not working as it blazor.web.js is required other components.