.NET Frameworkの素敵機能をJScriptで使いたい

概要

超今更な話題だが.NET FrameworkWSHから叩く事が出来るらしい。が、残念な事に全て使える訳ではない。そしてWSHで何が使えるのかまとめてあるページも見当たらない。そこでまずProgIDとCLSIDの2つを持つ物を列挙してみる。これらは使えるかどうかは別にして叩く事は問題なく出来るはずだ。そこからExceptionとついている物を除外する。これらは例外処理なので必要ない。結論から先に言うと有用なクラスなんて殆どない。WSHから.NETライブラリを叩こうと思っても情報があまり出てこない理由がよく分かった。

注意点

まず大前提としてWSHではメソッドのoverloadなんて概念は存在しない。したがって引数の数が違うだけの同名のメソッドは普通に叩くとエラーが返る。その場合はxxx_2のように最後にアンダースコア+数字をくっつけて区別するが数字の規則性が不明。

理屈では使用可能な.NET Frameworkの各クラス

  • System.AppDomainManager
  • System.AppDomainSetup

アプリケーションドメイン関連。

.NETのArrayは容量が固定である。それに引き替えArrayListは容量が動的に変化する。配列ではなくコレクションだったりlengthがCountだったりと違いはあるが感覚的にいうとこっちの方がJScriptで言う所の配列に近い。だからといってこれをわざわざ使う理由も思い当たらないが。

var arylist = new ActiveXObject("System.Collections.ArrayList");
arylist.add("foo");
arylist.add("bar");
for (var i=0, il=arylist.Count; i<il; i++) {
	WScript.Echo(arylist.item(i));
};
  • System.Collections.CaseInsensitiveComparer

2つのオブジェクトが等しいかどうかの判定。ArrayListのsortなんぞに使う。

  • System.Collections.CaseInsensitiveHashCodeProvider

廃止。

  • System.Collections.Hashtable

JScriptで言う所の連想配列

var hash = new ActiveXObject("System.Collections.Hashtable");
hash.add("a", "あ");
hash.add("i", "い");
hash.add("u", "う");
WScript.Echo(hash("a"));
WScript.Echo(hash.ContainsKey("a"));
WScript.Echo(hash.ContainsKey("e"));
WScript.Echo(hash.ContainsValue("あ"));
hash.Remove("a");
WScript.Echo(hash.ContainsKey("a"));
  • System.Collections.Queue

基本的に配列だが出来る事は配列の末尾への要素追加と先頭からの要素取り出し。先入れ先出しと表現するがつまり先頭から順番に処理していく方式。

var queue = new ActiveXObject("System.Collections.Queue");
queue.Enqueue("foo");//fooを配列末尾に追加
queue.Enqueue("bar");//barを配列末尾に追加
WScript.Echo(queue.Count);//配列の要素数は2
WScript.Echo(queue.Peek());//配列の先頭fooを返す
queue.Dequeue();//配列の先頭を削除
WScript.Echo(queue.Peek());//配列の先頭barを返す
WScript.Echo(queue.Count);//配列の要素数は1

とまあここまで書いておいてなんだが普通の配列で別に困らない。要は予想外の挙動をする心配のない、扱いが単純な配列。

  • System.Collections.SortedList

常にkeyでsortされている連想配列。ちょっと変わってるのは配列のようにindexでもアクセス可能という点。これは使い所がありそう。

var hash = new ActiveXObject("System.Collections.SortedList");
hash.Add("i", "い");
hash.Add("a", "あ");
hash.Add("u", "う");
WScript.Echo(hash("a"));//普通にkeyでアクセス
for (var i=0, il=hash.Count; i<il; i++) {
	WScript.Echo(hash.GetKey(i));//keyを取得
	WScript.Echo(hash.GetByIndex(i));//valueを取得
};

ループ部分は「a, あ, i, い, u, う」とsortされて表示される。

  • System.Collections.Stack

