Hermann  Frami

Hermann Frami

1679926923

Zksync-web-era-docs: ZkSync Era Documentation

zkSync Era Documentation


zkEVM

zkEVM is a virtual machine that executes smart contracts in a way that is compatible with zero-knowledge-proof computation. Our zkEVM keeps EVM semantics, but is also ZK-friendly and takes on traditional CPU architectures.

Constantly updated, zkSync Era Docs offers the most complete knowledge about the upcoming zkSync Era. zkSync Era release has built-in EVM compatibility which makes it a single key to release EVM-compatible ZK rollup. We call it zkEVM: long-awaited way to preserve the battle-tested code and knowledge gained after years of working with Solidity scaling it with Layer 2.

Build and setup

Initial setup

The Frontend team chose the yarn@berry packager, so don't forget to install node version LTS@14 after configuring yarn

# configure yarn version: berry or specifically 3.1.1.
$ yarn set version berry

Main scripts

# install dependencies
$ yarn add

# serve with hot reload at localhost:8080
$ yarn docs:dev
# static generation to dist
$ yarn docs:build

Development

CI pipeline will check that the files are formatted according to prettier, markdownlint founds no issues in document and spelling is correct. Also, there should be no dead links.

You can check it locally as follows:

# check dead links
$ yarn lint:dead
# check spelling
$ yarn lint:spell
# check with markdownlint
$ yarn lint:mdl
# check with prettier
$ yarn lint:fmt
# fix with markdownlint
$ yarn fix:mdl
# fix with prettier
$ yarn fix:fmt
# run all checks
$ yarn ci
# run all fixes
$ yarn ci:fix
# build for production
$ yarn ci:build

If lint:spell doesn't recognize a word but you're sure that it's correct, consider adding it to the cspell-zksync.txt.

Contributions

Adding new tutorials

To add a new tutorial:

  • Fork the repository and create a new branch locally to add your changes.
  • Add the tutorial markdown file inside the docs/dev/tutorials folder.
  • Give the file with a SEO-friendly name as it'll be part of the URL.
  • In the docs/.vuepress/config.js file, add the tutorial inside this block:
{
title: "Tutorials",
path: "/dev/tutorials",
collapsable: false,
children: [
  "/dev/tutorials/cross-chain-tutorial.md",
  "/dev/tutorials/custom-aa-tutorial.md",
  "/dev/tutorials/custom-paymaster-tutorial.md"],
  // ADD YOUR FILE HERE
},
  • If your tutorial contains images, make sure to compress them using https://squoosh.app/ before adding them to the docs/assets/images folder.
  • Finally, create a PR.

Deployment

main branch is automatically deployed to https://console.firebase.google.com/u/0/project/aqwzx-zksync-v2-docs

Deploying altogether

will do:

  • install node modules;
  • prepare, test and build documentation;
  • afterwards all contained into the dist folder will be deployed in form of the static website
yarn zk-ci-prepare
yarn firebase deploy

Extra documentation

cSpell

Configuration in .cSpell.json:

  • version — version of the setting file, always 0.1
  • language — language - current active spelling language
  • words[] — words - list of words to be always considered correct
  • dictionaries[]
"dictionaryDefinitions": [
  {
    "name": "zksync", "path": "./cspell-zksync.txt"
  }
]

Download Details:

Author: Matter-labs
Source Code: https://github.com/matter-labs/zksync-web-era-docs 
License: MIT, Apache-2.0 licenses found

#javascript #frontend #core #zksync #docs 

Zksync-web-era-docs: ZkSync Era Documentation

Интеграция Blazor WA в существующее веб-приложение ASP.NET Core

Узнайте, как интегрировать проект Blazor WebAssembly в существующее веб-приложение ASP.NET Core, используя знакомые файлы кода C# и синтаксис Razor для реализации пользовательского веб-интерфейса.

Когда вы думаете о разработке пользовательского интерфейса для интерактивной сети, ваши мысли сразу же могут обратиться к JavaScript. Следовательно, для многих разработчиков C# это означало бы изучение всех тонкостей совершенно нового языка программирования.

Тем не менее, это не должно быть так! Blazor WASM (он же Blazor WebAssembly) позволяет разработчикам реализовывать пользовательские веб-интерфейсы, используя знакомые файлы кода C# и синтаксис Razor. Затем эти исходные файлы компилируются в байт-код для загрузки для запуска поверх среды выполнения WebAssembly в клиентском браузере, что обеспечивает повышение производительности среды выполнения за счет компиляции.

Отображается блок-схема, показывающая, что компоненты Razor, написанные на .NET, компилируются в байтовый код и запускаются в среде выполнения WebAssembly, которая, в свою очередь, взаимодействует с DOM веб-страницы.
Источник изображения

Blazor WebAssembly — это распространенное решение для одностраничных веб-приложений (или SPA), которое соответствует типичному многоуровневому шаблону разработки веб-приложений. В многоуровневом дизайне пользовательский интерфейс реализуется отдельно от бизнес-логики и доступа к данным, причем последние два обычно развертываются как служба API.

Начало работы с Blazor WASM в новых проектах с нуля упрощается, поскольку Visual Studio включает шаблоны для проектов Blazor WebAssembly, но что произойдет, если вы захотите интегрировать Blazor WASM с существующим веб-приложением ASP.NET Core? Как мы постепенно переносим и модернизируем существующие веб-приложения, чтобы использовать возможности Blazor WASM?

В этой статье вы узнаете, как интегрировать проект Blazor WebAssembly в существующее веб-приложение ASP.NET Core. Кроме того, вы узнаете, как интегрировать пользовательский интерфейс Progress Telerik для Blazor , который предоставляет готовые к использованию компоненты для создания привлекательных веб-интерфейсов пользователя с помощью Blazor WebAssembly.

Шаг 1. Настройте веб-приложение и проекты Blazor WASM

В этой демонстрации мы создадим два проекта. Первый проект — это основное веб-приложение ASP.NET, представляющее наше существующее веб-приложение. Второй проект — это проект Blazor WebAssembly, в котором мы создадим новые компоненты Blazor для интеграции в наше существующее веб-приложение.

  • Откройте Visual Studio 2022 и выберите Create a new project.

Откроется диалоговое окно Visual Studio 2022 с выделенным параметром Создать новый проект.

  1. В диалоговом окне Создать новый проект найдите и выберите ASP.NET Core Web App. Нажмите Далее .

Диалоговое окно «Создать новый проект» отображается с ASP.NET Core Web App, введенным в строку поиска и выбранным из списка результатов.  Кнопка «Далее» выбрана.

  1. В диалоговом окне «Настроить новый проект» назовите проект Existing.Web, при необходимости выберите расположение в файловой системе и нажмите «Далее» .

Откроется диалоговое окно «Настроить новый проект», в котором имя проекта установлено на Existing.Web, а кнопка «Далее» нажата.

  • В диалоговом окне «Дополнительная информация» выберите .NET 7.0 (Standard Term Support) для платформы , затем нажмите «Создать» .

Откроется диалоговое окно «Дополнительная информация», в котором в качестве платформы выбрана платформа .NET 7.0, а кнопка «Создать» выделена.

Примечание . Рекомендации в этой статье также применимы к проектам .NET 6.0. .NET 5 больше не поддерживается, поэтому рекомендуется сначала обновить существующие приложения как минимум до .NET 6.0.

  1. На панели обозревателя решений щелкните решение правой кнопкой мыши и разверните меню "Добавить" . Выберите Новый проект .

Отображается контекстное меню решения с развернутым пунктом меню «Добавить» и выбранным пунктом «Новый проект».

  • In the Add new project dialog, search for Blazor WebAssembly and select Blazor WebAssembly App from the search results. Press Next.

Откроется диалоговое окно «Добавить новый проект» с Blazor WebAssembly, введенным в поле поиска.  Элемент приложения Blazor WebAssembly выбирается из результатов поиска, и кнопка «Далее» выделена.

  • В диалоговом окне «Настроить новый проект » назовите проект BlazorAppи нажмите «Далее» .

Откроется диалоговое окно «Настройка нового проекта», в котором BlazorApp введет имя проекта.  Кнопка «Далее» выделена.

  • В диалоговом окне «Дополнительная информация» выберите .NET 7.0 (Standard Term Support) для платформы , затем нажмите «Создать» .

Откроется диалоговое окно «Дополнительная информация», в котором в качестве платформы выбрана платформа .NET 7.0, а кнопка «Создать» выделена.

Примечание . Рекомендации в этой статье также применимы к проектам .NET 6.0. .NET 5 больше не поддерживается, поэтому рекомендуется сначала обновить существующие приложения как минимум до .NET 6.0.

Шаг 2. Подготовьте приложение Blazor WebAssembly

