Anyway to pass data in sidePane to the main pane in Dynamics 365

So within Dynamics 365 I decided to use the new Xrm.App.sidePanes method to create a side pane that embeds a HTML web resource. Specifically I’ve embedded the Amazon connect stream softphone. It all works perfectly. When running the side pane, it appears with the Amazon connect softphone. I’ve test called and it dials through well and I can see all the events that I need including the phone number of the incoming call.

I’ve added ClientGlobalContext.js.aspx javascript library to the HTML so that I can access the globalContext. Basically what I’m trying to do is have it so that when someone dials through to the Amazon connect sidepane embedded in Dynamics it:

  1. picks up the phone number from the Connect event.

  2. I run a web API call to Dynamics to find contact with that number and return the contactid

  3. Use that contactid to navigate the main pane (not the amazon connect embedded side pane) to that contact.

So far 1 and 2 seems to be working. I can run the web API call using the globalContext to return the base URL but I’m unable to find a method to navigate the main pane to the contact record. Any help would be greatly appreciated.

Under the amazon connect event listener for contact.onConnecting(). I added custom code in the handleContactAccepted function to retrieve the contactid via the web api and then use it to navigate to the contact record in the main pane. I am able to retrieve the contact ID using the phone number but can’t navigate to the contact using the main pane in Dynamics 365.

/**
 * Extends the contact events.
*/
export default function (contact) {
    console.debug("CDEBUG >> ContactEvents - New Contact contactId: " + contact.contactId);
    console.debug("CDEBUG >> ContactEvents - New Contact InitialContactId(): " + contact.getInitialContactId());

    // Route to the respective handler

    contact.onConnecting(handleContactConnecting);


    async function handleContactConnecting(contact) {
        console.debug('CDEBUG >> ContactEvents.handleContactConnecting() - Contact connecting to agent');
        // Add your custom code here
        function getContactIdByNumber(searchNumber) {
          return new Promise((resolve, reject) => {
            var req = new XMLHttpRequest();
            req.open(
              "GET",
              Xrm.Utility.getGlobalContext().getClientUrl() +
                `/api/data/v9.2/contacts?$select=contactid,telephone1&$filter=contains(telephone1,'${searchNumber}')`,
              true
            );
            req.setRequestHeader("OData-MaxVersion", "4.0");
            req.setRequestHeader("OData-Version", "4.0");
            req.setRequestHeader(
              "Content-Type",
              "application/json; charset=utf-8"
            );
            req.setRequestHeader("Accept", "application/json");
            req.setRequestHeader("Prefer", "odata.include-annotations=*");
            req.onreadystatechange = function () {
              if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 200) {
                  var results = JSON.parse(this.response);
                  console.log(results);
                  if (results.value.length > 0) {
                    resolve(results.value[0].contactid);
                  } else {
                    resolve(null);
                  }
                } else {
                  console.log(this.responseText);
                  reject(this.responseText);
                }
              }
            };
            req.send();
          });
        }
        console.log(contact);
        var connections = contact.getConnections();
        var c1 = connections[1];
        var c1Number = c1.getAddress();
        var recievingPhoneNumber = c1Number.phoneNumber;
        console.log(c1Number);
        console.log(recievingPhoneNumber);
        var formattedReceivingNumber = recievingPhoneNumber.replace("+","");
        console.log(formattedReceivingNumber);

        var contactId = await getContactIdByNumber(formattedReceivingNumber);

        console.log(contactId);

        var pageInput = {
            pageType: "entityrecord",
            entityName: "contact",
            entityId: contactId //replace with actual ID
        };
        var navigationOptions = {
            target: 1
        };
        Xrm.Navigation.navigateTo(pageInput, navigationOptions).then(
            function success() {
                    // Run code on success
            },
            function error() {
                    // Handle errors
            }
        );
        
    }


}

How do I create a file from a Gunzip response in Node.js