基本的に配列だが出来る事は末尾への要素追加と末尾からの要素取り出し。後入れ先出しと表現するがつまり要素を積み上げて行く方式。Queueと似ているがこちらは常に配列末尾が処理対象。

  • System.ContextStaticAttribute

staticな変数を複数のコンテキスト間で共有するかどうかのフラグ。

  • System.Data.SqlClient.SQLDebugging

SQL Server向けの物。たぶんデバッグ用のクラスなんだろう。説明にもコードから呼ばれる事を想定してないとはっきり書いてある。

  • System.Diagnostics.Debugger
  • System.Diagnostics.DebuggerHiddenAttribute
  • System.Diagnostics.DebuggerNonUserCodeAttribute
  • System.Diagnostics.DebuggerStepperBoundaryAttribute
  • System.Diagnostics.DebuggerStepThroughAttribute
  • System.Diagnostics.StackFrame
  • System.Diagnostics.StackTrace
  • System.Diagnostics.SymbolStore.SymDocumentType
  • System.Diagnostics.SymbolStore.SymLanguageType
  • System.Diagnostics.SymbolStore.SymLanguageVendor

ここまで全てデバッグ関連。

  • System.EnterpriseServices.CompensatingResourceManager.ClerkMonitor
  • System.EnterpriseServices.CompensatingResourceManager.Compensator

トランザクション処理関連。

  • System.EnterpriseServices.Internal.AppDomainHelper
  • System.EnterpriseServices.Internal.AssemblyLocator
  • System.EnterpriseServices.Internal.ClientRemotingConfig
  • System.EnterpriseServices.Internal.ClrObjectFactory
  • System.EnterpriseServices.Internal.ComManagedImportUtil
  • System.EnterpriseServices.Internal.ComSoapPublishError
  • System.EnterpriseServices.Internal.GenerateMetadata
  • System.EnterpriseServices.Internal.IISVirtualRoot
  • System.EnterpriseServices.Internal.Publish
  • System.EnterpriseServices.Internal.ServerWebConfig
  • System.EnterpriseServices.Internal.SoapClientImport
  • System.EnterpriseServices.Internal.SoapServerTlb
  • System.EnterpriseServices.Internal.SoapServerVRoot
  • System.EnterpriseServices.Internal.SoapUtility
  • System.EnterpriseServices.RegistrationConfig
  • System.EnterpriseServices.RegistrationHelper
  • System.EnterpriseServices.RegistrationHelperTx

COM+コンポーネントを叩く為の物。

  • System.EventArgs

eventデータを扱うクラス。

  • System.FlagsAttribute

列挙体を扱うクラスだが列挙体の宣言が無理そう。

  • System.Globalization.DateTimeFormatInfo

datetimeオブジェクトのformatを定義するクラス。

  • System.Globalization.StringInfo

文字列の反復処理に使うクラス。文字列を1文字ずつforループで回す様な物。利点はサロゲートペアが扱えるという程度。

  • System.Globalization.NumberFormatInfo

数値のformatを定義するクラス。

  • System.Globalization.GregorianCalendar
  • System.Globalization.HebrewCalendar
  • System.Globalization.HijriCalendar
  • System.Globalization.JapaneseCalendar
  • System.Globalization.JulianCalendar
  • System.Globalization.KoreanCalendar
  • System.Globalization.TaiwanCalendar
  • System.Globalization.ThaiBuddhistCalendar

文化固有の暦に関するクラス。このクラスからdatetimeオブジェクトを作るのに少々癖がある。使いにくい。

var date = new ActiveXObject("System.Globalization.JapaneseCalendar").ToDateTime(2016, 6, 27, 0, 0, 0, 0);
WScript.Echo(new ActiveXObject("System.Text.StringBuilder").AppendFormat("{0:yyyy-MM-dd}", date).ToString());

としてしまうとyearに4004年が入ってる。JapaneseCalendarだからだね。28と入れるとうまく2016が返ってくるが年号を何処で判断してるのかよく分からない。

  • System.IO.MemoryStream
  • System.IO.StringWriter

