Saturday, November 12, 2022

GraphQL React


TopicSubArea.tsx 




import { ApolloClient, gql, InMemoryCache, useQuery } from "@apollo/client";

import { Delete, Edit } from "@mui/icons-material";
import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, FormControl, Grid, InputLabel, MenuItem, Select, TextField, Typography } from "@mui/material";
import { AgGridReact } from "ag-grid-react";
import React, { useEffect, useState } from "react";
import apolloClient from "../../helpers/apolloclient.interceptor";
import { useFormik } from "formik";

const GET_TOPICSUBAREAS =
    gql`
query {
    topicSubArea
        {
            topicSubAreaId,
            topicSubAreaName,
            topicSubAreaDescription,
            abbreviation
        }
}
`;
const GET_EVENTLIST =
    gql`
    query {
        event {
            eventId
            eventName
        }
    }
   
`;

const TopicSubArea = () => {
    const [rowData, setRowData] = useState([]); // Set rowData to Array of Objects, one Object per Row
    const [open, setOpen] = React.useState(false);
    const [eventData, setEventData] = useState([]);

    const handleClickOpen = () => {
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    };

    const handleSave = () => {
        //  console.log(props)
        setOpen(false);
    }

    const [columnDefs, setColumnDefs] = useState([
        { field: 'topicSubAreaId', headerName: 'Id', filter: true, width: 100 },
        { field: 'topicSubAreaName', filter: true },
        { field: 'topicSubAreaDescription', headerName: 'Description', filter: true },
        { field: 'abbreviation', filter: true },
        {
            headerName: "", maxWidth: 70, cellRendererParams: { edit: 'editButton' }, filter: false, cellRenderer: (data: any) => {
                return <><Edit color="primary" /></>
            }
        },
        {
            headerName: "", maxWidth: 70, cellRendererParams: { delete: 'deleteButton' }, filter: false, cellRenderer: (data: any) => {
                return <><Delete color="error" /></>
            }
        }
    ]);

    // const client = new ApolloClient({

    //     uri: process.env.REACT_APP_MAGIC_API,
    //     cache: new InMemoryCache(),
    // });

    const client = apolloClient;

    useEffect(() => {
        client
            .query({
                query: GET_TOPICSUBAREAS
            })
            .then((response) => setRowData(response.data));
    }, []);

    useEffect(() => {
        client
            .query({
                query: GET_EVENTLIST
            })
            .then((response) => setEventData(response.data.event));
    }, []);


    const formik = useFormik({
        initialValues: {
            eventId: 0,
            topicSubAreaName: '',
            topicSubAreaDescription: '',
            abbreviation: '',
            dateCreated: "2022-10-20 05:25:39.339985+00",
            dateModified: "2022-10-20 05:25:39.339985+00",
        },
        onSubmit: values => {
            alert(JSON.stringify(values, null, 2));//save
            handleClose();
        },
    });


    var results: any = rowData;
    console.log(results.topicSubArea);
    const [eventId, setEventId] = useState(0);

    //this event is onChange event
    const handleChange = (event: any) => {
        setEventId(event.target.value);
    }


    return (
        <>

            <Grid container spacing={3}>
                <Grid item xs={4}>
<Button variant="contained" onClick={handleClickOpen}>Add TopicSubArea</Button>
                    <Dialog open={open} onClose={handleClose}>
                        <form onSubmit={formik.handleSubmit}>
                            <DialogTitle>Add TopicSubArea</DialogTitle>
                            <DialogContent>

                                <Select
                                    autoFocus
                                    value={eventId}
                                    fullWidth
                                    id="Event"
                                    label="Event"
                                    variant="standard"
                                    margin="dense"
                                    onChange={handleChange}
                                >
                                    {
                                        eventData.map((event: any) => {
                                            return (
   <MenuItem key={event.eventId} value={event.eventId}>{event.eventName}</MenuItem>
                                            )
                                        })
                                    }

                                </Select>

                                <TextField

                                    margin="dense"
                                    id="topicSubAreaName"
                                    label="topicSubAreaName"
                                    type="text"
                                    fullWidth
                                    variant="standard"
                                    value={formik.values.topicSubAreaName}
                                    onChange={formik.handleChange}
                                />
                                <TextField
                                    margin="dense"
                                    id="topicSubAreaDescription"
                                    label="topicSubAreaDescription"
                                    type="text"
                                    fullWidth
                                    variant="standard"
                                    value={formik.values.topicSubAreaDescription}
                                    onChange={formik.handleChange}
                                />
                                <TextField
                                    margin="dense"
                                    id="abbreviation"
                                    label="abbreviation"
                                    type="text"
                                    fullWidth
                                    variant="standard"
                                    value={formik.values.abbreviation}
                                    onChange={formik.handleChange}
                                />
                            </DialogContent>
                            <DialogActions>
                                <Button onClick={handleClose}>Cancel</Button>
                                <Button type="submit" >Add</Button>
                            </DialogActions>
                        </form>
                    </Dialog>
                </Grid>
                <Grid item xs={12}>
                    <Typography>TopicSubArea List</Typography>
  <div className="ag-theme-alpine" style={{ height: 400, width: 850 }}>
                        <AgGridReact
                            rowData={results.topicSubArea}
                            columnDefs={columnDefs}>
                        </AgGridReact>
                    </div>
                </Grid>
            </Grid>

        </>
    )
}