Шаблон приложения Blazor WebAssembly создает одностраничное приложение (SPA). Таким образом, когда приложение Blazor запускается, оно ищет элемент HTML с идентификатором , appчтобы содержать и отображать работающее приложение. Эту функцию необходимо отключить, так как в этом случае мы хотим, чтобы существующее веб-приложение обеспечивало общий пользовательский интерфейс, позволяя нам включать компоненты Blazor, разработанные в проекте Blazor WASM.

В панели обозревателя решений найдите проект BlazorApp и откройте файл Program.cs .

В файле Program.cs закомментируйте следующую строку кода и сохраните файл:

builder.RootComponents.Add<App>("#app");

Отображается Visual Studio 2022 с развернутым проектом BlazorApp и выбранным файлом кода Program.cs.  В окне редактора кода указанная выше строка кода закомментирована.

Шаг 3. Подготовьте существующий проект веб-приложения

Чтобы существующее веб-приложение ASP.NET Core могло использовать компоненты Blazor Web Assembly, нам потребуется ссылка на проект, пакет NuGet и некоторый код инфраструктуры.

  • В панели обозревателя решений найдите проект Existing.Web , затем щелкните правой кнопкой мыши и разверните элемент Добавить . Выберите ссылку на проект .

Отображается контекстное меню для проекта Existing.Web с развернутым элементом Добавить и выбранным элементом Ссылка на проект.

  • In the Reference Manager dialog, check the box next to BlazorApp and press OK.

Откроется диалоговое окно «Диспетчер ссылок» с установленным флажком рядом с BlazorApp и выделенной кнопкой «ОК».

  1. Щелкните правой кнопкой мыши проект Existing.Web еще раз и выберите Manage NuGet Packages .

Панель Solution Explorer отображается с развернутым контекстным меню и выделенным элементом Manage NuGet Packages.

  • На экране NuGet выберите вкладку «Обзор» и введите Microsoft.AspNetCore.Components.WebAssembly.Serverв поле поиска. Выберите Microsoft.AspNetCore.Components.WebAssembly.Server из результатов поиска и нажмите «Установить» . Примите любые лицензии.

Откроется экран NuGet с выбранной вкладкой Обзор и Microsoft.AspNetCore.Components.WebAssembly.Server, введенным в поле поиска.  В результатах поиска выбран элемент Microsoft.AspNetCore.Components.WebAssembly.Server, и кнопка «Установить» выделена.

  • В панели обозревателя решений найдите проект Existing.Web и откройте файл Program.cs .

Отображается панель обозревателя решений с развернутым проектом Existing.Web и выбранным файлом Program.cs.

  • Добавьте условие else в блок кода if (!app.Environment.IsDevelopment()) со следующим кодом:
else
{
    app.UseWebAssemblyDebugging();
}

Часть окна Program.cs отображается с выделенным кодом, упомянутым выше.

  • Непосредственно под блоком кода if (!app.Environment.IsDevelopment()) добавьте следующий код и сохраните файл:
app.UseBlazorFrameworkFiles();
app.MapFallbackToFile("index.html");

Часть окна Program.cs отображается с выделенным кодом, упомянутым выше.

  • В проекте Existing.Web разверните папку Pages . Разверните общую папку, найдите и откройте файл _Layout.cshtml .

На панели обозревателя решений отображается развернутый проект Existing.Web вместе с папками Pages и Shared.  Файл _Layout.cshtml выделен.

  • Найдите ссылки на сценарии ближе к нижней части страницы. Добавьте следующую ссылку на скрипт и сохраните файл:
<script src="_framework/blazor.webassembly.js"></script>

Часть окна кода для _Layout.cshtml отображается с выделенным вышеупомянутым кодом.

Примечание . Добавление сценария в _Layout.cs позволит вам добавлять компоненты Blazor в любое представление. Кроме того, вы можете включить сценарий только в каждое конкретное представление, в котором необходимы компоненты Blazor.

Шаг 4. Добавьте компонент Blazor в представление в существующем веб-приложении

Проект приложения Blazor WebAssembly поставляется с компонентом счетчика в виде шаблона. Теперь мы добавим этот компонент в представление в нашем существующем веб-приложении ASP.NET Core (Existing.Web).

  • В обозревателе решений найдите проект Existing.Web и разверните папку Pages . Откройте файл Index.cshtml . Это представление по умолчанию, которое отображается при запуске приложения Existing.Web.

На панели обозревателя решений отображается развернутый проект Existing.Web вместе с папкой Pages.  Файл Index.cshtml выделен.

  • Непосредственно под аннотацией @page добавьте следующий оператор using, чтобы предоставить нам доступ к компоненту Counter :
@using BlazorApp.Pages

Часть окна кода для Index.cshtml отображается с выделенным выше кодом.

  • Под элементом div добавьте следующий код, чтобы включить компонент Counter в представление:
<component type="typeof(Counter)" render-mode="WebAssemblyPrerendered" />

Часть окна кода для Index.cshtml отображается с выделенной выше разметкой.

Шаг 5. Запустите существующее веб-приложение

Запустите существующий проект веб-приложения и обратите внимание, как вы можете взаимодействовать с компонентом Counter из проекта Blazor WebAssembly.

  • В обозревателе решений щелкните правой кнопкой мыши проект Existing.Web и выберите пункт Установить как запускаемый проект .

Обозреватель решений отображается с развернутым контекстным меню проекта Existing.Web.  Элемент «Установить как запускаемый проект» выделен.

  • Щелкните правой кнопкой мыши проект Existing.Web еще раз и разверните элемент Debug . Выберите «Запустить без отладки» . Это запустит существующий проект веб-приложения.

Отображается контекстное меню проекта Existing.Web с развернутым элементом «Отладка» и выбранным параметром «Начать без отладки».

Примечание . В качестве альтернативы, поскольку мы установили стартовый проект, вы также можете запустить экземпляр (с отладкой или без нее) из меню панели инструментов.

  • В окне браузера несколько раз нажмите кнопку Click me компонента Counter и обратите внимание на увеличение счетчика.

Компонент счетчика отображается в существующем веб-приложении.  Кнопка Click me выбрана, и сумма счетчика выделена.

Шаг 6. Включите пользовательский интерфейс Telerik для Blazor

Теперь, когда мы успешно использовали компонент Blazor WebAssembly в нашем существующем веб-приложении ASP.NET Core, мы можем воспользоваться преимуществами компонентов, предоставляемых пользовательским интерфейсом Progress Telerik для Blazor. Эта библиотека компонентов совместима с проектами Blazor WebAssembly и Blazor Server.

Примечание . Проект сервера в нашем случае — это проект Existing.Web , и мы уже добавили код app.UseStaticFiles() , поэтому этот шаг можно пропустить (шаг 4, пункт № 2 в статье по ссылке).

  • Теперь мы добавим компонент пользовательского интерфейса Telerik для Blazor к существующему компоненту Counter . В проекте BlazorApp найдите и откройте файл Pages/Counter.razor .
  • Замените код в файле следующим и сохраните файл:
@page "/counter"

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

<br/>

<hr />

<TelerikButton OnClick="@SayHelloHandler" ThemeColor="primary">Say Hello</TelerikButton>

<br />

@helloString


@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }

    MarkupString helloString;

    void SayHelloHandler()
    {
        string msg = string.Format("Hello from <strong>Telerik Blazor</strong> at {0}.<br /> Now you can use C# to write front-end!", DateTime.Now);
        helloString = new MarkupString(msg);
    }
}
  • Запустите приложение еще раз и нажмите кнопку «Скажи привет» , чтобы использовать компонент TelerikButton!

Виджет Counter отображается с компонентом кнопки Telerik.  В сообщении отображается «Привет от Telerik Blazor» с отметкой времени и «Теперь вы можете использовать C# для написания внешнего интерфейса!»

Заключение

В этой статье мы интегрировали компоненты Blazor в существующее веб-приложение ASP.NET Core. Это открывает менее разрушительный путь миграции для переноса существующих проектов в Blazor WebAssembly.

Оригинальный источник статьи: https://www.telerik.com/

#blazor #webassembly #aspdotnet #core 

Интеграция Blazor WA в существующее веб-приложение ASP.NET Core
木村  直子

木村 直子

1679065260

将 Blazor WebAssembly 集成到现有的 ASP.NET Core Web 应用程序中

了解如何将 Blazor WebAssembly 项目集成到现有的 ASP.NET Core Web 应用程序中,使用熟悉的 C# 代码文件和 Razor 语法来实现您的 Web UI。

当您考虑为交互式 Web 开发用户界面时,您的想法可能会立即转向 JavaScript。因此,对于许多 C# 开发人员来说,这意味着学习一门全新编程语言的来龙去脉。

但是,情况并非如此!Blazor WASM(又名 Blazor WebAssembly)允许开发人员使用熟悉的 C# 代码文件和 Razor 语法实现 Web 用户界面。然后将这些源文件编译成字节码以供下载以在客户端浏览器中的 WebAssembly 运行时运行,由于编译而产生改进的运行时性能。

