How to host Razor and Angular pages in a single web app seamlessly

We have an web app (not a SPA but headed that direction) which uses 2 technologies: Razor (MVC) and Angular (Razor pages are being rewritten in angular over the next year so it has to be this way due to a lack of resources for a full migration).

Currently the angular pages are hosted in a separate web app (but under the same sub domain), so when MI1-MI3 are clicked, a new tab is launched which loads the corresponding angular page. The same is true when navigating back to the Razor page.

This means, that the Side and Nav(title bar) are duplicated within both applications and styled accordingly to give the appearance of being in the same app.

I inherited this code and don’t like this design as it breaks the experience for the user and leads to code duplication (the side bar menu items have some permission logic)

What I’d like to do is:

  1. Always keep the user in the same tab, refreshing or redirecting the page as necessary until we can get to a true SPA.
  2. Avoid the code duplication for the side bar and title/nav bar.

I’m considering a couple different approaches and would appreciate some feedback/guidance here:

  1. Razor application serve as the parent application and host the side and title bar in a content area that loads the either the Razor or angular page accordingly. If this is the approach:
    • Would an Iframe be suitable for the content area? What other methods can be used to pass data back and forth between the content area and the side bar? (SSO is involved so handing a JWT is necessary between pages)
  2. Re-write the parent app as angular and do the same as option 1 but in reverse, so the same question persists about the content area? (No time or resources to take this on, and the Razor portion is tightly coupled to the menu/side bar – decoupling is another ongoing effort)
  3. Continue duplicating the menu and side bar (unacceptable, as the potential for bugs, tech debt etc is quite high)

Any suggestions here? I’m looking for feasibility here especially with the iframe/new-suggestion idea.

Also, I’d like to merge the code bases to have them all built and deployed as a single web app – possible? I believe having an Angular folder within the MVC project would suffice? Caveats?

Site design