export default TopicSubArea

function learn()
{
}
const learn=function (){
} const learn = () => {
//arrow function
}

learn = () => {
//arrow function
}

const learn = () => "Hellow";




Friday, November 4, 2022

VB.Net

 Imports System.Data.SqlClient

Imports System.Configuration


Public Class Form1

    Private Sub btnInsert_Click(sender As Object, e As EventArgs) Handles btnInsert.Click

        Dim connectionString As String = ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString


        Dim name As String = txtName.Text ' Assuming you have a TextBox named txtName for the name input

        Dim email As String = txtEmail.Text ' Assuming you have a TextBox named txtEmail for the email input


        Using connection As New SqlConnection(connectionString)

            connection.Open()


            Dim insertQuery As String = "INSERT INTO YourTable (Name, Email) VALUES (@Name, @Email)" ' Replace with your table and column names


            Using cmd As New SqlCommand(insertQuery, connection)

                cmd.Parameters.AddWithValue("@Name", name)

                cmd.Parameters.AddWithValue("@Email", email)


                Dim rowsAffected As Integer = cmd.ExecuteNonQuery()


                If rowsAffected > 0 Then

                    MessageBox.Show("Data inserted successfully.")

                    ' Optionally, clear the input fields or perform other actions after successful insertion.

                Else

                    MessageBox.Show("Data insertion failed.")

                End If

            End Using

        End Using

    End Sub

End Class


Monday, September 26, 2022

IQ

 

Orsted Interview Questions
Introduction
Executive Summary Structure
● Name
● Graduated from, in what degree
● Total years of working experience
● Current role in what company
● What do you do at your current role
● Biggest strength
● Why are you looking out
● What interest you in this role
To understand further about your experience
● Years of experience in Angular and .Net Core
● How many projects in Angular and .Net Core that are built from scratch?
● Could you explain about your current system design? (How does front end
communicate with back end, how many layers of authentication, database used)
● How does the back end talk to the database?
● Are you familiar with Agile methodology?
● Are you involved in CI/CD? Devops?
● Where do you host your application?
● What do you do when you get stuck with a problem and you cannot solve it by
yourself?
● Do you deal with stakeholders regularly?
● How do you explain technical requirements to non technical people? (Hint: Draw
diagrams)
Back End related questions
● What is ORM (object relational mapping)
● What is .Net Core?
● Do you know what is the latest version of C#?
● Concept of cohesion and coupling
● 3 Probabilities of OOP (Encapsulation, inheritance, polymorphism)
● What is interface in C#?
● Can interface be inherited?
● How do you dispose method object in C#?
● What is dependency injection?
● What is delegate C#?
● What is reflection in C#?
● Difference between task and thread in C#
● C# Asynchronous Method
● Cross origin in C#
● What is an abstract class?
● Difference between local storage and session storage, cookies? How would you use

