Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

admin sample design + samples json #2

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Docs/Samples/basic.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[
{"$type":"UserInfo","UserName":"sadmin","FirstName":"Sample","LastName":"Admin","Email":"[email protected]","UserPassword":"[sample hash]","UserEnabled":true,"UserCreated":"1990-01-01T00:00:00","LastLogon":null,"UserGUID":"dbfcc244-2cb9-4934-857f-9d75404c1553","UserLastModified":null,"UserSecurityStamp":null,"UserPasswordLastChanged":null,"UserIsPendingRegistration":false,"UserRegistrationLinkExpiration":null,"UserAdministrationAccess":true,"UserIsExternal":false},
{"$type":"DataClass","ClassDisplayName":"Event","ClassName":"UMT.Event","ClassIsDocumentType":true,"ClassIsCoupledClass":true,"ClassNodeNameSource":"EventTitle","ClassTableName":"UMT_Event","ClassShowAsSystemTable":false,"ClassUsePublishFromTo":null,"ClassShowTemplateSelection":null,"ClassNodeAliasSource":"EventTitle","ClassLastModified":null,"ClassGuid":"3d36917e-de3e-4db3-9d71-7961d250085d","ClassShowColumns":null,"ClassInheritsFromClassGuid":null,"ClassContactMapping":null,"ClassContactOverwriteEnabled":null,"ClassConnectionString":null,"ClassDefaultObjectType":null,"ClassIsForm":false,"ClassResourceGuid":null,"ClassCustomizedColumns":null,"ClassCodeGenerationSettings":null,"ClassIconClass":null,"ClassURLPattern":null,"ClassUsesPageBuilder":true,"ClassHasURL":true,"ClassHasMetadata":true,"ClassIsPage":true,"ClassHasUnmanagedDbSchema":false,"ClassPrimaryKeyName":"EventID","Fields":[{"AllowEmpty":true,"Column":"EventTitle","ColumnSize":200,"ColumnType":"text","Enabled":true,"Guid":"0e1e63eb-918a-4135-a627-04393672d6f4","Visible":true,"Properties":{"FieldCaption":"Title"},"Settings":{"ControlName":"Kentico.Administration.TextInput"}},{"AllowEmpty":true,"Column":"EventText","ColumnSize":0,"ColumnType":"longtext","Enabled":true,"Guid":"a54aef74-42b3-438e-92b2-2f5b4386fb57","Visible":true,"Properties":{"FieldCaption":"Text"},"Settings":{"ControlName":"Kentico.Administration.TextArea"}},{"AllowEmpty":true,"Column":"EventDate","ColumnSize":0,"ColumnType":"datetime","Enabled":true,"Guid":"f3356f35-0a78-4a98-8696-a1becb725b0a","Visible":true,"Properties":{"FieldCaption":"Date"},"Settings":{"ControlName":"Kentico.Administration.DateTimeInput"}},{"AllowEmpty":true,"Column":"EventRecurrentYearly","ColumnSize":0,"ColumnType":"boolean","Enabled":true,"Guid":"98d2cf95-5027-488a-b833-89510f4662c1","Visible":true,"Properties":{"FieldCaption":"Event occurs every year"},"Settings":{"ControlName":"Kentico.Administration.Checkbox"}}]},
{"$type":"DataClass","ClassDisplayName":"Article","ClassName":"UMT.Article","ClassIsDocumentType":true,"ClassIsCoupledClass":true,"ClassNodeNameSource":"ArticleTitle","ClassTableName":"UMT_Article","ClassShowAsSystemTable":false,"ClassUsePublishFromTo":null,"ClassShowTemplateSelection":null,"ClassNodeAliasSource":"ArticleTitle","ClassLastModified":null,"ClassGuid":"2cb15794-9ab1-450f-b69b-ebdee1f5b5fe","ClassShowColumns":null,"ClassInheritsFromClassGuid":null,"ClassContactMapping":null,"ClassContactOverwriteEnabled":null,"ClassConnectionString":null,"ClassDefaultObjectType":null,"ClassIsForm":false,"ClassResourceGuid":null,"ClassCustomizedColumns":null,"ClassCodeGenerationSettings":null,"ClassIconClass":null,"ClassURLPattern":null,"ClassUsesPageBuilder":true,"ClassHasURL":true,"ClassHasMetadata":true,"ClassIsPage":true,"ClassHasUnmanagedDbSchema":false,"ClassPrimaryKeyName":"ArticleID","Fields":[{"AllowEmpty":true,"Column":"ArticleTitle","ColumnSize":200,"ColumnType":"text","Enabled":true,"Guid":"ea7da631-6d9c-413f-a746-93442b623908","Visible":true,"Properties":{"FieldCaption":"Article title"},"Settings":{"ControlName":"Kentico.Administration.TextInput"}},{"AllowEmpty":true,"Column":"ArticleText","ColumnSize":0,"ColumnType":"longtext","Enabled":true,"Guid":"a54aef74-42b3-438e-92b2-2f5b4386fb57","Visible":true,"Properties":{"FieldCaption":"Article text"},"Settings":{"ControlName":"Kentico.Administration.TextArea"}}]},
{"$type":"TreeNode","NodeClassGuid":"3d36917e-de3e-4db3-9d71-7961d250085d","NodeOwnerGuid":"dbfcc244-2cb9-4934-857f-9d75404c1553","NodeParentGuid":"acdd2058-bde0-4c9d-8332-45f417220571","NodeGUID":"50cf01d4-1c39-4910-82ca-298c9f7a4840","NodeAlias":"announcement-of-economic-results","NodeName":"Announcement of economic results","NodeOrder":null,"DocumentCulture":"en-US","DocumentName":"Announcement of economic results","DocumentLastPublished":null,"DocumentModifiedWhen":null,"DocumentCreatedWhen":null,"DocumentPublishFrom":null,"DocumentPublishTo":null,"DocumentGUID":"15f0efd6-6961-4640-af6d-9c06b3a0a24d","DocumentCreatedByUserGuid":"dbfcc244-2cb9-4934-857f-9d75404c1553","DocumentModifiedByUserGuid":null,"EventTitle":"Announcement of economic results","EventText":"\u003Ch1\u003EAnnouncement of economic results\u003C/h1\u003E","EventDate":"2023-07-01T11:00:00","EventRecurrentYearly":false},
{"$type":"TreeNode","NodeClassGuid":"3d36917e-de3e-4db3-9d71-7961d250085d","NodeOwnerGuid":"dbfcc244-2cb9-4934-857f-9d75404c1553","NodeParentGuid":"acdd2058-bde0-4c9d-8332-45f417220571","NodeGUID":"e2b53c6c-020d-45d3-acb7-c2651bf7171a","NodeAlias":"yearly-barbecue-for-customers","NodeName":"Yearly barbeque for customers","NodeOrder":null,"DocumentCulture":"en-US","DocumentName":null,"DocumentLastPublished":null,"DocumentModifiedWhen":null,"DocumentCreatedWhen":null,"DocumentPublishFrom":null,"DocumentPublishTo":null,"DocumentGUID":"34b4df1b-6261-4546-9382-941809e1936f","DocumentCreatedByUserGuid":"dbfcc244-2cb9-4934-857f-9d75404c1553","DocumentModifiedByUserGuid":null,"EventTitle":"Yearly barbeque for customers","EventText":"\u003Ch1\u003EBarbecue is here!\u003C/h1\u003E\u003Cp\u003Elet us invite You to our yearly friendly meeting with You - our customers\u003C/p\u003E","EventDate":"2023-06-01T11:00:00","EventRecurrentYearly":true}
]
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useState } from "react";
import { Button, ButtonSize, DropDownActionMenu, FileInput, MenuItem, TreeNodeMenuAction, UploadTile, UploadTileSize } from "@kentico/xperience-admin-components";
import { ActionTile, Box, Button, ButtonSize, Callout, CalloutPlacementType, CalloutType, Cols, Column, Divider, DividerOrientation, DropDownActionMenu, FileInput, Headline, HeadlineSize, Input, MenuItem, NotificationBarAlert, ProgressBar, RadioButton, RadioGroup, RadioGroupSize, Row, Select, Shelf, Spacing, Stack, TreeNodeMenuAction, UploadTile, UploadTileSize } from "@kentico/xperience-admin-components";


