전체 글

Blazor Server .NET 6 소개

2023. 3. 12. 14:04

 

Blazor가 뛰어난 프레임워크인 이유

2018년에 시작된 Blazor는 Microsoft에서 SPA(단일 페이지 애플리케이션) 프레임워크로 개발했습니다.
TypeScript/JavaScript 언어로 구축된 Angular, Vue, React와 같은 대부분의 기존 SPA 프레임워크. 반면에 Blazor는 C#을 사용하여 웹 사이트를 빌드하면 코드가 WebAssembly로 컴파일되고 브라우저에서 직접 실행됩니다. Blazor는 또한 기존 JSON 대신 WebAssembly를 사용하여 브라우저와 서버 간의 통신을 최적화합니다.
요약하자면:

  • 강력한 유형 언어(C#)로 웹 사이트를 구축합니다.
  • WebAssembly를 사용하여 클라이언트와 서버 간의 통신을 최적화합니다.
  • WebAssembly를 사용하여 브라우저에서 로직을 실행하여 성능을 최적화합니다.
  • 웹 사이트를 구축하려면 0에서 최소한의 JavaScript 지식이 필요합니다.
  • 기존 JavaScript 라이브러리와 호환됩니다.

비교 호스팅 모델

  Blazor Server Blazor WASM(WebAssembly)
서버 리소스에 대한 액세스 직접 간접
내장 SignalR 코어 아니요
내장 서비스 작업자 아니요
검증 및 프로세스 서버에서 클라이언트에서
생산 준비
클라이언트-서버 통신 바이트 코드 JSON, 바이트 코드

Blazor 서버는 웹 서버(NGINX, Apache, ...), Azure AppService에서 호스팅할 수 있습니다.

Blazor WebAssembly는 프런트엔드 웹 사이트이며 Azure Static WebApp, Azure AppService 또는 웹 서버(NGINX, Apache 등)에서 호스팅될 수 있습니다. 완전한 기능을 갖춘 Blazor WebAssembly의 경우 백엔드 기술(Azure Function, Grpc, ASP.NET Web API)과 결합해야 합니다.

728x90
728x90

ASP.NET Core

2022. 8. 23. 11:47

출처 : https://www.learnrazorpages.com/asp-net-core 
번역 : Code Reaper (제 맘대로 번역이라 오역과 의역이 난무합니다.)

ASP.NET Core

ASP.NET Core는 MS 최초의 크로스-플랫폼 웹 애플리케이션 프레임웍이다. .NET Core를 베이스로 하고 있는 Open-source 플랫폼이며, 프레임워크의 라이브러리들, SDK와 런타임으로 구성돼있다.

ASP.NET Core는 지난 2020년 발표된 .NET 5에 포함돼있다. (2022년 현재는 .NET 6 !).

 

ASP.NET Core를 선택해야 하는 이유

웹개발은 바뀌고 있다. 구현하려는 기능에 따라 모듈이 필요할 수도 있는데, 모든 플랫폼에서 Application의 규모를 쉽게 확장시키고 모듈을 적용하기 위해서는 클라우드 환경이 되어야 한다. 또한 Client-side 프레임웍과 RESTful API를 쉽게 개발하는 것도 필요하다. 그리고 프레임웍 자체가 빨라야 한다. 웹 개발 환경에서의 새로운 기능들을 즉시 적용할 필요가 있다. 개발자들은 사이트를 만드는데 필요한 툴을 선택하고 싶어한다.

일부 프레임웍은 이미 이 문제를 해소했다. Node.js의 Express같은 라이브러리가 대표적.
근데 옛날 .NET Framework 기반의 ASP.NET은 그렇지 못했다. 오직 Windows 웹서버와 결합돼있었고.  닷넷 Framework와 결합돼 있어서, 새로운 기능이 나오기 까지는 몇 년씩 걸리곤 했다. 그리고 Visual Studio에 굉장히 의존적이었다. (물론 Windows에서 돌아가는 IDE중에서는 Visual Studio가 최고다.)

참고로 VS for MAC은 Visual Studio 가 아닌, Xamarin Studio 버전이다. .NET Core 개발을 지원하는 Xamarin Studio의 버전인 것이다.

ASP.NET Core은 모듈화에 초점이 맞춰져 있다. HTTP 파이프라인은 필요할 때마다 꺼내 쓸 수 있는 개별 컴포넌트로 구성돼 있다. 이런 방식은 다음과 같은 장점이 있다:

  • 앱이 훨씬 가벼워진다. 필요한 컴포넌트만 가져다 쓰니까.
  • 다양한 출처에서 컴포넌트를 가져다 쓸 수 있다.
  • 남들이 만든 것 외에도 컴포넌트를 직접 만들어 쓸 수 있다.
  • 어떤 플랫폼에서 구동시킬지 선택 할 수 있다. (멀티 플랫폼)
  • 이전 ASP.NET 보다 훨~~~씬 빠르게 새로운 기능이 추가된다.

ASP.NET Core는 Model-View-Controller (MVC) 패턴을 기반으로 하는 웹 개발프레임웍을 제공한다. 이런 기반 위에 페이지를 중심으로 개발을 하던 개발자들을 위한 Razor Pages가 존재한다. ASP.NET은 REST 기반 웹서비스 (WebAPI)를 개발하기 위한 프레임웍도 포함하고 있다. 또한 웹소켓 베이스 프레임웍인 SignalR을 포함시킴으로써, 페이지의 실시간 업데이트가 가능해졌다.

 

728x90

pdb파일이 있으면 Trace stack을 할 수 있어서 좋다는 편리함이 있는데,

.NET6 환경에서는 pdb파일을 포함하는 옵션을 설정하려면

프로젝트 속성>>Build >> General 맨 아래쪽에 Debug symbols 라는 옵션을 바꿔주면 된다.

각각의 exe/dll에 pdb를 포함하려면 Embedded in DLL/EXE 를 선택한다.

728x90

비동기 Socket Server (1:1)

2021. 12. 23. 20:49

심플해보이지만 잘 작동하는 소스

// Author: CodeReaper
// Last update: 2022/01/01

using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncSocket
{
    /// <summary>
    /// 핸들링할 객체를 담아둘 Class
    /// </summary>
    public class StateObject
    {
        // Size of receive buffer.  
        public const int BufferSize = 1024;
        // Receive buffer.  
        public byte[] buffer = new byte[BufferSize];
        // Received data string.
        public StringBuilder sb = new StringBuilder();
        // Client socket.
        public Socket workSocket = null;
    }

    /// <summary>
    /// 비동기 소켓 서버
    /// </summary>
    public class Server
    {
        public int LocalPort { get; set; } = 0;

        //연결 event
        public event onConnectEventHandler onConnect;
        public delegate void onConnectEventHandler(object sender, string remoteIP, string remotePort);

        //연결해제 event
        public event onDisconnectEventHandler onDisconnect;
        public delegate void onDisconnectEventHandler(object sender);

        //수신 event
        public event onDataArrivalEventHandler onDataArrival;
        public delegate void onDataArrivalEventHandler(object sender, byte[] Data, int bytesRead);

        //송신 event
        public event onSendCompleteEventHandler onSendComplete;
        public delegate void onSendCompleteEventHandler(object sender, byte[] Data);

        public Server(int ListenPort = 0)
        {
            LocalPort = ListenPort;
        }

        protected StateObject _state = null;
        Socket listener;

        public async void Listen()
        {
            if (_state != null)
            {
                return;
            }

            if (LocalPort < 1)
            {
                return;
            }

            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, LocalPort);

            // Create a TCP/IP socket.  
            listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.  
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                while (true)
                {
                    Socket clientSock = await Task.Factory.FromAsync(listener.BeginAccept, listener.EndAccept, null);

                    onConnect?.Invoke(this, ((IPEndPoint)clientSock.RemoteEndPoint).Address.ToString(), ((IPEndPoint)clientSock.RemoteEndPoint).Port.ToString());
                    // Create the state object.  
                    _state = new StateObject();
                    _state.workSocket = clientSock;
                    clientSock.BeginReceive(_state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReadCallback), _state);
                }
            }
            catch
            {
                Stop();
            }
            finally
            {
            }

        }

        private void ReadCallback(IAsyncResult ar)
        {
            try
            {
                _state = (StateObject)ar.AsyncState;
                Socket handler = _state.workSocket;

                // Read data from the client socket.
                int bytesRead = handler.EndReceive(ar);

                if (bytesRead > 0)
                {
                    byte[] rcvBuff = new byte[bytesRead];
                    Array.Copy(_state.buffer, rcvBuff, bytesRead);

                    if (onDataArrival != null) { onDataArrival(this, rcvBuff, bytesRead); }
                    handler.BeginReceive(_state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), _state);
                }
                else
                {
                    Stop();
                }
            }
            catch
            {
                Stop();
            }
        }

        public void Stop()
        {
            try
            {
                _state.workSocket.Shutdown(SocketShutdown.Both);
                _state.workSocket.Close();
            }
            catch
            { }
            finally
            {
                _state = null;
                onDisconnect?.Invoke(this);
            }
        }

        public void Send(byte[] data)
        {
            try
            {
                if (_state == null || _state.workSocket == null)
                {
                    return;
                }

                _state.workSocket.Send(data, 0, data.Length, SocketFlags.None);
                onSendComplete?.Invoke(this, data);
            }
            catch
            { }
        }

        public bool Send(string msg, Encoding enc = null)
        {
            try
            {
                if (_state == null || _state.workSocket == null)
                {
                    return false;
                }
                if (enc == null)
                {
                    enc = Encoding.Default;
                }
                byte[] bytesEncoded = enc.GetBytes(msg);
                _state.workSocket.Send(bytesEncoded, 0, bytesEncoded.Length, SocketFlags.None);
                onSendComplete?.Invoke(this, bytesEncoded);
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw ex;
            }
        }

    }
}

 

