分類
ASP.NET

[ASP.NET] 使用 Visual Studio 2019 編輯網頁(沒有sln檔)

Situation

需要修改網頁(http://www.somewhere.com)且已知該網頁對應的網路空間(\\192.168.1.1\websitefolder),其網路空間看起來也有對應的Source Code,如.html , web.config等等,但沒有.sln 等等的解決方案檔。

Action

首先使用編輯器修改 index.html檔並觀察網頁是否出現對應的修改內容,結果網頁確實發生預期的改變。
開啟 VS2019 -> 不使用程式碼繼續 -> 在主畫面選擇”檔案” -> 開啟 -> 網站 -> 左方選擇檔案系統 -> 下方的資料夾填入對應的網路空間路徑(\\192.168.1.1\websitefolder)
VS2019 便可讀取該路徑內的所有檔案

Result

透過上方的Action便可使用 VS2019 編輯網頁 Source Code,可以一邊開啟網頁一邊確認編輯內容是否正確。
離開前VS2019會詢問是否儲存.sln檔。若選是,該.sln 便會儲存在本機端,之後只要點擊.sln檔便可直接編輯網頁內容。
關於版控的部分,可以直接使用檔案總管開啟對應的網路空間(\\192.168.1.1\websitefolder),接著右鍵點擊該目錄 -> git bash -> 可直接在該目錄使用 git 指令(有時候command line 反應會比較慢,不過基本上是沒問題的)
 

分類
ASP.NET

[ASP.NET] 判斷使用者IP為內網或外網

Situation

需要判斷使用者的IP 為內網或外網。

Action

使用者 IP 可以透過 Request.UserHostAddress 取得
“判斷內外網邏輯” 首先從重用性考慮,該邏輯之後可以在其他專案或模組重複使用,看起來應該提取到新類別中,如下

public class NetworkManager
{
    public enum NetType
    {
        INTERNET, INTRANET
    }
    public static NetType CheckIntranetOrInternet(string targetIP)
    {
        string[] targetIPSections = targetIP.Split('.');
        /// IP地址中,有三段地址專門用於私網的規劃,不能被用於網際網路上的連線如下
        /// Class A:10.0.0.0-10.255.255.255
        if (targetIPSections[0] == "10") {
            return NetType.INTRANET;
        }
        /// Class B:172.16.0.0-172.31.255.255
        if (targetIPSections[0] == "172")
        {
            int targetIPSecondSection = Convert.ToInt16(targetIPSections[1]);
            if (targetIPSecondSection >= 16 && targetIPSecondSection <= 31)
            {
                return NetType.INTRANET;
            }
        }
        /// Class C:192.168.0.0-192.168.255.255
        if (targetIPSections[0] == "192" && targetIPSections[1] == "168")
        {
            return NetType.INTRANET;
        }
        return NetType.INTERNET;
    }
}

CheckIntranetOrInternet 方法的參數型態其實有兩個選項為 Request 或 string,因為我習慣寫單元測試來覆蓋邏輯,string 會是比較好的選擇。
另一個為列舉,因為CheckIntranetOrInternet 方法的回傳值為內網或外網。
很多人會使用常數但我通常使用列舉來取代常數,特別是列舉可以清楚的規範且說明本身的意義

Result

這邊使用單元測試來測試邏輯,注意這邊並沒有覆蓋到所有邏輯。

[TestMethod]
public void CheckIntranetOrInternet_CheckInternet()
{
    Assert.AreEqual(NetworkManager.NetType.INTERNET, NetworkManager.CheckIntranetOrInternet("9.0.0.0"));
    Assert.AreEqual(NetworkManager.NetType.INTERNET, NetworkManager.CheckIntranetOrInternet("11.0.0.0"));
    Assert.AreEqual(NetworkManager.NetType.INTERNET, NetworkManager.CheckIntranetOrInternet("172.15.0.0"));
    Assert.AreEqual(NetworkManager.NetType.INTERNET, NetworkManager.CheckIntranetOrInternet("172.32.255.255"));
    Assert.AreEqual(NetworkManager.NetType.INTERNET, NetworkManager.CheckIntranetOrInternet("192.167.0.0"));
    Assert.AreEqual(NetworkManager.NetType.INTERNET, NetworkManager.CheckIntranetOrInternet("192.169.255.255"));
}
[TestMethod]
public void CheckIntranetOrInternet_CheckIntranet()
{
    Assert.AreEqual(NetworkManager.NetType.INTRANET, NetworkManager.CheckIntranetOrInternet("10.0.0.0"));
    Assert.AreEqual(NetworkManager.NetType.INTRANET, NetworkManager.CheckIntranetOrInternet("10.255.255.255"));
    Assert.AreEqual(NetworkManager.NetType.INTRANET, NetworkManager.CheckIntranetOrInternet("172.16.0.0"));
    Assert.AreEqual(NetworkManager.NetType.INTRANET, NetworkManager.CheckIntranetOrInternet("172.31.255.255"));
    Assert.AreEqual(NetworkManager.NetType.INTRANET, NetworkManager.CheckIntranetOrInternet("192.168.0.0"));
    Assert.AreEqual(NetworkManager.NetType.INTRANET, NetworkManager.CheckIntranetOrInternet("192.168.255.255"));
}

 

分類
ASP.NET

[ASP.NET] 使用 Conveyor by Keyoti 讓 localhost 轉成可連結的 IP

使用ASP.NET 在本機執行“開始偵錯”時,ASP.NET 會在本機上啟動https://localhost:xxx的網站伺服器。該網站伺服器讓開發者直接檢視網頁的呈現畫面,但卻無法使用行動裝置來觀看該網頁
可以使用 Android Simulator 加上 Conveyor by Keyoti (VS plugin)來解決這個問題。
Android Simulator 透過安裝 Android Studio 或 Xamarin 後再去 AVD Manager 設定 Simulator 來取得,這邊就不再詳述。
重點為 Conveyor by Keyoti,這個套件可以方便的將 localhost 轉為 IP,可讓行動裝置透過該IP來檢視網站。
Conveyor by Keyoti 和一般的VS套件相同,使用NuGet或官網下載安裝皆可。
安裝之後的另一個重點在於修改防火牆設定,讓該套件透過指定的Port來轉址。指定的Port其實就是一開始在本機執行”開始偵錯“由ASP.NET選擇的Port。
範例如下為一個最簡單的 WebForm Example 執行 “開始偵錯” 後的畫面。

可以看到該網站的URL為 https://localhost:44358/
44358 就是在防火牆需要另外設定的 Port,設定步驟如下(參考官網)

Manually configuring your firewall
Add an inbound firewall rule allowing access to the TCP port given in the Remote URL.
1.Open Windows 'Start' and type WF.msc.
2.Click 'Inbound Rules' on the left.
3.Click 'New Rules' on the right.
4.Choose 'Port' in the new dialog, then 'Next'.
5.Select TCP, and enter the port from the Remote URL next to 'Specific local ports' (45455-45500), then 'Next'.
6.Next, and next (you may want to disable 'Public'), give it a name like 'Conveyor: web dev server access enabled'.

下方畫面為安裝完Conveyor by Keyoti 後 在Visual Studio執行”開始偵錯”的提示畫面

中間的 https://192.168.59.1:45455 就是 Conveyor by Keyoti轉址後的結果。使用 Android Simulator 連線該URL 畫面如下
 

 
完成之後就可非常方便的透過行動裝置來檢視網站畫面。
事實上在使用 Conveyor by Keyoti之前還有嘗試用過 ngrok 和 http-server。
但這兩個工具在設定及執行上都不如預期的方便,反而是 Conveyor by Keyoti 不僅安裝方便,設定也只需要調整防火牆 Port。

分類
ASP.NET Web 前端

[ASP.NET] 在TextBox輸入內容後自動跳轉到指定UI元件

需求:

有些資料欄位在UI上設計為分段或分區輸入,如下方的手機欄位分為三個區塊。

使用者希望能夠在輸入完前一個區塊後自動跳轉到後一個區塊(1跳2,2跳3)
以下使用JavaScript來實作需求,首先實作跳轉方法。

            //輸入內容到限制長度後跳轉至指定元件
            function JumpToSpecifiedItem(currentItem, specificedItem) {
                if (currentItem.value.length == currentItem.maxLength) {
                    currentItem.form.elements[specificedItem].focus();
                }
            }

方法的第一個參數為目前使用者正在輸入的UI元件,這邊是透過maxLength來判斷是否要跳轉。
第二個參數為要跳轉的目標UI元件,該元件透過呼叫focus來達到跳轉。
接著就是UI元件部分。

<label id ="userPhoneNumberLabel">手機</label>
<div class="form-inline">
<asp:TextBox runat="server" ID="userPhoneNumberFirstSection" MaxLength="4" onKeyUp="JumpToSpecifiedItem(this,'ctl00$MainContent$userPhoneNumberSecondSection')"/>
<asp:TextBox runat="server" ID="userPhoneNumberSecondSection" MaxLength="3" onKeyUp="JumpToSpecifiedItem(this,'ctl00$MainContent$userPhoneNumberThirdSection')"/>
<asp:TextBox runat="server" ID="userPhoneNumberThirdSection" MaxLength="3" placeholder="000"/>
</div>

重點為

1.要設定ID
2.要設定MaxLength(因為是透過該值來判斷是否跳轉,當然也可以使用別的值)
3.呼叫JumpToSpecifiedItem方法,第2個參數要確認實際的ID值。(透過實際網頁上點擊F12來確認)
 
 

分類
ASP.NET git 使用紀錄 Web 前端

在ASP.NET Webform專案中加入專屬的 gitignore file

不用到處搜尋 .gitignore 檔案啦,先移動到專案的根目錄再輸入以下指令


dotnet new gitignore

就會在根目錄產生 .gitignore file,內容如下


## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# Tye
.tye/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*[.json, .xml, .info]
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# Ionide - VsCode extension for F# Support
.ionide/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
##
## Visual studio for Mac
##
# globs
Makefile.in
*.userprefs
*.usertasks
config.make
config.status
aclocal.m4
install-sh
autom4te.cache/
*.tar.gz
tarballs/
test-results/
# Mac bundle stuff
*.dmg
*.app
# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# JetBrains Rider
.idea/
*.sln.iml
##
## Visual Studio Code
##
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

至於 dotnet 只是啥
請參考 https://docs.microsoft.com/zh-tw/dotnet/core/tools/dotnet

分類
ASP.NET

找不到類型或命名空間名稱 using OfficeOpenXml

xxx.aspx.cs 使用 using OfficeOpenXml 出現找不到類型或命名空間名稱錯誤。

請使用 Nuget 安裝 EPPlus。