each?
Database
● How do you present a large amount of data? Do you improve the API or Repository
layers?
● Experience in Troubleshooting database - speed of loading data
● What are the steps to fine tune queries that were already provided?
● What is Stored Procedure and do you work on it?
● Do you have experience in updating / inserting functions in Stored Procedure?
● How do you ensure data consistency in a table?
● Experience in Transaction Query
● Indexing SQL
Unit Testing
● What is TDD and Unit Testing?
● How do you make a good unit test approach, what are the key measures?
● How do you simulate results from a unit test?
● How do you mock unit testing?
● What's your most used design patterns?
Front End related questions
Javascript
● Difference between variables in javascript
● Which method would you use if you want to remove the first item in the array
● Difference between double equal vs triple equal
Angular
● How do you pass parent components to child components?
● How do you evoke the child component method to parent class?
● How do you share data between 2 child components without going through the parent
component?
● How do you pass in a user token to APIs without the need to define every single API?
How do you define once to ensure a token can pass through every API?
● How to achieve calling live data to the front end via API?
● Let’s say a Parent component has a CSS Class name, if you were to reuse the CSS
Class in the child component and only want to overwrite 1 property, how do you do it
without affecting the parent component?
● What is View Encapsulation?
● File upload component - If you would like to use the original template in another front
end project, but you do not want to copy the same set of components, how do you do
it?
● How do you handle your authentication of authorisation for each component and
services where some allow access in page 1, some in page 2?
Q&A Session

Prepare a list of intelligent questions to ask the interviewers - ask about the company /
product / services / business model / team structure / culture/ future plans / expectations for
you and etc - anything that can't be easily Googled would be good questions.

Thursday, August 25, 2022

FileUploads

import { AgGridReact } from 'ag-grid-react';

import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react';
import { ApolloClient, gql, InMemoryCache } from "@apollo/client"
import { Button, getTextFieldUtilityClass, Grid, Paper, Stack, styled } from '@mui/material';
import ContentList from './ContentList';
import FileDownloadCellRenderer from './FileDownloadCellRenderer';
import FileUploadHistoryList from './FileUploadHistoryList';
import MilestoneList from './MilestoneList';
import Accordion from '@mui/material/Accordion';
import AccordionDetails from '@mui/material/AccordionDetails';
import AccordionSummary from '@mui/material/AccordionSummary';
import Typography from '@mui/material/Typography';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import * as _ from 'underscore';
import moment from 'moment';
import { Color } from 'ag-grid-community';

const GET_FILEUPLOADS =
  gql`
  query($contentId:Int) {
    fileUploads(where: {contentId:{eq:$contentId}}) {
      contentId
      fileType {
        fileTypeName
      }
      content {
          userInfo {
          longName
          }
      }
      version
      originalName
      fileName
      dateCreated
    }
  }
`;

const Item = styled(Paper)(({ theme }) => ({
  backgroundColor: theme.palette.mode === 'dark' ? '#1A2027' : '#fff',
  padding: theme.spacing(1),
  textAlign: 'left',
}));

const client = new ApolloClient({

  uri: process.env.REACT_APP_MAGIC_API,
  cache: new InMemoryCache(),
});

const MAGIC_API_FILES_BASE_URL ="http://localhost:8081/Files/";