MSDN에서 기본 소스 참조하고, 테스트를 거친 후에 품종 개량한 것입니다.

참고 사이트
https://docs.microsoft.com/ko-kr/dotnet/framework/network-programming/asynchronous-server-socket-example
https://www.csharpstudy.com/net/article/11-%eb%b9%84%eb%8f%99%ea%b8%b0-Socket-%ec%84%9c%eb%b2%84

 

728x90

Windows 셧다운 관련 Event ID

2021. 10. 12. 12:40

The event ID's below will show you these details.

Event ID Description
41 The system has rebooted without cleanly shutting down first. This error could be caused if the system stopped responding, crashed, or lost power unexpectedly.
1074 Logged when an app (ex: Windows Update) causes the system to restart, or when a user initiates a restart or shutdown.
6006 Logged as a clean shutdown. It gives the message "The Event log service was stopped".
6008 Logged as a dirty shutdown. It gives the message "The previous system shutdown at time on date was unexpected".


This tutorial will show you how to view the date, time, and user details of all shutdown and restart event logs in Windows 7, Windows 8, and Windows 10.

 

10016 오류 해결 방법

https://www.wintips.org/fix-application-specific-permission-settings-do-not-grant-local-launch-permission-for-windows-securitycenter-securityappbroker/

 

FIX: Application Specific Permission Settings do not grant Local Launch permission for Windows.SecurityCenter.SecurityAppBroker