显示的框图指示用 .NET 编写的 Razor 组件被编译为字节代码并在 WebAssembly 运行时上运行,而 WebAssembly 运行时又与网页的 DOM 交互。
图片来源

Blazor WebAssembly 是适用于单页 Web 应用程序(或 SPA)的流行解决方案,它遵循 Web 应用程序开发的典型 n 层模式。在 n 层设计中,用户界面与业务逻辑和数据访问分开实现,后两者通常部署为 API 服务。

由于 Visual Studio 包含 Blazor WebAssembly 项目的模板,新项目中的 Blazor WASM 入门得到了简化,但是当您想要将 Blazor WASM 与现有的 ASP.NET Core Web 应用程序集成时会发生什么?我们如何缓慢迁移和现代化现有 Web 应用程序以利用 Blazor WASM 的强大功能?

在本文中,您将了解如何将 Blazor WebAssembly 项目集成到现有的 ASP.NET Core Web 应用程序中。此外,您将学习如何为 Blazor 合并 Progress Telerik UI,它提供随时可用的组件,用于使用 Blazor WebAssembly 构建引人注目的 Web 用户界面体验。

步骤 1. 设置 Web 应用程序和 Blazor WASM 项目

在此演示中,我们将创建两个项目。第一个项目是一个 ASP.NET Core Web 应用程序,代表我们现有的 Web 应用程序。第二个项目是 Blazor WebAssembly 项目,我们将在其中构建新的 Blazor 组件以集成到我们现有的 Web 应用程序中。

  • 打开Visual Studio 2022并选择Create a new project.

Visual Studio 2022 对话框显示,其中突出显示了创建新项目的选项。

  1. “创建新项目”对话框中,搜索并选择ASP.NET Core Web App。按下一步

显示“创建新项目”对话框,其中在搜索栏中输入 ASP.NET Core Web 应用程序并从结果列表中选择。 下一步按钮被选中。

  1. Configure your new project对话框中,为 project 命名Existing.Web,可选择文件系统位置,然后按Next

Configure your new project 对话框显示,项目名称设置为 Existing.Web 并选择下一步按钮。

  • 附加信息对话框中,为框架选择.NET 7.0(标准术语支持),然后按创建

Additional information 对话框显示,其中选择了 .NET 7.0 作为框架,Create 按钮突出显示。

注意:本文中的指南也适用于 .NET 6.0 项目。.NET 5 不受支持,因此建议先将现有应用程序至少升级到 .NET 6.0。

  1. “解决方案资源管理器”面板中,右键单击解决方案并展开“添加”菜单。选择新建项目

解决方案的上下文菜单显示,其中展开了“添加”菜单项并选中了“新建项目”项。

  • “添加新项目”对话框中,搜索Blazor WebAssembly并从搜索结果中选择“Blazor WebAssembly 应用程序” 。下一步

显示添加新项目对话框,其中在搜索框中输入了 Blazor WebAssembly。 从搜索结果中选择了 Blazor WebAssembly App 项,并突出显示了 Next 按钮。

  • Configure your new project对话框中,为项目命名BlazorApp并按Next

配置新项目对话框随即显示,其中输入了 BlazorApp 作为项目名称。 “下一步”按钮突出显示。

  • 附加信息对话框中,为框架选择.NET 7.0(标准术语支持),然后按创建

Additional information 对话框显示,其中选择了 .NET 7.0 作为框架,Create 按钮突出显示。

注意:本文中的指南也适用于 .NET 6.0 项目。.NET 5 不受支持,因此建议先将现有应用程序至少升级到 .NET 6.0。

步骤 2. 准备 Blazor WebAssembly 应用程序

Blazor WebAssembly 应用程序模板生成单页应用程序 (SPA)。因此,当 Blazor 应用程序运行时,它会查找 ID 为 的 HTML 元素app来包含和显示正在运行的应用程序。需要禁用此功能,因为在这种情况下,我们希望现有的 Web 应用程序提供整体用户体验,同时允许我们合并在 Blazor WASM 项目中开发的 Blazor 组件。

“解决方案资源管理器”面板中,找到BlazorApp项目并打开Program.cs文件。

Program.cs文件中,注释掉以下代码行并保存文件:

builder.RootComponents.Add<App>("#app");

Visual Studio 2022 显示,其中展开了 BlazorApp 项目并选择了 Program.cs 代码文件。 在代码编辑器窗口中,上面提到的代码行被注释掉了。

步骤 3. 准备现有的 Web 应用程序项目

为了让现有的 ASP.NET Core Web 应用程序能够使用 Blazor Web Assembly 组件,我们需要一个项目引用、NuGet 包和一些基础结构代码。

  • Solution Explorer面板中,找到Existing.Web项目,然后右键单击并展开Add项。选择项目参考

Existing.Web 项目的上下文菜单显示,其中展开了 Add 项并选中了 Project reference 项。

  • Reference Manager对话框中,选中BlazorApp旁边的框,然后按OK

Reference Manager 对话框显示,BlazorApp 旁边有一个复选框,并且突出显示了 OK 按钮。

  1. 再次右键单击Existing.Web项目并选择Manage NuGet Packages

解决方案资源管理器面板显示,其中展开了上下文菜单并突出显示了管理 NuGet 包项。

  • NuGet屏幕上,选择浏览选项卡并输入Microsoft.AspNetCore.Components.WebAssembly.Server搜索框。从搜索结果中选择Microsoft.AspNetCore.Components.WebAssembly.Server并按Install。接受任何许可。

NuGet 屏幕显示,其中选择了浏览选项卡,并在搜索框中输入了 Microsoft.AspNetCore.Components.WebAssembly.Server。 从搜索结果中选择了 Microsoft.AspNetCore.Components.WebAssembly.Server 项,并突出显示了安装按钮。

  • “解决方案资源管理器”面板中,找到Existing.Web项目并打开Program.cs文件。

解决方案资源管理器面板显示,其中展开了 Existing.Web 项目并选中了 Program.cs 文件。

  • 使用以下代码向if (!app.Environment.IsDevelopment())代码块添加else条件:
else
{
    app.UseWebAssemblyDebugging();
}

Program.cs 窗口的一部分显示,上面提到的代码突出显示。

  • 在if (!app.Environment.IsDevelopment())代码块的正下方,添加以下代码并保存文件:
app.UseBlazorFrameworkFiles();
app.MapFallbackToFile("index.html");

Program.cs 窗口的一部分显示,上面提到的代码突出显示。

  • Existing.Web项目中,展开Pages文件夹。展开共享文件夹,找到并打开_Layout.cshtml文件。

Solution Explorer 面板显示 Existing.Web 项目以及 Pages 和 Shared 文件夹。 _Layout.cshtml 文件突出显示。

  • 找到靠近页面底部的脚本引用。添加以下脚本引用,并保存文件:
<script src="_framework/blazor.webassembly.js"></script>

_Layout.cshtml 的代码窗口的一部分显示上述代码突出显示。

注意:将脚本添加到_Layout.cs将允许您将 Blazor 组件添加到任何视图。或者,您可以选择仅在需要 Blazor 组件的每个特定视图中包含脚本。

步骤 4。将 Blazor 组件添加到现有 Web 应用程序中的视图

Blazor WebAssembly 应用程序项目附带一个计数器组件脚手架。我们现在将此组件添加到现有 ASP.NET Core Web 应用程序 (Existing.Web) 中的视图。

  • Solution Explorer中,找到Existing.Web项目并展开Pages文件夹。打开索引.cshtml文件。这是运行 Existing.Web 应用程序时显示的默认视图。

Solution Explorer 面板显示 Existing.Web 项目以及 Pages 文件夹。 Index.cshtml 文件突出显示。

  • 在@page注释的正下方,添加以下 using 语句以允许我们访问Counter组件:
@using BlazorApp.Pages

Index.cshtml 的代码窗口的一部分显示,上面的代码突出显示。

  • div元素下,添加以下代码以在视图中包含Counter组件:
<component type="typeof(Counter)" render-mode="WebAssemblyPrerendered" />

Index.cshtml 的代码窗口的一部分显示,上面的标记突出显示。

第 5 步。运行现有的 Web 应用程序

运行现有的 Web 应用程序项目并注意如何与Blazor WebAssembly 项目中的计数器组件进行交互。

  • Solution Explorer中,右键单击Existing.Web项目并选择Set as Startup Project项。

解决方案资源管理器显示,上下文菜单在 Existing.Web 项目上展开。 突出显示设置为启动项目项。

  • 再次右键单击Existing.Web项目并展开Debug项。选择开始而不调试。这将运行现有的 Web 应用程序项目。