I’m making successfull GET request using node.js and node-fetch to get an image file and save it to my computer. I am having trouble creating a file on my local machine given the Gunzip response I am getting. Here’s what part of the response looks like:

  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: Gunzip {
      _writeState: [Uint32Array],
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      bytesWritten: 0,
      _handle: [Zlib],
      _outBuffer: <Buffer 00 00 00 00 00 00 00 00 47 00 00 00 00 00 00 00 00 fa 80 1b 01 00 00 00 68 ff ff ff 0a 00 00 00 ff ff ff ff 31 00 00 00 ff ff ff ff 37 00 00 00 00 00 ... 16334 more bytes>,
      _outOffset: 0,
      _chunkSize: 16384,
      _defaultFlushFlag: 2,
      _finishFlushFlag: 2,
      _defaultFullFlushFlag: 3,
      _info: undefined,
      _maxOutputLength: 4294967296,
      _level: -1,
      _strategy: 0,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null,
      [Symbol(kError)]: null
    },
    disturbed: false,
    error: null
  }

Any help or ideas on what I should do to create and save the proper file would be greatly appreciated!

I’ve tried:

const dest = fs.createWriteStream('test.png');
                            resp.body.pipe(dest);
                            dest.on("end", function(succ) {
                                console.log('it worked');
                            });
                            dest.on("error", function(errrr) {
                                console.log('failureee');
                            });

but It seems to save an invalid file I cannot open

Thanks to all in advanced!

horizontally fixed position for element in React Component

I have an icon element in a ListItem component. This listItem component belongs a larger component (FiltersPanel component) which has scroll in it. Both horizontal scroll and the vertical scroll.

Hierarchy of component: …other high level component -> FiltersPanel -> FolderFilter -> GroupNavListView -> GroupNavListItem -> CollapsibleList -> CollapsibleListItem -> MenuIconElement

Now, I want to make the MenuIconElement position to fixed horizontally but not vertically. How this can be done.