Error[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Here ,I am making an array of objects data2[] and iterating over this array sending each of its objects , I got 1 response in the postman when I checked it , but not others because of this error .

const express = require("express")
const getOrganicData = require('../GoogleSearchScraping/organicData')
const url = require('url');
const router = new express.Router()

router.get('/searchExtended' , async (req, res) =>
{
 try {
      const queryObject = url.parse(req.url , true).query
      console.log("Query is "+queryObject.query);
      const data = await getOrganicData(queryObject.query)
      const organicData = data[0]
      const snippet = data[1]
      const htmlSnippet = data[2]
      const data2 = new Array(data[0].length)
        for (let i = 0; i < data2.length; i++) 
         {
          data2[i] = 
          {
          organicData: organicData[i],
          snippet: snippet[i],
          htmlSnippet: htmlSnippet[i],
          Rank: ""+(i+1)+""   
          }    
         }

        for (let i = 0; i < data2.length; i++) 
         {
          res.status(201).send(Object.values(data2[i]))
         }
    
     }
 catch (error) {
    res.status(400).send('Error '+error)
   }
})

module.exports = router ; 

Return value from callback

I have value inside callback function and couldn’t return successfully.

async pos(convertedCodeDBSearch) {
    var dd;
    const x =  await idealPostcodes.lookupAddress(convertedCodeDBSearch, function (error, searchResults)  {
      return searchResults.result.hits[1];
    });
    console.log('x', x);
  }

I need to return searchResults.result.hits[1]; from function.
Here is the code,
Thank you.

DISCORD JS V13: DiscordAPIError: Unknown interaction

—————————————-CODE—————————————

const { MessageActionRow, MessageButton, MessageSelectMenu, MessageEmbed } = require("discord.js")

const config = require("../../botconfig/main")
module.exports = {
  name: "help",

  run: async (client, message, args) => {
    const row = new MessageActionRow()
      .addComponents(
        new MessageSelectMenu()
          .setCustomId('select')
          .setPlaceholder('Nothing selected')

          .addOptions([
            {
              label: 'Main Menu',
              description: 'Shows the main menu',
              emoji: "909758706290417714",
              value: '0',
            },
            {
              label: 'Config Commands',
              description: 'Shows all the config commands',
              emoji: "888347974944571392",
              value: '1',
            },


            {
              label: 'Economy Commands',
              description: 'Shows all the economy commands',
              emoji: "910512217168941126",
              value: '2',
            },


            {
              label: 'Fun Commands',
              description: 'Shows all the fun commands',
              emoji: "920258063703879700",
              value: '3',
            },
            {
              label: 'Games Commands',
              description: 'Shows all the game commands',
              emoji: "922464211240632330",
              value: '4',
            },


            {
              label: 'Information Commands',
              description: 'Shows all the information commands',
              emoji: "911535908518527018",
              value: '5',
            },
            {
              label: 'Moderation Commands',
              description: 'Shows all the moderation commands',
              emoji: "908346330412355605",
              value: '6',
            },
            {
              label: 'Utility Commands',
              description: 'Shows all the utility commands',
              emoji: "922461948535271425",
              value: '7',
            },
            {
              label: 'Level Commands',
              description: 'Shows all commandsrelating to level and xp stuff.',
              emoji: "925024469720915990",
              value: '8',
            },
            {
              label: 'Owner Commands',
              description: 'This is for the BOT OWNER only',
              emoji: "925024469720915990",
              value: '9',
            },
          ]),
      );
    const row2 = new MessageActionRow()
      .addComponents(
        new MessageButton()
          .setLabel("Upvote me!")

          .setStyle("LINK")
          .setEmoji("859253758903320616")
          .setURL("https://dblist.ddns.net/bots/like/879000376274219048"),
        new MessageButton()
          .setLabel("Invite me")

          .setStyle("LINK")
          .setEmoji("924283654908313600")
          .setURL("https://discord.com/oauth2/authorize?client_id=879000376274219048&scope=bot&permissions=2684354568"),
        new MessageButton()
          .setLabel("Join Support Server")

          .setStyle("LINK")
          .setEmoji("866779952162799626")
          .setURL("https://discord.gg/5hphccNxTD"),
      )

    const embed = new MessageEmbed()
      .setTitle("**HELP MENU**")
      .setDescription(`Pls select a category to see more commands.nn> <:57291theqts:925020896840806460> `Prefix`: ${config.prefix}n> <:67322theqts:925020897587396638> `Total Commands`: ${client.commands.size}n> <:84733theqts:925020897813885019> `Total Servers`: ${client.guilds.cache.size}nn For info on bot commands use `.cmd <command>`n To report bugs, use `/report`nTo make suggestions, use `/suggest``)
      .setImage("https://cdn.discordapp.com/attachments/925026772544782366/925064779289227324/b68f7d0b-903b-42cc-9770-f37e49941bdd-preview.png")
      .setColor("#f4c2c2")


    message.reply({ embeds: , components: [row, row2] })

    let embed1 = new MessageEmbed()
      .setColor('#FFFFFF')
      .setTitle('**HELP MENU**')
      .addFields(
        { name: "**CONFIG COMMANDS**", value: "`setchatchannel`,`setautorole`, `set-countingchannel`, `setwelcomechannel`, `setleavechannel`" })
      .setImage("https://cdn.discordapp.com/attachments/926113119305105409/926199784153432094/standard_11.gif")
      .setColor("#f4c2c2")
      .setFooter('Page 1')



    let embed2 = new MessageEmbed()

      .setTitle('**Help Menu**')
      .setColor('#FFFFFF')
      .addFields(
        { name: "**ECONOMY COMMANDS**", value: "`balance`, `deposit`, `withdraw`, `search`, `shop`, `inv`, `pet`, `adopt`, `buy`, `sell`, `use`, `gamble`, `multi`, `beg`, `daily`, `fish`, `hunt`, `rob`, `rich` `postmeme`" })
      .setColor("#f4c2c2")
      .setImage("https://cdn.discordapp.com/attachments/926113119305105409/926199784153432094/standard_11.gif")
      .setFooter('Page 2')




    let embed3 = new MessageEmbed()
      .setTitle('**Help Menu**')
      .setColor('#FFFFFF')
      .addFields(
        { name: "**FUN COMMANDS**", value: "`8ball`, `activity`, `pixelize`, `meme`, `changemymind`,`clyde`, `slap`, `nitro`, `wasted`, `say`, `quote`, `punch`, `owo`, `lovecalc`, `smug`, `eject`, `emojify`" })
      .setColor("#f4c2c2")
      .setImage("https://cdn.discordapp.com/attachments/926113119305105409/926199784153432094/standard_11.gif")
      .setFooter('Page 3')

    let embed4 = new MessageEmbed()

      .setTitle('**Help Menu**')
      .setColor('#FFFFFF')
      .addFields(
        { name: "**GAMES COMMANDS**", value: "`c4`, `tictactoe`, `roadrace`, `snake`, `football`, `quickclick`, `catchthefish`, `akinator`, `trivia`, " })
      .setImage("https://cdn.discordapp.com/attachments/926113119305105409/926199784153432094/standard_11.gif")
      .setColor("#f4c2c2")
      .setFooter('Page 4')

    let embed5 = new MessageEmbed()
      .setTitle('**Help Menu**')
      .setColor('#FFFFFF')
      .addFields(
        { name: "**INFO COMMANDS**", value: "`help`, `cmd`, `botinfo`, `ping`, `invite`, `embed`, `ticket-panel`" })
      .setImage("https://cdn.discordapp.com/attachments/926113119305105409/926199784153432094/standard_11.gif")
      .setColor("#f4c2c2")
      .setFooter('Page 5')

    let embed6 = new MessageEmbed()
      .setTitle('**Help Menu**')
      .setColor('#FFFFFF')
      .addFields(
        { name: "**MOD COMMANDS**", value: "`ban`, `addroleall`, `removeroleall`, `softban`, `purge`, `mute`, `kick`, `tempmute`, `nuke` `stealemoji`, `resetwarns`, `warnings`, `warn`, `rmvwarn`,`addrole`, `removerole`" })
      .setFooter('Page 6')
      .setImage("https://cdn.discordapp.com/attachments/926113119305105409/926199784153432094/standard_11.gif")
      .setColor("#f4c2c2")
    let embed7 = new MessageEmbed()
      .setTitle('**Help Menu**')
      .setColor('#FFFFFF')
      .addFields({ name: "**UTILITY COMMANDS**", value: "`addtag`, `edittag`, `removetag`, `afk`, `rolelist`, `snipe`, `timer`, `calculator`, `avatar`, `serverinfo`, `ss`, `dump`" })
      .setImage("https://cdn.discordapp.com/attachments/926113119305105409/926199784153432094/standard_11.gif")
      .setColor("#f4c2c2")
      .setFooter('Page 7')
    
    let embed8 = new MessageEmbed()
      .setTitle('**Help Menu**')
      .setColor('#FFFFFF')
      .addFields({ name: "**LEVEL COMMANDS**", value: "`rank`, `leaderboard`, `addrole`, `removerole`, `listroles`" })
      .setImage("https://cdn.discordapp.com/attachments/925037840977526896/925057005335511101/b68f7d0b-903b-42cc-9770-f37e49941bdd-preview.png")
      .setColor("#f4c2c2")
      .setFooter('Page 8')
    let embed9 = new MessageEmbed()
      .setTitle('**Help Menu**')
      .setColor('#FFFFFF')
      .addFields({ name: "**OWNER COMMANDS**", value: "`addpremium`, `eval`, `reload`, `remove-premium`, `slt`, `terminal` " })
      .addFields({ name: "**OWNER ECONOMY COMMANDS**", value: "`addcoins`, `addbank`, `rmvcoins`, `rmvbank`, `resetcoins`, `resetbank`, `deluser`" })
      .setImage("https://cdn.discordapp.com/attachments/925037840977526896/925057005335511101/b68f7d0b-903b-42cc-9770-f37e49941bdd-preview.png")
      .setColor("#f4c2c2")
      .setFooter('Page 9')

    const filter = i => i.user.id === message.author.id;
    const collector = message.channel.createMessageComponentCollector({
      filter,
      time: 40000,
      componentType: "SELECT_MENU"
    });


    collector.on("collect", async (collected) => {
      const value = collected.values[0]
      if (value === "0") {
        collected.edit({ embeds: , components: [row, row2] })
      }
      if (value === "1") {
        collected.edit({ embeds: [embed1], components: [row, row2] })
      }
      if (value === "2") {
        collected.edit({ embeds: [embed2], components: [row, row2] })
      }
      if (value === "3") {
        collected.edit({ embeds: [embed3], components: [row, row2] })
      }
      if (value === "4") {
        collected.edit({ embeds: [embed4], components: [row, row2] })
      }
      if (value === "5") {
        collected.edit({ embeds: [embed5], components: [row, row2] })
      }
      if (value === "6") {
        collected.edit({ embeds: [embed6], components: [row, row2] })
      }
      if (value === "7") {
        collected.edit({ embeds: [embed7], components: [row, row2] })
      }
      if (value === "8") {
        collected.edit({ embeds: [embed8], components: [row, row2] })
      }
      if (value === "9") {
        collected.edit({ embeds: [embed9], components: [row, row2] })
      }


    })


  }
}

—————————————-NOTE—————————————

So this is my help command code. When i run the command it replies but doesnt update menu when i choose a menu it rather sends an error code in console saying DiscordAPIError: Unknown interaction. Ive tried lots of ways to fix this but none worked. Please help

Change `this` reference to parent object in JS class constructor [duplicate]

I have a class constructor with a nested object structure. Each level has a property x.

this.x > this.a.x > this.a.b.x

I want this.a.b.x to point to the value of this.a.x, but it instead points to this.x.

class Example {
    constructor() {
        this.x = 0;
        this.a = {
            x: this.x + 5,
            b: {
                x: this.x // I want this to equal 5
            }
        }
    }
}

const ex = new Example();
console.log(ex.x) // 0
console.log(ex.a.x) // 5
console.log(ex.a.b.x) // 0 <-- I want this to be 5

How can I change the this reference in this.a.b to point to this.a rather than this??

How can I make texts highlightable in ExtJs?

I’m still finding my way around Extjs, I’m currently displaying text data to a UI like so:

reference: 'agentLogGrid',

    store: {
        xclass: 'Ext.data.ChainedStore',
        source: 'LogViewSource',
    },

    itemConfig: {
        viewModel: true,
    },

    columns: [{
        text: 'Timestamp',
        xtype: 'templatecolumn',
        tpl: '{timestamp}',
        flex: 1,
    }, {
        text: 'Data',
        xtype: 'templatecolumn',
        tpl: '{data}',
        flex: 1,
    }],...

But the texts are not highlightable, that means I can’t highlight them and copy, or select and copy. When I mouse over, the pointer sees it as a link, but I can’t highlight or select. How do I make just the {data} highlightable?

Register Vuex action after store has been created

When looking at registerModule in the vuex documentation it becomes clear, that one can register a whole module after a store has been created.
Looking further, it seems possible to add a new Set of actions, getters and mutations and keep the state with the option preserveState set to true.

However, the documentation does not cover the option to just add another action after a module has been registered and keep all the rest.

Has anyone run into the same problem at some point?

Why is it returning undefined for the month. JS date

var date = new Date();
var month = date.getMonth();
var arr = [
   'лютого',
   'березня',
   'квітня',
   'травня',
   'червня',
   'липня',
   'серпня',
   'вересня',
   'жовтня',
   'листопада',
   'грудня',
   'січня',
];

$('.rf_title').text('Данi оновлено ' + date.getDate() + ' ' + arr[month-1] + ' ' + date.getFullYear() +' о ' + (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':' + '' + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())); 

I’m confused as to why this is showing undefined. It worked fine up until New Years. As soon as 2022 hit it’s done for.enter image description here

How to Map a JSON File With IDs

How can I map and return the values “Title” in React, with a JSON file that contains an ID for each record? For example:

{

"id001": {
      "Title": "Title-1",
      "Year": "1990",
      "Rated": "PG-13"
      },

"id002": {
      "Title": "Title-2",
      "Year": "1999",
      "Rated": "PG-13"
      },
      
...

}

Thank you so much!

Upload file through API with Javascript

Is it possible to upload a file using rest API to store this file in SharePoint library from a normal html page , I will be need to pass the access token as well “Authorization” : “Bearer token”

Here is the code I used but it gives error :

<html>
<input type="file" name="file" id="file">
<button onclick="doupload()" name="submit">Upload File</button>


<script>
function doupload() {
let data = document.getElementById("file").files[0];
let entry = document.getElementById("file").files[0];
console.log("doupload",entry,data)
fetch("https://test.sharepoint.com/sites/BM/_api/web/GetFolderByServerRelativeurl
("/sites/BM/BM_UPLOADS/")/Files/add(url=entry,overwrite=true)"
 + encodeURIComponent(entry.name), {method:"POST",body:data});
alert("your file has been uploaded");
location.reload();
};

</script>

How to number increment with limit

I am using number field with plus and minus for product quantity select for a project. I need to set a max limit when I press plus icon. I am using below code

$(document).ready(function() {
        $('.minus').click(function () {
            var $input = $(this).parent().find('input');
            var count = parseInt($input.val()) - 1;
            count = count < 1 ? 1 : count;
            $input.val(count);
            $input.change();
            return false;
        });
        $('.plus').click(function () {
            var $input = $(this).parent().find('input');
            $input.val(parseInt($input.val()) + 1 );
            $input.change();
           
            return false;
        });
    });

How to set a maximum limit for when i press + icon.

import class in typescript is throwing an error

Trying to import class in the file and it is throwing an error it might be quick fix i would appreciate the help.

class.ts

export class Cache {
    private cache: CCache;
    public async getCache(tokenId: string): Promise<any> {
        // add logic here 

        return memberInfo;

    }

}

otherFile.ts

    import { Cache } from "./class.ts";
        public before(args: any) {
        let specialtyCache: any;
        specialtyCache =  new Cache().getCache(args.token);
}

Error

Constructor of class 'Cache' is private and only accessible within the class declaration.ts

Javascript regex replace character if preceded AND followed by a letter

Basically I am working with a string that is a json string and I would like to turn it into a real json (by using the JSON.parse()) but there are some quotation marks in the middle of the sentences.

Example: ‘{“author”: “Jonah D”Almeida”, … }’
(I want to replace the one in between D and Almeida)

As it already has quotation marks around the whole sentence, javascript gives an error because it can’t create a json out of it and so, to solve that basically I want to replace the quotation mark in the middle of the sentence for a ‘ but only if it has letters preceeding and following the quotation mark.

My thought: myString.replace('letter before ... " ... letter after', "'")

Any idea how can I get this right?

How to change one array same as another array

I have two arrays. I want compare modified array with original array and I want to change the modifid array same as the original array. position want to be same also

I expecting output is,

const modified = [
                          {label: 'cover1', formUid: 1045},
                          {label: 'cover2', formUid: 211},
                          {label: 'cover3', formUid: 204},
                          {label: 'cover4', formUid: 258},
                          {label: 'cover1', formUid: 1045},
  ]

but now I am getting like this,

const modified = [
                          {label: 'cover2', formUid: 211},
                          {label: 'cover3', formUid: 204},
                          {label: 'cover4', formUid: 258},
                          {label: 'cover1', formUid: 1045},
      ]

here is my try,

const original = [
                          {label: 'cover1', formUid: 1045},
                          {label: 'cover2', formUid: 211},
                          {label: 'cover3', formUid: 204},
                          {label: 'cover4', formUid: 258},
                          {label: 'cover1', formUid: 1045},
                           
                       ];
                       
      const modified = [
                           {label: 'cover4', formUid: 258},
                          {label: 'cover2', formUid: 211},
                          {label: 'cover3', formUid: 204},
                          {label: 'cover1', formUid: 1045},
                           {label: 'cover1', formUid: 1045},
      ]
    
    function testFunc(original , modified){
    let originalCopyForPosision;
  
    originalCopyForPosision = [...original];
         
         modified.forEach((element,idx) => {
             
              let targetIndex = originalCopyForPosision.findIndex(e => e.formUid === element.formUid)
             
              if(idx === targetIndex){
              return
              }else{
             
                if(targetIndex > 0){
                  modified.splice(targetIndex,  1);
                  modified.splice(idx,0,element);
                }
               
              }
    
         })
    
    document.getElementById("originalArray").innerHTML = JSON.stringify(original);
    document.getElementById("modifiedArray").innerHTML = JSON.stringify(modified);
    
    }testFunc(original,modified)