MemoryStreamはストリームからメモリ上にデータを読み込む。StringWriterは文字列をストリームに書き込む。しかしこれだけではどうしようもないので叩く事はまずない。

  • System.MTAThreadAttribute

マルチスレッド関連クラス。

  • System.NonSerializedAttribute

変数のシリアル化を防止するフラグ。

  • System.Object

そのまんまオブジェクトを規定したクラス。これを単独で叩く事はない気がする。

  • System.ObsoleteAttribute

この属性が付いたクラスを叩くとコンパイルエラーを返すようになる。不必要な古いクラスに使う。クラス全体をコメントアウトするようなもんですな。

  • System.ParamArrayAttribute

メソッドの引数を配列で指定する。コードから直接叩くことはない。

  • System.Random

見ての通り乱数を生成する。JScriptにだってMath.randomがあるがこっちはもうちょっと使い勝手が良い。

var random = new ActiveXObject("System.Random");
WScript.Echo(random.Next());//0以上のランダムな整数を返す
WScript.Echo(random.Next_3(10));//指定した最大値より小さい0以上のランダムな整数を返す
WScript.Echo(random.Next_2(0, 10));//指定した範囲内のランダムな整数を返す

_3とか_2が付いているが冒頭で説明したoverloadメソッドの処理。

  • System.Reflection.AssemblyName
  • System.Reflection.AssemblyNameProxy

AssemblyNameはアセンブリの一意のIDを設定する。AssemblyNameProxyはremoteオブジェクトに渡すAssemblyName。アセンブリとはコンパイル済みのexe及びdll群。COMコンポーネントみたいな物ですな。

  • System.Reflection.ObfuscationAttribute

コードの難読化に関するクラス。デコンパイル対策。

  • System.Runtime.CompilerServices.CallConvCdecl
  • System.Runtime.CompilerServices.CallConvFastcall
  • System.Runtime.CompilerServices.CallConvStdcall
  • System.Runtime.CompilerServices.CallConvThiscall
  • System.Runtime.CompilerServices.CompilerGlobalScopeAttribute
  • System.Runtime.CompilerServices.DiscardableAttribute
  • System.Runtime.CompilerServices.IDispatchConstantAttribute
  • System.Runtime.CompilerServices.IUnknownConstantAttribute
  • System.Runtime.CompilerServices.MethodImplAttribute
  • System.Runtime.CompilerServices.NativeCppClassAttribute

コンパイラ関連クラス。

  • System.Runtime.Hosting.ApplicationActivator

アセンブリのアクティブ化に関するクラス。

  • System.Runtime.InteropServices.ComConversionLossAttribute
  • System.Runtime.InteropServices.ComImportAttribute
  • System.Runtime.InteropServices.ComRegisterFunctionAttribute
  • System.Runtime.InteropServices.ComUnregisterFunctionAttribute
  • System.Runtime.InteropServices.InAttribute
  • System.Runtime.InteropServices.OptionalAttribute
  • System.Runtime.InteropServices.OutAttribute
  • System.Runtime.InteropServices.PreserveSigAttribute
  • System.Runtime.InteropServices.RegistrationServices
  • System.Runtime.InteropServices.RuntimeEnvironment
  • System.Runtime.InteropServices.SetWin32ContextInIDispatchAttribute
  • System.Runtime.InteropServices.TypeLibConverter