Instructions to fix the event 10016 "Application Specific Permission Settings do not grant Local Launch permission for Windows.SecurityCenter.SecurityAppBroker" on Windows.

www.wintips.org

 

728x90

방화벽 설정 command

2021. 9. 17. 12:43

https://social.technet.microsoft.com/Forums/ko-KR/58a02324-fb88-4c33-a678-460827c7ae5e/net-advfirewall-firewall-4932450857-4816948277?forum=isaserverko 

 

net advfirewall firewall 사용 방법

질문 Vista이상의 상위 버전 윈도우에서는 netsh firewall 대신에 netsh advfirewall firewall 명령어를 사용을 추천 합니다. 대답 1.     프로그램 허용 a.     netsh advfirewall firewall add rule name=”My Application

social.technet.microsoft.com

 

1.     프로그램 허용

a.     netsh advfirewall firewall add rule name=”My Application” dir=in action=allow program=”C:\MyApp\MyApp.exe” enable=yes

 

b.     netsh advfirewall firewall add rule name=”My Application” dir=in action=allow program=”C:\MyApp\Myapp.exe” enable=yes remoteip=157.60.0.1, 172.16.0.0/16,LocalSubnet profile=domain

 

2.     포트 허용

 

a.     netsh advfirewall firewall add rule name=”Open Port 80” dir=in action=allow protocol=TCP localport=80

 