/*
Expand All @@ -12,23 +12,16 @@ import { Button, ButtonSize, DropDownActionMenu, FileInput, MenuItem, TreeNodeMe

interface CustomLayoutProps {
readonly label: string;
readonly contactGroups: any[];
}

let canContinue = true;
let toofast = false;

export const CustomLayoutTemplate = ({ label, contactGroups }: CustomLayoutProps) => {
const [labelValue, setLabelValue] = useState(label);

// console.log('contactGroups', contactGroups);

export const CustomLayoutTemplate = ({ label }: CustomLayoutProps) => {
const [file, setFile] = useState<File | null>(null);
const [state, setState] = useState<string[]>([]);
const [currentFile, setCurrentFile] = useState({ current: 0, total: 0 });

// const [blockCache, setBlockCache] = useState<number>(1500);

const [stats, setStats] = useState<{ [statKey: string]: number } | null>(null);

function parseFile(this: any, file: File, callback: (buffer: ArrayBuffer) => boolean, finishedCallback: () => void) {
var fileSize = file.size;
Expand Down Expand Up @@ -89,110 +82,203 @@ export const CustomLayoutTemplate = ({ label, contactGroups }: CustomLayoutProps
chunkReaderBlock(offset, chunkSize, file);
}

return (
<div>
<h1>{labelValue}</h1>
{/* {fu} */}
<input type="file" onChange={(event) => event.target.files != null ? setFile(event.target.files[0] || null) : null} />
{/* BytesSent: ${currentFile.current}
Total: ${currentFile.total} */}
<pre style={{ border: '2px dotted magenta' }}>{`Upload progress:${Math.floor((currentFile.current / currentFile.total) * 100)}%
`}<progress id="progress_" value={currentFile.current} max={currentFile.total} style={{ width: '100%' }}></progress></pre>
<Button
label="Send file"
size={ButtonSize.S}
onClick={() => {
if (file != null) {
console.log(file);
let port = location.port != '' ? `:${location.port}` : '';
const socket = new WebSocket('ws://' + location.hostname + `${port}/umtsample/ws`);
socket.binaryType = 'blob';
socket.onerror = (e) => {
console.log('error occured', e);
canContinue = false;
console.log('closing socket => error');
socket.close();
const onUpload = () => {
setStats(null);
setState([]);
if (file != null) {
console.log(file);
let port = location.port != '' ? `:${location.port}` : '';
const socket = new WebSocket('ws://' + location.hostname + `${port}/umtsample/ws`);
socket.binaryType = 'blob';
socket.onerror = (e) => {
console.log('error occured', e);
canContinue = false;
console.log('closing socket => error');
socket.close();
}
socket.onmessage = (event) => {
var p = JSON.parse(event.data);
switch (p.type) {
case "stats": {
try {
setStats(JSON.parse(p.payload));
}
socket.onmessage = (event) => {
var p = JSON.parse(event.data);
switch (p.type) {
case "headerConfirmed": {
console.log('header confirmed, starting import');
parseFile(file, (buffer) => {
// console.log('chunk');
if (socket.readyState == socket.OPEN) {
socket.send(buffer);
return true;
}
else {
return false;
}
}, () => {
console.log('sending end sequence');
var endMessage = Uint8Array.of(0x2D, 0x2D, 0x2D, 0x2D, 0x2D);
socket.send(endMessage);

setTimeout(() => {
// socket.send("---FINISHED---");
console.log('closing socket - timeout 60s');
socket.close();
}, 60000);
});
break;
}
case "toofast": {
toofast = true;
break;
}
case "msg": {
setState((prev) => [
...prev,
p.payload
])
break;
}
case "progress": {
const len = parseInt(p.payload);
setCurrentFile(prev => ({
total: prev.total,
current: prev.current + len
}))
break;
}
case "finished": {
console.log('closing socket');
canContinue = false;
if (socket.readyState < socket.CLOSING) {
socket.close();
}
break;
}
catch (e) {
console.error(e);
}
break;
}
case "headerConfirmed": {
console.log('header confirmed, starting import');
parseFile(file, (buffer) => {
// console.log('chunk');
if (socket.readyState == socket.OPEN) {
socket.send(buffer);
return true;
}
};
socket.onopen = function (event) {
canContinue = true;
setState((prev) => [
...prev,
`Sending file of length: ${file.size}`
])
console.log('connected');
setCurrentFile({
total: file.size,
current: 0
})

socket.send(JSON.stringify({
type: 'header',
payload: {
}
}));
};
} else {
alert('no file selected');
else {
return false;
}
}, () => {
console.log('sending end sequence');
var endMessage = Uint8Array.of(0x2D, 0x2D, 0x2D, 0x2D, 0x2D);
socket.send(endMessage);

setTimeout(() => {
// socket.send("---FINISHED---");
console.log('closing socket - timeout 60s');
socket.close();
}, 60000);
});
break;
}
}}
/>
<pre style={{ overflow: 'scroll' }}>{[...state].reverse().join("\r\n")}</pre>
</div>
case "toofast": {
toofast = true;
break;
}
case "msg": {
setState((prev) => [
...prev,
p.payload
])
break;
}
case "progress": {
const len = parseInt(p.payload);
setCurrentFile(prev => ({
total: prev.total,
current: prev.current + len
}))
break;
}
case "finished": {
console.log('closing socket');
canContinue = false;
if (socket.readyState < socket.CLOSING) {
socket.close();
}
break;
}
}
};
socket.onopen = function (event) {
canContinue = true;
setState((prev) => [
...prev,
`Sending file of length: ${file.size}`
])
console.log('connected');
setCurrentFile({
total: file.size,
current: 0
})

socket.send(JSON.stringify({
type: 'header',
payload: {
}
}));
};
} else {
alert('no file selected');
}
};

const newInterface = (
<Box spacing={Spacing.M}>
<Headline size={HeadlineSize.L} spacingBottom={Spacing.M}>
{label}
</Headline>
<Row spacing={Spacing.XL}>
<Column
cols={Cols.Col12}
colsMd={Cols.Col10}
colsLg={Cols.Col8}
order={Cols.Col2}
orderLg={Cols.Col1}
>
<Stack spacing={Spacing.XL} fullHeight={true}>
<Callout
type={CalloutType.QuickTip}
placement={CalloutPlacementType.OnPaper}
headline="Basic usage"
subheadline="Info"
>
Component <a target="_blank" href="https://github.com/Kentico/xperience-by-kentico-universal-migration-toolkit/blob/main/Docs/README.md">documentation</a> and <a target="_blank" href="https://github.com/Kentico/xperience-by-kentico-universal-migration-toolkit/tree/main/Docs/Samples">samples</a>
</Callout>

<div style={{ display: 'inline-block' }}>
<ActionTile label={"Legacy Kentico"} icon={"xp-cb-check"}></ActionTile>&nbsp;
<ActionTile label={"Sitecore"} icon={"xp-cb-check"}></ActionTile>&nbsp;
<ActionTile label={"Sitefinity"} icon={"xp-cb-check"}></ActionTile>&nbsp;
<ActionTile label={"Umbraco"} icon={"xp-cb-check"}></ActionTile>
</div>

<UploadTile
acceptFiles=".json"
firstLineLabel="Drag&Drop .json here"
secondLineLabel="or"
buttonLabel="Browse"
size={UploadTileSize.Full}
onUpload={([f]) => {
if (f instanceof File) {
setFile(f);
setCurrentFile({ current: 0, total: f.size });
}
}}
/>


{file !== null && (
<p style={{ color: 'var(--color-text-default-on-light)' }}>
File Selected: {file.name}
</p>
)}



{currentFile.total > 0 && (
<div>
<Headline size={HeadlineSize.S} spacingBottom={Spacing.M}>
Upload Progress
</Headline>
<ProgressBar
completed={Math.floor(
(currentFile.current / currentFile.total) * 100,
)}
/>
</div>
)}

<Button
label="Import data"
size={ButtonSize.S}
onClick={onUpload}
/>

<Divider orientation={DividerOrientation.Horizontal} />


<Shelf>
{stats && <Box spacing={Spacing.M}>
<Headline size={HeadlineSize.S}>Imported objects</Headline>
<pre style={{ color: 'var(--color-text-default-on-light)' }}>
{JSON.stringify(stats, null, 4)}
</pre>
</Box>}
{state.length > 0 && (<Box spacing={Spacing.M}>
<Headline size={HeadlineSize.S}>Import Log</Headline>
<pre style={{ color: 'var(--color-text-default-on-light)' }}>
{[...state].reverse().join('\r\n')}
</pre>
</Box>)}
</Shelf>

</Stack>
</Column>
</Row>
</Box>
);

return newInterface;
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Net.Sockets;
using System.Collections.Concurrent;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using CMS.Core;
Expand Down Expand Up @@ -63,6 +64,15 @@ async Task SendProgressReport(string message)
await webSocket.SendAsync(new ArraySegment<byte>(payload, 0, payload.Length), WebSocketMessageType.Text, true, CancellationToken.None);
}
}

async Task SendStats(IDictionary<string, int> stats)
{
if (webSocket.State == WebSocketState.Open)
{
byte[] payload = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { type = "stats", payload = System.Text.Json.JsonSerializer.Serialize(stats) }));
await webSocket.SendAsync(new ArraySegment<byte>(payload, 0, payload.Length), WebSocketMessageType.Text, true, CancellationToken.None);
}
}

async Task SendTooFastReport()
{
Expand Down Expand Up @@ -105,10 +115,13 @@ async Task SendConfirmHeader()
var data = importService.FromJsonStream(ms);
var observer = new ImportStateObserver();

var stats = new ConcurrentDictionary<string, int>();

observer = await importService.StartImportAsync(data!, new ImporterContext("Boilerplate", "en-US"), observer);
observer.ImportedInfo += async info =>
{
await SendProgressReport($"Processed: {info.TypeInfo.ObjectType} {info.GetValue(info.TypeInfo.GUIDColumn)}");
stats.AddOrUpdate(info.TypeInfo.ObjectType, s => 1, (s, i) => i + 1);
};
observer.ValidationError += async (model, id, validationResults) =>
{
Expand All @@ -121,7 +134,8 @@ async Task SendConfirmHeader()
};

await observer.ImportCompletedTask;


await SendStats(stats);
await SendProgressReport($"...finished");
}
finally
Expand Down
Loading
Loading