This question is similar to: [https://stackoverflow.com/questions/7903939/horizontally-fixed-element-with-absolute-vertical-position]
But the difference lies in the usage of react component. The scroll doesn’t belong to window instead it belongs only to a specific component.

possible unhandled promise rejection (id:0): [axioserror:network error]” , “axioserror network error”

I’m trying to communicate with a Node.js backend using React Native, and I’m using axios for this purpose. However, I keep encountering axios errors. To resolve this issue, I’ve tried numerous attempts. My laptop and Android device are both on the same network. The Postman requests work fine. I’ve also tried changing the endpoint address multiple times based on Google search results. For example, I’ve tried using ‘10.0.2.2’ for the emulator and my laptop’s IPv4 address for running on a physical device, but it still doesn’t work. My laptop runs on Windows. Another team member uses a Mac, and it works well on their laptop. What could be the problem?

error messeage is “possible unhandled promise rejection (id:0): [axioserror:network error]”
or “axioserror network error”

useEffect(() => {
    const templogin = async () => {
      try {
        const loginEndpoint = 'http://10.0.2.2:3000/auth/login';
        const loginData = {
          email: '[email protected]',
          password: 'tickle1234~',
        };
  
        axios.post(loginEndpoint, loginData)
          .then(response => {
            const accessToken = response.data.data.access_token;
            console.log('발급된 Token:', accessToken);
            setToken(accessToken);
          })
          .catch(error => {
            if (error.response) {
              // 요청이 이루어졌으며 서버가 2xx의 범위를 벗어나는 상태 코드로 응답했습니다.
              console.log(error.response.data);
              console.log(error.response.status);
              console.log(error.response.headers);
            } else if (error.request) {
              // 요청이 이루어 졌으나 응답을 받지 못했습니다.
              console.log(error.request);
            } else {
              // 오류를 발생시킨 요청을 설정하는 중에 문제가 발생했습니다.
              console.log('Error', error.message);
            }
            console.log(error.config);
          });
      } catch (error) {
        console.error('로그인 중 오류:', error);
      }
    };
    templogin();
  }, []);
  

  if (!token) {
    return null;
  }

Why do I still get the other months when I tried to call my statement?

Why do I still get random months even though I set the BETWEEN method in my statement when I tried to run in my nodejs? I am using mysql2

This is mysql call. This is working when I used the workbench. I get the data I want.

SELECT
    DATE_FORMAT(STR_TO_DATE(SUBSTRING_INDEX(tlc.time, ',', 1), '%d/%m/%y'), '%Y-%m') as formatted_month_year,
    tlc.userfullname,
    //rest of the code
FROM
    userlibrary tlc
LEFT JOIN
    users u ON tlc.userfullname = u.fullname
WHERE
    u.type = 'students' 
    AND DATE_FORMAT(STR_TO_DATE(SUBSTRING_INDEX(tlc.time, ',', 1), '%d/%m/%y'), '%Y-%m') BETWEEN '2022-11' AND '2023-04';

Now in my nodejs, What I do is get the url and use it as a query

*http://localhost:5000/api/result/table?from=01&startYear=2023&end=02&endYear=2023&type=students

This is my code.

       const sql = `
        SELECT
        DATE_FORMAT(STR_TO_DATE(SUBSTRING_INDEX(tlc.time, ',', 1), '%d/%m/%y'), '%Y-%m') as formatted_month_year,
        tlc.userfullname,
        u.department,
        u.type,
        tlc.affecteduser,
        tlc.eventcontext,
        tlc.component,
        tlc.eventname,
        tlc.description,
        tlc.origin,
        tlc.ipaddress
    FROM
        userlibrary tlc
    LEFT JOIN
        users u ON tlc.userfullname = u.fullname
    WHERE
        u.type = ?
    AND DATE_FORMAT(STR_TO_DATE(SUBSTRING_INDEX(tlc.time, ',', 1), '%d/%m/%y'), '%Y-%m') BETWEEN ? AND ?;


    `;

    const [results, fields] = await connection.query(sql, [
      type,
      `${startYear}-${from}`,
      `${endYear}-${end}`,
    ]);

So what I do is use this query, and then make the query call dynamic.

  • from : 01
  • end : 02
  • startYear: 2022
  • endYear: 2023

And this is the result I get.
Result

    "results": [{
            "department": "COLLEGE 1",
            "year": 2023,
            "month": "Apr",
            "event_count": 42
        },
        {
            "department": "COLLEGE 1",
            "year": 2023,
            "month": "Aug",
            "event_count": 42
        },
        {
            "department": "COLLEGE 1",
            "year": 2023,
            "month": "Dec",
            "event_count": 10
        },
        {
            "department": "COLLEGE 1",
            "year": 2023,
            "month": "Feb",
            "event_count": 45
        },
        {
            "department": "COLLEGE 1",
            "year": 2023,
            "month": "Jan",
            "event_count": 28
        },
        {
            "department": "COLLEGE 1",
            "year": 2023,
            "month": "Jul",
            "event_count": 7
        },
]

How to make the grid responsive on the mobile version. Using JS buttons

I have a grid block. I need to make a slider on the mobile version in the manner shown in the picture. What is the most correct way to implement a slider with JavaScript?open image

<div class="carousel_grid">
    <div class="div1">
      <p>text</p>
    </div>
    <div class="div2">
      <p>text</p>
    </div>
    <div class="div3">
      <p>text</p>
    </div>
    <div class="div4">
      <p>text</p>
    </div>
    <div class="div5">
      <p>text</p>
    </div>
    <div class="div6">
      <p>text</p>
    </div>
    <div class="div7">
      <p>text</p>
    </div>
</div>
.carousel_grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  grid-column-gap: 20px;
  grid-row-gap: 20px;
  
}
.carousel_grid div {
  color: #313131;
  font-family: "Arial";
  font-size: 20px;
  line-height: 110%;
   

}

.carousel_grid

.div1 { grid-area: 1 / 1 / 2 / 2; }
.div2 { grid-area: 1 / 2 / 2 / 3; }
.div3 { grid-area: 1 / 3 / 3 / 4; }
.div4 { grid-area: 2 / 1 / 3 / 2; }
.div5 { grid-area: 2 / 2 / 3 / 3; }
.div6 { grid-area: 3 / 1 / 4 / 2; }
.div7 { grid-area: 3 / 2 / 4 / 4; }