COMコンポーネントなどの呼び出し関連クラス。

  • System.Runtime.Remoting.Channels.ClientChannelSinkStack
  • System.Runtime.Remoting.Channels.ServerChannelSinkStack
  • System.Runtime.Remoting.Channels.TransportHeaders
  • System.Runtime.Remoting.Contexts.Context
  • System.Runtime.Remoting.Contexts.SynchronizationAttribute
  • System.Runtime.Remoting.InternalRemotingServices
  • System.Runtime.Remoting.Lifetime.ClientSponsor
  • System.Runtime.Remoting.Lifetime.LifetimeServices
  • System.Runtime.Remoting.Messaging.OneWayAttribute
  • System.Runtime.Remoting.Messaging.RemotingSurrogateSelector
  • System.Runtime.Remoting.Metadata.SoapAttribute
  • System.Runtime.Remoting.Metadata.SoapFieldAttribute
  • System.Runtime.Remoting.Metadata.SoapMethodAttribute
  • System.Runtime.Remoting.Metadata.SoapParameterAttribute
  • System.Runtime.Remoting.Metadata.SoapTypeAttribute
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapAnyUri
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapBase64Binary
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDate
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDateTime
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDay
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDuration
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapEntities
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapEntity
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapId
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapIdref
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapIdrefs
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapInteger
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapLanguage
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonthDay
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapName
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNcName
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNegativeInteger
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNmtoken
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNmtokens
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNonNegativeInteger
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNonPositiveInteger
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNormalizedString
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapNotation
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapPositiveInteger
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapQName
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapTime
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapToken
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapYear
  • System.Runtime.Remoting.Metadata.W3cXsd2001.SoapYearMonth
  • System.Runtime.Remoting.ObjRef
  • System.Runtime.Remoting.Proxies.ProxyAttribute
  • System.Runtime.Remoting.Services.EnterpriseServicesHelper
  • System.Runtime.Remoting.Services.TrackingServices

リモート処理に関するクラス。

  • System.Runtime.Serialization.FormatterConverter
  • System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
  • System.Runtime.Serialization.Formatters.InternalRM
  • System.Runtime.Serialization.Formatters.SoapFault
  • System.Runtime.Serialization.Formatters.SoapMessage
  • System.Runtime.Serialization.ObjectIDGenerator
  • System.Runtime.Serialization.OnDeserializedAttribute
  • System.Runtime.Serialization.OnDeserializingAttribute
  • System.Runtime.Serialization.OnSerializedAttribute
  • System.Runtime.Serialization.OnSerializingAttribute
  • System.Runtime.Serialization.OptionalFieldAttribute
  • System.Runtime.Serialization.SurrogateSelector

シリアル化および逆シリアル化に関するクラス。

  • System.Security.AllowPartiallyTrustedCallersAttribute

アクセス権限に関するクラス。

  • System.Security.Cryptography.CryptoConfig
  • System.Security.Cryptography.CspParameters
  • System.Security.Cryptography.DESCryptoServiceProvider
  • System.Security.Cryptography.DSACryptoServiceProvider
  • System.Security.Cryptography.DSASignatureDeformatter
  • System.Security.Cryptography.DSASignatureFormatter
  • System.Security.Cryptography.FromBase64Transform
  • System.Security.Cryptography.HMACMD5
  • System.Security.Cryptography.HMACRIPEMD160
  • System.Security.Cryptography.HMACSHA1
  • System.Security.Cryptography.HMACSHA256
  • System.Security.Cryptography.HMACSHA384
  • System.Security.Cryptography.HMACSHA512
  • System.Security.Cryptography.MACTripleDES
  • System.Security.Cryptography.MD5CryptoServiceProvider
  • System.Security.Cryptography.PKCS1MaskGenerationMethod
  • System.Security.Cryptography.RC2CryptoServiceProvider
  • System.Security.Cryptography.RijndaelManaged
  • System.Security.Cryptography.RIPEMD160Managed
  • System.Security.Cryptography.RNGCryptoServiceProvider
  • System.Security.Cryptography.RSACryptoServiceProvider
  • System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter
  • System.Security.Cryptography.RSAOAEPKeyExchangeFormatter
  • System.Security.Cryptography.RSAPKCS1KeyExchangeDeformatter
  • System.Security.Cryptography.RSAPKCS1KeyExchangeFormatter
  • System.Security.Cryptography.RSAPKCS1SignatureDeformatter
  • System.Security.Cryptography.RSAPKCS1SignatureFormatter
  • System.Security.Cryptography.SHA1CryptoServiceProvider
  • System.Security.Cryptography.SHA1Managed
  • System.Security.Cryptography.SHA256Managed
  • System.Security.Cryptography.SHA384Managed
  • System.Security.Cryptography.SHA512Managed
  • System.Security.Cryptography.SignatureDescription
  • System.Security.Cryptography.ToBase64Transform
  • System.Security.Cryptography.TripleDESCryptoServiceProvider
  • System.Security.Cryptography.X509Certificates.X509Certificate