const SubmissionEditor = () => {

  const gridRef = useRef(null); // Optional - for accessing Grid's API
  const [rowData, setRowData] = useState([]); // Set rowData to Array of Objects, one Object per Row // mother content
  const [fileUploadInfopPanelVisivility, SetFileUploadInfoPanelVisibility] = useState(false);
  const [expanded, setExpanded] = React.useState<string | false>(false);
  const [fileUploadData, setFileUploadData] = useState([]); //history and file uploads
  const [selectedContentId, setSelectedContentId] = useState(0);
  const [downloadURL, setDownloadURL] = useState('');  //history and file uploads
  const [mostRecentFileUploadInfo, setMostRecentFileUploadInfo] = useState({} as any);

  const handleChange =
    (panel: string) => (event: React.SyntheticEvent, isExpanded: boolean) => {
      setExpanded(isExpanded ? panel : false);
    };

  // Each Column Definition results in one Column.
  const [columnDefs, setColumnDefs] = useState([
    { field: 'fileName', filter: true },
    { field: 'version', filter: true },
    { field: 'originalName' },
    {
      headerName: "Open",
      field: "fileName",
      editable: false,
      cellRenderer: FileDownloadCellRenderer
    }

  ]);

  const onVisibilityChange = (contentId: number) => {

    setSelectedContentId(contentId);

    client
      .query({
        query: GET_FILEUPLOADS,
        variables: { "contentId": contentId }
      })
      .then((response) => {
        if (response && response.data && response.data.fileUploads && response.data.fileUploads.length) {

          setFileUploadData(response.data.fileUploads);

          let sortedList = _.sortBy(response.data.fileUploads, 'version');
          let mostRecentFile: any = sortedList.reverse()[0];

          let downloadUrl = MAGIC_API_FILES_BASE_URL + mostRecentFile.originalName;
          setDownloadURL(downloadUrl);

          setMostRecentFileUploadInfo(mostRecentFile);

          SetFileUploadInfoPanelVisibility(true);
          setExpanded('panel1');
        }
        else {
          SetFileUploadInfoPanelVisibility(false);
          setFileUploadData([]);
          setMostRecentFileUploadInfo({} as any);
          setDownloadURL('');
          setExpanded(false);
        }
      });
  }

  return (
    <div>
      <Grid container spacing={2}>
        <Grid item xs={12}>
          <p style={{ marginLeft: 5, fontSize:'20px',color:'black' }}>Submissions </p>
          <div><ContentList handleVisibility={onVisibilityChange} selectedContentId={selectedContentId} /></div>
        </Grid>
        {/*  <Grid item xs={4}>
          <p style={{ marginLeft: 5 }}>Milestones <Button variant="contained">UPdate</Button></p>

          <div className="ag-theme-alpine" style={{ height: 400 }}><MilestoneList /></div>
        </Grid> */}
        <Grid item xs={12}>
          {fileUploadInfopPanelVisivility ?
            <div>
              <Accordion expanded={expanded === 'panel1'} onChange={handleChange('panel1')}>
                <AccordionSummary
                  expandIcon={<ExpandMoreIcon />}
                  aria-controls="panel1bh-content"
                  id="panel1bh-header"
                >
                  <Typography sx={{ width: '33%', flexShrink: 0,color:'black',fontSize:'20px' }}>
                    Uploaded Files and History
                  </Typography>
                </AccordionSummary>
                <AccordionDetails>

                  <Stack spacing={1}>
                    <Item>Type : {mostRecentFileUploadInfo.fileType.fileTypeName} </Item>
                    <Item>Version : {mostRecentFileUploadInfo.version}</Item>
                    <Item>File Name : {mostRecentFileUploadInfo.fileName} &nbsp;  &nbsp; &nbsp; <a href={downloadURL}>Download</a></Item>
                    <Item>Uploaded By : {mostRecentFileUploadInfo.content.userInfo.longName}</Item>
                    <Item>Date Created : {moment(mostRecentFileUploadInfo.dateCreated).format('MM/DD/YYYY')}</Item>
                  </Stack>

                </AccordionDetails>
              </Accordion>
              <Accordion expanded={expanded === 'panel2'} onChange={handleChange('panel2')}>
                <AccordionSummary
                  expandIcon={<ExpandMoreIcon />}
                  aria-controls="panel2bh-content"
                  id="panel2bh-header"
                >
                  <Typography sx={{ width: '33%', flexShrink: 0 }}> File Upload History</Typography>
                </AccordionSummary>
                <AccordionDetails>

                </AccordionDetails>
              </Accordion>
            </div>
            : null}

        </Grid>
      </Grid>
    </div>



  );
}

export default SubmissionEditor;






Driving

 https://youtube.com/shorts/5Ac2qZHrApU?si=_X-G7pJFHiZoD-s7 https://www.youtube.com/watch?v=f6pSsex87oU