Existing.Web 项目的上下文菜单显示,其中展开了 Debug 项并选中了 Start Without Debugging 选项。

注意:或者,由于我们设置了启动项目,您也可以从工具栏菜单启动一个实例(有或没有调试)。

  • 在浏览器窗口中,多次按下 Counter 组件的Click me按钮,注意计数器是如何增加的。

Counter 组件显示在现有的 Web 应用程序中。 Click me 按钮被选中,计数器总数被突出显示。

步骤 6。为 Blazor 合并 Telerik UI

现在我们已经在现有的 ASP.NET Core Web 应用程序中成功使用了 Blazor WebAssembly 组件,我们可以利用 Progress Telerik UI 为 Blazor 提供的组件。此组件库与 Blazor WebAssembly 和 Blazor Server 项目兼容。

注意:我们案例中的服务器项目是Existing.Web项目,并且我们已经添加了app.UseStaticFiles()代码,因此可以跳过此步骤(链接文章中的第 4 步,第 2 项)。

  • 现在,我们将为 Blazor 组件添加一个 Telerik UI 到现有的Counter组件。在BlazorApp项目中,找到并打开Pages/Counter.razor文件。
  • 用以下内容替换文件中的代码并保存文件:
@page "/counter"

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

<br/>

<hr />

<TelerikButton OnClick="@SayHelloHandler" ThemeColor="primary">Say Hello</TelerikButton>

<br />

@helloString


@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }

    MarkupString helloString;

    void SayHelloHandler()
    {
        string msg = string.Format("Hello from <strong>Telerik Blazor</strong> at {0}.<br /> Now you can use C# to write front-end!", DateTime.Now);
        helloString = new MarkupString(msg);
    }
}
  • 再次运行应用程序,然后按下Say Hello按钮以使用 TelerikButton 组件!

计数器小部件与 Telerik 按钮组件一起显示。 该消息显示带有时间戳的来自 Telerik Blazor 的 Hello,现在您可以使用 C# 编写前端!

结论

在本文中,我们将 Blazor 组件集成到现有的 ASP.NET Core Web 应用程序中。这为将现有项目移动到 Blazor WebAssembly 开辟了一条破坏性较小的迁移路径。

文章原文出处:https: //www.telerik.com/

#blazor #webassembly #aspdotnet #core 

将 Blazor WebAssembly 集成到现有的 ASP.NET Core Web 应用程序中
Hermann  Frami

Hermann Frami

1679061429

Integrate Blazor WebAssembly into an Existing ASP.NET Core Web App

See how to integrate a Blazor WebAssembly project into an existing ASP.NET Core web application, using familiar C# code files and Razor syntax to implement your web UI.

When you think of developing a user interface for the interactive web, your thoughts may immediately turn to JavaScript. Consequently, for many C# developers, this would mean learning the ins and outs of an entirely new programming language.

However, this doesn’t have to be the case! Blazor WASM (aka Blazor WebAssembly) allows developers to implement web user interfaces using familiar C# code files and Razor syntax. These source files are then compiled into byte code for download to run atop the WebAssembly runtime in the client browser, yielding improved runtime performance due to the compilation.

A block diagram displays indicating Razor components written in .NET are compiled down to byte code and run on the WebAssembly runtime which in turn interacts with the DOM of the web page.
Image source

Blazor WebAssembly is a prevalent solution for single-page web applications (or SPAs) that adheres to the typical n-layer pattern of web application development. In the n-layer design, the user interface is implemented separately from the business logic and data access, with the latter two typically deployed as an API service.

Getting started with Blazor WASM in new greenfield projects is simplified as Visual Studio includes templates for Blazor WebAssembly projects, but what happens when you want to integrate Blazor WASM with an existing ASP.NET Core web application? How do we slowly migrate and modernize existing web applications to harness the power of Blazor WASM?

In this article, you will learn how to integrate a Blazor WebAssembly project into an existing ASP.NET Core web application. Furthermore, you’ll learn how to incorporate Progress Telerik UI for Blazor, which provides ready-to-use components for building compelling web user interface experiences with Blazor WebAssembly.

Step 1. Set up the Web Application and Blazor WASM Projects

In this demonstration, we’ll create two projects. The first project is an ASP.NET Core Web Application representing our existing web application. The second project is a Blazor WebAssembly project where we’ll build new Blazor components to integrate into our existing web application.

  • Open Visual Studio 2022 and choose to Create a new project.

The Visual Studio 2022 dialog displays with the option to Create a new project highlighted.

  1. On the Create a new project dialog, search for and select ASP.NET Core Web App. Press Next.

The Create a new project dialog displays with ASP.NET Core Web App entered in the search bar and selected from the list of results. The Next button is selected.

  1. On the Configure your new project dialog, name the project Existing.Web, optionally choose the file system location and press Next.

The Configure your new project dialog displays with the project name set to Existing.Web and the next button is selected.

  • On the Additional information dialog, select .NET 7.0 (Standard Term Support) for the Framework then press Create.

The Additional information dialog displays with .NET 7.0 selected as the framework and the Create button is highlighted.

Note: The guidance in this article will also work with .NET 6.0 projects. .NET 5 is out of support, so it is recommended to upgrade existing applications to at least .NET 6.0 first.

  1. In the Solution Explorer panel, right-click the solution and expand the Add menu. Select New Project.

The context menu of the solution displays with the Add menu item expanded and the New Project item selected.

  • In the Add new project dialog, search for Blazor WebAssembly and select Blazor WebAssembly App from the search results. Press Next.

The Add a new project dialog displays with Blazor WebAssembly entered in the search box. The Blazor WebAssembly App item is selected from the search results and the Next button is highlighted.

  • In the Configure your new project dialog, name the project BlazorApp and press Next.

The Configure your new project dialog displays with BlazorApp entered for the project name. The Next button is highlighted.

  • On the Additional information dialog, select .NET 7.0 (Standard Term Support) for the Framework then press Create.

The Additional information dialog displays with .NET 7.0 selected as the framework and the Create button is highlighted.

Note: The guidance in this article will also work with .NET 6.0 projects. .NET 5 is out of support, so it is recommended to upgrade existing applications to at least .NET 6.0 first.

Step 2. Prepare the Blazor WebAssembly Application

The Blazor WebAssembly App template generates a single-page application (SPA). Therefore, when the Blazor application runs, it looks for an HTML element with the ID of app to contain and display the running application. This functionality needs to be disabled as, in this case, we want the existing web application to provide the overall user experience while allowing us to incorporate Blazor components developed in the Blazor WASM project.

In the Solution Explorer panel, locate the BlazorApp project and open the Program.cs file.

In the Program.cs file, comment out the following line of code and save the file:

builder.RootComponents.Add<App>("#app");

Visual Studio 2022 displays with the BlazorApp project expanded and the Program.cs code file selected. In the code editor window the line of code mentioned above is commented out.

Step 3. Prepare the Existing Web Application Project

In order for the existing ASP.NET Core web application to make use of the Blazor Web Assembly components, we will need a project reference, NuGet package and some infrastructure code.

  • In the Solution Explorer panel, locate the Existing.Web project then right-click and expand the Add item. Select Project Reference.

The context menu for the Existing.Web project displays with the Add item expanded and the Project reference item selected.

  • In the Reference Manager dialog, check the box next to BlazorApp and press OK.

The Reference Manager dialog displays with a checked box next to BlazorApp and the OK button is highlighted.

  1. Right-click the Existing.Web project once more and select Manage NuGet Packages.

The Solution Explorer panel displays with the context menu expanded and the Manage NuGet Packages item highlighted.

  • On the NuGet screen, select the Browse tab and enter Microsoft.AspNetCore.Components.WebAssembly.Server into the search box. Select Microsoft.AspNetCore.Components.WebAssembly.Server from the search results and press Install. Accept any Licenses.

The NuGet screen displays with the Browse tab selected and Microsoft.AspNetCore.Components.WebAssembly.Server entered in the search box. The Microsoft.AspNetCore.Components.WebAssembly.Server item is selected from the search results and the Install button is highlighted.

  • In the Solution Explorer panel, locate the Existing.Web project and open the Program.cs file.

The Solution Explorer panel displays with the Existing.Web project expanded and the Program.cs file selected.

  • Add an else condition to the if (!app.Environment.IsDevelopment()) code block with the following code:
else
{
    app.UseWebAssemblyDebugging();
}

A portion of the Program.cs window displays with the code mentioned above highlighted.

  • Directly below the if (!app.Environment.IsDevelopment()) code block, add the following code and save the file:
app.UseBlazorFrameworkFiles();
app.MapFallbackToFile("index.html");

A portion of the Program.cs window displays with the code mentioned above highlighted.

  • In the Existing.Web project, expand the Pages folder. Expand the Shared folder, locate and open the _Layout.cshtml file.