3.     허용된 프로그램과 포트 룰 제거 하기

 

a.     netsh advfirewall firewall delete rule name=”rulename” program=”C:\MyApp\MyApp.exe”

 

b.     netsh advfirewall firewall delete rule name=”rulename” protocol=udp localport=500

 

4.     ICMP 설정 하기

 

a.     netsh advfirewall  firewall add rule name=”ICMP Allow incoming V4 echo request” protocol=icmpv4:8,any dir=in action=allow

 

b.     netsh advfirewall firewall add rule name=”All  ICMP V4” protocol=icmpv4:any,any dir=in action=allow

 

 

5.     로깅 설정

 

a.     netsh advfirewall set currentprofile logging filename %systemroot%\system32\LogFiles\Filewall\pfirewall.log

 

b.     netsh advfirewall set currentprofile logging maxfilesize 4096

 

c.     netsh advfirewall set currentprofile logging droppedconnections enable

 

d.     netsh advfirewall set currentprofile logging allowedconnections enable

 

 

 

6.     방화벽 On/Off

 

a.     netsh advfirewall set currentprofile state on

 

b.     netsh advfirewall set currentprofile state on
netsh advfirewall set currentprofile firewallpolicy blockinboundalways,allowoutbound

 

c.     netsh advfirewall set domainprofile state on
netsh advfirewall set domainprofile firewallpolicy blockinbound,allowoutbound

 

d.     netsh advfirewall set domainprofile state on
netsh advfirewall set private profile state on

 

 

7.     방화벽 설정 초기화

 

a.     Netsh advfirewall reset

 

 

8.     특정 서비스 허용

 

a.     netsh  advfirewall firewall set rule group=”File and Printer Sharing” new enable=yes

 

b.     netsh  advfirewall firewall set rule group=”remote desktop” new enable=yes

 

c.     netsh  advfirewall firewall set rule group=”remote desktop” new enable=yes profile=domain

 

d.     netsh advfirewall firewall set rule group=”remote desktop” new enable=yes profile=private



적용 대상

 

Windows Vista

Windows 7

Windows 2008

Windows 2008 R2

728x90

master나 tempdb는 제외하고 생성된 모든 테이블을 삭제

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR

SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_SCHEMA + '].[' +  tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + '];'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME

OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql

WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec sp_executesql @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END

CLOSE @Cursor DEALLOCATE @Cursor
GO

EXEC sp_MSforeachtable 'DROP TABLE ?'
GO

 

출처1 : https://stackoverflow.com/questions/8439650/how-to-drop-all-tables-in-a-sql-server-database

 

How to drop all tables in a SQL Server database?

I'm trying to write a script that will completely empty a SQL Server database. This is what I have so far: USE [dbname] GO EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all' EXEC

stackoverflow.com

참고 : https://www.mssqltips.com/sqlservertip/6798/drop-all-tables-sql-server/

 

Drop All Tables SQL Server

In this article we cover different ways to drop all tables from a SQL Server database.

www.mssqltips.com

 

728x90

+ Recent posts