I use media queries to narrow the grid size down to one block, creating a block with a slider that defaults to display: none. and using js selectors I load the necessary blocks

Getting an error while saving file(image) to firebase storage in Node.js that is TypeError [ERR_INVALID_ARG_TYPE]

I am sending the Bio Interests and ProfilePicture in body of my request and wants to save those in my firestore database, Bio and interests have no problem in that, but profilePicture Blob is giving me error while saving it to the storage bucket.

this is my userController.updateProfile function

exports.updateProfile = async (req, res, next) => {
  try {
    const { bio, interests, profilePicture } = req.body;
    const user = req.user;

    const bucket = STORAGE.bucket();
    const folderPath = `users/${user.uid}`;
    const fileName = `profile_image_${user.uid}.jpg`;
    const file = bucket.file(`${folderPath}/${fileName}`);

    await file.save(profilePicture._data, { // probably here is where I am getting the error
      contentType: profilePicture._data.type,
    });

    const imageUrl = await file.getSignedUrl({ action: 'read', expires: '03-01-2500' });

    await AUTH.updateUser(user.uid, {
      photoURL: imageUrl,
    });

    const userRef = DB.collection('users').doc(user.uid);
    await userRef.update({
      bio: bio,
      interests: interests,
      profilePicture: imageUrl,
    });

    return res.status(200).json({
      userUpdated: true,
    })

  } catch (error) {
    console.error(error);
    res.status(500).json({ message: error.message });
  }
}

this is my updateProfile function form my clientside where i am making the request to this API endpoint.

const updateProfile = async () => {
    if (interests.length === 5 && bio.length > 0) {
      try {
        setLoading(true)
        const idToken = await FIREBASE_AUTH.currentUser.getIdToken();
        const encryptedIdToken = encryptData(idToken, SECRET_KEY);
        const encryptedBio = encryptData(bio, SECRET_KEY);
        const encryptedInterests = encryptData(JSON.stringify(interests), SECRET_KEY);

        // creating a blob out of an image and if user did not select any profile picture
        then it will be null but i am selecting the profile image each time        
        let blob = null;
        if (profileImage) {
          const ImageResponse = await fetch(profileImage);
          blob = await ImageResponse.blob();
        }
        const response = await fetch('http://10.0.2.2:5000/users/update', {
          method: 'PUT',
          credentials: 'include',
          headers: {
            'Authorization': 'Bearer ' + encryptedIdToken,
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ bio: encryptedBio, interests: encryptedInterests, profilePicture: blob })
        })
        const data = await response.json();
        if (response.status === 200 && data.userCreated) {
          setLoggedIn(true);
        }

        setLoading(false);
      } catch (error) {
        setLoading(false)
        throw new Error(error)
      }
    }
    return false;
  }

and this is the error which I am facing (sorry for my hiding my folder names I don’t want to reveal my unique concept app idea don’t mind it please)
enter image description here

What are the ways to add a html content preview to jQuery Datatables cells

Below is an example to elaborate the situation.
| id | name |
| ——– | ————– |
| 1 | Apple |
| 2 | Orange |

I’m using Code Igniter for my project Framework. The datatable is called from serverside and encode into json file return to frontend. Ids are tags that link to another page. When hovers over the id, I want it to display a preview of what the the page looks like withs few specific data.

In controller.php,
I tried create a variable that stores the html content. But tooltip does not pass html content.

$tip_box = 
"<div class='tip_box'>
<div class='tip_content'>
  <h2>".$row->name."</h2>
  <div>".$row->description."</div>
</div>
</div>";

$id = '<a href="'.site_url('controller/info').'" data-tooltip="'.$tip_box.'">$row->id</a>';

How do I import a npm module and function from another file when developing for a chrome extension?

I am trying to develop a Chrome extension using Manifest V3. This is a part of my manifest.json which declares a service worker.

    "background": {
        "type": "module",
        "service_worker": "ui/backend/service-worker.js"
    }