The Solution Explorer panel displays with the Existing.Web project expanded along with the Pages and Shared folders. The _Layout.cshtml file is highlighted.

  • Locate the script references close to the bottom of the page. Add the following script reference, and save the file:
<script src="_framework/blazor.webassembly.js"></script>

A portion of the code window for _Layout.cshtml displays with the aforementioned code highlighted.

Note: Adding the script to _Layout.cs will allow you to add Blazor components to any view. Alternatively, you can choose to only include the script on each specific view that Blazor components are needed.

Step 4. Add a Blazor Component to a View in the Existing Web Application

The Blazor WebAssembly App project comes with a Counter component scaffolded. We’ll now add this component to a view in our existing ASP.NET Core Web Application (Existing.Web).

  • In Solution Explorer, locate the Existing.Web project and expand the Pages folder. Open the Index.cshtml file. This is the default view that displays when the Existing.Web application is run.

The Solution Explorer panel displays with the Existing.Web project expanded along with the Pages folder. The Index.cshtml file is highlighted.

  • Directly beneath the @page annotation, add the following using statement to give us access to the Counter component:
@using BlazorApp.Pages

A portion of the code window for Index.cshtml displays with the above code highlighted.

  • Beneath the div element, add the following code to include the Counter component in the view:
<component type="typeof(Counter)" render-mode="WebAssemblyPrerendered" />

A portion of the code window for Index.cshtml displays with the above markup highlighted.

Step 5. Run the Existing Web Application

Run the existing web application project and notice how you can interact with the Counter component from the Blazor WebAssembly project.

  • In Solution Explorer, right-click the Existing.Web project and select the Set as Startup Project item.

The Solution Explorer displays with the context menu expanded on the Existing.Web project. The Set as Startup Project item is highlighted.

  • Right-click the Existing.Web project once more and expand the Debug item. Select Start Without Debugging. This will run the existing web application project.

The context menu of the Existing.Web project displays with the Debug item expanded and the Start Without Debugging option selected.

Note: Alternatively, since we set the startup project you can also start an instance (with or without debugging) from the toolbar menu.

  • In the browser window, press the Counter component’s Click me button multiple times and notice how the counter increases.

The Counter component displays within the existing web application. The Click me button is selected and the counter total is highlighted.

Step 6. Incorporate Telerik UI for Blazor

Now that we’ve successfully used a Blazor WebAssembly component in our existing ASP.NET Core Web Application, we can take advantage of the components provided by Progress Telerik UI for Blazor. This component library is compatible with both Blazor WebAssembly and Blazor Server projects.

Note: The Server project in our case is the Existing.Web project, and we’ve already added the app.UseStaticFiles() code, so this step can be skipped (Step 4, item #2 in the article linked).

  • Now we’ll add a Telerik UI for Blazor component to the existing Counter component. In the BlazorApp project, locate and open the Pages/Counter.razor file.
  • Replace the code in the file with the following and save the file:
@page "/counter"

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

<br/>

<hr />

<TelerikButton OnClick="@SayHelloHandler" ThemeColor="primary">Say Hello</TelerikButton>

<br />

@helloString


@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }

    MarkupString helloString;

    void SayHelloHandler()
    {
        string msg = string.Format("Hello from <strong>Telerik Blazor</strong> at {0}.<br /> Now you can use C# to write front-end!", DateTime.Now);
        helloString = new MarkupString(msg);
    }
}
  • Run the application once more, and press the Say Hello button to use the TelerikButton component!

The Counter widget is displayed with the Telerik button component. The message displays Hello from Telerik Blazor with a timestamp and Now you can use C# to write front-end!

Conclusion

In this article, we integrated Blazor components into an existing ASP.NET Core web application. This opens up a less disruptive migration path for moving existing projects to Blazor WebAssembly.

Original article source at: https://www.telerik.com/

#blazor #webassembly #aspdotnet #core 

Integrate Blazor WebAssembly into an Existing ASP.NET Core Web App
Rupert  Beatty

Rupert Beatty

1678305420

JSQCoreDataKit: A Swifter Core Data Stack

JSQCoreDataKit 

A swifter Core Data stack

About

This library aims to do the following:

  • Encode Core Data best practices, so you don't have to think "is this correct?" or "is this the right way to do this?"
  • Provide better interoperability with Swift
  • Harness Swift features and enforce Swift paradigms
  • Bring functional paradigms to Core Data
  • Make Core Data more Swifty
  • Simplify the processes of standing up the Core Data stack
  • Aid in testing your Core Data models
  • Reduce the boilerplate involved with Core Data

Requirements

  • Xcode 13.0+
  • Swift 5.5+
  • iOS 11.0+
  • macOS 10.12+
  • tvOS 11.0+
  • watchOS 4.0+
  • SwiftLint

Installation

CocoaPods

pod 'JSQCoreDataKit', '~> 9.0.0'

Swift Package Manager

Add JSQCoreDataKit to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/jessesquires/JSQCoreDataKit.git", from: "9.0.0")
]

Alternatively, you can add the package directly via Xcode.

Documentation

You can read the documentation here. Generated with jazzy. Hosted by GitHub Pages.

Additional Resources

Contributing

Interested in making contributions to this project? Please review the guides below.

Also, consider sponsoring this project or buying my apps! ✌️

Credits

Created and maintained by @jesse_squires.


Download Details:

Author: jessesquires
Source Code: https://github.com/jessesquires/JSQCoreDataKit 
License: MIT license

#swift #ios #core #data 

JSQCoreDataKit: A Swifter Core Data Stack
Monty  Boehm

Monty Boehm

1677598981

Swift App Demonstrating Core ML Stable Diffusion

Swift Core ML Diffusers 🧨

This is a native app that shows how to integrate Apple's Core ML Stable Diffusion implementation in a native Swift UI application. The Core ML port is a simplification of the Stable Diffusion implementation from the diffusers library. This application can be used for faster iteration, or as sample code for any use cases.

This is what the app looks like on macOS: App Screenshot

On first launch, the application downloads a zipped archive with a Core ML version of Stability AI's Stable Diffusion v2 base, from this location in the Hugging Face Hub. This process takes a while, as several GB of data have to be downloaded and unarchived.

For faster inference, we use a very fast scheduler: DPM-Solver++, that we ported to Swift from our diffusers DPMSolverMultistepScheduler implementation.

Compatibility and Performance

  • macOS Ventura 13.1, iOS/iPadOS 16.2, Xcode 14.2.
  • Performance (after the initial generation, which is slower)
    • ~8s in macOS on MacBook Pro M1 Max (64 GB). Model: Stable Diffusion v2-base, ORIGINAL attention implementation, running on CPU + GPU.
    • 23 ~ 30s on iPhone 13 Pro. Model: Stable Diffusion v2-base, SPLIT_EINSUM attention, CPU + Neural Engine, memory reduction enabled.

See this post and this issue for additional performance figures.

The application will try to guess the best hardware to run models on. You can override this setting using the Advanced section in the controls sidebar.

How to Run

The easiest way to test the app on macOS is by downloading it from the Mac App Store.

How to Build

You need Xcode to build the app. When you clone the repo, please update common.xcconfig with your development team identifier. Code signing is required to run on iOS, but it's currently disabled for macOS.

Known Issues

Performance on iPhone is somewhat erratic, sometimes it's ~20x slower and the phone heats up. This happens because the model could not be scheduled to run on the Neural Engine and everything happens in the CPU. We have not been able to determine the reasons for this problem. If you observe the same, here are some recommendations:

  • Detach from Xcode
  • Kill apps you are not using.
  • Let the iPhone cool down before repeating the test.
  • Reboot your device.

Next Steps

  • Allow additional models to be downloaded from the Hub.

Download Details:

Author: Huggingface
Source Code: https://github.com/huggingface/swift-coreml-diffusers 
License: Apache-2.0 license

#swift #app #core 

Swift App Demonstrating Core ML Stable Diffusion
Nat  Grady

Nat Grady

1676342160

How to Cache Mechanism in .Net Core

How to Cache Mechanism in .Net Core

Sometimes our application frequently calls the same method and fetches the data from the database. The output of these requests is the same at all times. It doesn't get changed or updated in the database. In this case, we can use caching to reduce the database calls and retrieve the data directly from the cache memory.

There are 3 types of cache available,

  • In-Memory Cache - The data are cached in the server's memory.
  • Persistent in-process Cache - The data are cached in some file or database.
  • Distributed Cache - The data are cached in a shared cache and multiple processes. Example: Redis cache

In-Memory Cache

In-Memory cache means storing the cache data on the server's memory.

Pros

It is easier and quicker than other caching mechanisms

  • Reduce load on Web Services/ Database
  • Increase Performance
  • Highly Reliable

It is suited for small and middle applications.

Cons

If the cache is not configured properly then, it can consume the server’s resources.

  • Increased Maintenance.