MD5SHA1などのハッシュ化に関するクラス。これはそこそこ使えるかと思いきや引数をバイト列で渡さないといけない。おまけに返り値もバイト列なので16進数化の処理が必要。ファイルのバイト列はADODB.Streamで文字列のバイト列はSystem.Text.UTF8Encodingなどでそれぞれ取得出来るが、そこまでしてハッシュを扱う必要があるケースがあるのか微妙。

//fileのハッシュを取得
//バイト列を取得
var ado = new ActiveXObject("ADODB.Stream");
ado.Type = 1;
ado.Open();
ado.loadFromFile(filename);
var bytes = ado.read();
ado.Close();
//md5を計算
var md5 = new ActiveXObject("System.Security.Cryptography.MD5CryptoServiceProvider");
md5.ComputeHash_2(bytes);
//16進数に変換
var element = new ActiveXObject("Msxml2.DOMDocument").createElement("temp");
element.dataType = "bin.hex";
element.nodeTypedValue = md5.Hash;
WScript.Echo(element.text);

//文字列のハッシュを取得
//バイト列を取得
var bytes = new ActiveXObject("System.Text.UTF8Encoding").GetBytes_4("0123456789abcdef");
//以下は上記と同じ
//md5を計算
var md5 = new ActiveXObject("System.Security.Cryptography.MD5CryptoServiceProvider");
md5.ComputeHash_2(bytes);
//16進数に変換
var element = new ActiveXObject("Msxml2.DOMDocument").createElement("temp");
element.dataType = "bin.hex";
element.nodeTypedValue = md5.Hash;
WScript.Echo(element.text);

この項目はMsxml2.DOMDocumentのdataType ってなによ?も参照の事。

  • System.Security.HostSecurityManager

アプリケーションドメインのセキュリティに関するクラス。

  • System.Security.Permissions.GacIdentityPermission
  • System.Security.Permissions.HostProtectionAttribute
  • System.Security.Policy.AllMembershipCondition
  • System.Security.Policy.ApplicationDirectoryMembershipCondition
  • System.Security.Policy.ApplicationTrust
  • System.Security.Policy.Evidence
  • System.Security.Policy.GacInstalled
  • System.Security.Policy.GacMembershipCondition
  • System.Security.Policy.TrustManagerContext
  • System.Security.SuppressUnmanagedCodeSecurityAttribute
  • System.Security.UnverifiableCodeAttribute

セキュリティ関連のクラス。

  • System.SerializableAttribute

シリアル化可能である事を示すフラグ。

  • System.STAThreadAttribute

マルチスレッドに対応してないCOMを叩く時はこれを明示しないと怒られる。

  • System.Text.StringBuilder

.NETのStringオブジェクトは内容の変更が出来ないという何だかなあ的な仕様なのでこのクラスを使って置換変更を行う。

  • System.Text.ASCIIEncoding
  • System.Text.UnicodeEncoding
  • System.Text.UTF7Encoding
  • System.Text.UTF8Encoding

エンコーディングなんだからさぞかし便利かと思いきやここでいうエンコードはバイト列への変換の事。encodeURIComponent的な物を想像してはいけない。おまけにShiftJISがない。

var encode = new ActiveXObject("System.Text.UTF8Encoding");
var bytes = encode.GetBytes_4("test");
var string = encode.GetString(bytes);
WScript.Echo(string);
  • System.Threading.Mutex
  • System.Threading.Overlapped
  • System.Threading.ReaderWriterLock
  • System.ThreadStaticAttribute

マルチスレッド関連のクラス。