Inside my service-worker.js, this is all I do.

import { initTracker } from "./tracker.js";
import Browser from "webextension-polyfill";

initTracker();

Inside my tracker.js file, I just have some basic functions defined. I am using Webpack as my module bundler. How can I make sure that I can use the webextension-polyfill module and its APIs within my chrome extension and its service worker? I currently get the error

Uncaught TypeError: Failed to resolve module specifier "webextension-polyfill". Relative references must start with either "/", "./", or "../".
Service worker registration failed. Status code: 15

How to move SVG / polyline

Right now the polyline/chevron is to the right of the words. How do I make it so that it is at the beginning of each accordion instead. Thank you

Here is the code. Please let me know how to move the polyline! I would like it at the beginning of the accordion headers instead.

I’m not sure what could work

<script src="https://unpkg.com/[email protected]"></script>

<!-- <script src="https://unpkg.com/vue/dist/vue.js"></script> -->

<style>

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap');

* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#app {
font: 100%/1.4 Roboto, sans-serif;
/*padding: 2em;*/
color: white;
}
h1,
h2,
h3 {
margin-bottom: 0.7em;
}
ol,
ul {
list-style-position: inside;
}
/* accordion component*
*/
.V-accordion {
user-select: none;
border: 1px solid #efefef;
border-radius: 5px;
overflow: hidden;
margin: 10px;
}
.V-accordion + .V-accordion {
border-top: ;
}
.V-accordion_trigger {
cursor: pointer;
padding: 0.7rem 1.5rem;
transition: all 0.4s;
}
.V-accordion_trigger:hover {
color: gold/*#477dca*/;
}
.V-accordion_trigger-icon {
transition: transform 0.2s cubic-bezier(0.23, 1, 0.32, 1);
}
.V-accordion_trigger-icon.open {
transform: rotate(180deg);
}
.V-accordion_body {
padding: 1rem 1.5rem;
background: /*#f1f1f1*/;
}
.accordion-enter-active {
animation: accordion 0.5s forwards;
}
.accordion-leave-active {
animation: accordion 0.2s 0.2s reverse;
}
@-moz-keyframes accordion {
0% {
opacity: 0;
transform: translateY(100%);
}
100% {
transform: translateY(0);
}
}
@-webkit-keyframes accordion {
0% {
opacity: 0;
transform: translateY(100%);
}
100% {
transform: translateY(0);
}
}
@-o-keyframes accordion {
0% {
opacity: 0;
transform: translateY(100%);
}
100% {
transform: translateY(0);
}
}
@keyframes accordion {
0% {
opacity: 0;
transform: translateY(100%);
}
100% {
transform: translateY(0);
}
}

</style>

<div id="app">
<accordion title="FAQ title 1">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ea enim aliquid itaque esse dolorum aperiam, rerum ab possimus voluptatibus modi nobis, maiores quisquam ut sint impedit dignissimos assumenda tempora quam.</p>
</accordion>
<accordion title="FAQ title 2">
<ol>
<li>Lorem ipsum dolor sit amet consectetur</li>
<li>Lorem ipsum dolor sit amet consectetur</li>
<li>Lorem ipsum dolor sit amet consectetur</li>
</ol>
</accordion>
<accordion title="FAQ title 3">
<h3>Lorem ipsum dolor sit amet</h3>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Blanditiis explicabo porro, voluptatum laborum cumque molestiae quibusdam accusamus sed, quam sint ducimus libero distinctio? Dolore laborum, quos dolorem recusandae deleniti quasi.</p>
</accordion>
</div>

<script>
Vue.component('accordion', {
props: ['title'],
template:
`
<div class="V-accordion">
<div class="V-accordion_trigger" @click="open = !open">
{{ title }}
<svg class="V-accordion_trigger-icon" :class="{open:open}" width="40" height="12">
<polyline points="12,10 20,2 28,10" stroke="gold" stroke-width="3" fill="none"></polyline>
</svg>
</div>
<transition :name="animation">
<div class="V-accordion_body" v-show="open">
<slot></slot>
</div>
</transition>
</div>
`,
props: {
title: {
type: String,
default: 'FAQ'
},
animation: {
type: String,
default: 'accordion'
}
},
data() {
return {
open: false
}
}
});