Scalability Issues. It is suitable for a single server. If we have many servers then, can't share the cache with all servers.

Original article source at: https://www.c-sharpcorner.com/

#dotnet #core #cache 

How to Cache Mechanism in .Net Core
Oral  Brekke

Oral Brekke

1670256741

Developing a Database Execution Policies in Entity Framework Core 6

We were developing a database project in .NET 6 using Entity Framework Core. Our back-end database engine was MySql rather than SQL server. It was a remote database. Short operations like single read and write worked fine but suddenly I stuck somewhere and got this horrible error.

Database Execution Policies In Entity Framework Core 6

The error was

“A second operation was started on this context instance before a previous operation was completed. This is usually caused by different threads concurrently using the same instance of DbContext.”

I started the operation again and surprisingly, this time the error was different regardless of the fact that all the inputs I provided were the same.

The error I got this time is:

The configured execution strategy 'MySqlRetryingExecutionStrategy' does not support user-initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit.'

Please note that if you are using SQL Server as a database engine, You’ll receive SqlRetryingExecutionStrategy rather than MySqlRetryingExecutionStrategy.

Database Execution Policies In Entity Framework Core 6

I tested the application many times and explored the stack trace in detail and also do a lot of search online but failed to figure out the issue as my app followed all the suggested solution standards.

I started following a thread on github where one important thing was mentioned.

One has to be careful while working with sync and async method. If you are following sync method patterns in your code, better to follow it completely, mean use sync method in all of your codebase. Don’t mix sync calls with async calls in your code.

If you working with async methods in your code it is highly recommended to use the async method with await in all the places in your codebase.

This last line give me some hint to find out the issue so started exploring the code backward. From the position where error or exception was coming while going backward from line to line, there was an async function which has no await before its invocation.

Database Execution Policies In Entity Framework Core 6

As soon as I applied this await prior to this call, both errors are gone.

Original article source at: https://www.c-sharpcorner.com/

#database #core #csharp 

Developing a Database Execution Policies in Entity Framework Core 6
Rocio  O'Keefe

Rocio O'Keefe

1661609700

Afya_moja_core: A Shared Library for Afyamoja and Myafyahub

afya_moja_core

afya_moja_core is an open source project — it's one among many other shared libraries that make up the wider ecosystem of software made and open sourced by Savannah Informatics Limited.

A shared library for ProHealth360 and ProHealth360 Daktari that is responsible for rendering and exposing shared components

Installation Instructions

Use this package as a library by depending on it

Run this command:

  • With Flutter:
flutter pub add afya_moja_core

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  afya_moja_core: ^0.2.14

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Lastly:

Import it like so:

import 'package:afya_moja_core/buttons.dart';

Usage

Check the example provided for how to use this package.

Dart & Flutter Version

  • Dart 2: >= 2.16.2
  • Flutter: >=2.10.5

Developing & Contributing

First off, thanks for taking the time to contribute!

Be sure to check out detailed instructions on how to contribute to this project here and go through out Code of Conduct.

GPG Signing: As a contributor, you need to sign your commits. For more details check here

Download Details:

Author: Savannahghi
Source Code: https://github.com/savannahghi/afya_moja_core 
License: MIT license

#flutter #dart #core 

Afya_moja_core: A Shared Library for Afyamoja and Myafyahub
Mike  Kozey

Mike Kozey

1661428707

Sio_core: Wallet Core Implementation

sio_core

Simplio wallet core library for blockchain interactions, developed in Dart, can be used in Flutter framework.

Sio_core library is working hand in hand with trust_wallet_core_lib, so please check the setup of trust_wallet_core_lib.

Example:

// ignore_for_file: avoid_print

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:sio_core/sio_core.dart';
import 'package:trust_wallet_core_lib/trust_wallet_core_ffi.dart';
import 'package:trust_wallet_core_lib/trust_wallet_core_lib.dart' as trust_core;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'sio_core example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'sio_core example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late trust_core.HDWallet wallet;

  final mnemonic =
      'horror select baby exile convince sunset outside vehicle write decade powder energy';

  Future<String> example() async {
    if (Mnemonic.isValid(mnemonic: mnemonic)) {
      wallet = Mnemonic.import(mnemonic: mnemonic);
    } else {
      throw Exception(['Mnemonic is not valid!']);
    }
    // ignore: unused_local_variable
    final solAddress = wallet.getAddressForCoin(TWCoinType.TWCoinTypeSolana);
    print('My solana address: $solAddress');

    var toAddress = '3fTR8GGL2mniGyHtd3Qy2KDVhZ9LHbW59rCc7A3RtBWk';

    var amount = '2000';

    try {
      final latestBlockHash = await UtilsSolana.latestBlockHashRequest(
          apiEndpoint: 'https://api.mainnet-beta.solana.com/');
      print(latestBlockHash);
      final signedSolanaTx = BuildTransaction.solana(
        recipient: toAddress,
        amount: amount,
        wallet: wallet,
        latestBlockHash: latestBlockHash,
      );
      print(signedSolanaTx.toJson());
      try {
        // Broadcasting will throw exception - it is normal unless u move funds in your solana address
        final broadcastSolanaTx = await Broadcast.solana(
          signedTxEncoded: signedSolanaTx.rawTx!,
          apiEndpoint: 'https://api.mainnet-beta.solana.com',
        );
        print(broadcastSolanaTx);
      } catch (exception) {
        print(exception);
      }
    } catch (exception) {
      print(exception);
    }

    const tokenMintAddress = 'SioTkQxHyAs98ouRiyi1YDv3gLMSrX3eNBg61GH7NrM';
    try {
      final latestBlockHash = await UtilsSolana.latestBlockHashRequest(
          apiEndpoint: 'https://api.mainnet-beta.solana.com/');
      print(latestBlockHash);
      final signedSolanaTokenTx = BuildTransaction.solanaToken(
        amount: amount,
        decimals: 8,
        tokenMintAddress: tokenMintAddress,
        recipientSolanaAddress: toAddress,
        wallet: wallet,
        latestBlockHash: latestBlockHash,
      );
      print(signedSolanaTokenTx.toJson());
      final broadcastSolanaTokenTx = await Broadcast.solana(
        signedTxEncoded: signedSolanaTokenTx.rawTx!,
        apiEndpoint: 'https://api.mainnet-beta.solana.com/',
      );
      // Broadcasting will throw exception - it is normal unless u move funds in your solana address
      print(broadcastSolanaTokenTx);
    } catch (exception) {
      print(exception);
    }

    return 'Success';
  }

  @override
  void initState() {
    trust_core.TrustWalletCoreLib.init();
    super.initState();
    example();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: const <Widget>[],
      ),
    );
  }
}

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add sio_core

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  sio_core: ^0.1.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:sio_core/sio_core.dart';

List of supported chains here.

Download Details:

Author: SimplioOfficial
Source Code: https://github.com/SimplioOfficial/sio_core 
License: BSD-3-Clause license

#flutter #dart #core 

Sio_core: Wallet Core Implementation
Elian  Harber

Elian Harber

1659918480

Iotex-core: Official Implementation Of IoTeX Blockchain Protocol in Go

iotex-core

Official Golang implementation of the IoTeX protocol.       

Welcome to the official Go implementation of IoTeX protocol! IoTeX is building the next generation of the decentralized blockchain protocol for powering real-world information marketplace in a decentralized-yet-scalable way. Refer to IoTeX whitepaper for details. 

New to IoTeX?

Please visit https://iotex.io official website or IoTeX onboard pack to learn more about IoTeX network.

Run a delegate?

Please visit IoTeX Delegate Manual for detailed setup process.

Building the source code

Minimum requirements

ComponentsVersionDescription
Golang≥ 1.17.3Go programming language
Protoc≥ 3.6.0Protocol buffers, required only when you rebuild protobuf messages

Compile

Download the code to your desired local location (doesn't have to be under $GOPATH/src)

git clone git@github.com:iotexproject/iotex-core.git
cd iotex-core

If you put the project code under your $GOPATH\src, you will need to set up an environment variable

export GO111MODULE=on
set GO111MODULE=on (for windows)

Build the project for general purpose (server, ioctl) by

make

Build the project for broader purpose (server, ioctl, injector...) by

make all 

If the dependency needs to be updated, run

go get -u
go mod tidy

If you want learn more advanced usage about go mod, you can find out here.

Run unit tests only by

make test

Build the docker image by

make docker

Run iotex-core

Start (or resume) a standalone server to operate on an blockchain by

make run

Restart the server from a clean state by

make reboot

If "make run" fails due to corrupted or missing state database while block database is in normal condition, e.g., failing to get factory's height from underlying DB, please try to recover state database by

make recover

Then, "make run" again.

Use CLI

Users could interact with iotex blockchain by

ioctl [command]

Refer to CLI document for more details.

Contact

Contribution

We are glad to have contributors out of the core team; contributions, including (but not limited to) style/bug fixes, implementation of features, proposals of schemes/algorithms, and thorough documentation, are welcomed. Please refer to our contribution guideline for more information. Development guide documentation is here.

For any major protocol level changes, we use IIP to track the proposal, decision and etc.

Contributors

Thank you for considering contributing to the IoTeX framework! 

Author: iotexproject
Source Code: https://github.com/iotexproject/iotex-core 
License: Apache-2.0 license

#go #golang #core #cryptography #blockchain 

Iotex-core: Official Implementation Of IoTeX Blockchain Protocol in Go
Rocio  O'Keefe

Rocio O'Keefe

1659717540

Trust_wallet_core_lib: A Flutter Plugin for Trust Wallet Core

trust_wallet_core_lib

A Flutter plugin for trust wallet core. It can access all api list in https://github.com/trustwallet/wallet-core/tree/master/include/TrustWalletCore (from trust_wallet_core 2.6.20)

This project was originally copied from weishirongzhen

trust_wallet_core_lib is supporting Android and iOS platforms only. (Only Android platform was tested).

Android

minSdk require >=23

Add

class MainActivity: FlutterActivity() {
    init {
        System.loadLibrary("TrustWalletCore")
    }
}

in your android project MainActivity.kt file

iOS

min ios platform support >=13.0

Flutter

Before using this package, you need to initialize it:

 FlutterTrustWalletCore.init();

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add trust_wallet_core_lib

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  trust_wallet_core_lib: ^0.0.6+2.9.6

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:trust_wallet_core_lib/trust_wallet_core_lib.dart';

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:trust_wallet_core_lib/trust_wallet_core_lib.dart';
import 'package:trust_wallet_core_lib_example/bitcoin_address_example.dart';
import 'package:trust_wallet_core_lib_example/bitcoin_transaction_example.dart';
import 'package:trust_wallet_core_lib_example/ethereum_example.dart';
import 'package:trust_wallet_core_lib_example/private_key_is_valid_example.dart';
import 'package:trust_wallet_core_lib_example/tron_example.dart';

List<String> logs = [];

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Example(),
    );
  }
}

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  late HDWallet wallet;

  @override
  void initState() {
    TrustWalletCoreLib.init();
    super.initState();
    String mnemonic =
        "rent craft script crucial item someone dream federal notice page shrug pipe young hover duty"; // 有测试币的 tron地址
    wallet = HDWallet.createWithMnemonic(mnemonic);
  }

  Widget _exampleItem({
    required String name,
    required WidgetBuilder builder,
  }) {
    return ElevatedButton(
      onPressed: () {
        Navigator.of(context).push(MaterialPageRoute(builder: builder));
      },
      child: Text(name),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('wallet core example app'),
      ),
      body: SafeArea(
        child: Column(
          children: [
            Text(wallet.mnemonic()),
            Expanded(
              child: ListView(
                padding: EdgeInsets.zero,
                children: [
                  _exampleItem(
                    name: 'Ethereum',
                    builder: (_) {
                      return EthereumExample(wallet);
                    },
                  ),
                  _exampleItem(
                    name: 'Bitcoin Address',
                    builder: (_) {
                      return BitcoinAddressExample(wallet);
                    },
                  ),
                  _exampleItem(
                    name: 'Bitcoin Transaction',
                    builder: (_) {
                      return BitcoinTransactionExample(wallet);
                    },
                  ),
                  _exampleItem(
                    name: 'Tron',
                    builder: (_) {
                      return TronExample(wallet);
                    },
                  ),
                  _exampleItem(
                    name: 'PrivateKey.isValid(a,b)',
                    builder: (_) {
                      return PrivateKeyIsValidExample(wallet);
                    },
                  ),
                ],
              ),
            ),
            ElevatedButton(
              onPressed: () async {
                wallet.delete();
                wallet = HDWallet();
                setState(() {});
              },
              child: Text("gen"),
            ),
          ],
        ),
      ),
    );
  }
}

Author: Ciripel
Source Code: https://github.com/ciripel/trust_wallet_core_lib 
License: MIT license

#flutter #dart #core 

Trust_wallet_core_lib: A Flutter Plugin for Trust Wallet Core
Hunter  Krajcik

Hunter Krajcik

1657912200

Nui_core: A New Flutter Package

nui_core

A new Flutter package.

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add nui_core

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  nui_core: ^0.1.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:nui_core/nui_core.dart';

Getting Started

This project is a starting point for a Dart package, a library module containing code that can be shared easily across multiple Flutter or Dart projects.

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

Original article source at: https://pub.dev/packages/nui_core 

#flutter #dart #core 

Nui_core: A New Flutter Package
Royce  Reinger

Royce Reinger

1657835580

Stanford-core-nlp: Ruby Bindings to The Stanford Core NLP Tools

Stanford CoreNLP

Ruby bindings for the Stanford CoreNLP Toolchain.

This gem provides high-level Ruby bindings to the Stanford CoreNLP package, a set natural language processing tools for tokenization, sentence segmentation, part-of-speech tagging, lemmatization, and parsing of English, French and German. The package also provides named entity recognition and coreference resolution for English.

This gem is compatible with Ruby 2.3 and 2.4 as well as JRuby 1.7 and 9. Older Ruby version should work as well.

You need Java 8 for the latest CoreNLP version (since 3.5.0, 2014-10-31), earlier versions are tested on both Java 6 and Java 7.

The version schema has been changed to reflect the development of Stanford CoreNLP itself. We'll release a gem for every new version from Stanford.

Supported Human Languages

We strive to support all languages Stanford CoreNLP can work with.

Annotatorarzhenfrdees
Tokenize / Segment 
Sentence Split
Part of Speech
Lemma     
Named Entities  
Constituency Parsing
Dependency Parsing  
Sentiment Analysis     
Mention Detection    
Coreference    
Open IE     

Installation

First, install the gem: gem install stanford-core-nlp. Then, download the Stanford Core NLP JAR and model files: Stanford CoreNLP

Place the contents of the extracted archive inside the /bin/ folder of the stanford-core-nlp gem (e.g. [...]/gems/stanford-core-nlp-0.x/bin/).

Configuration

You may want to set some optional configuration options. Here are some examples:

# Set an alternative path to look for the JAR files
# Default is gem's bin folder.
StanfordCoreNLP.jar_path = '/path_to_jars/'

# Set an alternative path to look for the model files
# Default is gem's bin folder.
StanfordCoreNLP.model_path = '/path_to_models/'

# Pass some alternative arguments to the Java VM.
# Default is ['-Xms512M', '-Xmx1024M'] (be prepared
# to take a coffee break).
StanfordCoreNLP.jvm_args = ['-option1', '-option2']

# Redirect VM output to log.txt
StanfordCoreNLP.log_file = 'log.txt'

# Change a specific model file.
StanfordCoreNLP.set_model('pos.model', 'english-left3words-distsim.tagger')

Using the gem

# Use the model files for a different language than English.
StanfordCoreNLP.use :french # or :german

text = 'Angela Merkel met Nicolas Sarkozy on January 25th in ' +
   'Berlin to discuss a new austerity package. Sarkozy ' +
   'looked pleased, but Merkel was dismayed.'

pipeline =  StanfordCoreNLP.load(:tokenize, :ssplit, :pos, :lemma, :parse, :ner, :dcoref)
text = StanfordCoreNLP::Annotation.new(text)
pipeline.annotate(text)

text.get(:sentences).each do |sentence|
  # Syntatical dependencies
  puts sentence.get(:basic_dependencies).to_s
  sentence.get(:tokens).each do |token|
    # Default annotations for all tokens
    puts token.get(:value).to_s
    puts token.get(:original_text).to_s
    puts token.get(:character_offset_begin).to_s
    puts token.get(:character_offset_end).to_s
    # POS returned by the tagger
    puts token.get(:part_of_speech).to_s
    # Lemma (base form of the token)
    puts token.get(:lemma).to_s
    # Named entity tag
    puts token.get(:named_entity_tag).to_s
    # Coreference
    puts token.get(:coref_cluster_id).to_s
    # Also of interest: coref, coref_chain,
    # coref_cluster, coref_dest, coref_graph.
  end
end

Important: You need to load the StanfordCoreNLP pipeline before using the StanfordCoreNLP::Annotation class.

The Ruby symbol (e.g. :named_entity_tag) corresponding to a Java annotation class is the snake_case of the class name, with 'Annotation' at the end removed. For example, NamedEntityTagAnnotation translates to :named_entity_tag, PartOfSpeechAnnotation to :part_of_speech, etc.

A good reference for names of annotations are the Stanford Javadocs for CoreAnnotations, CoreCorefAnnotations, and TreeCoreAnnotations. For a full list of all possible annotations, see the config.rb file inside the gem.