const vm = new Vue({
el: "#app",
data: {
},
computed: {
},
methods: {
},
mounted() {
}
});
</script>

Square that fills according to the origin of the pointer

I’m requesting help for something I thought was easier to code.
I would like to code a square that “fills” gradually (like a bucket or a bathtub..but without gravity!) when the pointer hovers it and according to the direction of the pointer. That is, if the pointer comes from the right of the square, the color fills it from right to left, if it comes from the bottom, the color fills it from the bottom to the top…etc.

This is a code that fills my square in any direction but only if i change some properties. This is this code:


    <div class="square" ></div>

  <style>::after
   .square {
    width: 400px;
    height: 400px;
    border: solid 1px black;
    
    position: relative;

  }
  
  .square::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(#3498db, #3498db);
    transform-origin: bottom;
    transform: scaleY(0); 

    transition: transform 0.5s ease; 
}

  
  .square:hover::before {
    transform: scaleY(1); 
    
  }
  </style>

Here, the color fills the square from bottom to top. By modifying transform-origin: bottom with transform-origin: top ,it will go from top to bottom. The same with left and right AND replaceing the two scaleY by scaleX, itl will go from left to right or right to end?

But how to combine this code with someting (I suppose in javascript) that will indicate the origine of the pointer so that the color automatically fills the square in the direction of the pointer?

Thank you for helping a beginner!

Didier

Transferring array data into a PHP script obtained via the SOAP protocol and transferring it to a Java script

I’m new to coding.
I receive data using the soap protocol, I receive a PHP array

    <?php   
    $geostation = array ();
    foreach ($res->TripPointArr as $point) {
    $geostation[] = array(
    'stationName' =>$point->StationNm,
    'longitude' => $point->StLONGITUDE,
    'latitude' => $point->StLATITUDE,
    'timearrft' => $point->DtTmArrivalFt
    );
    }`
    $jsondata = json_encode($geostation);
    echo $jsondata;
        fetch('getdata.php')
        .then(response => response.json())
        .then(data => {
        console.log(data);
        })
       .catch(error => console.error('Ошибка при получении данных:', error));

I get an error SyntaxError: Unexpected non-whitespace character after JSON at position 5795
when I try to convert the entire array to json.
But if I exclude the elements ‘timesendft’ ‘timearrft’ from the array, the names and coordinates remain, then the json is valid, and if I remove the coordinates and leave the names and date and time, then everything is fine too. But if you try the entire array, then json gives an error.

How to avoid onMouseEnter getting triggered every time the child element gets replaced?

I have the following div:

                <div className="header-right-side-language"
                     onClick={handleCountrySwitch}
                     onMouseEnter={handleHover}
                     onMouseLeave={handleNoHover}
                     style={languageButtonStyle}>
                    {currentCountry === 'US' ?
                        <>
                            <US title="United States"/>
                            <p>EN</p>
                        </>
                        : <>
                            <EG title="Egypt"/>
                            <p>AR</p>
                        </>
                    }
                </div>

and here are the called functions:

const handleCountrySwitch = () => {
        // Toggle between US and EG on click
        setCurrentCountry((prevCountry) => (prevCountry === 'US' ? 'EG' : 'US'));
        setLanguageButtonStyle((prevStyle) => ({ ...prevStyle, opacity: 1 }));
};
const handleHover = () => {
        // Update opacity
        setLanguageButtonStyle((prevStyle) => ({ ...prevStyle, opacity: 0.5 }));
};
const handleNoHover = () => {
        // Update opacity
        setLanguageButtonStyle((prevStyle) => ({ ...prevStyle, opacity: 1 }));
};

Due to the re-rendering of the component when the child element is completely replaced, the onMouseEnter gets re-triggered (only if I am hovering over the or not the

).