Loading specific classes

You may want to load additional Java classes (including any class from the Stanford NLP packages). The gem provides an API for this:

# Default base class is edu.stanford.nlp.pipeline.
StanfordCoreNLP.load_class('PTBTokenizerAnnotator')
puts StanfordCoreNLP::PTBTokenizerAnnotator.inspect
  # => #<Rjb::Edu_stanford_nlp_pipeline_PTBTokenizerAnnotator>

# Here, we specify another base class.
StanfordCoreNLP.load_class('MaxentTagger', 'edu.stanford.nlp.tagger')
puts StanfordCoreNLP::MaxentTagger.inspect
  # => <Rjb::Edu_stanford_nlp_tagger_maxent_MaxentTagger:0x007f88491e2020>

List of annotator classes

Here is a full list of annotator classes provided by the Stanford Core NLP package. You can load these classes individually using StanfordCoreNLP.load_class (see above). Once this is done, you can use them like you would from a Java program. Refer to the Java documentation for a list of functions provided by each of these classes.

  • PTBTokenizerAnnotator - tokenizes the text following Penn Treebank conventions.
  • WordToSentenceAnnotator - splits a sequence of words into a sequence of sentences.
  • POSTaggerAnnotator - annotates the text with part-of-speech tags.
  • MorphaAnnotator - morphological normalizer (generates lemmas).
  • NERAnnotator - annotates the text with named-entity labels.
  • NERCombinerAnnotator - combines several NER models.
  • TrueCaseAnnotator - detects the true case of words in free text.
  • ParserAnnotator - generates constituent and dependency trees.
  • NumberAnnotator - recognizes numerical entities such as numbers, money, times, and dates.
  • TimeWordAnnotator - recognizes common temporal expressions, such as "teatime".
  • QuantifiableEntityNormalizingAnnotator - normalizes the content of all numerical entities.
  • SRLAnnotator - annotates predicates and their semantic roles.
  • DeterministicCorefAnnotator - implements anaphora resolution using a deterministic model.
  • NFLAnnotator - implements entity and relation mention extraction for the NFL domain.

List of model files

Here is a full list of the default models for the Stanford Core NLP pipeline. You can change these models individually using StanfordCoreNLP.set_model (see above).

  • 'pos.model' - 'english-left3words-distsim.tagger'
  • 'ner.model' - 'all.3class.distsim.crf.ser.gz'
  • 'parse.model' - 'englishPCFG.ser.gz'
  • 'dcoref.demonym' - 'demonyms.txt'
  • 'dcoref.animate' - 'animate.unigrams.txt'
  • 'dcoref.female' - 'female.unigrams.txt'
  • 'dcoref.inanimate' - 'inanimate.unigrams.txt'
  • 'dcoref.male' - 'male.unigrams.txt'
  • 'dcoref.neutral' - 'neutral.unigrams.txt'
  • 'dcoref.plural' - 'plural.unigrams.txt'
  • 'dcoref.singular' - 'singular.unigrams.txt'
  • 'dcoref.states' - 'state-abbreviations.txt'
  • 'dcoref.extra.gender' - 'namegender.combine.txt'

Testing

To run the specs for each language (after copying the JARs into the bin folder):

rake spec[english]
rake spec[german]
rake spec[french]

Using the latest version of the Stanford CoreNLP

Using the latest version of the Stanford CoreNLP (version 3.5.0 as of 31/10/2014) requires some additional manual steps:

  • Download Stanford CoreNLP version 3.5.0 from http://nlp.stanford.edu/.
  • Place the contents of the extracted archive inside the /bin/ folder of the stanford-core-nlp gem (e.g. [...]/gems/stanford-core-nlp-0.x/bin/) or inside the directory location configured by setting StanfordCoreNLP.jar_path.
  • Download the full Stanford Tagger version 3.5.0 from http://nlp.stanford.edu/.
  • Make a directory named 'taggers' inside the /bin/ folder of the stanford-core-nlp gem (e.g. [...]/gems/stanford-core-nlp-0.x/bin/) or inside the directory configured by setting StanfordCoreNLP.jar_path.
  • Place the contents of the extracted archive inside taggers directory.
  • Download the bridge.jar file from https://github.com/louismullie/stanford-core-nlp.
  • Place the downloaded bridge.jar file inside the /bin/ folder of the stanford-core-nlp gem (e.g. [...]/gems/stanford-core-nlp-0.x/bin/) or inside the directory configured by setting StanfordCoreNLP.jar_path.
  • Configure your setup (for English) as follows:
StanfordCoreNLP.use :english
StanfordCoreNLP.model_files = {}
StanfordCoreNLP.default_jars = [
  'joda-time.jar',
  'xom.jar',
  'stanford-corenlp-3.5.0.jar',
  'stanford-corenlp-3.5.0-models.jar',
  'jollyday.jar',
  'bridge.jar'
]

Or configure your setup (for French) as follows:

StanfordCoreNLP.use :french
StanfordCoreNLP.model_files = {}
StanfordCoreNLP.set_model('pos.model', 'french.tagger')
StanfordCoreNLP.default_jars = [
  'joda-time.jar',
  'xom.jar',
  'stanford-corenlp-3.5.0.jar',
  'stanford-corenlp-3.5.0-models.jar',
  'jollyday.jar',
  'bridge.jar'
]

Or configure your setup (for German) as follows:

StanfordCoreNLP.use :german
StanfordCoreNLP.model_files = {}
StanfordCoreNLP.set_model('pos.model', 'german-fast.tagger')
StanfordCoreNLP.default_jars = [
  'joda-time.jar',
  'xom.jar',
  'stanford-corenlp-3.5.0.jar',
  'stanford-corenlp-3.5.0-models.jar',
  'jollyday.jar',
  'bridge.jar'
]

Contributing

We are very glad to see you in this section and highly appreciate any help!

If you want to contribute please agree that your work will be published under the terms of the GPL v.3.0 license.

Some of the open tasks for contributors are listed on the issues page. You may want to start there.

Then feel free to fork the code and send us a pull request.

Download Details: 
Author: louismullie
Source Code: https://github.com/louismullie/stanford-core-nlp 
License: View license

#ruby #nlp #core 

Stanford-core-nlp: Ruby Bindings to The Stanford Core NLP Tools
Reid  Rohan

Reid Rohan

1657829460

Reconnect-core: Generic Stream Reconnection Module

reconnect-core

Generic stream reconnection module.

Usage

Create a reconnect instance that keeps reconnecting over tcp:

var inject = require('reconnect-core');
var net = require('net');

// build you own reconnect module
var reconnect = inject(function () {
  // arguments are what you passed to .connect
  // this is the reconnect instance
  return net.connect.apply(null, arguments);
});

var re = reconnect({
  // all options are optional
  initialDelay: 1e3,
  maxDelay: 30e3,
  strategy: 'fibonacci',      // available: fibonacci, exponential, or a custom backoff instance (see below)
  failAfter: Infinity,
  randomisationFactor: 0,
  immediate: false
}, function (stream) {
  // stream = the stream you should consume
})
.on('connect', function (con) {
  // con = underlying connection  
})
.on('reconnect', function (n, delay) {
  // n = current number of reconnect  
  // delay = delay used before reconnect
})
.on('disconnect', function (err) {
  // err = possible error  
})
.on('error', function (err) {
  // never forget
})
.connect(port)

// disconnect
re.disconnect();

// ...or prevent reconnecting
re.reconnect = false;

// reset the internal backoff timer
re.reset();

Strategies

reconnect utilises the backoff library to control backoff behaviour. There are 2 options for choosing a strategy for your reconnect instance, pass one of the following to the strategy key when creating your instance:

  • Pass the string "fibonacci" or "exponential" to utilise these built-in backoff strategies, options passed to your reconnect instance will also be passed to these strategies.
  • Pass a Backoff instance, this allows you to customise your backoff strategy by implementing a Backoff Strategy.

An example using a custom strategy:

var inject = require('reconnect-core');
var backoff = require('backoff');
var net = require('net');

// build you own reconnect module
var reconnect = inject(function () {
  // arguments are what you passed to .connect
  // this is the reconnect instance
  return net.connect.apply(null, arguments);
});

// Reconnect every 10 seconds
var myStrategy = {
  next: function() { return 10e3; },
  reset: function() { }
}

var re = reconnect({
  strategy: new backoff.Backoff(myStrategy),
  failAfter: Infinity,
  immediate: false
}, function (stream) {
  // stream = the stream you should consume
})

Available implementations

Installation

With npm do:

npm install reconnect-core

Kudos

This has been refactored out of dominictarr's reconnect module.

Author: juliangruber
Source Code: https://github.com/juliangruber/reconnect-core 
License: MIT

#javascript #node #core #stream 

Reconnect-core: Generic Stream Reconnection Module