Showing preview only (1,292K chars total). Download the full file or copy to clipboard to get everything.
Repository: RickStrahl/Westwind.Utilities
Branch: master
Commit: a0fa76021cb9
Files: 142
Total size: 1.2 MB
Directory structure:
gitextract_wnw4ww1a/
├── .gitattributes
├── .github/
│ └── FUNDING.yml
├── .gitignore
├── Changelog.md
├── LICENSE.md
├── Readme.md
├── Westwind.Utilities/
│ ├── .gitignore
│ ├── Configuration/
│ │ ├── AppConfiguration.cd
│ │ ├── AppConfiguration.cs
│ │ └── Providers/
│ │ ├── ConfigurationFileConfigurationProvider.cs
│ │ ├── ConfigurationProviderBase.cs
│ │ ├── IConfigurationProvider.cs
│ │ ├── JsonFileConfigurationProvider.cs
│ │ ├── StringConfigurationProvider.cs
│ │ └── XmlFileConfigurationProvider.cs
│ ├── Data/
│ │ ├── ValidationError.cs
│ │ └── ValidationErrorCollection.cs
│ ├── InternetTools/
│ │ ├── HttpClient.cs
│ │ └── SmtpClientNative.cs
│ ├── LICENSE.MD
│ ├── Properties/
│ │ ├── Resources.Designer.cs
│ │ └── Resources.resx
│ ├── SupportClasses/
│ │ ├── DelegateFactory.cs
│ │ ├── Encryption.cs
│ │ ├── Expando.cs
│ │ ├── ObjectFactory.cs
│ │ ├── PropertyBag.cs
│ │ ├── Scheduler.cs
│ │ ├── StringSerializer.cs
│ │ ├── UrlEncodingParser.cs
│ │ └── UrlParser.cs
│ ├── Utilities/
│ │ ├── AsyncUtils.cs
│ │ ├── ComObject.cs
│ │ ├── DataUtils.cs
│ │ ├── DebugUtils.cs
│ │ ├── ExensionMethods/
│ │ │ ├── DateTimeExtensions.cs
│ │ │ ├── DictionaryExtensions.cs
│ │ │ ├── LinqExtensions.cs
│ │ │ └── MemoryStreamExtensions.cs
│ │ ├── FileUtils.cs
│ │ ├── GenericUtils.cs
│ │ ├── HtmlUtils.cs
│ │ ├── HttpClientUtils.cs
│ │ ├── HttpUtils.cs
│ │ ├── HttpUtilsWebClient.cs
│ │ ├── ImageUtils.cs
│ │ ├── JsonSerializationUtils.cs
│ │ ├── KnownFolders.cs
│ │ ├── LanguageUtils.cs
│ │ ├── NetworkUtils.cs
│ │ ├── PasswordScrubber.cs
│ │ ├── ReflectionUtils.cs
│ │ ├── SecurityUtils.cs
│ │ ├── SerializationUtils.cs
│ │ ├── ShellUtils.cs
│ │ ├── StringUtils.cs
│ │ ├── TimeUtils.cs
│ │ ├── VersionUtils.cs
│ │ └── XmlUtils.cs
│ ├── Westwind.Utilities.csproj
│ ├── Westwind.Utilities.sln
│ └── publish-nuget.ps1
├── Westwind.Utilities.Data/
│ ├── Configuration/
│ │ └── SqlServerConfigurationProvider.cs
│ ├── ConnectionStringInfo.cs
│ ├── DataAccessBase.cs
│ ├── DataTableExtensions.cs
│ ├── DynamicDataReader.cs
│ ├── DynamicDataRow.cs
│ ├── LICENSE.MD
│ ├── Security/
│ │ └── UserTokenManager.cs
│ ├── SqlDataAccess.cs
│ ├── SqlUtils.cs
│ ├── Westwind.Utilities.Data.csproj
│ └── publish-nuget.ps1
├── Westwind.Utilities.Test/
│ ├── App.config
│ ├── AppConfiguration/
│ │ ├── AutoConfigFileConfigurationTests.cs
│ │ ├── ConfigurationClasses/
│ │ │ ├── AutoConfigFileConfiguration.cs
│ │ │ ├── CustomConfigFileConfiguration.cs
│ │ │ ├── DatabaseConfiguration.cs
│ │ │ ├── JsonFileConfiguration.cs
│ │ │ ├── LicenseInformation.cs
│ │ │ ├── StringConfigFileConfiguration.cs
│ │ │ └── XmlFileConfiguration.cs
│ │ ├── CustomConfigFileConfigurationTests.cs
│ │ ├── DatabaseConfigurationTests.cs
│ │ ├── JsonFileConfigurationTests.cs
│ │ ├── StringConfigurationTests.cs
│ │ └── XmlFileConfigurationTests.cs
│ ├── AsyncUtilsTests.cs
│ ├── DataUtilsTests.cs
│ ├── DynamicDataReaderTests.cs
│ ├── DynamicDataRowTests.cs
│ ├── EncryptionTests.cs
│ ├── ExpandUrlsParserTest.cs
│ ├── ExpandoTests.cs
│ ├── FileUtilsTests.cs
│ ├── HttpClientTests.cs
│ ├── HttpClientUtilsTests.cs
│ ├── HttpUtilsTests.cs
│ ├── ImagingTests.cs
│ ├── Models/
│ │ └── Entities/
│ │ ├── Customer.cs
│ │ ├── LineItem.cs
│ │ ├── Order.cs
│ │ └── WebLogEntry.cs
│ ├── NetworkUtilsTests.cs
│ ├── ObjectFactoryTests.cs
│ ├── PasswordScrubberTests.cs
│ ├── PropertyBagTest.cs
│ ├── ReflectionUtilsTests.cs
│ ├── SanitizeHtmlTests.cs
│ ├── ShellUtilsTests.cs
│ ├── SmtpClientNativeTests.cs
│ ├── SqlDataAccessFoxProTests.cs
│ ├── SqlDataAccessMySqlTests.cs
│ ├── SqlDataAccessSqlLiteTests.cs
│ ├── SqlDataAccessTests.cs
│ ├── StrExtractTest.cs
│ ├── StringSerializerTests.cs
│ ├── StringUtilsTests.cs
│ ├── SupportClasses/
│ │ ├── DebugModes.cs
│ │ ├── JsonNetSerializationUtilsTests.cs
│ │ └── TestHelpers.cs
│ ├── SupportFiles/
│ │ ├── _MyJsonConfiguration.json
│ │ └── customers.DBF
│ ├── TimeUtilsTests.cs
│ ├── UrlEncodingParserTests.cs
│ ├── UserTokenManagerTests.cs
│ ├── VersionExtensionsTests.cs
│ ├── Westwind.Utilities.Test.csproj
│ ├── Westwind.Utilities.Test.dll.config
│ ├── WindowsUtilsTests.cs
│ ├── XmlUtilsTest.cs
│ └── _TestConfigurationSettings.cs
├── Westwind.Utilities.Windows/
│ ├── LICENSE.MD
│ ├── Utilities/
│ │ ├── ComObject.cs
│ │ ├── HtmlUtils.cs
│ │ └── WindowsUtils.cs
│ ├── Westwind.Utilities.Windows.csproj
│ ├── Westwind.Utilities.Windows.sln
│ └── publish-nuget.ps1
├── Westwind.Utilities.sln
└── Westwind.Utilities.slnx
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
================================================
FILE: .github/FUNDING.yml
================================================
github: RickStrahl
custom: "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=K677THUA2MJSE&source=url"
custom: "https://store.west-wind.com/product/donation"
================================================
FILE: .gitignore
================================================
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
Test/
UnitTestProject2/
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
project.fragment.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.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
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# 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
# TODO: 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
*.snupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable 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
# 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
node_modules/
orleans.codegen.cs
# 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
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# 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/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
*.saved.bak
================================================
FILE: Changelog.md
================================================
# Westwind.Utilities Changelog
## 5.3
* **HttpClientUtils.DownloadBytes/Async**
Added routine to easily download bytes from an Http server.
* **HttpClientUtils.DownloadFile/Async**
Download content directly to file from an Http Server.
* **Additional HttpClientUtils Settings Object Response Properties**
Provided several helper properties to facilitate common header access. Explicitly exposed new Response properties: `ResponseContentType`, `ResponseContentLength`, `ResponseContentHeaders` and `ResponseHeaders`.
### 5.2
* **Add .NET 10 Target**
Change Targets to .NET 10 and .NET 8.0 (and .NET Standard and net472). Dropped .NET 9 target (handled by .NET 8.0).
* **Add HttpClientRequestSettings.AddPostKey() and AddPostFile() Methods**
You can now easily create Http Form POST variables for using `settings.RequestPostMode` and using `setting.AddPostKey()` and `settings.AddPostFile()`. You can also retrieve the PostBuffer explicitly using `settings.GetPostBuffer()` and `settings.GetPostBufferBytes()` which allows easy creation of a POST buffer you can send to a raw Http request even outside of `HttpClientUtils`. Useful utility for quick form variable encoding.
* **ImageUtils.IsImage()**
Two versions one for filename extension check, and one for binary data image signature check.
### 5.1.10
* **FileUtils.CopyFileEnsureDirectory()**
Added method that copies a file and creates the corresponding directory structure if it doesn't exist.
* **StringUtils.StripAfter()**
Method that strips text after a matched delimiter at the end of the string or returns the original string.
* **StringUtils.ReplaceLastNthInstance()**
Method that replaces the last nth instance of a sub string in an existing string.
### 5.1.6
* **FileUtils.GetRelativeFilePath()**
Compares two file paths and returns a relative path to the second file from the first. This version works with files, while the existing `GetRelativePath()` works with a base folder (slightly different behavior).
* **FileUtils.ResolvePath()**
Returns an absolute file path for a relative path and a base file or folder.
* **FileUtils.IsRelativePath()**
Checks a path string if a path is a relative path (ie. not rooted). Doesn't compare against another file, but simply checks whether the file meets the criteria for a relative Url.
* **FileUtils.TildefyUserPath()**
Replaces the user path with the `~` to make the path generic. Useful if you store file or folder info in configuration files in a shared location that can be accessed from different computers. You can use `FileUtils.ExpandPathEnvironmentVariables()` to expand the `~` in addition to environment variables.
* **Add Sync Methods to HttpClientUtils (Core only)**
Add several sync methods to the `HttpClientUtils()` helper - `DownloadString()`, `DownloadBytes()`, `DownloadStream()` to complement the async versions. These new methods are not supported for .NET Framework - where you need to use HttpUtils that use older `WebClient()` for sync operations.
* **Basic PasswordScrubber Class for Json and Sql Connections**
Added a very basic Password scrubber that attempts to scrub passwords for keys you provide. By default `password` and `pwd` are parsed but you can scrub any values that you need specifically. Two methods: `ScrubJsonValues()` and `ScrubSqlConnectionValues()`.
* **Option on FileUtils.CopyDirectory() to ignore errors**
Added option to ignore errors typically caused by locked files when copying directories. By default exceptions are thrown for file copy errors. With the switch set errors are ignored. This can be useful in scenarios where directories need to be copied where there might be some locked files in use (bound images for example) where it's OK to not copy those files.
### 5.0.9
* **Add HttpClientUtils support for .NET Framework**
The HttpClientUtils class now works on .NET Framework. It was previously only supported on .NET Core.
* **Add FileUtils.ReadAllBytesAsync() and WriteAllBytesAsync()**
Support functions for .NET Framework to support missing `System.IO.File` async methods.
* **Update Microsoft.Data.SqlClient**
Microsoft finally fixed the vulnerability related Azure dependencies in Microsoft.Data.SqlClient.
### 5.0.7
* **StringUtils 'Many' Operations**
String extension methods that operate on 'many' values for various string operations: `EqualsMany()`, `ContainsMany()`, `StartsWithMany()`, `ReplaceMany()`. The finds
* **AsyncUtils.DelayExecution()**
Added a couple of handlers that allow delayed code execution off a timer. Pass in an Action to execute, a timeout and an optional error handler.
* **AsyncUtils.Timeout() and TimeoutWithResult()**
Task extension method that provide for timing out Task execution. Two overloads one that returns true/false and one that returns a value (similar to `Task.WaitAsync()` new in .NET 8.0 but not available prior).
* **VersionUtils.FormatVersion()**
A generic and configurable string formatter that makes it easier to display version strings more consistently by specifying the number of tokens to display and which `.0` tokens to trim (and leave).
* **Fix: UrlEncodingParser Null Value Handling**
Fix null values in the query collection from blowing up the parser and string output. Null values explicitly assigned or missing values now return `string.Empty` - no more null returns.
### 5.0
**Breaking Changes**
* **New Westwind.utilities.Windows Package**
Added a new package that moves the `WindowsUtils` class to the new package. Also a copied version of `HtmlUtils` has moved to this pacakge as it includes `System.Web` references. Several legacy, System.Web specific methods have been removed from `HtmlUtils` in the core library and now only exist in the Windows library:
* HtmlUtils.ResolveUrl()
* HtmlUtils.ImageRef()
* HtmlUtils.Href()
* **Westwind.Utilities.Data now uses `Microsoft.Data.SqlClient` for NETFX**
Switched over for both the netStandard and net472 targets to use `Microsoft.Data.SqlClient` for consistency. This will increase the size of distribution but it allows for support for latest SQL features.
* **Removed Westwind Logging**
The old legacy logging library has been removed as it was severely data and introduced nasty dependencies. Apps that depend on it can stick to 4.x versions or move to some more modern logging abstraction.
### 4.0.21
* **StringUtils.GetLastCharacters()**
Retrieves up to the last n characters from the end of a string.
* **WindowsUtils.IsUserAnAdmin()**
Determines if user is an Administrator on Windows.
* **StringUtils.ToBase64String()/FromBase64String()**
Helper method that simplifies converting strings to and from Base64 without having to go through the intermediary byte conversion explicitly.
* **Fix: HttpClientUtils HasErrors Result**
Fix `HttpClientRequestSettings.HasErrors` when requests hard fail due to network issues.
### 4.0
* **Refactor Data Utilities into separate Westwind.Utilities.Data Library**
Due to the large required SQL Data dependencies on .NET Core, we've removed the data access components from this library and separated them out into a `Westwind.Utilities.Data`. Functionality remains the same, but now requires adding this second library in order to use the data features. This keeps the original library dependencies small even on .NET Standard/Core.
* **StringUtils.Occurs()**
Counts the number of times a character or substring occurs in a given string.
* **StringUtils.StringToStream() and StringUtils.StreamToString()**
Converts a string to a `MemoryStream` with Encoding, or reads a string from an input stream.
* **StringUtils.GetMaxCharacters()**
String extension method that retrieves a string with n characters max optionally from a specified start position.
* **Fix StringSerializer Null Values**
Fix null values for string properties that were returning the string `"null"` instead of an actual `null`.
* **Fix: AppConfiguration.Write() if Provider is not configured**
Fix `Write()` method when the provider is not configured yet by loading Provider via `OnCreateDefaultProvider()` rather than doing a full initialize which reloaded the config data. This preserves the data and only loads the provider and was the cause of occasional failures if assigning a new configuration object completely.
* **Remove .NET 4.0 Target**
We've removed the .NET 4.0 target, leaving `net462` and `netstandard2.0` as the two targets for this library.
* **Update Newtonsoft.Json**
Update to latest JSON.NET Nuget package.
* **ReflectionUtils.ShallowClone()**
Helper method to clone an object using shallow value cloning. Means: Single level clone only. Value types are cloned, References are just attached as is. Basically calls private `MemberwiseClone()` method on the source object.
* **FileUtils.GetShortPath()**
Returns a short path that uses 8.3 character file syntax. This allows shortening long paths that exceed `MAX_PATH` to work with APIs that don't support long file or extended path syntax.
* **TimeUtils.IsBetween**
Add helper extension method to DateTime and TimeSpan for checking for date between a high and low date.
* **Fix TimeUtils ShortDate Formatting**
Make short date formatting locale aware. Add optional date separator parameter.
* **AsyncUtils.FireAndForget() / Task.FireAndForget()**
Added a couple of extension methods that allow for safe execution of async methods by explicitly continuing the task if an exception occurs. Works around hte issue that exceptions can otherwise wait around to be fired until the finalizer runs which can cause unexpected failures.
* **JsonSerializationUtils CamelCase Support for Serialization**
You can now specify an additional optional parameter `camelCase` on the `Serialize()` and `serializeToFile()` methods that applies camelCasing to JSON output, instead of the exact case output used by default.
* **StreamExtensions.AsString()**
Returns the contents of a stream as a string with optional encoding.
* **MemoryStreamExtensions.AsString()**
Helper extension method that lets you convert a memory stream to a string with optional Encoding.
### 3.0.55
<small>March 12, 2021</small>
* **NetworkUtils.IsLocalIpAddress**
Checks to see if an IP Address is a local address by checking for localhost/loopback and checking host IP (if valid) against local IP Addresses.
* **Fix: Replace Timeout with TimeoutMs**
Replace Timeout property with TimeoutMs to fix issues with sub-1000ms request timeouts. Conversions from calling applications often resulted in invalid values being assigned due to the conversion from milliseconds to seconds. The existing Timeout property (in seconds) is marked `[Obsolete]` but remains available for use.
* **ValidationErrors.HasErrors Property**
Added a `HasErrors` property to make the check for errors more explicit than `ValidationErrors.Count > 0`.
### 3.0.51
<small>February 17, 2021</small>
* **Switch Data Access to Microsoft.Data.SqlClient**
Switch the Sql Client library to the new `Microsoft.Data.SqlClient` for .NET Standard and .NET Standard. The full framework libs continue using `System.Data.SqlClient` native in the framework `System.Data` assembly.
* **Add HttpUtils.DownloadImageToFile\Async()**
Added method to download images from a URL and save them to file. Fixes up the file extension depending on the mime type of the Web request.
* **ImageUtils.GetExtensionFromMediaType()**
This method retrieves a file extension based on a media/content type. Commonly needed if you're downloading images from the Web to determine what type of file needs to be created.
* **HttpUtils.DownloadBytes\Async() for Binary data**
Http helper to download HTTP contents into a `byte[]`.
* **ComObject Wrapper for .NET Core**
Added `ComObject` class that allows wrapping COM objects in .NET Core so they work with late binding since .NET Core doesn't support `dynamic` to access COM objects. This class implements `DynamicObject` and retrieves missing member data via Reflection simplifying COM access in .NET Core.
* **Fix issues with StringUtils.TextAbstract() & Line Breaks**
Fix behavior of text abstract with line breaks not being turned into spaces consistently. Also check for null.
* **ShellUtils.OpenUrl() - Platform agnostic Browser Opening**
This method opens a URL in the system browser on Windows, Mac and Linux.
* **WindowsUtils.TryGetRegistryKey() Signature Change**
Change the signature to TryGetRegistryKey() to pass in the base key into the optional `baseKey` parameter. The previously used `bool` value was not effective if something other than HKLM or HKCU was used.
Note: this is a potentially breaking change.
* **FileUtils.HasInvalidPathCharacters()**
Added a function that checks paths for invalid characters. Uses default invalid character list, plus you can pass in additional characters to be deemed invalid.
> ### Breaking Changes for 3.0.50
> * **WindowUtilities.TryGetRegistryKey() parameter Change**
The baseKey parameter replaces a `bool` parameter. Signature for most scenarios will stay the same if the parameter was omitted but the new version breaks binary compatibility which a simple recompile should fix.
>
> * **Renamed `DataAccessBase.Find<T>()` KeyLookup overload**
> Renamed this method to `FindKey<T>()` to avoid ambiguous reference errors. This will break compilation if the method is used for key lookups. You might also want to do a check for all `.Find()` usage to ensure it's not unintentionally firing `Find<T>()` when `FindKey<T>()` is desired.
### 3.0.40
*May 22nd, 2020*
* **ReflectionUtils.InvokeEvent()**
Method that allows triggering of events even from outside of the host class using Reflection without requiring a wrapper `OnEvent()` handler method to force operation into the original definition's class.
* **XmlIgnore for XML Configuration**
You can now specify `[XmlIgnore]` for properties when using XML configure to have properties ignored when serializing, deserializing. This worked for external files before, but not for config file configuration in full framework.
* **FileUtils.ShortFilename**
Turn a Windows long filename into a short filename. Use to get around 256 MAX_PATH limitations for some operations.
* **SqlDataAccess.DoesTableExist()**
Added a method that checks to see if a table exist in the current database.
* **DataUtils.RemoveBytes()**
Removes a sequence of bytes from a byte array.
* **Fix: TextAbstract() remove Line Breaks**
`TextAbstract()` now removes line breaks when creating the the abstract and replaces them with spaces.
* **Fix: FileUtils.SafeFilename trailing Spaces**
Fix trailing spaces issue in SafeFilename, when last character is a replacement character.
* **Fix: Missing resources**
Project conversion appears to have removed resx resources for localization resulting in empty messages for some operations.
* **Fix: Xml Logging Adapter with Empty File**
Fix error when creating a new XML error log and appending the XML closing tag.
### 3.0.30
*August 28th, 2019*
* **Add some Async Methods to DataAccessBase**
Add `ExecuteNonQueryAsync`, `ExecuteScalarAsync`, `InsertEntityAsync` methods. More to come in future updates.
* **StringUtils.Right() Method**
Add method to retrieve the rightmost characters from a string.
* **Add TextLogAdapter**
Add a log adapter for plain text output.
* **Update: ShellUtils.ExecuteProcess with Output Capture**
Add overload for `ShellUtils.ExecuteProcess()` that allows passing in a string that is filled with the output generated from execution of a command line tool or an optional `Action<string>` that can intercept output as it's generated and fire your own capture code.
### 3.0.28
*June 23rd, 2019*
* **DataUtils.IndexOfByteArray()**
Small helper that finds a array of bytes or a string in an buffer of bytes and returns an index. Similar to `Span.IndexOf` but works in environments where not available, and also supports searching for decoded strings.
* **Fix: HtmlUtils.HtmlEncode()**
Handle encoding of single quotes `'` as well as double quotes. Also marked this method as obsolete (despite the PR fix :-)) since this is handled by `System.Net.WebUtility` class now (since .NET 4.0).
* **Fix: ReflectionUtils.CallMethodExCom()**
Fix bug when traversing object hierarchy.
* **Add .NET 4.8 to WindowsUtilities.GetDotnetVersion()**
Add support for .NET 4.8 and also fix an errant `Debug.Writeline()` in this method.
### 3.0.24
*February 28th, 2019*
* **Fix: HtmlUtils.SanitizeHtml() for multi-line**
Fix SanitizeHtml() function to work across line breaks for a tag.
* **XmlUtils.XmlString()**
Create an XML encode string for elements or attributes.
* **FileUtils.DeleteFiles()**
Added routine that deletes files in a folder based on a path spec, optionally recursively.
* **DebugUtils.GetCodeWithLineNumbers()**
Add method that creates lines with line numbers appended. Useful for displaying source code.
* **StringUtils.Truncate()**
Added method that truncates a string if it exceeds a certain number of characters.
### 3.0.20
*September 6th, 2018*
* **HtmlUtils.SanitizeHtml()**
RegEx based HTML sanitation that handles the most common script injection scenarios for `<script>`,`<iframe>`,`<form>` etc. tags, `javascript:` script embeds and `onXXX` DOM element event handlers.
* **StringUtils.IndexOfNth() and .LastIndexOfNth()**
Helper that returns an index for the nTh occurrance of a matched character in string.
* **ShellUtils.OpenInExplorer()**
Allows opening an Explorer Window for for a folder or file in a folder. (full framework only)
* **ShellUtils.ExecuteProcess()**
Wrapper around Process.Start() that captures exceptions and handles a few common scenarios simply including execution with timeout and presetting the Window. (full framework only)
* **ShellUtils.OpenTerminal()**
Opens a shell window using Powershell or Command Prompt in a given pre-selected folder. (full framework only)
* **WindowsUtils.GetWindowsVersion() and GetDotnetVerision()**
Helpers that retrieve a display version string that can be used by an application to display the Windows and .NET version in a meaningful way.
* **HttpClient.HttpVerb Property**
Added HttpVerb property directly to the HttpClient object. This replaces the previous approach that required `CreateHttpWebRequest()` followed by setting `client.WebRequest.Method` explicit.
* **LanguageUtils.IgnoreErrors()**
Helper functions that allows you to execute a block of code explicitly with a wrapped around try/catch block. Two version - one that returns true or false, one that allows the operation to return a result.
* **ImageUtils.AdjustAspectRatio**
Image helper routine that crops an image according to a new aspect ratio from the center outward. Useful for creating uniform images in uploaded files for previews. Also optionally resizes the adjusted image to a fixed width or height.
### 3.0.10
*January 9th, 2018*
* **FileUtils.AddTrailingSlash()**
Adds a trailing OS specific slash to the end of a path if there isn't one.
* **FileUtils.ExpandPathEnvironmentVariables()**
Method that checks for %envVar% embedded in the path and tries to evaluate the value from environment vars.
* **Fix: FileUtils.GetRelativePath()**
Fix Uri usage with local file paths.
### 3.0.4
*November 12th, 2017*
* **DataUtils.GetSqlProviderFactory()**
Add helper function to allow retrieving a SQL Provider factory without having to take a dependency on the assembly that contains the provider. This is provided for .NET Standard 2.0 which doesn't have `DbProviderFactories.GetFactory()` support that provides this functionality.
* **FileUtils.NormalizePath() and NormalizeDirectory()**
Added function to normalize a path for the given platform it runs on - forward backward slashes. Mainly useful for legacy code that explicitly formatted paths to Windows formatting. NormalizeDirectory ensures a trailing path slash on a path.
* **FileUtils.GetCompactPath()**
Added to return a filename that is trimmed in the middle with elipsis for long file names. You specify a max string length the and the method truncates accordingly.
* **FileUtils.SafeFileName() Updates**
`SafeFileName()` now has options for the replacement character for invalid characters replaced as well (blank by default) as well as for spaces (which by default are not stripped).
### 3.0.1
*August 5th, 2017*
* **Support for .NET Core 2.0**
Version 3.0 adds support for .NET Core 2.0. Most features of the toolkit have been carried forward, but some features like configuration using standard .NET Configuration files is not available in .NET Core. There are a few other features that are not available.
* **StringUtils.TokenizeString() and DetokenizeString()**
Added a function that looks for a string pattern based on start and end characters, and replaces the text with numbered tokens. DetokenizeString() then can reinsert the tokens back into the string. Useful for parsing out parts of string for manipulation and then re-adding the values edited out.
* **StringUtils.GetLines() optional maxLines Parameter**
Added an optional parameter to `GetLines()` to allow specifying the number of lines returned. Internally still all strings are parsed first, but the result retrieves only the max number of lines.
* **StringUtils.GenerateUniqueId() additional characters**
You can now add additional character to be included in the unique ID in addition to numbers and digits. This makes the string more resilient to avoid dupe values.
* **Add support for HMAC hashing in Encryption.ComputeHash()**
HMAC provides a standardized way to introduces salted values into hashes that results in fixed length hashes are not vulnerable to length attacks. ComputeHash now exposes HMAC versions of the standard hash algorithms.
* **Add Encryption.EncryptBytes() and Encryption.DecryptBytes()**
Added additional overloads that allow passing byte buffer for the encryption key to make it easier to work with OS data API.
* **Add SecureString Overloads to Encrypt/Decrypt Functions**
The various implementations of Encrypt/DecryptString/Bytes now work with SecureString values for the encryption key to minimize holding unencrypted keys in memory as string for all but the immediate encrypt/decrypt operations.
* **DataUtils.DataTableToObjectList<T>**
You can now convert a data table to a strongly typed list with this new function.
* **XmlUtils.GetXmlEnum()/GetXmlBool() and XmlUtils.GetAttributeXmlBool()**
Added additional conversion methods to the XML helpers to facilitate retrieving values from XML documents more easily.
* **LinqUtils.FlattenTree**
Flattens a tree type list into a flat enumarable by letting your provide the property for the children to flatten. `var topics = topicTree.FlattenTree(t=> t.Topics);`.
* **FileUtils.CopyDirectory()**
Copies an entire directory tree to another directory. If the target exists files and folders are merged.
* **Fix: HMAC Processing in Encryption.ComputeHash()**
HMAC hash computation was broken as salt was added to the data rather than just passed to the hash generator. Fixed.
> ### Breaking Changes for 3.0
> ##### .NET Core 2.0 Version
> * ConfigurationFileProvider for Configuration is not supported
> * We recommend you switch to JsonConfiguration
> * SqlDataAccess ctor requires that you pass in a **full** connection string or SqlProvider Factory.
> * SqlDataAccess connection string names and provider names are no longer supported. (this may get fixed as additional .NET Core APIs are made available by Microsoft to support providers)
> * Encrypt.Encrypt()/Decrypt() use 24 bit keys where the old version for full framework uses 16 bit keys
> The result is that encrypted values can't be duplicated currently with .NET Core implementation. This may get fixed in later updates of .NET Core as 16 bit TripleDES keys are possibly reintroduced.
> * Encryption DataProtection API methods don't work with .NET 2.0 since those are based on Windows APIs
### 2.70
*December 15th, 2016*
* **Fix binary encoding for extended characters in Encryption class**
Binary encoding now uses UTF encoding to encrypt/decrypt strings in order to support extended characters.
* **Encryption adds support for returning binary string data as BinHex**
You can now return binary values in BinHex format in addition to the default base64 encoded string values.
* **FileUtils.GetPhsysicalPath()**
This function returns a given pathname with the proper casing for the file that exists on disk. If the file doesn't exist it
* **Fix Encoding in HttpUtils**
Fix encoding bug that didn't properly manage UTF-8 encoding in uploaded JSON content.
================================================
FILE: LICENSE.md
================================================
MIT License
===========
Copyright (c) 2012-2024 West Wind Technologies
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: Readme.md
================================================
# Westwind.Utilities

| Library | Versions and Stats |
|-------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Westwind.Utilities | <a href="https://www.nuget.org/packages/Westwind.Utilities/"></a>  |
| Westwind.Utilities.Data | <a href="https://www.nuget.org/packages/Westwind.Utilities.Data/"></a>  |
| Westwind.Utilities.Windows | <a href="https://www.nuget.org/packages/Westwind.Utilities.Windows/"></a>  |
| Documentation | <a href="https://docs.west-wind.com/westwind.utilities/"></a> |
### A general purpose utility and helper library for .NET development
Supports the following Targets:
* .NET 9.0,8.0
* .NET Standard 2.0
* .NET 4.62+
### Installation
You can install the package [from NuGet](http://nuget.org/packages/Westwind.Utilities/) using the Visual Studio Package Manager or NuGet UI:
```
PM> install-package westwind.utilities
```
As of version 4.0 the `Data` related features are located in a separate NuGet Package:
```
PM> install-package westwind.utilities.data
```
> #### Upgrading from v3 and using Data Access Features?
> If you're switching from v3 or earlier and are using the Data Access features of the library, this is a breaking change that requires you to add the new `westwind.utilities.data` package.
### What is it?
Every .NET application requires small, common and often repeated tasks. This library is a collection of those things that I commonly need on a regular basis and have compiled over the years.
* [Get it on NuGet](https://nuget.org/packages/Westwind.Utilities/)
* [Usage Documentation](https://docs.west-wind.com/westwind.utilities/_5am0u0jou.htm)
* [Class Documentation](https://docs.west-wind.com/westwind.utilities/_5am0u09dd.htm)
It includes tools for:
* [**Application Configuration**](https://docs.west-wind.com/westwind.utilities?page=_2le027umn.htm)
class to create code-first strongly typed configuration classes for your applications
* [**Lightweight ADO.NET Data Access Layer**](https://docs.west-wind.com/westwind.utilities?=page=_3ou0v2jum.htm)
ideal for components or apps that need data access but don't need the bulk of Entity Framework or similar ORM.
<small>*requires adding the `westwind.utilities.data` package.*</small>
* **General Purpose Utility Classes**:
* [StringUtils](https://docs.west-wind.com/westwind.utilities?topic=Class%20StringUtils)
* [HtmlUtils](https://docs.west-wind.com/westwind.utilities?topic=Class%20HtmlUtils)
* [ReflectionUtils](https://docs.west-wind.com/westwind.utilities?topic=Class%20ReflectionUtils)
* [SerializationUtils](https://docs.west-wind.com/westwind.utilities?topic=Class%20SerializationUtils)
* [DataUtils](https://docs.west-wind.com/westwind.utilities?topic=Class%20DataUtils)
* [FileUtils](https://docs.west-wind.com/westwind.utilities?topic=Class%20FileUtils)
* [TimeUtils](https://docs.west-wind.com/westwind.utilities?topic=Class%20TimeUtils)
* [XmlUtils](https://docs.west-wind.com/westwind.utilities?topic=Class%20TimeUtils)
* [StringSerializer](https://docs.west-wind.com/westwind.utilities?topic=Class%20StringSerializer)
* [Expando](https://docs.west-wind.com/westwind.utilities?topic=Class%20Expando)
* [PropertyBag](https://docs.west-wind.com/westwind.utilities?topic=Class%20PropertyBag)
* [Scheduler](https://docs.west-wind.com/westwind.utilities?topic=Class%20Scheduler) (for background processing)
* [Encryption](https://docs.west-wind.com/westwind.utilities?topic=Class%20Encryption)
* [HttpClient](https://docs.west-wind.com/westwind.utilities?topic=Class%20HttpClient) (HttpWebRequest wrapper)
* [HttpUtils](https://docs.west-wind.com/westwind.utilities?topic=Class%20HttpUtils) (Simple REST client helpers)
* [SmptClientNative](https://docs.west-wind.com/westwind.utilities?topic=Class%20SmtpClientNative) (SmtpClient Wrapper)
* [DelegateFactory](https://docs.west-wind.com/westwind.utilities?topic=Class%20DelegateFactory)
and much, much more.
It's worthwhile to browse through the source code or the documentation
to find out the myriad of useful functionality that is available, all
in a small single assembly.
This assembly is the base for most other West Wind libraries.
## License
This library is published under **MIT license** terms.
**Copyright © 2012-2023 Rick Strahl, West Wind Technologies**
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: Westwind.Utilities/.gitignore
================================================
###############
# folder #
###############
/**/DROP/
/**/TEMP/
/**/packages/
/**/bin/
/**/obj/
_site
================================================
FILE: Westwind.Utilities/Configuration/AppConfiguration.cd
================================================
<?xml version="1.0" encoding="utf-8"?>
<ClassDiagram MajorVersion="1" MinorVersion="1">
<Comment CommentText="<-- User implemented class
">
<Position X="2.865" Y="3.531" Height="0.255" Width="1.7" />
</Comment>
<Class Name="Westwind.Utilities.Configuration.AppConfiguration">
<Position X="0.5" Y="0.5" Width="2.25" />
<TypeIdentifier>
<HashCode>AQAAAAAAAAAEAQAAAAAAAAAgAAAAAAAAAAAAAAEAAAA=</HashCode>
<FileName>Configuration\AppConfiguration.cs</FileName>
</TypeIdentifier>
<ShowAsAssociation>
<Field Name="Provider" />
</ShowAsAssociation>
</Class>
<Class Name="Westwind.Utilities.Configuration.ConfigurationProviderBase<TAppConfiguration>">
<Position X="6.75" Y="0.5" Width="3.25" />
<TypeIdentifier>
<HashCode>AQBBAIAAAYAQAQAAAAAAAAAgAAAAAAAAAAAAIQEAAAE=</HashCode>
<FileName>Configuration\ConfigurationProviderBase.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" />
</Class>
<Class Name="Westwind.Utilities.Configuration.XmlFileConfigurationProvider<TAppConfiguration>">
<Position X="9" Y="5.25" Width="3.5" />
<TypeIdentifier>
<HashCode>QAAAAAAAgAAAAAAAAAAAAAAgAAASAAAAAAAAAAEAAAA=</HashCode>
<FileName>Configuration\XmlFileConfigurationProvider.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="Westwind.Utilities.Configuration.ConfigurationFileConfigurationProvider<TAppConfiguration>">
<Position X="0.5" Y="5.25" Width="3.75" />
<TypeIdentifier>
<HashCode>AAABAQEIQAAACAAAAAAAgAAoAAAAAQAAAAAAIAEAAAA=</HashCode>
<FileName>Configuration\ConfigurationFileConfigurationProvider.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="Westwind.Utilities.Configuration.SqlServerConfigurationProvider<TAppConfiguration>">
<Position X="4.75" Y="5.25" Width="3.75" />
<TypeIdentifier>
<HashCode>CAAAAAACAAAAAAQAAAAAgAAgAAAgAAAAACAAAQEQAAA=</HashCode>
<FileName>Configuration\SqlServerConfigurationProvider.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="Westwind.Utilities.Configuration.MyAppConfiguration">
<Position X="0.5" Y="2.75" Width="2.25" />
<TypeIdentifier>
<HashCode>AgAAAAAAAAAAASAAAAAAEAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>Configuration\AppConfiguration.cs</FileName>
</TypeIdentifier>
</Class>
<Interface Name="Westwind.Utilities.Configuration.IConfigurationProvider">
<Position X="3.75" Y="0.5" Width="2.25" />
<TypeIdentifier>
<HashCode>AQAAAIAAAYAAAQAAAAAAAAAgAAAAAAAAAAAAAQEAAAA=</HashCode>
<FileName>Configuration\IConfigurationProvider.cs</FileName>
</TypeIdentifier>
</Interface>
<Font Name="Microsoft Sans Serif" Size="8.25" />
</ClassDiagram>
================================================
FILE: Westwind.Utilities/Configuration/AppConfiguration.cs
================================================
#region License
/*
**************************************************************
* Author: Rick Strahl
* (c) West Wind Technologies, 2009-2024
* http://www.west-wind.com/
*
* Created: 09/12/2009
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
using System;
using System.Xml.Serialization;
using System.Diagnostics;
using Westwind.Utilities.Properties;
namespace Westwind.Utilities.Configuration
{
/// <summary>
/// This class provides a base class for code-first, strongly typed configuration
/// settings in .NET. It supports storing of configuration data in
/// .NET .config files, plain XML files, strings and SQL Server databases and
/// custom providers.
///
/// Using this class is easy: Create a subclass of AppConfiguration and
/// then simply add properties to the class. Then instantiate the class,
/// call Initialize(), then simply access the class
/// properties to read configuration values.
///
/// The default implementation uses standard .NET configuration files and a
/// custom section within that file to hold configuration values. Other
/// providers can be used to store data to different stores and you can create
/// your own custom providers to store configuration data in yet other stores.
/// <seealso>Managing Configuration Settings with AppConfiguration</seealso>
/// </summary>
public abstract class AppConfiguration
{
/// <summary>
/// An instance of a IConfigurationProvider that
/// needs to be passed in via constructor or set
/// explicitly to read and write from the configuration
/// store.
/// </summary>
[XmlIgnore]
[NonSerialized]
public IConfigurationProvider Provider = null;
/// <summary>
/// Contains an error message if a method returns false or the object fails to
/// load the configuration data.
/// <seealso>Class AppConfiguration</seealso>
/// </summary>
[XmlIgnore]
[NonSerialized]
public string ErrorMessage = string.Empty;
/// <summary>
/// Internal flag that checks to see if Initialize was called
/// if not - automatically calls it without parameters
/// </summary>
protected bool InitializeCalled = false;
/// <summary>
/// Default constructor of this class SHOULD ALWAYS be implemented in
/// every subclass to allow serialization instantiation and setting
/// of initial property values.
/// </summary>
public AppConfiguration()
{ }
/// <summary>
/// This method initializes the configuration object with a provider
/// and performs an initial read from the config store.
/// </summary>
/// <param name="provider">
/// Optional - preconfigured ConfigurationProvider instance.
/// If not passed ConfigurationFileConfigurationProvider is used.
/// </param>
/// <param name="sectionName">
/// Optional - sub-section name used for config files. Not used by all config stores
/// </param>
/// <param name="configData">
/// Optional - additional config data to pass to OnInitialize if implemented
/// </param>
public void Initialize(IConfigurationProvider provider = null,
string sectionName = null,
object configData = null)
{
provider = provider ?? Provider;
// Initialization occurs only once
if (InitializeCalled)
return;
InitializeCalled = true;
if (string.IsNullOrEmpty(sectionName))
sectionName = GetType().Name;
OnInitialize(provider,sectionName,configData);
}
/// <summary>
/// Override this method to handle custom initialization tasks.
///
/// This method should: create a provider and call it's Read()
/// method to populate the current instance of the configuration
/// object.
///
/// If all you need is to create a default provider configuration
/// use the OnCreateDefaultProvider() method to override instead.
/// Use this method if you need to perform custom actions beyond
/// provider instantiation.
/// </summary>
/// <param name="provider">Provider value - can be null in which case ConfigurationFileProvider is used</param>
/// <param name="sectionName">Sub Section name - can be null. Classname is used if null. Can be "appSettings" </param>
/// <param name="configData">
/// Any additional configuration data that can be used to
/// configure the provider.
/// </param>
protected virtual void OnInitialize(IConfigurationProvider provider,
string sectionName,
object configData)
{
if (provider == null)
provider = OnCreateDefaultProvider(sectionName, configData);
Provider = provider;
if (!Provider.Read(this) && !string.IsNullOrWhiteSpace(Provider.ErrorMessage))
Trace.WriteLine(Resources.ConfigurationInitializationError + ": " + Provider.ErrorMessage);
}
/// <summary>
/// Override this method to use a specialized configuration provider for your config class
/// when no explicit provider is passed to the Initialize() method.
/// </summary>
/// <param name="sectionName">Optional section name that was passed to Initialize()</param>
/// <param name="configData">Optional config data that was passed to Initialize()</param>
/// <returns>Instance of configuration provider</returns>
protected virtual IConfigurationProvider OnCreateDefaultProvider(string sectionName, object configData)
{
// dynamically construct the generic provider type
#if NETFRAMEWORK
var providerType = typeof(ConfigurationFileConfigurationProvider<>);
#else
var providerType = typeof(JsonFileConfigurationProvider<>);
#endif
var type = GetType();
Type typeProvider = providerType.MakeGenericType(type);
var provider = Activator.CreateInstance(typeProvider) as IConfigurationProvider;
// if no section name is passed it goes into standard appSettings
if (!string.IsNullOrEmpty(sectionName))
provider.ConfigurationSection = sectionName;
return provider;
}
/// <summary>
/// Writes the current configuration information data to the
/// provider's configuration store.
/// </summary>
/// <returns></returns>
public virtual bool Write()
{
if (Provider == null)
{
Provider = OnCreateDefaultProvider(null,null);
InitializeCalled = true;
}
if (!Provider.Write(this))
{
ErrorMessage = Provider.ErrorMessage;
return false;
}
return true;
}
/// <summary>
/// Writes the current configuration information to an
/// XML string. String is in .NET XML Serialization format.
/// </summary>
/// <returns></returns>
public virtual string WriteAsString()
{
Initialize();
string xml = string.Empty;
Provider.EncryptFields(this);
SerializationUtils.SerializeObject(this, out xml);
if (!string.IsNullOrEmpty(xml))
Provider.DecryptFields(this);
return xml;
}
/// <summary>
/// Reads the configuration information from the
/// provider's store and returns a new instance
/// of an configuration object.
/// </summary>
/// <typeparam name="T">This configuration class type</typeparam>
/// <returns></returns>
public virtual T Read<T>()
where T : AppConfiguration, new()
{
Initialize();
var inst = Provider.Read<T>();
if (inst == null)
{
ErrorMessage = Provider.ErrorMessage;
return null;
}
return inst;
}
/// <summary>
/// Reads the configuration from the provider's store
/// into the current object instance.
/// </summary>
/// <returns></returns>
public virtual bool Read()
{
Initialize();
if (!Provider.Read(this))
{
ErrorMessage = Provider.ErrorMessage;
return false;
}
return true;
}
/// <summary>
/// Reads configuration data from a string and populates the current
/// instance with the values.
///
/// Data should be serialized in XML Searlization format created
/// with <seealso cref="WriteAsString" />
/// </summary>
/// <param name="xml">Xml string in XML Serialization format</param>
/// <returns>true or false</returns>
public virtual bool Read(string xml)
{
Initialize();
var newInstance = SerializationUtils.DeSerializeObject(xml, GetType());
DataUtils.CopyObjectData(newInstance, this, "Provider,Errormessage");
if (newInstance != null)
{
Provider.DecryptFields(this);
}
return true;
}
/// <summary>
/// Reads configuration based on a provider configuration
/// and returns a new instance of the configuration object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="provider">A configured <seealso cref="IConfigurationProvider"/>" provider</param>
/// <returns>instance of configuration or null on failure</returns>
public static T Read<T>(IConfigurationProvider provider)
where T : AppConfiguration, new()
{
return provider.Read<T>() as T;
}
/// <summary>
/// Creates a new instance of the config object and retrieves
/// configuration information from the provided string. String
/// should be in XML Serialization format or created by the
/// <seealso cref="WriteAsString"/> method.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <param name="provider">Required if encryption decryption is desired</param>
/// <returns>config instance or null on failure</returns>
public static T Read<T>(string xml, IConfigurationProvider provider)
where T : AppConfiguration, new()
{
T result = SerializationUtils.DeSerializeObject(xml, typeof(T)) as T;
if (result != null && provider != null)
provider.DecryptFields(result);
return result;
}
/// <summary>
/// Creates a new instance of the config object and retrieves
/// configuration information from the provided string. String
/// should be in XML Serialization format or created by the
/// <seealso cref="WriteAsString"/> method.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <returns>config instance or null on failure</returns>
public static T Read<T>(string xml)
where T : AppConfiguration, new()
{
return Read<T>(xml, null);
}
}
/// <summary>
/// Sample class for diagram display
/// </summary>
class MyAppConfiguration : AppConfiguration
{
public MyAppConfiguration()
{
MyProperty = "My default property value";
MaxPageListItems = 15;
ApplicationTitle = "My great application!";
}
public string MyProperty { get; set; }
public int MaxPageListItems { get; set; }
public string ApplicationTitle { get; set; }
protected override IConfigurationProvider OnCreateDefaultProvider(string sectionName, object configData)
{
return base.OnCreateDefaultProvider(sectionName, configData);
}
}
}
================================================
FILE: Westwind.Utilities/Configuration/Providers/ConfigurationFileConfigurationProvider.cs
================================================
#if NETFULL
#region License
/*
**************************************************************
* Author: Rick Strahl
* © West Wind Technologies, 2009-2013
* http://www.west-wind.com/
*
* Created: 09/12/2009
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Globalization;
using System.Xml.Serialization;
using Westwind.Utilities.Properties;
namespace Westwind.Utilities.Configuration
{
/// <summary>
/// Reads and Writes configuration settings in .NET config files and
/// sections. Allows reading and writing to default or external files
/// and specification of the configuration section that settings are
/// applied to.
/// </summary>
public class ConfigurationFileConfigurationProvider<TAppConfiguration> :
ConfigurationProviderBase<TAppConfiguration>
where TAppConfiguration : AppConfiguration, new()
{
/// <summary>
/// Optional - the Configuration file where configuration settings are
/// stored in. If not specified uses the default Configuration Manager
/// and its default store.
/// </summary>
public string ConfigurationFile { get; set; }
/// <summary>
/// internal property used to ensure there are no multiple write
/// operations at the same time
/// </summary>
private object syncWriteLock = new object();
/// <summary>
/// Internally used reference to the Namespace Manager object
/// used to make sure we're searching the proper Namespace
/// for the appSettings section when reading and writing manually
/// </summary>
private XmlNamespaceManager XmlNamespaces = null;
//Internally used namespace prefix for the default namespace
private string XmlNamespacePrefix = "ww:";
/// <summary>
/// Reads configuration settings into a new instance of the configuration object.
/// </summary>
/// <typeparam name="TAppConfig"></typeparam>
/// <returns></returns>
public override TAppConfig Read<TAppConfig>()
{
TAppConfig config = Activator.CreateInstance(typeof (TAppConfig), true) as TAppConfig;
if (!Read(config))
return null;
return config;
}
/// <summary>
/// Reads configuration settings from the current configuration manager.
/// Uses the internal APIs to write these values.
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public override bool Read(AppConfiguration config)
{
// Config reading from external files works a bit differently
// so use a separate method to handle it
if (!string.IsNullOrEmpty(ConfigurationFile))
return Read(config, ConfigurationFile);
Type typeWebConfig = config.GetType();
PropertyInfo[] properties =
typeWebConfig.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);
// Set a flag for missing fields
// If we have any we'll need to write them out into .config
bool missingFields = false;
// Refresh the sections - req'd after write operations
// sometimes sections don't want to re-read
if (string.IsNullOrEmpty(ConfigurationSection))
ConfigurationManager.RefreshSection("appSettings");
else
ConfigurationManager.RefreshSection(ConfigurationSection);
NameValueCollection configManager;
configManager = string.IsNullOrEmpty(ConfigurationSection)
? ConfigurationManager.AppSettings as NameValueCollection
: ConfigurationManager.GetSection(ConfigurationSection) as NameValueCollection;
if (configManager == null)
{
Write(config);
return true;
}
// Loop through all fields and properties
foreach (PropertyInfo property in properties)
{
if (!property.CanWrite || Attribute.IsDefined(property, typeof(XmlIgnoreAttribute)))
continue;
Type fieldType = property.PropertyType;
string fieldName = property.Name.ToLowerInvariant();
// Error Message is an internal public property
if (fieldName == "errormessage" || fieldName == "provider")
continue;
if (!IsIList(fieldType))
{
// Single value
string value = configManager[fieldName];
if (value == null)
{
missingFields = true;
continue;
}
try
{
if (property.CanWrite)
{
// Assign the value to the property
ReflectionUtils.SetPropertyEx(config, property.Name,
StringToTypedValue(value, fieldType, CultureInfo.InvariantCulture));
}
}
catch
{
}
}
else
{
// List Value
var list = Activator.CreateInstance(fieldType) as IList;
var elType = fieldType.GetElementType();
if (elType == null)
{
var generic = fieldType.GetGenericArguments();
if (generic != null && generic.Length > 0)
elType = generic[0];
}
int count = 1;
string value = string.Empty;
while (value != null)
{
value = configManager[fieldName + count];
if (value == null)
break;
list.Add(StringToTypedValue(value, elType, CultureInfo.InvariantCulture));
count++;
}
try
{
if(property.CanWrite)
ReflectionUtils.SetPropertyEx(config, property.Name, list);
}
catch { }
}
}
DecryptFields(config);
// We have to write any missing keys
if (missingFields)
Write(config);
return true;
}
bool IsIList(Type type)
{
// Enumerable types explicitly supported as 'simple values'
if (type == typeof(string) || type == typeof( byte[]) )
return false;
if (type.GetInterface("IList") != null)
return true;
return false;
}
/// <summary>
/// Reads Configuration settings from an external file or explicitly from a file.
/// Uses XML DOM to read values instead of using the native APIs.
/// </summary>
/// <param name="config">Configuration instance</param>
/// <param name="filename">Filename to read from</param>
/// <returns></returns>
public override bool Read(AppConfiguration config, string filename)
{
Type typeWebConfig = config.GetType();
PropertyInfo[] properties = typeWebConfig.GetProperties(BindingFlags.Public |
BindingFlags.Instance);
// Set a flag for missing fields
// If we have any we'll need to write them out
bool missingFields = false;
XmlDocument Dom = new XmlDocument();
try
{
Dom.Load(filename);
}
catch
{
// Can't open or doesn't exist - so try to create it
if (!Write(config))
return false;
// Now load again
Dom.Load(filename);
}
// Retrieve XML Namespace information to assign default
// Namespace explicitly.
GetXmlNamespaceInfo(Dom);
string ConfigSection = ConfigurationSection;
if (ConfigSection == string.Empty)
ConfigSection = "appSettings";
foreach (var property in properties)
{
if (!property.CanWrite || Attribute.IsDefined(property, typeof(XmlIgnoreAttribute)))
continue;
Type fieldType = null;
string typeName = null;
fieldType = property.PropertyType;
typeName = property.PropertyType.Name.ToLower();
string propertyName = property.Name;
if (propertyName == "Provider" || propertyName == "ErrorMessage")
continue;
XmlNode Section = Dom.DocumentElement.SelectSingleNode(XmlNamespacePrefix + ConfigSection, XmlNamespaces);
if (Section == null)
{
Section = CreateConfigSection(Dom, ConfigurationSection);
Dom.DocumentElement.AppendChild(Section);
}
string Value = GetNamedValueFromXml(Dom, propertyName, ConfigSection);
if (Value == null)
{
missingFields = true;
continue;
}
// Assign the Property
ReflectionUtils.SetPropertyEx(config, propertyName,
StringToTypedValue(Value, fieldType, CultureInfo.InvariantCulture));
}
DecryptFields(config);
// We have to write any missing keys
if (missingFields)
Write(config);
return true;
}
public override bool Write(AppConfiguration config)
{
EncryptFields(config);
lock (syncWriteLock)
{
// Load the config file into DOM parser
XmlDocument Dom = new XmlDocument();
string configFile = ConfigurationFile;
if (string.IsNullOrEmpty(configFile))
configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
try
{
Dom.Load(configFile);
}
catch
{
// Can't load the file - create an empty document
string Xml =
@"<?xml version='1.0'?>
<configuration>
</configuration>";
Dom.LoadXml(Xml);
}
// Load up the Namespaces object so we can
// reference the appropriate default namespace
GetXmlNamespaceInfo(Dom);
// Parse through each of hte properties of the properties
Type typeWebConfig = config.GetType();
PropertyInfo[] properties = typeWebConfig.GetProperties(BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public);
string ConfigSection = "appSettings";
if (!string.IsNullOrEmpty(ConfigurationSection))
ConfigSection = ConfigurationSection;
// make sure we're getting the latest values before we write
ConfigurationManager.RefreshSection(ConfigSection);
foreach (var property in properties)
{
if (!property.CanRead || Attribute.IsDefined(property, typeof(XmlIgnoreAttribute)))
continue;
// Don't persist ErrorMessage property
if (property.Name == "ErrorMessage" || property.Name == "Provider")
continue;
object rawValue = null;
rawValue = property.GetValue(config, null);
string value = TypedValueToString(rawValue, CultureInfo.InvariantCulture);
if (value == "ILIST_TYPE")
{
var count = 0;
foreach (var item in rawValue as IList)
{
value = TypedValueToString(item, CultureInfo.InvariantCulture);
WriteConfigurationValue(property.Name + ++count, value, property, Dom, ConfigSection);
}
}
else
{
WriteConfigurationValue(property.Name, value, property, Dom, ConfigSection);
}
} // for each
try
{
// this will fail if permissions are not there
Dom.Save(configFile);
ConfigurationManager.RefreshSection(ConfigSection);
}
catch(Exception ex)
{
ErrorMessage = "Unable to save configuration file: " + ex.Message;
return false;
}
finally
{
DecryptFields(config);
}
}
return true;
}
private void WriteConfigurationValue(string keyName, string Value, MemberInfo Field, XmlDocument Dom, string ConfigSection)
{
XmlNode Node = Dom.DocumentElement.SelectSingleNode(
XmlNamespacePrefix + ConfigSection + "/" +
XmlNamespacePrefix + "add[@key='" + keyName + "']", XmlNamespaces);
if (Node == null)
{
// Create the node and attributes and write it
Node = Dom.CreateNode(XmlNodeType.Element, "add", Dom.DocumentElement.NamespaceURI);
XmlAttribute Attr2 = Dom.CreateAttribute("key");
Attr2.Value = keyName;
XmlAttribute Attr = Dom.CreateAttribute("value");
Attr.Value = Value;
Node.Attributes.Append(Attr2);
Node.Attributes.Append(Attr);
XmlNode Parent = Dom.DocumentElement.SelectSingleNode(
XmlNamespacePrefix + ConfigSection, XmlNamespaces);
if (Parent == null)
Parent = CreateConfigSection(Dom, ConfigSection);
Parent.AppendChild(Node);
}
else
{
// just write the value into the attribute
Node.Attributes.GetNamedItem("value").Value = Value;
}
}
/// <summary>
/// Returns a single value from the XML in a configuration file.
/// </summary>
/// <param name="Dom"></param>
/// <param name="Key"></param>
/// <param name="ConfigSection"></param>
/// <returns></returns>
protected string GetNamedValueFromXml(XmlDocument Dom, string Key, string ConfigSection)
{
XmlNode Node = Dom.DocumentElement.SelectSingleNode(
XmlNamespacePrefix + ConfigSection + @"/" +
XmlNamespacePrefix + "add[@key='" + Key + "']", XmlNamespaces);
if (Node == null)
return null;
return Node.Attributes["value"].Value;
}
/// <summary>
/// Used to load up the default namespace reference and prefix
/// information. This is required so that SelectSingleNode can
/// find info in 2.0 or later config files that include a namespace
/// on the root element definition.
/// </summary>
/// <param name="Dom"></param>
protected void GetXmlNamespaceInfo(XmlDocument Dom)
{
// Load up the Namespaces object so we can
// reference the appropriate default namespace
if (Dom.DocumentElement.NamespaceURI == null || Dom.DocumentElement.NamespaceURI == string.Empty)
{
XmlNamespaces = null;
XmlNamespacePrefix = string.Empty;
}
else
{
if (Dom.DocumentElement.Prefix == null || Dom.DocumentElement.Prefix == string.Empty)
XmlNamespacePrefix = "ww";
else
XmlNamespacePrefix = Dom.DocumentElement.Prefix;
XmlNamespaces = new XmlNamespaceManager(Dom.NameTable);
XmlNamespaces.AddNamespace(XmlNamespacePrefix, Dom.DocumentElement.NamespaceURI);
XmlNamespacePrefix += ":";
}
}
/// <summary>
/// Creates a Configuration section and also creates a ConfigSections section for new
/// non appSettings sections.
/// </summary>
/// <param name="dom"></param>
/// <param name="configSection"></param>
/// <returns></returns>
private XmlNode CreateConfigSection(XmlDocument dom, string configSection)
{
// Create the actual section first and attach to document
XmlNode AppSettingsNode = dom.CreateNode(XmlNodeType.Element,
configSection, dom.DocumentElement.NamespaceURI);
XmlNode Parent = dom.DocumentElement.AppendChild(AppSettingsNode);
// Now check and make sure that the section header exists
if (configSection != "appSettings")
{
XmlNode ConfigSectionHeader = dom.DocumentElement.SelectSingleNode(XmlNamespacePrefix + "configSections",
XmlNamespaces);
if (ConfigSectionHeader == null)
{
// Create the node and attributes and write it
XmlNode ConfigSectionNode = dom.CreateNode(XmlNodeType.Element,
"configSections", dom.DocumentElement.NamespaceURI);
// Insert as first element in DOM
ConfigSectionHeader = dom.DocumentElement.InsertBefore(ConfigSectionNode,
dom.DocumentElement.ChildNodes[0]);
}
// Check for the Section
XmlNode Section = ConfigSectionHeader.SelectSingleNode(XmlNamespacePrefix + "section[@name='" + configSection + "']",
XmlNamespaces);
if (Section == null)
{
Section = dom.CreateNode(XmlNodeType.Element, "section",
null);
XmlAttribute Attr = dom.CreateAttribute("name");
Attr.Value = configSection;
XmlAttribute Attr2 = dom.CreateAttribute("type");
Attr2.Value = "System.Configuration.NameValueSectionHandler,System,Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
XmlAttribute Attr3 = dom.CreateAttribute("requirePermission");
Attr3.Value = "false";
Section.Attributes.Append(Attr);
Section.Attributes.Append(Attr3);
Section.Attributes.Append(Attr2);
ConfigSectionHeader.AppendChild(Section);
}
}
return Parent;
}
/// <summary>
/// Converts a type to string if possible. This method supports an optional culture generically on any value.
/// It calls the ToString() method on common types and uses a type converter on all other objects
/// if available
/// </summary>
/// <param name="rawValue">The Value or Object to convert to a string</param>
/// <param name="culture">Culture for numeric and DateTime values</param>
/// <param name="unsupportedReturn">Return string for unsupported types</param>
/// <returns>string</returns>
static string TypedValueToString(object rawValue, CultureInfo culture = null, string unsupportedReturn = null)
{
if (rawValue == null)
return string.Empty;
if (culture == null)
culture = CultureInfo.CurrentCulture;
Type valueType = rawValue.GetType();
string returnValue = null;
if (valueType == typeof(string))
returnValue = rawValue as string;
else if (valueType == typeof(int) || valueType == typeof(decimal) ||
valueType == typeof(double) || valueType == typeof(float) || valueType == typeof(Single))
returnValue = string.Format(culture.NumberFormat, "{0}", rawValue);
else if (valueType == typeof(DateTime))
returnValue = string.Format(culture.DateTimeFormat, "{0}", rawValue);
else if (valueType == typeof(bool) || valueType == typeof(Byte) || valueType.IsEnum)
returnValue = rawValue.ToString();
else if (valueType == typeof (byte[]))
returnValue = Convert.ToBase64String(rawValue as byte[]);
else if (valueType == typeof(Guid?))
{
if (rawValue == null)
returnValue = string.Empty;
else
return rawValue.ToString();
}
else if (rawValue is IList)
return "ILIST_TYPE";
else
{
// Any type that supports a type converter
TypeConverter converter = TypeDescriptor.GetConverter(valueType);
if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string)))
returnValue = converter.ConvertToString(null, culture, rawValue);
else
{
// Last resort - just call ToString() on unknown type
if (!string.IsNullOrEmpty(unsupportedReturn))
returnValue = unsupportedReturn;
else
returnValue = rawValue.ToString();
}
}
return returnValue;
}
/// <summary>
/// Turns a string into a typed value generically.
/// Explicitly assigns common types and falls back
/// on using type converters for unhandled types.
///
/// Common uses:
/// * UI -> to data conversions
/// * Parsers
/// <seealso>Class ReflectionUtils</seealso>
/// </summary>
/// <param name="sourceString">
/// The string to convert from
/// </param>
/// <param name="targetType">
/// The type to convert to
/// </param>
/// <param name="culture">
/// Culture used for numeric and datetime values.
/// </param>
/// <returns>object. Throws exception if it cannot be converted.</returns>
static object StringToTypedValue(string sourceString, Type targetType, CultureInfo culture = null)
{
object result = null;
bool isEmpty = string.IsNullOrEmpty(sourceString);
if (culture == null)
culture = CultureInfo.CurrentCulture;
if (targetType == typeof(string))
result = sourceString;
else if (targetType == typeof(Int32) || targetType == typeof(int))
{
if (isEmpty)
result = 0;
else
result = Int32.Parse(sourceString, NumberStyles.Any, culture.NumberFormat);
}
else if (targetType == typeof(Int64))
{
if (isEmpty)
result = (Int64)0;
else
result = Int64.Parse(sourceString, NumberStyles.Any, culture.NumberFormat);
}
else if (targetType == typeof(Int16))
{
if (isEmpty)
result = (Int16)0;
else
result = Int16.Parse(sourceString, NumberStyles.Any, culture.NumberFormat);
}
else if (targetType == typeof(decimal))
{
if (isEmpty)
result = 0M;
else
result = decimal.Parse(sourceString, NumberStyles.Any, culture.NumberFormat);
}
else if (targetType == typeof(DateTime))
{
if (isEmpty)
result = DateTime.MinValue;
else
result = Convert.ToDateTime(sourceString, culture.DateTimeFormat);
}
else if (targetType == typeof(byte))
{
if (isEmpty)
result = 0;
else
result = Convert.ToByte(sourceString);
}
else if (targetType == typeof(double))
{
if (isEmpty)
result = 0F;
else
result = Double.Parse(sourceString, NumberStyles.Any, culture.NumberFormat);
}
else if (targetType == typeof(Single))
{
if (isEmpty)
result = 0F;
else
result = Single.Parse(sourceString, NumberStyles.Any, culture.NumberFormat);
}
else if (targetType == typeof(bool))
{
if (!isEmpty &&
sourceString.ToLower() == "true" || sourceString.ToLower() == "on" || sourceString == "1")
result = true;
else
result = false;
}
else if (targetType == typeof(Guid))
{
if (isEmpty)
result = Guid.Empty;
else
result = new Guid(sourceString);
}
else if (targetType.IsEnum)
result = Enum.Parse(targetType, sourceString);
else if (targetType == typeof (byte[]))
result = Convert.FromBase64String(sourceString);
else if (targetType.Name.StartsWith("Nullable`"))
{
if (sourceString.ToLower() == "null" || sourceString == string.Empty)
result = null;
else
{
targetType = Nullable.GetUnderlyingType(targetType);
result = StringToTypedValue(sourceString, targetType);
}
}
else
{
// Check for TypeConverters or FromString static method
TypeConverter converter = TypeDescriptor.GetConverter(targetType);
if (converter != null && converter.CanConvertFrom(typeof (string)))
result = converter.ConvertFromString(null, culture, sourceString);
else
{
// Try to invoke a static FromString method if it exists
try
{
var mi = targetType.GetMethod("FromString");
if (mi != null)
{
return mi.Invoke(null, new object[1] {sourceString});
}
}
catch
{
// ignore error and assume not supported
}
Debug.Assert(false, string.Format("Type Conversion not handled in StringToTypedValue for {0} {1}",
targetType.Name, sourceString));
throw (new InvalidCastException(Resources.StringToTypedValueValueTypeConversionFailed +
targetType.Name));
}
}
return result;
}
}
}
#endif
================================================
FILE: Westwind.Utilities/Configuration/Providers/ConfigurationProviderBase.cs
================================================
#region License
/*
**************************************************************
* Author: Rick Strahl
* West Wind Technologies, 2009-2013
* http://www.west-wind.com/
*
* Created: 09/12/2009
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
using System;
using System.Reflection;
using Westwind.Utilities.Properties;
namespace Westwind.Utilities.Configuration
{
/// <summary>
/// Base Configuration Provider Implementation. This implementation provides
/// for the basic layout of a provider and fields that implement the
/// IConfigurationProvider interface.
///
/// The Read and Write methods must be overridden - all other methods and
/// fields are optional
///
/// </summary>
public abstract class ConfigurationProviderBase<TAppConfiguration> : IConfigurationProvider
where TAppConfiguration : AppConfiguration, new()
{
/// <summary>
/// Displays error information when results fail.
/// </summary>
public virtual string ErrorMessage
{
get { return _ErrorMessage; }
set { _ErrorMessage = value; }
}
private string _ErrorMessage = string.Empty;
/// <summary>
/// A comma delimiter list of property names that are
/// to be encrypted when persisted to the store
/// </summary>
public virtual string PropertiesToEncrypt
{
get { return _PropertiesToEncrypt; }
set { _PropertiesToEncrypt = value; }
}
private string _PropertiesToEncrypt = string.Empty;
/// <summary>
/// The encryption key to encrypt the fields
/// set with FieldsToEncrypt
/// </summary>
public virtual string EncryptionKey
{
get { return _EncryptionKey; }
set { _EncryptionKey = value; }
}
private string _EncryptionKey = "x@3|zg?4%ui*";
/// <summary>
/// Optional Section name that can differentiate groups of config
/// values in multi-section files like Config files.
/// </summary>
public string ConfigurationSection {get; set; }
/// <summary>
/// Reads a configurations settings from the configuration store
/// into a new existing instance.
/// </summary>
/// <typeparam name="T">Specific Config Settings Class</typeparam>
/// <returns></returns>
public abstract T Read<T>()
where T : AppConfiguration, new();
/// <summary>
/// Reads configuration settings from the store into a passed
/// instance of the configuration instance.
/// </summary>
/// <param name="config">Specific config settings class instance</param>
/// <returns>true or false</returns>
public abstract bool Read(AppConfiguration config);
/// <summary>
/// Writes the configuration settings from a specific instance
/// into the configuration store.
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public abstract bool Write(AppConfiguration config);
/// <summary>
/// Creates a new instance of the application object and retrieves
/// configuration information from the provided string. String
/// should be in XML Serialization format or created by the WriteAsString
/// method.
/// </summary>
/// <typeparam name="T">Type of the specific configuration class</typeparam>
/// <param name="xml">An xml string that contains XML Serialized serialization data</param>
/// <returns>The deserialized instance or null on failure</returns>
public virtual T Read<T>(string xml)
where T : AppConfiguration, new()
{
if (string.IsNullOrEmpty((xml)))
{
return null;
}
T result;
try
{
result = SerializationUtils.DeSerializeObject(xml, typeof(T)) as T;
}
catch (Exception ex)
{
SetError(ex);
return null;
}
if (result != null)
DecryptFields(result);
return result;
}
/// <summary>
/// Reads data into configuration from an XML string into a passed
/// instance of the a configuration object.
/// </summary>
/// <param name="config">An instance of a custom configuration object</param>
/// <param name="xml">Xml of serialized configuration instance.</param>
/// <returns>true or false</returns>
public virtual bool Read(AppConfiguration config, string xml)
{
TAppConfiguration newConfig = null;
// if no data was passed leave the object
// in its initial state.
if (string.IsNullOrEmpty(xml))
return true;
try
{
newConfig = SerializationUtils.DeSerializeObject(xml, config.GetType()) as TAppConfiguration;
if (newConfig == null)
{
SetError(Resources.ObjectCouldNotBeDeserializedFromXml);
return false;
}
}
catch (Exception ex)
{
SetError(ex);
return false;
}
if (newConfig != null)
{
DecryptFields(newConfig);
DataUtils.CopyObjectData(newConfig, config, "Provider,ErrorMessage");
return true;
}
return false;
}
/// <summary>
/// Writes the current configuration information to an
/// XML string. String is XML Serialization format.
/// </summary>
/// <returns>xml string of serialized config object</returns>
public virtual string WriteAsString(AppConfiguration config)
{
string xml = string.Empty;
EncryptFields(config);
try
{
SerializationUtils.SerializeObject(config, out xml, true);
}
catch (Exception ex)
{
SetError(ex);
return string.Empty;
}
finally
{
DecryptFields(config);
}
return xml;
}
/// <summary>
/// Encrypts all the fields in the current object based on the EncryptFieldList
/// </summary>
/// <returns></returns>
public virtual void EncryptFields(AppConfiguration config)
{
if (string.IsNullOrEmpty(PropertiesToEncrypt))
return;
string encryptFieldList = "," + PropertiesToEncrypt.ToLower() + ",";
string[] fieldTokens = encryptFieldList.Split(new char[1] {','}, StringSplitOptions.RemoveEmptyEntries);
foreach(string fieldName in fieldTokens)
{
// Encrypt the field if in list
if (encryptFieldList.Contains("," + fieldName.ToLower() + ","))
{
object val = string.Empty;
try
{
val = ReflectionUtils.GetPropertyEx(config, fieldName);
}
catch
{
throw new ArgumentException(string.Format("{0}: {1}",Resources.InvalidEncryptionPropertyName,fieldName));
}
// only encrypt string values
var strVal = val as string;
if (string.IsNullOrEmpty(strVal))
continue;
val = Encryption.EncryptString(strVal, EncryptionKey);
try
{
ReflectionUtils.SetPropertyEx(config, fieldName, val);
}
catch
{
throw new ArgumentException(string.Format("{0}: {1}", Resources.InvalidEncryptionPropertyName, fieldName));
}
}
}
}
/// <summary>
/// Internally decryptes all the fields in the current object based on the EncryptFieldList
/// </summary>
/// <returns></returns>
public virtual void DecryptFields(AppConfiguration config)
{
if (string.IsNullOrEmpty(PropertiesToEncrypt))
return;
string encryptFieldList = "," + PropertiesToEncrypt.ToLower() + ",";
string[] fieldTokens = encryptFieldList.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string fieldName in fieldTokens)
{
// Encrypt the field if in list
if (encryptFieldList.Contains("," + fieldName.ToLower() + ","))
{
object val = string.Empty;
try
{
val = ReflectionUtils.GetPropertyEx(config, fieldName);
}
catch
{
throw new ArgumentException(string.Format("{0}: {1}", Resources.InvalidEncryptionPropertyName, fieldName));
}
// only encrypt string values
var strVal = val as string;
if (string.IsNullOrEmpty(strVal))
continue;
val = Encryption.DecryptString(strVal, EncryptionKey);
try
{
ReflectionUtils.SetPropertyEx(config, fieldName, val);
}
catch
{
throw new ArgumentException(string.Format("{0}: {1}", Resources.InvalidEncryptionPropertyName, fieldName));
}
}
}
}
/// <summary>
/// Sets an error message when an error occurs
/// </summary>
/// <param name="message"></param>
protected virtual void SetError(string message)
{
if (string.IsNullOrEmpty(message))
{
ErrorMessage = string.Empty;
return;
}
ErrorMessage = message;
}
/// <summary>
/// Writes an exception and innerexception message
/// into the error message text
/// </summary>
/// <param name="ex"></param>
protected virtual void SetError(Exception ex)
{
string message = ex.Message;
if (ex.InnerException != null)
message += " " + ex.InnerException.Message;
SetError(message);
}
/// <summary>
/// Helper method to create a new instance of the Configuration object.
/// </summary>
/// <returns></returns>
protected TAppConfiguration CreateConfigurationInstance()
{
return Activator.CreateInstance(typeof(TAppConfiguration)) as TAppConfiguration;
}
}
}
================================================
FILE: Westwind.Utilities/Configuration/Providers/IConfigurationProvider.cs
================================================
#region License
/*
**************************************************************
* Author: Rick Strahl
* West Wind Technologies, 2009
* http://www.west-wind.com/
*
* Created: 09/12/2009
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
using System;
using System.Reflection;
namespace Westwind.Utilities.Configuration
{
/// <summary>
/// Configuration Provider interface that provides read and write services
/// to various configuration storage mechanisms.
///
/// Used in conjunction with the <seealso cref="AppConfiguration"/> class.
/// A base implementation from which to inherit is provided in the
/// <seealso cref="Westwind.Utilities.Configuration.ConfigurationProviderBase{TAppConfiguration}"/> class.
/// </summary>
public interface IConfigurationProvider
{
/// <summary>
/// Holds an error message after a read or write operation
/// failed.
/// </summary>
string ErrorMessage { get; set; }
/// <summary>
/// A comma delimited list of fields that are to be encrypted
/// </summary>
string PropertiesToEncrypt { get; set; }
/// <summary>
/// The encryption key used to encrypt fields in config objects
/// </summary>
string EncryptionKey { get; set; }
/// <summary>
/// Optional Section name that can be used to sub-segment in multi-config files
/// </summary>
string ConfigurationSection { get; set; }
/// <summary>
/// Reads configuration information into new configuration object instance
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
T Read<T>()
where T : AppConfiguration, new();
/// <summary>
/// Reads configuration information into a provided config object instance
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
bool Read(AppConfiguration config);
T Read<T>(string xml)
where T: AppConfiguration, new();
/// <summary>
/// Reads configuration information from an XML string (Xml Serialization format)
/// into a provided config object instance
/// </summary>
/// <param name="config"></param>
/// <param name="xml"></param>
/// <returns></returns>
bool Read(AppConfiguration config, string xml);
/// <summary>
/// Writes configuration information into a provided object instance
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
bool Write(AppConfiguration config);
/// <summary>
/// Writes configuration for a provided config object and returns
/// the serialized data as a string.
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
string WriteAsString(AppConfiguration config);
/// <summary>
/// Encrypts fields in a config object as specified in the cref="PropertiesToEncrypt" property.
/// </summary>
/// <param name="config"></param>
void EncryptFields(AppConfiguration config);
/// <summary>
/// Decryptes the encyrpted fields in a config object a
/// </summary>
/// <param name="config"></param>
void DecryptFields(AppConfiguration config);
}
}
================================================
FILE: Westwind.Utilities/Configuration/Providers/JsonFileConfigurationProvider.cs
================================================
#region License
/*
**************************************************************
* Author: Rick Strahl
* West Wind Technologies, 2009-2013
* http://www.west-wind.com/
*
* Created: 09/12/2009
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
namespace Westwind.Utilities.Configuration
{
/// <summary>
/// Reads and Writes configuration settings in .NET config files and
/// sections. Allows reading and writing to default or external files
/// and specification of the configuration section that settings are
/// applied to.
/// </summary>
public class JsonFileConfigurationProvider<TAppConfiguration> : ConfigurationProviderBase<TAppConfiguration>
where TAppConfiguration : AppConfiguration, new()
{
/// <summary>
/// Optional - the Configuration file where configuration settings are
/// stored in. If not specified uses the default Configuration Manager
/// and its default store.
/// </summary>
public string JsonConfigurationFile
{
get { return _JsonConfigurationFile; }
set { _JsonConfigurationFile = value; }
}
private string _JsonConfigurationFile = "applicationConfiguration.json";
/// <summary>
/// Reads configuration into the current instance of the config object passed in.
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public override bool Read(AppConfiguration config)
{
var newConfig = JsonSerializationUtils.DeserializeFromFile(JsonConfigurationFile, typeof(TAppConfiguration)) as TAppConfiguration;
if (newConfig == null)
{
if (Write(config))
return true;
return false;
}
DecryptFields(newConfig);
DataUtils.CopyObjectData(newConfig, config, "Provider,ErrorMessage");
return true;
}
/// <summary>
/// Return
/// </summary>
/// <typeparam name="TAppConfig"></typeparam>
/// <returns></returns>
public override TAppConfig Read<TAppConfig>()
{
var result = JsonSerializationUtils.DeserializeFromFile(JsonConfigurationFile, typeof(TAppConfig)) as TAppConfig;
if (result != null)
DecryptFields(result);
return result;
}
/// <summary>
/// Write configuration to XmlConfigurationFile location
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public override bool Write(AppConfiguration config)
{
EncryptFields(config);
bool result = JsonSerializationUtils.SerializeToFile(config, JsonConfigurationFile, false, true);
// Have to decrypt again to make sure the properties are readable afterwards
DecryptFields(config);
return result;
}
}
}
================================================
FILE: Westwind.Utilities/Configuration/Providers/StringConfigurationProvider.cs
================================================
#region License
/*
**************************************************************
* Author: Rick Strahl
* West Wind Technologies, 2009-2013
* http://www.west-wind.com/
*
* Created: 09/12/2009
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
using System;
namespace Westwind.Utilities.Configuration
{
/// <summary>
/// Reads and Writes configuration settings from strings - which you manage
/// yourself. Using strings for the configuration provider allows for easy
/// storage into any non-supported configuration stores that you control
/// through your code as long as it supports strings.
///
/// The string provider is a real minimal implementation that only implements
/// WriteAsString(config) and Read(string). It inherits all of its functionality
/// from the base provider.
/// </summary>
public class StringConfigurationProvider<TAppConfiguration> : ConfigurationProviderBase<TAppConfiguration>
where TAppConfiguration : AppConfiguration, new()
{
public string InitialStringData { get; set; }
/// <summary>
/// Reads from the InitialStringData string data
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public override T Read<T>()
{
return this.Read<T>(InitialStringData);
}
/// <summary>
/// Reads configuration information into config from InitialStringData
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public override bool Read(AppConfiguration config)
{
return Read(config, InitialStringData);
}
/// <summary>
/// Not supported for StringConfiguration
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public override bool Write(AppConfiguration config)
{
throw new NotImplementedException();
}
}
}
================================================
FILE: Westwind.Utilities/Configuration/Providers/XmlFileConfigurationProvider.cs
================================================
#region License
/*
**************************************************************
* Author: Rick Strahl
* West Wind Technologies, 2009-2013
* http://www.west-wind.com/
*
* Created: 09/12/2009
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
using System;
using System.IO;
using Westwind.Utilities.Properties;
namespace Westwind.Utilities.Configuration
{
/// <summary>
/// Reads and Writes configuration settings in .NET config files and
/// sections. Allows reading and writing to default or external files
/// and specification of the configuration section that settings are
/// applied to.
/// </summary>
public class XmlFileConfigurationProvider<TAppConfiguration> : ConfigurationProviderBase<TAppConfiguration>
where TAppConfiguration: AppConfiguration, new()
{
/// <summary>
/// Optional - the Configuration file where configuration settings are
/// stored in. If not specified uses the default Configuration Manager
/// and its default store.
/// </summary>
public string XmlConfigurationFile
{
get { return _XmlConfigurationFile; }
set { _XmlConfigurationFile = value; }
}
private string _XmlConfigurationFile = string.Empty;
public bool UseBinarySerialization
{
get { return _UseBinarySerialization; }
set { _UseBinarySerialization = value; }
}
private bool _UseBinarySerialization = false;
public override bool Read(AppConfiguration config)
{
var newConfig = SerializationUtils.DeSerializeObject(XmlConfigurationFile,typeof(TAppConfiguration),UseBinarySerialization) as TAppConfiguration;
if (File.Exists(XmlConfigurationFile) && newConfig == null)
throw new ArgumentException(string.Format(Resources.InvalidXMLConfigurationFileFormat,XmlConfigurationFile));
if (newConfig == null)
{
if(Write(config))
return true;
return false;
}
DecryptFields(newConfig);
DataUtils.CopyObjectData(newConfig, config, "Provider,ErrorMessage");
return true;
}
/// <summary>
/// Return
/// </summary>
/// <typeparam name="TAppConfig"></typeparam>
/// <returns></returns>
public override TAppConfig Read<TAppConfig>()
{
var result = SerializationUtils.DeSerializeObject(XmlConfigurationFile,typeof(TAppConfig),UseBinarySerialization) as TAppConfig;
if (result != null)
DecryptFields(result);
return result;
}
/// <summary>
/// Write configuration to XmlConfigurationFile location
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public override bool Write(AppConfiguration config)
{
EncryptFields(config);
bool result = SerializationUtils.SerializeObject(config, XmlConfigurationFile, UseBinarySerialization);
// Have to decrypt again to make sure the properties are readable afterwards
DecryptFields(config);
return result;
}
}
}
================================================
FILE: Westwind.Utilities/Data/ValidationError.cs
================================================
#region License
/*
**************************************************************
* Author: Rick Strahl
* West Wind Technologies, 2009
* http://www.west-wind.com/
*
* Created: 09/12/2009
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
using System.Collections;
using System.Text;
namespace Westwind.Utilities
{
/// <summary>
/// Object that holds a single Validation Error for the business object
/// </summary>
public class ValidationError
{
/// <summary>
/// The error message for this validation error.
/// </summary>
public string Message
{
get
{
return cMessage;
}
set
{
cMessage = value;
}
}
string cMessage = "";
/// <summary>
/// The name of the field that this error relates to.
/// </summary>
public string ControlID
{
get { return this .cFieldName; }
set { cFieldName = value; }
}
string cFieldName = "";
/// <summary>
/// An ID set for the Error. This ID can be used as a correlation between bus object and UI code.
/// </summary>
public string ID
{
get { return cID; }
set { cID = value; }
}
string cID = "";
public ValidationError() : base() {}
public ValidationError(string message)
{
Message = message;
}
public ValidationError(string message, string fieldName)
{
Message = message;
ControlID = fieldName;
}
public ValidationError(string message, string fieldName, string id)
{
Message = message;
ControlID = fieldName;
ID = id;
}
public override string ToString()
{
return Message;
}
}
}
================================================
FILE: Westwind.Utilities/Data/ValidationErrorCollection.cs
================================================
using System.Collections;
using System.Text;
namespace Westwind.Utilities
{
/// <summary>
/// A collection of ValidationError objects that is used to collect
/// errors that occur duing calls to the Validate method.
/// </summary>
public class ValidationErrorCollection : CollectionBase
{
/// <summary>
/// Indexer property for the collection that returns and sets an item
/// </summary>
public ValidationError this[int index]
{
get
{
return (ValidationError)List[index];
}
set
{
List[index] = value;
}
}
/// <summary>
/// Shortcut to determine whether this instance has errors
/// </summary>
public bool HasErrors => this.Count > 0;
/// <summary>
/// Adds a new <see cref="T:ValidationError">ValidationError</see> to the collection
///
/// </summary>
/// <param name="error">
/// Validation Error object
/// </param>
/// <returns>Void</returns>
public void Add(ValidationError error)
{
List.Add(error);
}
/// <summary>
/// Adds a new error to the collection
/// <seealso>T:ValidationErrorCollection</seealso>
/// </summary>
/// <param name="message">
/// Message of the error
/// </param>
/// <param name="fieldName">
/// optional field name that it applies to (used for Databinding errors on
/// controls)
/// </param>
/// <param name="id">
/// An optional ID you assign the error
/// </param>
/// <returns>Void</returns>
public void Add(string message, string fieldName = "", string id = "")
{
var error = new ValidationError()
{
Message = message,
ControlID = fieldName,
ID = id
};
Add(error);
}
/// <summary>
/// Like Add but allows specifying of a format.
/// Adds a <see cref="T:ValidationError">ValidationError</see>.
///
/// <seealso>T:ValidationErrorCollection</seealso>
/// <seealso>T:ValidationError</seealso>
/// </summary>
/// <param name="message">A format message into which arguments are embedded using `{0}` `{1}` syntax etc.</param>
/// <param name="fieldName">Optional name of the field</param>
/// <param name="id">Optional Id</param>
/// <param name="arguments">Any arguments to send</param>
public void AddFormat(string message, string fieldName, string id, params object[] arguments)
{
Add(string.Format(message, arguments), fieldName, id);
}
/// <summary>
/// Removes the item specified in the index from the Error collection
/// </summary>
/// <param name="index"></param>
public void Remove(int index)
{
if (index > List.Count - 1 || index < 0)
List.RemoveAt(index);
}
/// <summary>
/// Adds a validation error if the condition is true. Otherwise no item is
/// added.
/// <seealso>ValidationErrorCollection</seealso>
/// </summary>
/// <param name="condition">
/// If true this error is added. Otherwise not.
/// </param>
/// <param name="message">
/// The message for this error
/// </param>
/// <param name="fieldName">
/// Name of the UI field (optional) that this error relates to. Used optionally
/// by the databinding classes.
/// </param>
/// <param name="id">
/// An optional Error ID.
/// </param>
/// <returns>value of condition</returns>
public bool Assert(bool condition, string message, string fieldName, string id)
{
if (condition)
Add(message, fieldName, id);
return condition;
}
/// <summary>
/// Adds a validation error if the condition is true. Otherwise no item is
/// added.
/// <seealso>Class ValidationErrorCollection</seealso>
/// </summary>
/// <param name="condition">
/// If true the Validation Error is added.
/// </param>
/// <param name="message">
/// The Error Message for this error.
/// </param>
/// <returns>value of condition</returns>
public bool Assert(bool condition, string message)
{
if (condition)
Add(message);
return condition;
}
/// <summary>
/// Adds a validation error if the condition is true. Otherwise no item is
/// added.
/// <seealso>T:ValidationErrorCollection</seealso>
/// </summary>
/// <param name="condition">
/// If true the Validation Error is added.
/// </param>
/// <param name="message">
/// The Error Message for this error.
/// </param>
/// <param name="fieldName">
/// Optional fieldName that can be linked in UI
/// </param>
/// <returns>string</returns>
public bool Assert(bool condition, string message, string fieldName)
{
if (condition)
Add(message, fieldName);
return condition;
}
/// <summary>
/// Asserts a business rule - if condition is true it's added otherwise not.
/// </summary>
/// <param name="condition">
/// If this condition evaluates to true the Validation Error is added
/// </param>
/// <param name="error">
/// Validation Error Object
/// </param>
/// <returns>value of condition</returns>
public bool Assert(bool condition, ValidationError error)
{
if (condition)
List.Add(error);
return condition;
}
/// <summary>
/// Returns a string representation of the errors in this collection.
/// The string is separated by CR LF after each line.
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (Count < 1)
return string.Empty;
StringBuilder sb = new StringBuilder(128);
foreach (ValidationError error in this)
{
sb.AppendLine(error.Message);
}
return sb.ToString();
}
/// <summary>
/// Returns a string representation of the errors in this collection.
/// The string is separated by CR LF after each line but it
/// uses an optional string prefix on each line.
/// </summary>
/// <param name="prefixLine">A string prefix that pre-pended on each error line (plus a space)</param>
/// <returns></returns>
public string ToString(string prefixLine)
{
if (Count < 1)
return string.Empty;
StringBuilder sb = new StringBuilder(128);
foreach (ValidationError error in this)
{
sb.AppendLine($"{prefixLine} {error.Message}");
}
return sb.ToString();
}
/// <summary>
/// Returns an HTML representation of the errors in this collection.
/// The string is returned as an HTML unordered list.
/// </summary>
/// <returns></returns>
public string ToHtml()
{
if (Count < 1)
return "";
StringBuilder sb = new StringBuilder(256);
sb.Append("<ul>\r\n");
foreach (ValidationError error in this)
{
sb.Append("<li>");
if (error.ControlID != null && error.ControlID != "")
sb.AppendFormat("<a href='#' onclick=\"_errorLinkClick('{0}');return false;\" " +
"style='text-decoration:none'>{1}</a>",
error.ControlID.Replace(".","_"),error.Message);
else
sb.Append(error.Message);
sb.AppendLine("</li>");
}
sb.Append("</ul>\r\n");
string script =
@" <script>
function _errorLinkClick(id) {
var $t = $('#' + id);
if ($t.length == 0) {
$t = $('#txt' + id);
}
if ($t.length == 0) {
$t = $('#cmb' + id);
}
$t.addClass('errorhighlight').focus();
setTimeout(function() {
$t.removeClass('errorhighlight');
}, 5000);
}
</script>";
sb.AppendLine(script);
return sb.ToString();
}
}
}
================================================
FILE: Westwind.Utilities/InternetTools/HttpClient.cs
================================================
#region License
/*
**************************************************************
* Author: Rick Strahl
* � West Wind Technologies, 2009
* http://www.west-wind.com/
*
* Created: 09/12/2009
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.IO.Compression;
using System.Threading.Tasks;
using Westwind.Utilities;
namespace Westwind.Utilities.InternetTools
{
/// <summary>
/// An HTTP wrapper class that abstracts away the common needs for adding post keys
/// and firing update events as data is received. This class is real easy to use
/// with many common operations requiring single method calls.
///
/// The class also provides automated cookie and state handling, GZip compression
/// decompression, simplified proxy and authentication mechanisms to provide a
/// simple single level class interface. The underlying WebRequest is also
/// exposed so you will not loose any functionality from the .NET BCL class.
/// </summary>
#if NET6_0_OR_GREATER
[Obsolete("Westwind.HttpClient is obsolete in .NET Core as it uses the old HttpWebRequest class. Please use System.Net.HttpClient or " +
"`Westwind.Utilities.HttpClientUtils` or in Net4.x for sync Operations `Westwind.Utilities.HttpUtils`")]
#endif
public class HttpClient : IDisposable
{
/// <summary>
/// Determines how data is POSTed when when using AddPostKey() and other methods
/// of posting data to the server. Support UrlEncoded, Multi-Part, XML and Raw modes.
/// </summary>
public HttpPostMode PostMode { get; set; } = HttpPostMode.UrlEncoded;
/// <summary>
/// User name used for Authentication.
/// To use the currently logged in user when accessing an NTLM resource you can use "AUTOLOGIN".
/// </summary>
public string Username { get; set; }
/// <summary>
/// Password for Authentication.
/// </summary>
public string Password { get; set; }
/// <summary>
/// Address of the Proxy Server to be used.
/// Use optional DEFAULTPROXY value to specify that you want to IE's Proxy Settings
/// </summary>
public string ProxyAddress { get; set; }
/// <summary>
/// Semicolon separated Address list of the servers the proxy is not used for.
/// </summary>
public string ProxyBypass { get; set; }
/// <summary>
/// Username for a password validating Proxy. Only used if the proxy info is set.
/// </summary>
public string ProxyUsername { get; set; }
/// <summary>
/// Password for a password validating Proxy. Only used if the proxy info is set.
/// </summary>
public string ProxyPassword { get; set; }
/// <summary>
/// Timeout for the Web request in seconds. Times out on connection, read and send operations.
/// Default is 30 seconds.
/// </summary>
[Obsolete("Please use TimeoutMs instead")]
public int Timeout {
get
{
if (_timeoutMs < 0)
return -1;
return _timeoutMs * 1000;
}
set
{
if(value >= 1)
_timeoutMs = value * 1000;
else if (value == -1)
_timeoutMs = -1;
{
if (value > 0)
_timeoutMs = 1;
else if (value < 0)
_timeoutMs = -1;
else
_timeoutMs = 0;
}
}
}
/// <summary>
/// Timeout for the Web request in seconds. Times out on connection, read and send operations.
/// Default is 30 seconds (30,000ms).
/// </summary>
public int TimeoutMs
{
get => _timeoutMs;
set => _timeoutMs = value;
}
private int _timeoutMs = 30_000;
/// <summary>
/// Returns whether the last request was cancelled through one of the
/// events.
/// </summary>
public bool Cancelled { get; set; }
/// <summary>
/// Use this option to set a custom content type.
/// If possible use PostMode to specify a predefined
/// content type as it will ensure that Post data is
/// appropriately formatted.
///
/// If setting the content type manually POST data
/// </summary>
public string ContentType
{
get { return _ContentType; }
set {
_ContentType = value;
if (_ContentType == null)
return;
if (_ContentType.StartsWith("application/x-www-form-urlencoded"))
PostMode = HttpPostMode.UrlEncoded;
else if (_ContentType.StartsWith("multipart/form-data"))
PostMode = HttpPostMode.MultiPart;
else
PostMode = HttpPostMode.Raw;
}
}
private string _ContentType;
// this doesn't seem necessary - . NET will automatically decode common encodings like UTF-8
///// <summary>
///// The Encoding used to decode the response data
///// </summary>
//public Encoding ResponseEncoding
//{
// get { return _ResponseEncoding; }
// set { _ResponseEncoding = value; }
//}
//private Encoding _ResponseEncoding = Encoding.Default;
/// <summary>
/// When true will automatically add Accept-Encoding: gzip,deflate header
/// and automatically decompress gzip and deflate content
/// </summary>
public bool UseGZip { get; set; }
/// <summary>
/// Keeps track of request timings for the last executed request. Tracks started,
/// firstbyte and lastbyte times as well as ms to first byte
/// (actually first 'buffer' loaded) and last byte.
/// </summary>
/// <remarks>Does not work with DownloadStream() since you control the stream's operations.</remarks>
public HttpTimings HttpTimings { get; set; }
/// <summary>
/// Error Message if the Error Flag is set or an error value is returned from a method.
/// </summary>
public string ErrorMessage
{
get { return _ErrorMessage; }
set { _ErrorMessage = value; }
}
/// <summary>
/// Error flag if an error occurred.
/// </summary>
public bool Error { get; set; }
/// <summary>
/// Determines whether errors cause exceptions to be thrown. By default errors
/// are handled in the class and the Error property is set for error conditions.
/// (not implemented at this time).
/// </summary>
public bool ThrowExceptions { get; set; }
/// <summary>
/// If set to true will automatically track cookies
/// between multiple successive requests on this
/// instance. Uses the CookieCollection property
/// to persist cookie status.
///
/// When set posts values in the CookieCollection,
/// and on return fills the CookieCollection with
/// cookies from the Response.
/// </summary>
public bool HandleCookies { get; set; }
/// <summary>
/// Holds the internal Cookie collection before or after a request. This
/// collection is used only if HandleCookies is set to .t. which also causes it
/// to capture cookies and repost them on the next request.
/// </summary>
public CookieCollection Cookies
{
get
{
if (_Cookies == null)
Cookies = new CookieCollection();
return _Cookies;
}
set { _Cookies = value; }
}
/// <summary>
/// WebResponse object that is accessible after the request is complete and
/// allows you to retrieve additional information about the completed request.
///
/// The Response Stream is already closed after the GetUrl methods complete
/// (except GetUrlResponse()) but you can access the Response object members
/// and collections to retrieve more detailed information about the current
/// request that completed.
/// </summary>
public HttpWebResponse WebResponse { get; set; }
/// <summary>
/// WebRequest object that can be manipulated and set up for the request if you
/// called .
///
/// Note: This object must be recreated and reset for each request, since a
/// request's life time is tied to a single request. This object is not used if
/// you specify a URL on any of the GetUrl methods since this causes a default
/// WebRequest to be created.
/// </summary>
public HttpWebRequest WebRequest { get; set; }
/// <summary>
/// The buffersize used for the Send and Receive operations
/// </summary>
public int BufferSize { get; set; } = 100;
/// <summary>
/// Lets you specify the User Agent browser string that is sent to the server.
/// This allows you to simulate a specific browser if necessary.
/// </summary>
public string UserAgent { get; set; } = "West Wind HTTP .NET Client";
public string HttpVerb { get; set; } = "GET";
// member properties
//string cPostBuffer = string.Empty;
private MemoryStream _PostStream;
private BinaryWriter _PostData;
private string _ErrorMessage = string.Empty;
private CookieCollection _Cookies;
private string _MultiPartBoundary = "-----------------------------" + DateTime.Now.Ticks.ToString("x");
/// <summary>
/// The HttpClient Default Constructor
/// </summary>
public HttpClient()
{
HttpTimings = new HttpTimings();
}
/// <summary>
/// Creates a new WebRequest instance that can be set prior to calling the
/// various Get methods. You can then manipulate the WebRequest property, to
/// custom configure the request.
///
/// Instead of passing a URL you can then pass null.
///
/// Note - You need a new Web Request for each and every request so you need to
/// set this object for every call if you manually customize it.
/// </summary>
/// <param name="String Url">
/// The Url to access with this WebRequest
/// </param>
/// <returns>Boolean</returns>
public bool CreateWebRequestObject(string Url)
{
try
{
#pragma warning disable SYSLIB0014
WebRequest = (HttpWebRequest) System.Net.WebRequest.Create(Url);
#pragma warning restore SYSLIB0014
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
return false;
}
return true;
}
#region POST data
/// <summary>
/// Resets the Post buffer by clearing out all existing content
/// </summary>
public void ResetPostData()
{
_PostStream = new MemoryStream();
_PostData = new BinaryWriter(_PostStream);
}
public void SetPostStream(Stream postStream)
{
MemoryStream ms = new MemoryStream(1024);
FileUtils.CopyStream(postStream, ms, 1024);
ms.Flush();
ms.Position = 0;
_PostStream = ms;
_PostData = new BinaryWriter(ms);
}
/// <summary>
/// Adds POST form variables to the request buffer.
/// PostMode determines how parms are handled.
/// </summary>
/// <param name="key">Key value or raw buffer depending on post type</param>
/// <param name="value">Value to store. Used only in key/value pair modes</param>
public void AddPostKey(string key, byte[] value)
{
if (value == null)
return;
if (key == "RESET")
{
ResetPostData();
return;
}
if (_PostData == null)
{
_PostStream = new MemoryStream();
_PostData = new BinaryWriter(_PostStream);
}
if (string.IsNullOrEmpty(key))
_PostData.Write(value);
else if(PostMode == HttpPostMode.UrlEncoded)
_PostData.Write(
Encoding.Default.GetBytes(key + "=" +
StringUtils.UrlEncode(Encoding.Default.GetString(value)) +
"&") );
else if (PostMode == HttpPostMode.MultiPart)
{
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
_PostData.Write(iso.GetBytes(
"--" + _MultiPartBoundary + "\r\n" +
"Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n"));
_PostData.Write(value);
_PostData.Write(iso.GetBytes("\r\n"));
}
else // Raw or Xml, JSON modes
_PostData.Write( value );
}
/// <summary>
/// Adds POST form variables to the request buffer.
/// PostMode determines how parms are handled.
/// </summary>
/// <param name="key">Key value or raw buffer depending on post type</param>
/// <param name="value">Value to store. Used only in key/value pair modes</param>
public void AddPostKey(string key, string value)
{
if (value == null)
return;
AddPostKey(key,Encoding.Default.GetBytes(value));
}
/// <summary>
/// Adds a fully self contained POST buffer to the request.
/// Works for XML or previously encoded content.
/// </summary>
/// <param name="fullPostBuffer">String based full POST buffer</param>
public void AddPostKey(string fullPostBuffer)
{
AddPostKey(null,fullPostBuffer );
}
/// <summary>
/// Adds a fully self contained POST buffer to the request.
/// Works for XML or previously encoded content.
/// </summary>
/// <param name="fullPostBuffer">Byte array of a full POST buffer</param>
public void AddPostKey(byte[] fullPostBuffer)
{
AddPostKey(null,fullPostBuffer);
}
/// <summary>
/// Allows posting a file to the Web Server. Make sure that you
/// set PostMode
/// </summary>
/// <param name="key"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public bool AddPostFile(string key,string fileName, string contentType = "application/octet-stream")
{
byte[] lcFile;
if (PostMode != HttpPostMode.MultiPart)
{
_ErrorMessage = "File upload allowed only with Multi-part forms";
Error = true;
return false;
}
try
{
FileStream loFile = new FileStream(fileName,System.IO.FileMode.Open,System.IO.FileAccess.Read);
lcFile = new byte[loFile.Length];
_ = loFile.Read(lcFile,0,(int) loFile.Length);
loFile.Close();
}
catch(Exception e)
{
_ErrorMessage = e.Message;
Error = true;
return false;
}
if (_PostData == null)
{
_PostStream = new MemoryStream();
_PostData = new BinaryWriter(_PostStream);
}
_PostData.Write( Encoding.Default.GetBytes(
"--" + _MultiPartBoundary + "\r\n" +
"Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" +
new FileInfo(fileName).Name + "\"\r\n" +
"Content-Type: " + contentType +
"\r\n\r\n" ) );
_PostData.Write( lcFile );
_PostData.Write( Encoding.Default.GetBytes("\r\n")) ;
return true;
}
/// <summary>
/// Returns the contents of the post buffer. Useful for debugging
/// </summary>
/// <returns></returns>
public string GetPostBuffer()
{
var bytes = _PostStream?.ToArray();
if (bytes == null)
return null;
return Encoding.Default.GetString(bytes);
}
#endregion
#region Run Requests
/// <summary>
/// Return a the result from an HTTP Url into a StreamReader.
/// Client code should call Close() on the returned object when done reading.
/// </summary>
/// <param name="url">Url to retrieve.</param>
/// <returns></returns>
public StreamReader DownloadStream(string url)
{
try
{
Encoding enc;
HttpWebResponse Response = DownloadResponse(url);
if (Response == null)
return null;
try
{
if (!string.IsNullOrEmpty(Response.CharacterSet))
enc = Encoding.GetEncoding(Response.CharacterSet);
else
enc = Encoding.Default;
}
catch
{
// Invalid encoding passed
enc = Encoding.Default;
}
Stream responseStream = Response.GetResponseStream();
//if (Response.ContentEncoding.ToLower().Contains("gzip"))
// responseStream = new GZipStream(Response.GetResponseStream(), CompressionMode.Decompress);
//else if (Response.ContentEncoding.ToLower().Contains("deflate"))
// responseStream = new DeflateStream(Response.GetResponseStream(), CompressionMode.Decompress);
// drag to a stream
StreamReader strResponse = new StreamReader(responseStream, enc);
return strResponse;
}
catch (Exception ex)
{
Error = true;
ErrorMessage = "Unable to read response: " + ex.Message;
return null;
}
}
/// <summary>
/// Return an HttpWebResponse object for a request. You can use the Response to
/// read the result as needed. This is a low level method. Most of the other 'Get'
/// methods call this method and process the results further.
/// </summary>
/// <remarks>Important: The Response object's Close() method must be called when you are done with the object.</remarks>
/// <param name="url">Url to retrieve.</param>
/// <returns>An HttpWebResponse Object</returns>
[Obsolete("Use DownloadResponse instead.")]
public HttpWebResponse GetUrlResponse(string url)
{
return DownloadResponse(url);
}
public async Task<HttpWebResponse> DownloadResponseAsync(string url)
{
Cancelled = false;
//try
//{
Error = false;
_ErrorMessage = string.Empty;
Cancelled = false;
if (WebRequest == null)
{
#pragma warning disable SYSLIB0014
WebRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
#pragma warning restore SYSLIB0014
//WebRequest.Headers.Add("Cache","no-cache");
}
WebRequest.UserAgent = UserAgent;
WebRequest.Timeout = TimeoutMs;
WebRequest.Method = HttpVerb;
#if NETFULL
WebRequest.ReadWriteTimeout = TimeoutMs;
#endif
// Handle Security for the request
if (!string.IsNullOrEmpty(Username))
{
if (Username == "AUTOLOGIN" || Username == "AutoLogin")
WebRequest.Credentials = CredentialCache.DefaultCredentials;
else
WebRequest.Credentials = new NetworkCredential(Username, Password);
}
// Handle Proxy Server configuration
if (!string.IsNullOrEmpty(ProxyAddress))
{
if (ProxyAddress == "DEFAULTPROXY")
{
WebRequest.Proxy = HttpWebRequest.DefaultWebProxy;
}
else
{
WebProxy Proxy = new WebProxy(ProxyAddress, true);
if (ProxyBypass.Length > 0)
{
Proxy.BypassList = ProxyBypass.Split(';');
}
if (ProxyUsername.Length > 0)
Proxy.Credentials = new NetworkCredential(ProxyUsername, ProxyPassword);
WebRequest.Proxy = Proxy;
}
}
if (UseGZip)
{
// TODO: Check if already set
WebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
WebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
// Handle cookies - automatically re-assign
if (HandleCookies || (_Cookies != null && _Cookies.Count > 0))
{
WebRequest.CookieContainer = new CookieContainer();
if (_Cookies != null && _Cookies.Count > 0)
{
WebRequest.CookieContainer.Add(_Cookies);
}
}
HttpTimings.StartRequest();
// Deal with the POST buffer if any
if (_PostData != null)
{
if (WebRequest.Method == "GET")
WebRequest.Method = "POST";
switch (PostMode)
{
case HttpPostMode.UrlEncoded:
WebRequest.ContentType = "application/x-www-form-urlencoded";
break;
case HttpPostMode.MultiPart:
WebRequest.ContentType = "multipart/form-data; boundary=" + _MultiPartBoundary;
_PostData.Write(Encoding.GetEncoding(1252).GetBytes("--" + _MultiPartBoundary + "--\r\n"));
break;
case HttpPostMode.Xml:
WebRequest.ContentType = "text/xml";
break;
case HttpPostMode.Json:
WebRequest.ContentType = "application/json";
break;
case HttpPostMode.Raw:
//WebRequest.ContentType = "application/octet-stream";
break;
default:
goto case HttpPostMode.UrlEncoded;
}
if (!string.IsNullOrEmpty(ContentType))
WebRequest.ContentType = ContentType;
// TODO: Make POSTing async
using (Stream requestStream = WebRequest.GetRequestStream())
{
if (SendData == null)
_PostStream.WriteTo(requestStream); // Simplest version - no events
else
StreamPostBuffer(requestStream); // Send in chunks and fire events
//*** Close the memory stream
_PostStream.Close();
_PostStream = null;
//*** Close the Binary Writer
if (_PostData != null)
{
_PostData.Dispose();
_PostData = null;
}
}
// clear out the Post buffer
ResetPostData();
// If user cancelled the 'upload' exit
if (Cancelled)
{
ErrorMessage = "HTTP Request was cancelled.";
Error = true;
return null;
}
}
// Retrieve the response headers
HttpWebResponse Response;
try
{
Response = await WebRequest.GetResponseAsync() as HttpWebResponse;
}
catch (WebException ex)
{
// Check for 500 error return - if so we still want to return a response
// Client can check oHttp.WebResponse.StatusCode
if (ex.Status == WebExceptionStatus.ProtocolError)
{
Response = (HttpWebResponse)ex.Response;
}
else
{
if(ThrowExceptions)
throw;
Error = true;
ErrorMessage = ex.Message + "." + url;
return null;
}
}
WebResponse = Response;
// Close out the request - it cannot be reused
WebRequest = null;
// ** Save cookies the server sends
if (HandleCookies)
{
if (Response.Cookies.Count > 0)
{
if (_Cookies == null)
_Cookies = Response.Cookies;
else
{
// ** If we already have cookies update the list
foreach (Cookie oRespCookie in Response.Cookies)
{
bool bMatch = false;
foreach (Cookie oReqCookie in _Cookies)
{
if (oReqCookie.Name == oRespCookie.Name)
{
oReqCookie.Value = oRespCookie.Value;
bMatch = true;
break; //
}
} // for each ReqCookies
if (!bMatch)
_Cookies.Add(oRespCookie);
}
}
}
}
return Response;
}
/// <summary>
/// Return an HttpWebResponse object for a request. You can use the Response to
/// read the result as needed. This is a low level method. Most of the other 'Get'
/// methods call this method and process the results further.
/// </summary>
/// <remarks>Important: The Response object's Close() method must be called when you are done with the object.</remarks>
/// <param name="url">Url to retrieve.</param>
/// <returns>An HttpWebResponse Object</returns>
public HttpWebResponse DownloadResponse(string url)
{
Cancelled = false;
//try
//{
Error = false;
_ErrorMessage = string.Empty;
Cancelled = false;
if (WebRequest == null)
{
#pragma warning disable SYSLIB0014
WebRequest = (HttpWebRequest) System.Net.WebRequest.Create(url);
#pragma warning restore SYSLIB0014
//WebRequest.Headers.Add("Cache","no-cache");
}
WebRequest.UserAgent = UserAgent;
WebRequest.Timeout = TimeoutMs;
WebRequest.Method = HttpVerb;
#if NETFULL
WebRequest.ReadWriteTimeout = TimeoutMs;
#endif
// Handle Security for the request
if (!string.IsNullOrEmpty(Username))
{
if (Username == "AUTOLOGIN" || Username == "AutoLogin")
WebRequest.Credentials = CredentialCache.DefaultCredentials;
else
WebRequest.Credentials = new NetworkCredential(Username,Password);
}
// Handle Proxy Server configuration
if (!string.IsNullOrEmpty(ProxyAddress))
{
if (ProxyAddress == "DEFAULTPROXY")
{
WebRequest.Proxy = HttpWebRequest.DefaultWebProxy;
}
else
{
WebProxy Proxy = new WebProxy(ProxyAddress,true);
if (ProxyBypass.Length > 0)
{
Proxy.BypassList = ProxyBypass.Split(';');
}
if (ProxyUsername.Length > 0)
Proxy.Credentials = new NetworkCredential(ProxyUsername,ProxyPassword);
WebRequest.Proxy = Proxy;
}
}
if (UseGZip)
{
// TODO: Check if already set
WebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
WebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
// Handle cookies - automatically re-assign
if (HandleCookies || (_Cookies != null && _Cookies.Count > 0) )
{
WebRequest.CookieContainer = new CookieContainer();
if (_Cookies != null && _Cookies.Count > 0)
{
WebRequest.CookieContainer.Add(_Cookies);
}
}
HttpTimings.StartRequest();
// Deal with the POST buffer if any
if (_PostData != null)
{
if (WebRequest.Method == "GET")
WebRequest.Method = "POST";
switch (PostMode)
{
case HttpPostMode.UrlEncoded:
WebRequest.ContentType = "application/x-www-form-urlencoded";
break;
case HttpPostMode.MultiPart:
WebRequest.ContentType = "multipart/form-data; boundary=" + _MultiPartBoundary;
_PostData.Write(Encoding.GetEncoding(1252).GetBytes("--" + _MultiPartBoundary + "--\r\n"));
break;
case HttpPostMode.Xml:
WebRequest.ContentType = "text/xml";
break;
case HttpPostMode.Json:
WebRequest.ContentType = "application/json";
break;
case HttpPostMode.Raw:
//WebRequest.ContentType = "application/octet-stream";
break;
default:
goto case HttpPostMode.UrlEncoded;
}
if (!string.IsNullOrEmpty(ContentType))
WebRequest.ContentType = ContentType;
using (Stream requestStream = WebRequest.GetRequestStream())
{
if (SendData == null)
_PostStream.WriteTo(requestStream); // Simplest version - no events
else
StreamPostBuffer(requestStream); // Send in chunks and fire events
//*** Close the memory stream
_PostStream.Close();
_PostStream = null;
//*** Close the Binary Writer
if (_PostData != null)
{
_PostData.Dispose();
_PostData = null;
}
}
// clear out the Post buffer
ResetPostData();
// If user cancelled the 'upload' exit
if (Cancelled)
{
ErrorMessage = "HTTP Request was cancelled.";
Error = true;
return null;
}
}
if ((WebRequest.Method == "POST" || WebRequest.Method == "PUT" || WebRequest.Method == "PATCH") &&
_PostData == null)
{
WebRequest.ContentLength = 0;
}
// Retrieve the response headers
HttpWebResponse Response;
try
{
Response = (HttpWebResponse) WebRequest.GetResponse();
}
catch(WebException ex)
{
// Check for 500 error return - if so we still want to return a response
// Client can check oHttp.WebResponse.StatusCode
if (ex.Status == WebExceptionStatus.ProtocolError)
{
Response = (HttpWebResponse) ex.Response;
}
else
{
if (ThrowExceptions)
throw;
Error = true;
ErrorMessage = ex.GetBaseException().Message + " " + url;
return null;
}
}
WebResponse = Response;
// Close out the request - it cannot be reused
WebRequest = null;
// ** Save cookies the server sends
if (HandleCookies)
{
if (Response.Cookies.Count > 0)
{
if (_Cookies == null)
_Cookies = Response.Cookies;
else
{
// ** If we already have cookies update the list
foreach (Cookie oRespCookie in Response.Cookies)
{
bool bMatch = false;
foreach (Cookie oReqCookie in _Cookies)
{
if (oReqCookie.Name == oRespCookie.Name)
{
oReqCookie.Value = oRespCookie.Value;
bMatch = true;
break; //
}
} // for each ReqCookies
if (!bMatch)
_Cookies.Add(oRespCookie);
}
}
}
}
return Response;
}
/// <summary>
/// Sends the Postbuffer to the server
/// </summary>
/// <param name="PostData"></param>
protected void StreamPostBuffer(Stream PostData)
{
if (_PostStream.Length < BufferSize)
{
_PostStream.WriteTo(PostData);
// Handle Send Data Even
// Here just let it know we're done
if (SendData != null)
{
ReceiveDataEventArgs Args = new ReceiveDataEventArgs();
Args.CurrentByteCount = _PostStream.Length;
Args.Done = true;
SendData(this, Args);
}
}
else
{
// Send data up in 8k blocks
byte[] Buffer = _PostStream.GetBuffer();
int lnSent = 0;
int lnToSend = (int)_PostStream.Length;
int lnCurrent = 1;
while (true)
{
if (lnToSend < 1 || lnCurrent < 1)
{
if (SendData != null)
{
ReceiveDataEventArgs Args = new ReceiveDataEventArgs();
Args.CurrentByteCount = lnSent;
Args.TotalBytes = Buffer.Length;
Args.Done = true;
SendData(this, Args);
}
break;
}
lnCurrent = lnToSend;
if (lnCurrent > BufferSize)
{
lnCurrent = BufferSize;
lnToSend = lnToSend - lnCurrent;
}
else
{
lnToSend = lnToSend - lnCurrent;
}
PostData.Write(Buffer, lnSent, lnCurrent);
lnSent = lnSent + lnCurrent;
if (SendData != null)
{
ReceiveDataEventArgs Args = new ReceiveDataEventArgs();
Args.CurrentByteCount = lnSent;
Args.TotalBytes = Buffer.Length;
if (Buffer.Length == lnSent)
{
Args.Done = true;
SendData(this, Args);
break;
}
SendData(this, Args);
if (Args.Cancel)
{
Cancelled = true;
break;
}
}
}
}
}
/// <summary>
/// Returns the content of a URL as a string
/// </summary>
/// <param name="url"></param>
/// <param name="bufferSize">The intermediate download buffer used</param>
/// <param name="encoding">A .NET Encoding scheme or null to attempt sniffing from Charset.</param>
/// <returns></returns>
[Obsolete("Use the DownloadString() method instead.")]
public string GetUrl(string url, long bufferSize = 8192, Encoding encoding = null)
{
return DownloadString(url, bufferSize, encoding);
}
/// <summary>
/// Returns the content of a URL as a string using a specified Encoding
/// </summary>
/// <param name="url"></param>
/// <param name="bufferSize">Internal download buffer size used to hold data chunks.</param>
/// <param name="encoding">A .NET Encoding scheme or null to attempt sniffing from Charset.</param>
/// <returns></returns>
public string DownloadString(string url, long bufferSize = 8192, Encoding encoding = null)
{
byte[] bytes = DownloadBytes(url, bufferSize);
if (bytes == null)
return null;
if (encoding == null)
{
encoding = Encoding.Default;
try
{
if (!string.IsNullOrEmpty(WebResponse.CharacterSet))
{
string charset = WebResponse.CharacterSet.ToLower();
// special case UTF-8 since it's most common
if (charset.Contains("utf-8"))
encoding = Encoding.UTF8;
else if (charset.Contains("utf-16"))
encoding = Encoding.Unicode;
else if (charset.Contains("utf-32"))
encoding = Encoding.UTF32;
else
encoding = Encoding.GetEncoding(WebResponse.CharacterSet);
}
}
catch { } // ignore encoding assignment failures
}
return encoding.GetString(bytes);
}
/// <summary>
/// Returns the content of a URL as a string using a specified Encoding
/// </summary>
/// <param name="url"></param>
/// <param name="bufferSize">Internal download buffer size used to hold data chunks.</param>
/// <param name="encoding">A .NET Encoding scheme or null to attempt sniffing from Charset.</param>
/// <returns></returns>
public async Task<string> DownloadStringAsync(string url, long bufferSize = 8192, Encoding encoding = null)
{
byte[] bytes = await DownloadBytesAsync(url, bufferSize);
if (bytes == null)
return null;
if (encoding == null)
{
encoding = Encoding.Default;
try
{
if (!string.IsNullOrEmpty(WebResponse.CharacterSet))
{
string charset = WebResponse.CharacterSet.ToLower();
// special case UTF-8 since it's most common
if (charset.Contains("utf-8"))
encoding = Encoding.UTF8;
else if (charset.Contains("utf-16"))
encoding = Encoding.Unicode;
else if (charset.Contains("utf-32"))
encoding = Encoding.UTF32;
else
encoding = Encoding.GetEncoding(WebResponse.CharacterSet);
}
}
catch { } // ignore encoding assignment failures
}
return encoding.GetString(bytes);
}
/// <summary>
/// Returns a partial response from the URL by specifying only
/// given number of bytes to retrieve. This can reduce network
/// traffic and keep string formatting down if you are only
/// interested a small port at the top of the page. Also
/// returns full headers.
/// </summary>
/// <param name="url"></param>
/// <param name="size"></param>
/// <returns></returns>
[Obsolete("Use DownloadStringPartial() instead.")]
public string GetUrlPartial(string url, int size)
{
return GetUrlPartial(url, size);
}
/// <summary>
/// Returns a partial response from the URL by specifying only
/// given number of bytes to retrieve. This can reduce network
/// traffic and keep string formatting down if you are only
/// interested a small port at the top of the page. Also
/// returns full headers.
/// </summary>
/// <param name="url"></param>
/// <param name="size"></param>
/// <returns></returns>
public string DownloadStringPartial(string url, int size)
{
char[] buffer;
using (StreamReader sr = DownloadStream(url))
{
if (sr == null)
return null;
buffer = new char[size];
sr.Read(buffer, 0, size);
}
return new string(buffer);
}
/// <summary>
/// Retrieves URL into an Byte Array.
/// </summary>
/// <remarks>Fires the ReceiveData Event</remarks>
/// <param name="url">Url to read</param>
/// <param name="bufferSize">Size of the buffer for each read. 0 = 8192</param>
/// <returns></returns>
public byte[] DownloadBytes(string url, long bufferSize = 8192)
{
HttpWebResponse response = DownloadResponse(url);
if (response == null)
return null;
long responseSize = bufferSize;
if (response.ContentLength > 0)
responseSize = WebResponse.ContentLength;
else
// No content size provided
responseSize = -1;
Stream responseStream = responseStream = response.GetResponseStream();
//if (response.ContentEncoding.ToLower().Contains("gzip"))
//{
// responseStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress);
// responseSize = -1; // we don't have a size
//}
//else if (response.ContentEncoding.ToLower().Contains("deflate"))
//{
// responseStream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress);
// responseSize = -1; // we don't have a size
//}
//else
if (responseStream == null)
{
Error = true;
ErrorMessage = "Failed to retrieve a response from " + url;
return null;
}
using (responseStream)
{
if (bufferSize < 1)
bufferSize = 4096;
var ms = new MemoryStream((int) bufferSize);
byte[] buffer = new byte[bufferSize];
var args = new ReceiveDataEventArgs();
args.TotalBytes = responseSize;
long bytesRead = 1;
int count = 0;
long totalBytes = 0;
while (bytesRead > 0)
{
if (responseSize != -1 && totalBytes + bufferSize > responseSize)
bufferSize = responseSize - totalBytes;
bytesRead = responseStream.Read(buffer, 0, (int) bufferSize);
if (bytesRead > 0)
{
if (totalBytes == 0)
HttpTimings.FirstByteTime = DateTime.UtcNow;
// write to stream
ms.Write(buffer, 0, (int) bytesRead);
count++;
totalBytes += bytesRead;
// Raise an event if hooked up
if (ReceiveData != null)
{
// Update the event handler
args.CurrentByteCount = totalBytes;
args.NumberOfReads = count;
args.CurrentChunk = null; // don't send anything here
ReceiveData(this, args);
// Check for cancelled flag
if (args.Cancel)
{
Cancelled = true;
break;
}
}
}
} // while
HttpTimings.LastByteTime = DateTime.UtcNow;
// Send Done notification
if (ReceiveData != null && !args.Cancel)
{
// Update the event handler
args.Done = true;
ReceiveData(this, args);
}
//ms.Flush();
ms.Position = 0;
return ms.ToArray();
}
}
/// <summary>
/// Retrieves URL into an Byte Array.
/// </summary>
/// <remarks>Fires the ReceiveData Event</remarks>
/// <param name="url">Url to read</param>
/// <param name="bufferSize">Size of the buffer for each read. 0 = 8192</param>
/// <returns></returns>
public async Task<byte[]> DownloadBytesAsync(string url, long bufferSize = 8192)
{
HttpWebResponse response = await DownloadResponseAsync(url);
if (response == null)
return null;
long responseSize = bufferSize;
if (response.ContentLength > 0)
responseSize = WebResponse.ContentLength;
else
// No content size provided
responseSize = -1;
Stream responseStream = response.GetResponseStream();
if (responseStream == null)
{
Error = true;
ErrorMessage = "Failed to retrieve a response from " + url;
return null;
}
if (response.ContentEncoding != null)
{
if(response.ContentEncoding.ToLower().Contains("gzip"))
{
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
responseSize = -1; // we don't have a size
}
else if (response.ContentEncoding.ToLower().Contains("deflate"))
{
responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
responseSize = -1; // we don't have a size
}
}
using (responseStream)
{
if (bufferSize < 1)
bufferSize = 4096;
var ms = new MemoryStream((int)bufferSize);
byte[] buffer = new byte[bufferSize];
var args = new ReceiveDataEventArgs();
args.TotalBytes = responseSize;
long bytesRead = 1;
int count = 0;
long totalBytes = 0;
while (bytesRead > 0)
{
if (responseSize != -1 && totalBytes + bufferSize > responseSize)
bufferSize = responseSize - totalBytes;
bytesRead = await responseStream.ReadAsync(buffer, 0, (int)bufferSize);
if (bytesRead > 0)
{
if (totalBytes == 0)
HttpTimings.FirstByteTime = DateTime.UtcNow;
// write to stream
ms.Write(buffer, 0, (int)bytesRead);
count++;
totalBytes += bytesRead;
// Raise an event if hooked up
if (ReceiveData != null)
{
// Update the event handler
args.CurrentByteCount = totalBytes;
args.NumberOfReads = count;
args.CurrentChunk = null; // don't send anything here
ReceiveData(this, args);
// Check for cancelled flag
if (args.Cancel)
{
Cancelled = true;
break;
}
}
}
} // while
HttpTimings.LastByteTime = DateTime.UtcNow;
// Send Done notification
if (ReceiveData != null && !args.Cancel)
{
// Update the event handler
args.Done = true;
ReceiveData(this, args);
}
ms.Position = 0;
var bytes = ms.ToArray();
ms.Dispose();
return bytes;
}
}
/// <summary>
/// Writes the output from the URL request to a file firing events.
/// </summary>
/// <param name="Url">Url to fire</param>
/// <param name="BufferSize">Buffersize - how often to fire events</param>
/// <param name="OutputFile">File to write response to</param>
/// <returns>true or false</returns>
[Obsolete("Use DownloadFile() instead.")]
public bool GetUrlFile(string Url, long BufferSize, string OutputFile)
{
return DownloadFile(Url, BufferSize, OutputFile);
}
/// <summary>
/// Writes the output from the URL request to a file firing events.
/// </summary>
/// <param name="url">Url to fire</param>
/// <param name="bufferSize">Buffersize - how often to fire events</param>
/// <param name="outputFile">File to write response to</param>
/// <returns>true or false</returns>
public bool DownloadFile(string url,long bufferSize,string outputFile)
{
byte[] result = DownloadBytes(url,bufferSize);
if (result == null)
return false;
File.Delete(outputFile);
File.WriteAllBytes(outputFile, result);
return File.Exists(outputFile);
}
#endregion
#region Certificates
/// <summary>
/// Sets the certificate policy.
///
/// Note this is a global setting and affects the entire application.
/// It's recommended you set this for the application and not on
/// a per request basis.
/// </summary>
/// <param name="Ignore"></param>
public static bool IgnoreCertificateErrors
{
set
{
if (value)
#pragma warning disable SYSLIB0014
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(CheckCertificateCallback);
#pragma warning restore SYSLIB0014
else
#pragma warning disable SYSLIB0014
ServicePointManager.ServerCertificateValidationCallback -= new RemoteCertificateValidationCallback(CheckCertificateCallback);
#pragma warning restore SYSLIB0014
}
}
/// <summary>
/// Handles the Certificate check
/// </summary>
/// <param name="sender"></param>
/// <param name="cert"></param>
/// <param name="chain"></param>
/// <param name="errors"></param>
/// <returns></returns>
private static bool CheckCertificateCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
#endregion
#region Events and Event Delegates and Arguments
/// <summary>
/// Fires progress events when receiving data from the server
/// </summary>
public event ReceiveDataDelegate ReceiveData;
public delegate void ReceiveDataDelegate(object sender, ReceiveDataEventArgs e);
/// <summary>
/// Fires progress events when using GetUrlEvents() to retrieve a URL.
/// </summary>
public event ReceiveDataDelegate SendData;
/// <summary>
/// Event arguments passed to the ReceiveData event handler on each block of data sent
/// </summary>
public class ReceiveDataEventArgs
{
/// <summary>
/// Size of the cumulative bytes read in this request
/// </summary>
public long CurrentByteCount=0;
/// <summary>
/// The number of total bytes of this request
/// </summary>
public long TotalBytes = 0;
/// <summary>
/// The number of reads that have occurred - how often has this event been called.
/// </summary>
public int NumberOfReads = 0;
/// <summary>
/// The current chunk of data being read
/// </summary>
public char[] CurrentChunk;
/// <summary>
/// Flag set if the request is currently done.
/// </summary>
public bool Done = false;
/// <summary>
/// Flag to specify that you want the current request to cancel. This is a write-only flag
/// </summary>
public bool Cancel = false;
}
#endregion
/// <summary>
/// Releases response and request data
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
if (WebResponse != null)
{
WebResponse.Dispose(); // introduced in 4.5
WebResponse = null;
}
if (WebRequest != null)
WebRequest = null;
}
}
/// <summary>
/// Enumeration of the various HTTP POST modes supported by HttpClient
/// </summary>
public enum HttpPostMode
{
UrlEncoded,
MultiPart,
Xml,
Json,
Raw
};
#if NETFULL
/// <summary>
/// Internal object used to allow setting WebRequest.CertificatePolicy to
/// not fail on Cert errors
/// </summary>
internal class AcceptAllCertificatePolicy : ICertificatePolicy
{
public AcceptAllCertificatePolicy()
{
}
public bool CheckValidationResult(ServicePoint sPoint,
X509Certificate cert, WebRequest wRequest, int certProb)
{
// Always accept
return true;
}
}
#endif
public class HttpTimings
{
public DateTime StartedTime { get; set; }
public DateTime FirstByteTime { get; set; }
public DateTime LastByteTime { get; set; }
public void StartRequest()
{
StartedTime = DateTime.UtcNow;
FirstByteTime = DateTime.UtcNow;
LastByteTime = DateTime.UtcNow;
}
public int TimeToFirstByteMs
{
get { return (int) FirstByteTime.Subtract(StartedTime).TotalMilliseconds; }
}
public int TimeToLastByteMs
{
get { return (int)LastByteTime.Subtract(StartedTime).TotalMilliseconds; }
}
public bool IsEmpty()
{
return StartedTime < new DateTime(2010, 1, 1);
}
}
}
================================================
FILE: Westwind.Utilities/InternetTools/SmtpClientNative.cs
================================================
#region License
/*
**************************************************************
* Author: Rick Strahl
* West Wind Technologies, 2009
* http://www.west-wind.com/
*
* Created: 09/12/2009
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
using System;
using System.Text;
using System.Threading;
using System.IO;
using System.Net.Mail;
using System.Net;
using System.Security;
using System.Collections.Generic;
namespace Westwind.Utilities.InternetTools
{
/// <summary>
/// SMTP Wrapper around System.Net.Email.SmtpClient. Provided
/// here mainly to provide compatibility with existing wwSmtp code
/// and to provide a slightly more user friendly front end interface
/// on a single object.
/// </summary>
public class SmtpClientNative : IDisposable
{
/// <summary>
/// Mail Server to send message through. Should be a domain name
/// (mail.yourserver.net) or IP Address (211.123.123.123).
///
/// You can also provide a port number as part of the string which will
/// override the ServerPort (yourserver.net:211)
/// <seealso>Class wwSmtp</seealso>
/// </summary>
public string MailServer = string.Empty;
/// <summary>
/// Port on the mail server to send through. Defaults to port 25.
/// </summary>
public int ServerPort = 25;
/// <summary>
/// Use Tls Security
/// </summary>
public bool UseSsl = false;
/// <summary>
/// Email address or addresses of the Recipient. Comma delimit multiple addresses. To have formatted names use
/// "Rick Strahl" <rstrahl@west-wind.com>
/// </summary>
public string Recipient = string.Empty;
/// <summary>
/// Carbon Copy Recipients
/// </summary>
public string CC = string.Empty;
/// <summary>
/// Blind Copy Recipients
/// </summary>
public string BCC = string.Empty;
/// <summary>
/// Email address of the sender
/// </summary>
public string SenderEmail = string.Empty;
/// <summary>
/// Display name of the sender (optional)
/// </summary>
public string SenderName = String.Empty;
/// <summary>
/// The ReplyTo address
/// </summary>
public string ReplyTo = String.Empty;
/// <summary>
/// Message Subject.
/// </summary>
public string Subject = String.Empty;
/// <summary>
/// The body of the message.
/// </summary>
public string Message = String.Empty;
/// <summary>
/// Username to connect to the mail server.
/// </summary>
public string Username = String.Empty;
/// <summary>
/// Password to connect to the mail server.
/// </summary>
public string Password = String.Empty;
/// <summary>
/// Any attachments you'd like to send
/// </summary>
public string Attachments = String.Empty;
/// <summary>
/// List of attachment objects
/// </summary>
public List<Attachment> AttachmentList = new List<Attachment>();
/// <summary>
/// The content type of the message. text/plain default or you can set to any other type like text/html
/// </summary>
public string ContentType = "text/plain";
/// <summary>
/// Character Encoding for the message.
/// </summary>
public string CharacterEncoding = "8bit";
/// <summary>
/// The character Encoding used to write the stream out to disk
/// Defaults to the default Locale used on the server.
/// </summary>
public System.Text.Encoding Encoding = Encoding.Default;
/// <summary>
///
/// </summary>
public string AlternateText = string.Empty;
/// <summary>
/// The content type for the alternate
/// </summary>
public string AlternateTextContentType = "text/plain";
/// <summary>
/// The user agent for the x-mailer
/// </summary>
public string UserAgent = "";
/// <summary>
/// Determines the priority of the message
/// </summary>
public string Priority = "Normal";
/// <summary>
/// Determines whether a return receipt is sent
/// </summary>
public bool ReturnReceipt = false;
/// <summary>
///
/// </summary>
/// <returns></returns>
protected internal List<AlternateView> AlternateViews = new List<AlternateView>();
/// <summary>
/// An optional file name that appends logging information for the TCP/IP messaging
/// to the specified file.
/// </summary>
public string LogFile = string.Empty;
/// <summary>
/// Determines whether wwSMTP passes back errors as exceptions or
/// whether it sets error properties. Right now only error properties
/// work reliably.
/// </summary>
public bool HandleExceptions = true;
/// <summary>
/// An Error Message if the result is negative or Error is set to true;
/// </summary>
public string ErrorMessage = string.Empty;
/// <summary>
/// Error Flag set when an error occurs.
/// </summary>
public bool Error = false;
/// <summary>
/// Connection timeouts for the mail server in seconds. If this timeout is exceeded waiting for a connection
/// or for receiving or sending data the request is aborted and fails.
/// </summary>
public int Timeout = 30;
/// <summary>
/// SMTP headers for this email request
/// </summary>
public Dictionary<string, string> Headers = new Dictionary<string, string>();
/// <summary>
/// Event fired when sending of a message or multiple messages
/// is complete and the connection is to be closed. This event
/// occurs only once per connection as opposed to the MessageSendComplete
/// event which fires after each message is sent regardless of the
/// number of SendMessage operations.
/// </summary>
public event delSmtpNativeEvent SendComplete;
/// <summary>
/// Event fired when an error occurs during processing and before
/// the connection is closed down.
/// </summary>
public event delSmtpNativeEvent SendError;
/// <summary>
/// Internal instance of SmtpClient that holds the 'connection'
/// effectively.
/// </summary>
private SmtpClient smtp = null;
/// <summary>
/// Adds an Smtp header to this email request. Headers are
/// always cleared after a message has been sent or failed.
/// </summary>
/// <param name="headerName"></param>
/// <param name="value"></param>
public void AddHeader(string headerName, string value)
{
if (headerName.ToLower() == "clear" || headerName.ToLower() == "reset")
this.Headers.Clear();
else
{
if (!Headers.ContainsKey(headerName))
this.Headers.Add(headerName, value);
else
this.Headers[headerName] = value;
}
}
/// <summary>
/// Adds headers from a CR/LF separate string that has key:value header pairs
/// defined.
/// </summary>
/// <param name="headers"></param>
public void AddHeadersFromString(string headers)
{
string[] lines = headers.Split(new char[2] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string[] tokens = line.Split(':');
if (tokens.Length != 2)
continue;
this.AddHeader(tokens[0].Trim(), tokens[1].Trim());
}
}
/// <summary>
/// Lets you load the actual SMTP client instance
/// prior to use so you can manipulate the actual
/// Smtp instance.
/// </summary>
/// <returns></returns>
public SmtpClient LoadSmtpClient()
{
int serverPort = this.ServerPort;
string server = this.MailServer;
// if there's a port we need to split the address
string[] parts = server.Split(':');
if (parts.Length > 1)
{
server = parts[0];
serverPort = int.Parse(parts[1]);
}
if (server == null || server == string.Empty)
{
this.SetError("No Mail Server specified.");
this.Headers.Clear();
return null;
}
smtp = null;
try
{
smtp = new SmtpClient(server, serverPort);
if (this.UseSsl)
smtp.EnableSsl = true;
}
catch (SecurityException)
{
this.SetError("Unable to create SmptClient due to missing permissions. If you are using a port other than 25 for your email server, SmtpPermission has to be explicitly added in Medium Trust.");
this.Headers.Clear();
return null;
}
// This is a Total Send Timeout not a Connection timeout!
smtp.Timeout = this.Timeout * 1000;
if (!string.IsNullOrEmpty(this.Username))
smtp.Credentials = new NetworkCredential(this.Username, this.Password);
return smtp;
}
/// <summary>
/// Starts a new SMTP session. Note this doesn't actually open a connection
/// but just configures and sets up the SMTP session. The actual connection
/// is opened only when a message is actually sent
/// </summary>
/// <returns></returns>
public bool Connect()
{
if (smtp == null)
smtp = LoadSmtpClient();
if (smtp == null)
return false;
return true;
}
/// <summary>
/// Cleans up and closes the connection
/// </summary>
/// <returns></returns>
public bool Close()
{
this.smtp = null;
// clear all existing headers
this.Headers.Clear();
return true;
}
/// <summary>
/// Fully self contained mail sending method. Sends an email message by connecting
/// and disconnecting from the email server.
/// </summary>
/// <returns>true or false</returns>
public bool SendMail()
{
if (!this.Connect())
return false;
try
{
// Create and configure the message
using (MailMessage msg = this.GetMessage())
{
smtp.Send(msg);
if (this.SendComplete != null)
this.SendComplete(this);
}
}
catch (Exception ex)
{
string msg = ex.Message;
if (ex.InnerException != null)
msg = ex.InnerException.Message;
this.SetError(msg);
if (this.SendError != null)
this.SendError(this);
return false;
}
finally
{
// close connection and clear out headers
this.Close();
}
return true;
}
/// <summary>
/// Run mail sending operation on a separate thread and asynchronously
/// Operation does not return any information about completion.
/// </summary>
/// <returns></returns>
public void SendMailAsync()
{
//ThreadStart delSendMail = new ThreadStart(this.SendMailRun);
//delSendMail.BeginInvoke(null, null);
Thread mailThread = new Thread(this.SendMailRun);
mailThread.Start();
}
protected void SendMailRun()
{
// Create an extra reference to insure GC doesn't collect
// the reference from the caller
SmtpClientNative Email = this;
Email.SendMail();
}
/// <summary>
/// Sends an individual message. Allows sending several messages
/// on the same SMTP session without having to reconnect each time.
///
/// This version assigns default properties assigned from the main
/// mail object and allows overriding only of recipients
///
/// Call after Connect() has been called and call Close() to
/// close the connection afterwards
/// </summary>
/// <returns></returns>
public bool SendMessage(string recipient, string ccList, string bccList)
{
try
{
// Create and configure the message
using (MailMessage msg = this.GetMessage())
{
this.AssignMailAddresses(msg.To, recipient);
this.AssignMailAddresses(msg.CC, ccList);
this.AssignMailAddresses(msg.Bcc, bccList);
smtp.Send(msg);
}
if (this.SendComplete != null)
this.SendComplete(this);
}
catch (Exception ex)
{
this.SetError(ex.Message);
if (this.SendError != null)
this.SendError(this);
return false;
}
return true;
}
/// <summary>
/// Configures the message interface
/// </summary>
/// <param name="msg"></param>
protected virtual MailMessage GetMessage()
{
MailMessage msg = new MailMessage();
msg.Body = this.Message;
msg.Subject = this.Subject;
msg.From = new MailAddress(this.SenderEmail, this.SenderName);
if (!string.IsNullOrEmpty(this.ReplyTo))
msg.ReplyToList.Add(new MailAddress(this.ReplyTo));
// Send all the different recipients
this.Assig
gitextract_wnw4ww1a/ ├── .gitattributes ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── Changelog.md ├── LICENSE.md ├── Readme.md ├── Westwind.Utilities/ │ ├── .gitignore │ ├── Configuration/ │ │ ├── AppConfiguration.cd │ │ ├── AppConfiguration.cs │ │ └── Providers/ │ │ ├── ConfigurationFileConfigurationProvider.cs │ │ ├── ConfigurationProviderBase.cs │ │ ├── IConfigurationProvider.cs │ │ ├── JsonFileConfigurationProvider.cs │ │ ├── StringConfigurationProvider.cs │ │ └── XmlFileConfigurationProvider.cs │ ├── Data/ │ │ ├── ValidationError.cs │ │ └── ValidationErrorCollection.cs │ ├── InternetTools/ │ │ ├── HttpClient.cs │ │ └── SmtpClientNative.cs │ ├── LICENSE.MD │ ├── Properties/ │ │ ├── Resources.Designer.cs │ │ └── Resources.resx │ ├── SupportClasses/ │ │ ├── DelegateFactory.cs │ │ ├── Encryption.cs │ │ ├── Expando.cs │ │ ├── ObjectFactory.cs │ │ ├── PropertyBag.cs │ │ ├── Scheduler.cs │ │ ├── StringSerializer.cs │ │ ├── UrlEncodingParser.cs │ │ └── UrlParser.cs │ ├── Utilities/ │ │ ├── AsyncUtils.cs │ │ ├── ComObject.cs │ │ ├── DataUtils.cs │ │ ├── DebugUtils.cs │ │ ├── ExensionMethods/ │ │ │ ├── DateTimeExtensions.cs │ │ │ ├── DictionaryExtensions.cs │ │ │ ├── LinqExtensions.cs │ │ │ └── MemoryStreamExtensions.cs │ │ ├── FileUtils.cs │ │ ├── GenericUtils.cs │ │ ├── HtmlUtils.cs │ │ ├── HttpClientUtils.cs │ │ ├── HttpUtils.cs │ │ ├── HttpUtilsWebClient.cs │ │ ├── ImageUtils.cs │ │ ├── JsonSerializationUtils.cs │ │ ├── KnownFolders.cs │ │ ├── LanguageUtils.cs │ │ ├── NetworkUtils.cs │ │ ├── PasswordScrubber.cs │ │ ├── ReflectionUtils.cs │ │ ├── SecurityUtils.cs │ │ ├── SerializationUtils.cs │ │ ├── ShellUtils.cs │ │ ├── StringUtils.cs │ │ ├── TimeUtils.cs │ │ ├── VersionUtils.cs │ │ └── XmlUtils.cs │ ├── Westwind.Utilities.csproj │ ├── Westwind.Utilities.sln │ └── publish-nuget.ps1 ├── Westwind.Utilities.Data/ │ ├── Configuration/ │ │ └── SqlServerConfigurationProvider.cs │ ├── ConnectionStringInfo.cs │ ├── DataAccessBase.cs │ ├── DataTableExtensions.cs │ ├── DynamicDataReader.cs │ ├── DynamicDataRow.cs │ ├── LICENSE.MD │ ├── Security/ │ │ └── UserTokenManager.cs │ ├── SqlDataAccess.cs │ ├── SqlUtils.cs │ ├── Westwind.Utilities.Data.csproj │ └── publish-nuget.ps1 ├── Westwind.Utilities.Test/ │ ├── App.config │ ├── AppConfiguration/ │ │ ├── AutoConfigFileConfigurationTests.cs │ │ ├── ConfigurationClasses/ │ │ │ ├── AutoConfigFileConfiguration.cs │ │ │ ├── CustomConfigFileConfiguration.cs │ │ │ ├── DatabaseConfiguration.cs │ │ │ ├── JsonFileConfiguration.cs │ │ │ ├── LicenseInformation.cs │ │ │ ├── StringConfigFileConfiguration.cs │ │ │ └── XmlFileConfiguration.cs │ │ ├── CustomConfigFileConfigurationTests.cs │ │ ├── DatabaseConfigurationTests.cs │ │ ├── JsonFileConfigurationTests.cs │ │ ├── StringConfigurationTests.cs │ │ └── XmlFileConfigurationTests.cs │ ├── AsyncUtilsTests.cs │ ├── DataUtilsTests.cs │ ├── DynamicDataReaderTests.cs │ ├── DynamicDataRowTests.cs │ ├── EncryptionTests.cs │ ├── ExpandUrlsParserTest.cs │ ├── ExpandoTests.cs │ ├── FileUtilsTests.cs │ ├── HttpClientTests.cs │ ├── HttpClientUtilsTests.cs │ ├── HttpUtilsTests.cs │ ├── ImagingTests.cs │ ├── Models/ │ │ └── Entities/ │ │ ├── Customer.cs │ │ ├── LineItem.cs │ │ ├── Order.cs │ │ └── WebLogEntry.cs │ ├── NetworkUtilsTests.cs │ ├── ObjectFactoryTests.cs │ ├── PasswordScrubberTests.cs │ ├── PropertyBagTest.cs │ ├── ReflectionUtilsTests.cs │ ├── SanitizeHtmlTests.cs │ ├── ShellUtilsTests.cs │ ├── SmtpClientNativeTests.cs │ ├── SqlDataAccessFoxProTests.cs │ ├── SqlDataAccessMySqlTests.cs │ ├── SqlDataAccessSqlLiteTests.cs │ ├── SqlDataAccessTests.cs │ ├── StrExtractTest.cs │ ├── StringSerializerTests.cs │ ├── StringUtilsTests.cs │ ├── SupportClasses/ │ │ ├── DebugModes.cs │ │ ├── JsonNetSerializationUtilsTests.cs │ │ └── TestHelpers.cs │ ├── SupportFiles/ │ │ ├── _MyJsonConfiguration.json │ │ └── customers.DBF │ ├── TimeUtilsTests.cs │ ├── UrlEncodingParserTests.cs │ ├── UserTokenManagerTests.cs │ ├── VersionExtensionsTests.cs │ ├── Westwind.Utilities.Test.csproj │ ├── Westwind.Utilities.Test.dll.config │ ├── WindowsUtilsTests.cs │ ├── XmlUtilsTest.cs │ └── _TestConfigurationSettings.cs ├── Westwind.Utilities.Windows/ │ ├── LICENSE.MD │ ├── Utilities/ │ │ ├── ComObject.cs │ │ ├── HtmlUtils.cs │ │ └── WindowsUtils.cs │ ├── Westwind.Utilities.Windows.csproj │ ├── Westwind.Utilities.Windows.sln │ └── publish-nuget.ps1 ├── Westwind.Utilities.sln └── Westwind.Utilities.slnx
SYMBOL INDEX (1235 symbols across 115 files)
FILE: Westwind.Utilities.Data/Configuration/SqlServerConfigurationProvider.cs
class SqlServerConfigurationProvider (line 61) | public class SqlServerConfigurationProvider<TAppConfiguration> : Configu...
method Read (line 122) | public override T Read<T>()
FILE: Westwind.Utilities.Data/ConnectionStringInfo.cs
class ConnectionStringInfo (line 23) | public class ConnectionStringInfo
method GetConnectionStringInfo (line 49) | public static ConnectionStringInfo GetConnectionStringInfo(string conn...
method RetrieveConnectionStringFromConfig (line 97) | public static string RetrieveConnectionStringFromConfig(string connect...
FILE: Westwind.Utilities.Data/DataAccessBase.cs
class DataAccessBase (line 67) | [DebuggerDisplay("{ ErrorMessage } {ConnectionString} {LastSql}")]
method DataAccessBase (line 76) | protected DataAccessBase()
method DataAccessBase (line 87) | protected DataAccessBase(string connectionString)
method DataAccessBase (line 105) | protected DataAccessBase(string connectionString, string providerName)
method DataAccessBase (line 119) | protected DataAccessBase(string connectionString, DbProviderFactory pr...
method DataAccessBase (line 144) | public DataAccessBase(string connectionString, DataAccessProviderTypes...
method GetConnectionInfo (line 161) | public void GetConnectionInfo(string connectionString, string provider...
method OpenConnection (line 268) | public virtual bool OpenConnection()
method CloseConnection (line 329) | public virtual void CloseConnection()
method CloseConnection (line 346) | public virtual void CloseConnection(DbCommand Command)
method CreateCommand (line 368) | public virtual DbCommand CreateCommand(string sql, CommandType command...
method CreateCommand (line 412) | public virtual DbCommand CreateCommand(string sql, params object[] par...
method AddParameters (line 426) | protected void AddParameters(DbCommand command, object[] parameters)
method ParseObjectParameters (line 459) | public DbParameterCollection ParseObjectParameters(DbCommand command, ...
method CreateParameter (line 489) | public virtual DbParameter CreateParameter(string parameterName, objec...
method CreateParameter (line 508) | public virtual DbParameter CreateParameter(string parameterName, objec...
method CreateParameter (line 523) | public virtual DbParameter CreateParameter(string parameterName, objec...
method CreateParameter (line 538) | public virtual DbParameter CreateParameter(string parameterName, objec...
method CreateParameter (line 554) | public virtual DbParameter CreateParameter(string parameterName, objec...
method BeginTransaction (line 570) | public virtual bool BeginTransaction()
method CommitTransaction (line 590) | public virtual bool CommitTransaction()
method RollbackTransaction (line 613) | public virtual bool RollbackTransaction()
method ExecuteNonQuery (line 634) | public virtual int ExecuteNonQuery(DbCommand Command)
method ExecuteNonQuery (line 683) | public virtual int ExecuteNonQuery(string sql, params object[] paramet...
method ExecuteNonQueryAsync (line 698) | public virtual async Task<int> ExecuteNonQueryAsync(DbCommand Command)
method ExecuteNonQueryAsync (line 746) | public virtual async Task<int> ExecuteNonQueryAsync(string sql, params...
method ExecuteScalar (line 766) | public virtual object ExecuteScalar(DbCommand command, params object[]...
method ExecuteScalar (line 798) | public virtual object ExecuteScalar(string sql, params object[] parame...
method ExecuteScalarAsync (line 819) | public virtual async Task<object> ExecuteScalarAsync(DbCommand command...
method ExecuteScalarAsync (line 852) | public virtual async Task<object> ExecuteScalarAsync(string sql, param...
method RunSqlScript (line 875) | public bool RunSqlScript(string script, bool continueOnError = false, ...
method DoesTableExist (line 934) | public virtual bool DoesTableExist(string tablename, string schema = n...
method ExecuteReader (line 958) | public virtual DbDataReader ExecuteReader(DbCommand command, params ob...
method ExecuteReader (line 997) | public virtual DbDataReader ExecuteReader(string sql, params object[] ...
method ExecuteDynamicDataReader (line 1017) | public virtual dynamic ExecuteDynamicDataReader(string sql, params obj...
method ExecuteReader (line 1033) | [Obsolete("Use the Query method instead with the same syntax")]
method ExecuteReader (line 1050) | [Obsolete("Use the Query method instead with the same syntax")]
method Query (line 1071) | public virtual IEnumerable<T> Query<T>(string sql, params object[] par...
method QueryList (line 1097) | public virtual List<T> QueryList<T>(string sql, params object[] parame...
method QueryList (line 1124) | public virtual List<T> QueryList<T>(DbCommand command, params object[]...
method QueryListWithExclusions (line 1154) | public virtual List<T> QueryListWithExclusions<T>(string sql, string p...
method QueryListWithExclusions (line 1184) | public virtual List<T> QueryListWithExclusions<T>(DbCommand command, s...
method Query (line 1217) | public virtual IEnumerable<T> Query<T>(DbCommand command, params objec...
method QueryWithExclusions (line 1251) | public virtual IEnumerable<T> QueryWithExclusions<T>(string sql, strin...
method QueryWithExclusions (line 1285) | public virtual IEnumerable<T> QueryWithExclusions<T>(DbCommand sqlComm...
method ExecuteStoredProcedureReader (line 1312) | public virtual DbDataReader ExecuteStoredProcedureReader(string stored...
method ExecuteStoredProcedureReader (line 1337) | public virtual IEnumerable<T> ExecuteStoredProcedureReader<T>(string s...
method ExecuteStoredProcedureNonQuery (line 1358) | public virtual int ExecuteStoredProcedureNonQuery(string storedProc, p...
method ExecuteTable (line 1380) | public virtual DataTable ExecuteTable(string tablename, DbCommand comm...
method ExecuteTable (line 1426) | public virtual DataTable ExecuteTable(string Tablename, string Sql, pa...
method ExecuteDataSet (line 1448) | public virtual DataSet ExecuteDataSet(string Tablename, DbCommand Comm...
method ExecuteDataSet (line 1462) | public virtual DataSet ExecuteDataSet(string tablename, string sql, pa...
method ExecuteDataSet (line 1475) | public virtual DataSet ExecuteDataSet(DataSet dataSet, string tableNam...
method ExecuteDataSet (line 1521) | public virtual DataSet ExecuteDataSet(DataSet dataSet, string tablenam...
method CreatePagingCommand (line 1540) | public virtual DbCommand CreatePagingCommand(string sql, int pageSize,...
method GetEntity (line 1575) | public virtual bool GetEntity(object entity, DbCommand command, string...
method GetEntity (line 1611) | public bool GetEntity(object entity, string sql, object[] parameters)
method GetEntity (line 1632) | public virtual bool GetEntity(object entity, string table, string keyF...
method FindKey (line 1656) | public virtual T FindKey<T>(object keyValue, string tableName,string k...
method Find (line 1688) | public virtual T Find<T>(string sql, params object[] parameters)
method FindEx (line 1709) | public virtual T FindEx<T>(string sql, string propertiesToSkip, params...
method UpdateEntity (line 1731) | public virtual bool UpdateEntity(object entity, string table, string k...
method GetUpdateEntityCommand (line 1762) | public virtual DbCommand GetUpdateEntityCommand(object entity, string ...
method GetUpdateEntityCommand (line 1834) | public virtual DbCommand GetUpdateEntityCommand(object entity, string ...
method UpdateEntity (line 1913) | public virtual bool UpdateEntity(object entity, string table, string k...
method InsertEntity (line 1947) | public object InsertEntity(object entity, string table, string propert...
method InsertEntityAsync (line 1986) | public async Task<object> InsertEntityAsync(object entity, string tabl...
method GetInsertEntityCommand (line 2022) | public DbCommand GetInsertEntityCommand(object entity, string table, s...
method SaveEntity (line 2095) | public virtual bool SaveEntity(object entity, string table, string key...
method SetError (line 2127) | protected virtual void SetError(string message, int errorNumber)
method SetError (line 2146) | protected virtual void SetError(string message, Exception ex = null)
method SetError (line 2153) | protected virtual void SetError(DbException ex)
method SetError (line 2161) | protected virtual void SetError(SqlException ex)
method SetError (line 2170) | protected virtual void SetError(Exception ex)
method SetError (line 2193) | protected virtual void SetError()
method Dispose (line 2201) | public void Dispose()
FILE: Westwind.Utilities.Data/DataTableExtensions.cs
class DataTableDynamicExtensions (line 15) | public static class DataTableDynamicExtensions
method DynamicRow (line 23) | public static dynamic DynamicRow(this DataTable dt, int index)
method DynamicRows (line 35) | public static DynamicDataRows DynamicRows(this DataTable dt)
class DynamicDataRows (line 47) | public class DynamicDataRows : IEnumerator<DynamicDataRow>, IEnumerable<...
method DynamicDataRows (line 76) | public DynamicDataRows(DataRowCollection rows)
method GetEnumerator (line 82) | IEnumerator<DynamicDataRow> IEnumerable<DynamicDataRow>.GetEnumerator()
method GetEnumerator (line 89) | IEnumerator IEnumerable.GetEnumerator()
method Dispose (line 95) | public void Dispose()
method MoveNext (line 103) | public bool MoveNext()
method Reset (line 108) | public void Reset()
FILE: Westwind.Utilities.Data/DynamicDataReader.cs
class DynamicDataReader (line 17) | public class DynamicDataReader : DynamicObject
method DynamicDataReader (line 28) | public DynamicDataReader(IDataReader dataReader)
method TryGetMember (line 41) | public override bool TryGetMember(GetMemberBinder binder, out object r...
method TryInvokeMember (line 69) | public override bool TryInvokeMember(InvokeMemberBinder binder, object...
FILE: Westwind.Utilities.Data/DynamicDataRow.cs
class DynamicDataRow (line 15) | public class DynamicDataRow : DynamicObject
method DynamicDataRow (line 26) | public DynamicDataRow(DataRow dataRow)
method TryGetMember (line 40) | public override bool TryGetMember(GetMemberBinder binder, out object r...
method TrySetMember (line 67) | public override bool TrySetMember(SetMemberBinder binder, object value)
FILE: Westwind.Utilities.Data/Security/UserTokenManager.cs
class UserTokenManager (line 17) | public class UserTokenManager
method UserTokenManager (line 41) | public UserTokenManager(string connectionString = null)
method IsTokenValid (line 52) | public bool IsTokenValid(string tokenId, bool renewLease = true)
method GetToken (line 72) | public UserToken GetToken(string tokenId, bool checkForExpiration = tr...
method GetTokenByTokenIdentifier (line 119) | public UserToken GetTokenByTokenIdentifier(string tokenIdentifier, boo...
method CreateNewToken (line 171) | public string CreateNewToken(string userId, string referenceId = null,...
method DeleteToken (line 237) | public bool DeleteToken(string userTokenId)
method DeleteTokenForUserId (line 256) | public bool DeleteTokenForUserId(string userId)
method DeleteExpiredTokens (line 272) | public bool DeleteExpiredTokens()
method CreateUserTokenSqlTable (line 294) | public virtual bool CreateUserTokenSqlTable()
method IsUserTokenTable (line 329) | public bool IsUserTokenTable()
method GetSqlData (line 348) | SqlDataAccess GetSqlData()
method SetError (line 358) | protected void SetError()
method SetError (line 363) | protected void SetError(string message)
method SetError (line 373) | protected void SetError(Exception ex, bool checkInner = false)
class UserToken (line 392) | public class UserToken
method UserToken (line 394) | public UserToken()
method ToString (line 452) | public override string ToString() => Id ?? "no id set";
FILE: Westwind.Utilities.Data/SqlDataAccess.cs
class SqlDataAccess (line 53) | public class SqlDataAccess : DataAccessBase
method SqlDataAccess (line 56) | public SqlDataAccess()
method SqlDataAccess (line 62) | public SqlDataAccess(string connectionString)
method SqlDataAccess (line 67) | public SqlDataAccess(string connectionString, string providerName)
method SqlDataAccess (line 75) | public SqlDataAccess(string connectionString, DbProviderFactory provider)
method SqlDataAccess (line 79) | public SqlDataAccess(string connectionString, DataAccessProviderTypes ...
method CreatePagingCommand (line 92) | public override DbCommand CreatePagingCommand(string sql, int pageSize...
FILE: Westwind.Utilities.Data/SqlUtils.cs
class SqlUtils (line 21) | public class SqlUtils
method GetDbProviderFactory (line 32) | public static DbProviderFactory GetDbProviderFactory(string dbProvider...
method GetDbProviderFactory (line 55) | public static DbProviderFactory GetDbProviderFactory(DataAccessProvide...
method GetDbProviderFactory (line 84) | public static DbProviderFactory GetDbProviderFactory(string providerName)
method GetSqlCommand (line 115) | public static SqlCommand GetSqlCommand(string ConnectionString, string...
method GetSqlDataReader (line 156) | public static SqlDataReader GetSqlDataReader(string ConnectionString, ...
method GetDataTable (line 184) | public static DataTable GetDataTable(string Tablename, string Connecti...
method CloseConnection (line 215) | public static void CloseConnection(SqlCommand Command)
FILE: Westwind.Utilities.Test/AppConfiguration/AutoConfigFileConfigurationTests.cs
class AutoConfigFileConfigurationTests (line 13) | [TestClass]
method DefaultConstructorInstanceTest (line 35) | [TestMethod]
method DefaultConstructorWithCustomProviderTest (line 53) | [TestMethod]
method DefaultConstructorWithAppSettingsProviderTest (line 79) | [TestMethod]
method AutoConfigWriteConfigurationTest (line 118) | [TestMethod]
method WriteConfigurationTest (line 141) | [TestMethod]
method DefaultConstructor2InstanceTest (line 184) | [TestMethod]
method WriteConfiguration2Test (line 203) | [TestMethod]
method NoConstructorWriteConfiguration2Test2 (line 229) | [TestMethod]
class NoConstructorConfiguration (line 239) | public class NoConstructorConfiguration : AppConfiguration
method New (line 246) | public static NoConstructorConfiguration New()
FILE: Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/AutoConfigFileConfiguration.cs
class AutoConfigFileConfiguration (line 21) | public class AutoConfigFileConfiguration : Westwind.Utilities.Configurat...
method AutoConfigFileConfiguration (line 36) | public AutoConfigFileConfiguration()
class AutoConfigFile2Configuration (line 60) | public class AutoConfigFile2Configuration : AppConfiguration
method AutoConfigFile2Configuration (line 67) | public AutoConfigFile2Configuration()
class NoConstructorConfiguration (line 79) | public class NoConstructorConfiguration : AppConfiguration
method New (line 86) | public static NoConstructorConfiguration New()
FILE: Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/CustomConfigFileConfiguration.cs
class CustomConfigFileConfiguration (line 16) | public class CustomConfigFileConfiguration : Westwind.Utilities.Configur...
method CustomConfigFileConfiguration (line 36) | public CustomConfigFileConfiguration()
method OnCreateDefaultProvider (line 65) | protected override IConfigurationProvider OnCreateDefaultProvider(stri...
FILE: Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/DatabaseConfiguration.cs
class DatabaseConfiguration (line 14) | public class DatabaseConfiguration : Westwind.Utilities.Configuration.Ap...
method DatabaseConfiguration (line 25) | public DatabaseConfiguration()
method OnCreateDefaultProvider (line 40) | protected override IConfigurationProvider OnCreateDefaultProvider(stri...
method Initialize (line 69) | public void Initialize(string connectionString, string tableName = null)
FILE: Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/JsonFileConfiguration.cs
class JsonFileConfiguration (line 14) | public class JsonFileConfiguration : Westwind.Utilities.Configuration.Ap...
method JsonFileConfiguration (line 25) | public JsonFileConfiguration()
method Initialize (line 43) | public void Initialize(string configFile)
method OnCreateDefaultProvider (line 48) | protected override IConfigurationProvider OnCreateDefaultProvider(stri...
FILE: Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/LicenseInformation.cs
class LicenseInformation (line 6) | public class LicenseInformation
method FromString (line 12) | public static LicenseInformation FromString(string data)
method ToString (line 17) | public override string ToString()
FILE: Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/StringConfigFileConfiguration.cs
class StringConfiguration (line 13) | public class StringConfiguration : Westwind.Utilities.Configuration.AppC...
method StringConfiguration (line 23) | public StringConfiguration()
method OnCreateDefaultProvider (line 33) | protected override IConfigurationProvider OnCreateDefaultProvider(stri...
method Initialize (line 49) | public void Initialize(string xml)
FILE: Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/XmlFileConfiguration.cs
class XmlFileConfiguration (line 14) | public class XmlFileConfiguration : Westwind.Utilities.Configuration.App...
method XmlFileConfiguration (line 26) | public XmlFileConfiguration()
method Initialize (line 44) | public void Initialize(string configFile)
method OnCreateDefaultProvider (line 49) | protected override IConfigurationProvider OnCreateDefaultProvider(stri...
FILE: Westwind.Utilities.Test/AppConfiguration/CustomConfigFileConfigurationTests.cs
class CustomConfigurationTests (line 13) | [TestClass]
method DefaultConstructorInstanceTest (line 35) | [TestMethod]
method CustomFileLocationInstanceTest (line 51) | [TestMethod]
method WriteConfigurationTest (line 71) | [TestMethod]
method WriteAndReadConfigurationTest (line 128) | [TestMethod]
method WriteEncryptedConfigurationTest (line 176) | [TestMethod]
FILE: Westwind.Utilities.Test/AppConfiguration/DatabaseConfigurationTests.cs
class DatabaseConfigurationTests (line 13) | [TestClass]
method DefaultConstructorInstanceTest (line 48) | [TestMethod]
method WriteConfigurationTest (line 61) | [TestMethod]
FILE: Westwind.Utilities.Test/AppConfiguration/JsonFileConfigurationTests.cs
class JsonFileConfigurationTests (line 13) | [TestClass]
method JsonFileConfigurationTests (line 22) | public JsonFileConfigurationTests()
method DefaultConstructorInstanceTest (line 32) | [TestMethod]
method WriteConfigurationTest (line 45) | [TestMethod]
method WriteEncryptedConfigurationTest (line 73) | [TestMethod]
method RawJsonFileWithSingletonTest (line 113) | [TestMethod]
class MyJsonConfiguration (line 125) | public class MyJsonConfiguration : AppConfiguration
method MyJsonConfiguration (line 129) | static MyJsonConfiguration()
FILE: Westwind.Utilities.Test/AppConfiguration/StringConfigurationTests.cs
class StringConfigurationTests (line 26) | [TestClass]
method WriteConfigurationTest (line 51) | [TestMethod]
method ReadConfigurationFromStringTest (line 85) | [TestMethod]
method WriteEncryptedConfigurationTest (line 111) | [TestMethod]
FILE: Westwind.Utilities.Test/AppConfiguration/XmlFileConfigurationTests.cs
class XmlConfigurationTests (line 11) | [TestClass]
method DefaultConstructorInstanceTest (line 40) | [TestMethod]
method WriteConfigurationTest (line 53) | [TestMethod]
method WriteEncryptedConfigurationTest (line 91) | [TestMethod]
FILE: Westwind.Utilities.Test/AsyncUtilsTests.cs
class AsyncUtilsTests (line 10) | [TestClass]
method TimeoutAfter2SecondsTest (line 13) | [TestMethod]
method SucceedTimeoutAfter2SecondsTest (line 27) | [TestMethod]
method ExceptionTimeoutAfter2SecondsTest (line 52) | [TestMethod]
method TimeoutWithResultAfter2SecondsTest (line 78) | [TestMethod]
method NoTimeoutWithResultAfter2SecondsTest (line 103) | [TestMethod]
method TaskExceptionWithResultAfter2SecondsTest (line 126) | [TestMethod]
method SucceedTimeoutAfter2SecondsWithTaskWaitTest (line 150) | [TestMethod]
method DoSomething (line 174) | private async Task<int> DoSomething(int timeout)
method DoThrow (line 180) | private async Task<int> DoThrow(int timeout)
FILE: Westwind.Utilities.Test/DataUtilsTests.cs
class DataUtilsTests (line 15) | [TestClass]
method DataTableToListTest (line 22) | [TestMethod]
method IndexOfByteArrayTest (line 39) | [TestMethod]
method IndexOfByteArrayEndTest (line 48) | [TestMethod]
method IndexOfByteArrayBeginTest (line 57) | [TestMethod]
method ReplaceBytesTest (line 66) | [TestMethod]
method ReplaceBytesEndTest (line 82) | [TestMethod]
method ReplaceBytesBeginningTest (line 97) | [TestMethod]
method ReplaceBytesBeginningAndEndTest (line 112) | [TestMethod]
method GetPostGreSqlProviderTest (line 130) | [TestMethod]
method GetMySqlProviderTest (line 141) | [TestMethod]
FILE: Westwind.Utilities.Test/DynamicDataReaderTests.cs
class DynamicDataReaderTests (line 21) | [TestClass]
method MyClassInitialize (line 49) | [ClassInitialize()]
method BasicDataReaderTimerTests (line 68) | [TestMethod]
method BasicDynamicDataReaderTimerTest (line 104) | [TestMethod]
FILE: Westwind.Utilities.Test/DynamicDataRowTests.cs
class DynamicDataRowTests (line 16) | [TestClass]
method DynamicDataRowTests (line 19) | public DynamicDataRowTests()
method BasicDataRowTests (line 66) | [TestMethod]
method DynamicDataTableTest (line 96) | [TestMethod]
FILE: Westwind.Utilities.Test/EncryptionTests.cs
class EncryptionTests (line 9) | [TestClass]
method SimpleEncryptDecryptWith16ByteKey (line 17) | [TestMethod]
method SimpleEncryptWith24ByteKey (line 28) | [TestMethod]
method EncryptDecryptString (line 39) | [TestMethod]
method EncryptDecryptWithExtendedCharacterString (line 54) | [TestMethod]
method EncryptDecryptWithExtendedCharacterStringByteKey (line 70) | [TestMethod]
method EncryptDecryptWithExtendedCharacterByteData (line 85) | [TestMethod]
method HashValues (line 100) | [TestMethod]
method HashValuesHMAC (line 131) | [TestMethod]
method BinHexBase64CompareTest (line 173) | [TestMethod]
FILE: Westwind.Utilities.Test/ExpandUrlsParserTest.cs
class ExpandUrlsParserTest (line 13) | [TestClass]
method ExpandUrlsParserTest (line 16) | public ExpandUrlsParserTest()
method ParseExpandedLinks (line 63) | [TestMethod]
method ParseOddExpandedLinks (line 76) | [TestMethod]
FILE: Westwind.Utilities.Test/ExpandoTests.cs
class ExpandoTests (line 17) | [TestClass]
method ExpandoTests (line 20) | public ExpandoTests()
method ExandoBasicTests (line 69) | [TestMethod]
method AddAndReadDynamicPropertiesTest (line 113) | [TestMethod]
method AddAndReadDynamicIndexersTest (line 135) | [TestMethod]
method PropertyAsIndexerTest (line 154) | [TestMethod]
method DynamicAccessToPropertyTest (line 166) | [TestMethod]
method IterateOverDynamicPropertiesTest (line 183) | [TestMethod]
method MixInObjectInstanceTest (line 208) | [TestMethod]
method TwoWayJsonSerializeExpandoTyped (line 225) | [TestMethod]
method TwoWayXmlSerializeExpandoTyped (line 269) | [TestMethod]
method ExpandoObjectJsonTest (line 310) | [TestMethod]
method UserExampleTest (line 331) | [TestMethod]
method ExpandoMixinTest (line 376) | [TestMethod]
class ObjWithProp (line 401) | public class ObjWithProp : Expando
method GivenPropWhenSetWithIndexThenPropsValue (line 406) | [TestMethod]
method InvalidAssignmentErrorOnStaticProperty (line 420) | [TestMethod]
method ExpandoFromDictionary (line 438) | [TestMethod]
method ExpandoFromList (line 459) | [TestMethod]
class ExpandoInstance (line 479) | public class ExpandoInstance : Expando
method ExpandoInstance (line 484) | public ExpandoInstance()
method ExpandoInstance (line 491) | public ExpandoInstance(object instance)
class Address (line 496) | public class Address
method Address (line 502) | public Address()
class User (line 510) | public class User : Expando
method User (line 518) | public User() : base()
method User (line 523) | public User(object instance)
FILE: Westwind.Utilities.Test/FileUtilsTests.cs
class FileUtilsTest (line 8) | [TestClass]
method SafeFilenameTest (line 11) | [TestMethod]
method NormalizePathTest (line 22) | [TestMethod]
method NormalizeDirectoryTest (line 42) | [TestMethod]
method CompactPathTest (line 77) | [TestMethod]
method TildefyPathTest (line 101) | [TestMethod]
method CopyDirectory (line 128) | [TestMethod]
method ExpandPathEnvironmentVariablesTest (line 163) | [TestMethod]
method ExpandPathEnvironmentVariablesUserFolderTest (line 174) | [TestMethod]
method DeleteFilesTest (line 186) | [TestMethod]
method FindFileHierarchicalUp (line 227) | [TestMethod]
method FindFileHierarchicalDown (line 239) | [TestMethod]
method FindFilesHierarchal (line 249) | [TestMethod]
method GetRelativePathTest (line 266) | [TestMethod]
method IsRelativePathTest (line 288) | [TestMethod]
method ResolvePathTest (line 313) | [TestMethod]
FILE: Westwind.Utilities.Test/HttpClientTests.cs
class HttpClientTests (line 10) | [TestClass]
method InvalidUrlTest (line 14) | [TestMethod]
method HttpTimingsTest (line 27) | [TestMethod]
method HttpTimingsTestsAsync (line 41) | [TestMethod]
method AddPostKeyGetPostBufferTest (line 54) | [TestMethod]
method AddPostKeyRawGetPostBufferTest (line 69) | [TestMethod]
FILE: Westwind.Utilities.Test/HttpClientUtilsTests.cs
class HttpClientUtilsTests (line 15) | [TestClass]
method HttpClientUtilsTests (line 18) | public HttpClientUtilsTests()
method HttpRequestStringWithUrlTest (line 24) | [TestMethod]
method HttpRequestStringWithBadUrlTest (line 36) | [TestMethod]
method ASynchBytesDownloadTest (line 59) | [TestMethod]
method DownloadAsFileAsyncTest (line 67) | [TestMethod]
method DownloadAsFileWithSettingsAsyncTest (line 82) | [TestMethod]
method SynchronousStringDownloadTest (line 107) | [TestMethod]
method SynchronousStringSettingsDownload (line 115) | [TestMethod]
method SynchronousBytesDownload (line 126) | [TestMethod]
method HttpRequestJsonStringWithUrlTest (line 135) | [TestMethod]
method HttpRequestHtmlPostTest (line 153) | [TestMethod]
method HttpRequestBadJsonPostTest (line 169) | [TestMethod]
method HttpRequestBadJsonPostWithExceptionsTest (line 206) | [TestMethod]
method HttpMaxResponseSizeTest (line 242) | [TestMethod]
method HttpPostRequest (line 259) | [TestMethod]
method HttpUploadFileRequest (line 280) | [TestMethod]
method DownloadImageAsyncTest (line 301) | [TestMethod]
method DownloadImageAsyncSettingsTest (line 316) | [TestMethod]
FILE: Westwind.Utilities.Test/HttpUtilsTests.cs
class HttpUtilsTests (line 11) | [TestClass]
method HttpUtilsTests (line 14) | public HttpUtilsTests()
method HttpRequestStringWithUrlTest (line 20) | [TestMethod]
method HttpRequestStringWithUrlAsyncTest (line 27) | [TestMethod]
method InvalidUrlTest (line 34) | [TestMethod]
method HttpRequestStringWithSettingsTest (line 50) | [TestMethod]
method JsonRequestTest (line 65) | [TestMethod]
method JsonRequestAsyncTest (line 81) | [TestMethod]
method JsonRequestPostTest (line 99) | [TestMethod]
method JsonRequestPostAsyncTest (line 143) | [TestMethod]
method DownloadImageFile (line 189) | [TestMethod]
method HttpTimeout (line 217) | [ExpectedException(typeof(WebException))]
class CodeSnippet (line 231) | public class CodeSnippet
FILE: Westwind.Utilities.Test/ImagingTests.cs
class ImagingTests (line 10) | [TestClass]
method RotateFileToFileTest (line 21) | [TestMethod]
method RotateFileToSelfFileTest (line 34) | [TestMethod]
method RotateFileInMemory (line 47) | [TestMethod]
method ResizeBitMap (line 66) | [TestMethod]
method ResizeBitMapFile (line 80) | [TestMethod]
method ResizeSquareBitMap (line 91) | [TestMethod]
method ResizeHighQualityBitMap (line 112) | [TestMethod]
FILE: Westwind.Utilities.Test/Models/Entities/Customer.cs
class Customer (line 11) | public class Customer
method Customer (line 35) | public Customer()
FILE: Westwind.Utilities.Test/Models/Entities/LineItem.cs
class LineItem (line 9) | public class LineItem
FILE: Westwind.Utilities.Test/Models/Entities/Order.cs
class Order (line 10) | public class Order
method Order (line 24) | public Order()
FILE: Westwind.Utilities.Test/Models/Entities/WebLogEntry.cs
class WebLogEntry (line 47) | public class WebLogEntry : LogEntry
method WebLogEntry (line 49) | public WebLogEntry() { }
method WebLogEntry (line 50) | public WebLogEntry(Exception ex) : base(ex) { }
method WebLogEntry (line 53) | public WebLogEntry(Exception ex, HttpContext context) : base(ex)
method UpdateFromRequest (line 132) | public bool UpdateFromRequest()
method UpdateFromRequest (line 144) | public bool UpdateFromRequest(HttpContext context)
class LogEntry (line 184) | public class LogEntry
method LogEntry (line 187) | public LogEntry()
method LogEntry (line 191) | public LogEntry(Exception ex)
method UpdateFromException (line 275) | public void UpdateFromException(Exception ex)
type ErrorLevels (line 288) | [Flags]
FILE: Westwind.Utilities.Test/NetworkUtilsTests.cs
class NetworkUtilsTests (line 13) | [TestClass]
method NetworkUtilsTests (line 16) | public NetworkUtilsTests()
method GetBaseDomain (line 53) | [TestMethod]
method IsLocalIpAddress (line 64) | [TestMethod]
FILE: Westwind.Utilities.Test/ObjectFactoryTests.cs
class ObjectFactoryTests (line 13) | [TestClass]
method ObjectFactoryTests (line 16) | public ObjectFactoryTests()
method GetUniqueObjectKeyTest (line 63) | [TestMethod]
method ThreadScopedObjectTest (line 83) | [TestMethod]
class Information (line 108) | class Information
method Information (line 113) | public Information()
method Information (line 116) | public Information(string name)
FILE: Westwind.Utilities.Test/PasswordScrubberTests.cs
class PasswordScrubberTests (line 13) | [TestClass]
method PasswordScrubberTests (line 16) | public PasswordScrubberTests()
method SqlConnectionStringTest (line 57) | [TestMethod]
method JsonScrubTest (line 76) | [TestMethod]
method JsonAndSqlConnectionScrubTest (line 101) | [TestMethod]
FILE: Westwind.Utilities.Test/PropertyBagTest.cs
class PropertyBagTest (line 14) | [TestClass]
method PropertyBagTest (line 17) | public PropertyBagTest()
method PropertyBagTwoWayObjectSerializationTest (line 66) | [TestMethod]
method PropertyBagInContainerTwoWayObjectSerializationTest (line 99) | [TestMethod]
method PropertyBagTwoWayValueTypeSerializationTest (line 139) | [TestMethod]
method SerializationToJson (line 161) | [TestMethod]
method SerializationToXml (line 180) | [TestMethod]
method DictionaryXmlSerializerTest (line 201) | [TestMethod]
method ToXml (line 219) | string ToXml(object obj)
class ContainerObject (line 232) | public class ContainerObject
class ComplexObject (line 238) | public class ComplexObject
FILE: Westwind.Utilities.Test/ReflectionUtilsTests.cs
class ReflectionUtilsTests (line 7) | [TestClass]
method TypedValueToStringTest (line 10) | [TestMethod]
FILE: Westwind.Utilities.Test/SanitizeHtmlTests.cs
class SanitizeHtmlTests (line 7) | [TestClass]
method HtmlSanitizeScriptTags (line 10) | [TestMethod]
method HtmlSanitizeJavaScriptTags (line 21) | [TestMethod]
method HtmlSanitizeJavaScriptTagsSingleQuotes (line 32) | [TestMethod]
method HtmlSanitizeJavaScriptTagsSingleQuotesWithLineBreaksInTag (line 43) | [TestMethod]
method HtmlSanitizeJavaScriptTagsWithUnicodeQuotes (line 54) | [TestMethod]
method HtmlSanitizeEventAttributes (line 66) | [TestMethod]
method HtmlSanitizeEventAttributesWithLineBreaks (line 80) | [TestMethod]
method IncorrectOnParsingBugTest (line 93) | [TestMethod]
method IncorrectOnEventParsingWithFakeEventInBodyTest (line 105) | [TestMethod]
FILE: Westwind.Utilities.Test/ShellUtilsTests.cs
class ShellUtilsTests (line 12) | [TestClass]
method ExecuteProcessAndGetOutput (line 15) | [TestMethod]
method ExecuteProcessAndCaptureOutputAction (line 29) | [TestMethod]
method ExecuteProcess (line 44) | [TestMethod]
FILE: Westwind.Utilities.Test/SmtpClientNativeTests.cs
class SmtpClientNativeTests (line 9) | [TestClass]
method SendMailTest (line 17) | [TestMethod]
method SendMailAsyncTest (line 43) | [TestMethod]
FILE: Westwind.Utilities.Test/SqlDataAccessFoxProTests.cs
class SqlDataAccessFoxProTests (line 30) | [TestClass]
method SqlDataAccessFoxProTests (line 36) | public SqlDataAccessFoxProTests()
method Initialize (line 63) | [ClassInitialize()]
method SimpleSelectOleDbTest (line 68) | [TestMethod]
method InsertEntityOleDbTest (line 91) | [TestMethod]
method UpdateEntityOleDbTest (line 121) | [TestMethod]
FILE: Westwind.Utilities.Test/SqlDataAccessMySqlTests.cs
class SqlDataAccessMySqlTests (line 10) | [TestClass]
method SqlDataAccessMySqlTests (line 16) | public SqlDataAccessMySqlTests()
method Initialize (line 35) | [ClassInitialize()]
method GetMySqlInstance (line 57) | [TestMethod]
method ExecuteReaderTest (line 67) | [TestMethod]
method CreateTable (line 85) | [TestMethod]
FILE: Westwind.Utilities.Test/SqlDataAccessSqlLiteTests.cs
class SqlDataAccessSqliteTests (line 10) | [TestClass]
method SqlDataAccessSqliteTests (line 16) | public SqlDataAccessSqliteTests()
method Initialize (line 35) | [ClassInitialize()]
method GetSqliteInstance (line 57) | [TestMethod]
method ExecuteReaderTest (line 67) | [TestMethod]
method CreateTable (line 84) | [TestMethod]
FILE: Westwind.Utilities.Test/SqlDataAccessTests.cs
class SqlDataAccessTests (line 16) | [TestClass]
method SqlDataAccessTests (line 22) | public SqlDataAccessTests()
method Initialize (line 41) | [ClassInitialize()]
method ExecuteReaderTest (line 57) | [TestMethod]
method ExecuteNonQueryTest (line 76) | [TestMethod]
method InsertEntityTest (line 91) | [TestMethod]
method UdateEntityTest (line 114) | [TestMethod]
method FindTest (line 141) | [TestMethod]
method FindByKeyTest (line 152) | [TestMethod]
method DataReaderToObjectTest (line 166) | [TestMethod]
method ExecuteDataReaderToListTest (line 185) | [TestMethod]
method ExecuteDataReaderWithNoMatchingDataTest (line 207) | [TestMethod]
method QueryWithNoMatchingDataTest (line 217) | [TestMethod]
method QueryToIEnumerableTest (line 232) | [TestMethod]
method QueryToListTest (line 258) | [TestMethod]
method QueryToCustomer (line 278) | [TestMethod]
method ExecuteDataReaderToListManualTest (line 295) | [TestMethod]
method NewParametersReaderTest (line 332) | [TestMethod]
method NewParametersTableTest (line 363) | [TestMethod]
method NewParametersExecuteEntityTest (line 392) | [TestMethod]
method NewParametersxecuteDynamicTest (line 416) | [TestMethod]
method FindByIdTest (line 441) | [TestMethod]
method FindBySqlTest (line 458) | [TestMethod]
method QueryTest (line 471) | [TestMethod]
method ExecuteDynamicDataReaderTest (line 492) | [TestMethod]
method QueryException (line 514) | [TestMethod]
method DoesTableExist (line 534) | [TestMethod]
method BinaryDataTest (line 544) | [TestMethod]
FILE: Westwind.Utilities.Test/StrExtractTest.cs
class StrExtractTest (line 14) | [TestClass]
method StrExtractTest (line 17) | public StrExtractTest()
method ExtractStringTest (line 61) | [TestMethod]
method ExtractStringWithDelimetersTest (line 81) | [TestMethod]
method RegExExtractionTest (line 109) | [TestMethod]
method ReplaceStringTest (line 120) | [TestMethod]
FILE: Westwind.Utilities.Test/StringSerializerTests.cs
class StringSerializerTests (line 13) | [TestClass]
method StringSerializerTest (line 18) | [TestMethod]
method StringSerializerNullTest (line 62) | [TestMethod]
method StringSerializerWithNullStringValuesTest (line 77) | [TestMethod]
method XmlSerializerSizeTest (line 101) | [TestMethod]
method JsonSerializerSizeTest (line 134) | [TestMethod]
method LosSerializerSizeTest (line 165) | [TestMethod]
class UserState (line 201) | [Serializable]
class Role (line 259) | [Serializable]
FILE: Westwind.Utilities.Test/StringUtilsTests.cs
class StringUtilsTests (line 13) | [TestClass]
method StringUtilsTests (line 16) | public StringUtilsTests()
method ToCamelCaseTest (line 56) | [TestMethod]
method FromCamelCaseTest (line 80) | [TestMethod]
method ToCamelCaseUpperCasingTest (line 123) | [TestMethod]
method NormalizeIndentationTest (line 147) | [TestMethod]
method ReplicateStringTest (line 188) | [TestMethod]
method ReplicateCharTest (line 195) | [TestMethod]
method Base36EncodeTest (line 201) | [TestMethod]
method GenerateUniqueId (line 230) | [TestMethod]
method RandomStringTest (line 247) | [TestMethod]
method RandomStringWithNumbersTest (line 258) | [TestMethod]
method ExtractStringTest (line 269) | [TestMethod]
method ExtractStringWithDelimitersTest (line 281) | [TestMethod]
method GetLinesTest (line 318) | [TestMethod]
method CountLinesTest (line 341) | [TestMethod]
method IndexOfNthCharTest (line 361) | [TestMethod]
method IndexOfNthStringTest (line 391) | [TestMethod]
method LastIndexOfNthStringTest (line 421) | [TestMethod]
method LastIndexOfNthCharTest (line 451) | [TestMethod]
method StringTokenization (line 484) | [TestMethod]
method NormalizeLineFeedTest (line 515) | [TestMethod]
method TextAbstractTest (line 539) | [TestMethod]
method IsStringInListTest (line 553) | [TestMethod]
method OccursCharTest (line 566) | [TestMethod]
method OccursStringTest (line 587) | [TestMethod]
method GetMaxCharactersTest (line 614) | [TestMethod]
method GetLastCharactersTest (line 637) | [TestMethod]
method ToAndFromBase64StringTest (line 657) | [TestMethod]
FILE: Westwind.Utilities.Test/SupportClasses/DebugModes.cs
type DebugModes (line 9) | public enum DebugModes
FILE: Westwind.Utilities.Test/SupportClasses/JsonNetSerializationUtilsTests.cs
class JsonNetSerializationUtilsTests (line 10) | [TestClass]
method JsonStringSerializeTest (line 13) | [TestMethod]
method JsonStringSerializeCamelCaseTest (line 25) | [TestMethod]
method JsonSerializeToFile (line 38) | [TestMethod]
method JsonDeserializeStringTest (line 49) | [TestMethod]
method DeserializeFromFileTest (line 67) | [TestMethod]
method JsonNativeInstantiation (line 89) | [TestMethod]
method NativePerfTest (line 132) | [TestMethod]
method Native2PerfTest (line 163) | [TestMethod]
method UtilsPerfTest (line 185) | [TestMethod]
method PrettifyJsonStringTest (line 208) | [TestMethod]
FILE: Westwind.Utilities.Test/SupportClasses/TestHelpers.cs
class TestHelpers (line 7) | public class TestHelpers
method GetTestConfigFilePath (line 9) | public static string GetTestConfigFilePath()
method GetApplicationConfigFile (line 15) | public static string GetApplicationConfigFile()
method DeleteTestConfigFile (line 21) | public static void DeleteTestConfigFile()
FILE: Westwind.Utilities.Test/TimeUtilsTests.cs
class TimeUtilsTest (line 8) | [TestClass]
method FriendlyElapsedTimeOverflowTest (line 14) | [TestMethod]
FILE: Westwind.Utilities.Test/UrlEncodingParserTests.cs
class UrlEncodingParserTests (line 12) | [TestClass]
method QueryStringTest (line 15) | [TestMethod]
method QueryStringNullTest (line 42) | [TestMethod]
method QueryValuesNullTest (line 60) | [TestMethod]
method QueryStringMultipleTest (line 79) | [TestMethod]
method QueryStringPlusSigns (line 108) | [TestMethod]
method WriteUrlTest (line 122) | [TestMethod]
method HttpUtilityTest (line 194) | [TestMethod]
FILE: Westwind.Utilities.Test/UserTokenManagerTests.cs
class UserTokenManagerTests (line 12) | [TestClass]
method Initialize (line 17) | [TestInitialize]
method CreateTokenTest (line 26) | [TestMethod]
method UpdateTokenTest (line 36) | [TestMethod]
method ValidateTokenTest (line 61) | [TestMethod]
method GetTokenByTokenIdentifierTest (line 74) | [TestMethod]
FILE: Westwind.Utilities.Test/VersionExtensionsTests.cs
class VersionExtensionsTests (line 13) | [TestClass]
method DefaultVersionStringTest (line 16) | [TestMethod]
method MinTokenCountProvidedTest (line 34) | [TestMethod]
method MaxTokenProvidedTest (line 52) | [TestMethod]
FILE: Westwind.Utilities.Test/WindowsUtilsTests.cs
class WindowsUtilsTests (line 8) | [TestClass]
method GetDotnetVersionTest (line 11) | [TestMethod]
method GetWindowsVersionTest (line 23) | [TestMethod]
FILE: Westwind.Utilities.Test/XmlUtilsTest.cs
class XmlUtilsTest (line 15) | [TestClass]
method XmlUtilsTest (line 18) | public XmlUtilsTest()
method ElementValuesTest (line 52) | [TestMethod]
method AttributeValuesTest (line 80) | [TestMethod]
method XmlStringForElement (line 103) | [TestMethod]
method XmlStringForAttributes (line 115) | [TestMethod]
type TestKeyValues (line 130) | public enum TestKeyValues
FILE: Westwind.Utilities.Test/_TestConfigurationSettings.cs
class TestConfigurationSettings (line 4) | public class TestConfigurationSettings
FILE: Westwind.Utilities.Windows/Utilities/ComObject.cs
class ComObject (line 17) | #if NET6_0_OR_GREATER
method ComObject (line 32) | public ComObject(object instance)
method CreateFromProgId (line 45) | public static ComObject CreateFromProgId(string progid)
method CreateFirstFrom (line 65) | public static ComObject CreateFirstFrom(Guid clsid)
method ComObject (line 85) | public ComObject(string progid)
method ComObject (line 94) | public ComObject(Guid clsid)
method Detach (line 103) | public object Detach()
method TryGetMember (line 113) | public override bool TryGetMember(GetMemberBinder binder, out object r...
method TrySetMember (line 128) | public override bool TrySetMember(SetMemberBinder binder, object value)
method TryInvokeMember (line 146) | public override bool TryInvokeMember(InvokeMemberBinder binder, object...
method TryGetIndex (line 160) | public override bool TryGetIndex(GetIndexBinder binder, object[] index...
method WrapIfRequired (line 187) | private static object WrapIfRequired(object obj)
method Dispose (line 190) | public void Dispose()
FILE: Westwind.Utilities.Windows/Utilities/HtmlUtils.cs
class HtmlUtils (line 15) | #if NET6_0_OR_GREATER
method FixHTMLForDisplay (line 25) | public static string FixHTMLForDisplay(string html)
method StripHtml (line 38) | public static string StripHtml(string html)
method DisplayMemo (line 53) | public static string DisplayMemo(string htmlText)
method DisplayMemoEncoded (line 71) | public static string DisplayMemoEncoded(string text)
method HtmlEncode (line 102) | [Obsolete("Use System.Net.WebUtility.HtmlEncode() instead.")]
method Href (line 158) | public static string Href(string text, string url, string target = nul...
method Href (line 174) | public static string Href(string url)
method ImgRef (line 186) | public static string ImgRef(string imageUrl, string additionalMarkup =...
method ResolveUrl (line 215) | internal static string ResolveUrl(string originalUrl)
method BinaryToEmbeddedBase64 (line 259) | public static string BinaryToEmbeddedBase64(byte[] imageBytes, string ...
method EmbeddedBase64ToBinary (line 272) | public static (byte[] bytes, string mimeType) EmbeddedBase64ToBinary(s...
method HtmlAbstract (line 296) | public static string HtmlAbstract(string html, int length)
method SanitizeHtml (line 329) | public static string SanitizeHtml(string html, string htmlTagBlacklist...
FILE: Westwind.Utilities.Windows/Utilities/WindowsUtils.cs
class WindowsUtils (line 14) | #if NET6_0_OR_GREATER
method GetDotnetVersion (line 150) | public static string GetDotnetVersion()
method GetWindowsVersion (line 214) | public static string GetWindowsVersion()
method TryGetRegistryKey (line 233) | public static bool TryGetRegistryKey(string path, string key, out dyna...
method IsUserAnAdmin (line 257) | [DllImport("shell32.dll", SetLastError = true)]
FILE: Westwind.Utilities/Configuration/AppConfiguration.cs
class AppConfiguration (line 59) | public abstract class AppConfiguration
method AppConfiguration (line 92) | public AppConfiguration()
method Initialize (line 109) | public void Initialize(IConfigurationProvider provider = null,
method OnInitialize (line 144) | protected virtual void OnInitialize(IConfigurationProvider provider,
method OnCreateDefaultProvider (line 163) | protected virtual IConfigurationProvider OnCreateDefaultProvider(strin...
method Write (line 188) | public virtual bool Write()
method WriteAsString (line 210) | public virtual string WriteAsString()
method Read (line 232) | public virtual T Read<T>()
method Read (line 252) | public virtual bool Read()
method Read (line 273) | public virtual bool Read(string xml)
method Read (line 296) | public static T Read<T>(IConfigurationProvider provider)
method Read (line 312) | public static T Read<T>(string xml, IConfigurationProvider provider)
method Read (line 332) | public static T Read<T>(string xml)
class MyAppConfiguration (line 343) | class MyAppConfiguration : AppConfiguration
method MyAppConfiguration (line 345) | public MyAppConfiguration()
method OnCreateDefaultProvider (line 356) | protected override IConfigurationProvider OnCreateDefaultProvider(stri...
FILE: Westwind.Utilities/Configuration/Providers/ConfigurationFileConfigurationProvider.cs
class ConfigurationFileConfigurationProvider (line 59) | public class ConfigurationFileConfigurationProvider<TAppConfiguration> :
method Read (line 93) | public override TAppConfig Read<TAppConfig>()
method Read (line 108) | public override bool Read(AppConfiguration config)
method IsIList (line 225) | bool IsIList(Type type)
method Read (line 247) | public override bool Read(AppConfiguration config, string filename)
method Write (line 327) | public override bool Write(AppConfiguration config)
method WriteConfigurationValue (line 419) | private void WriteConfigurationValue(string keyName, string Value, Mem...
method GetNamedValueFromXml (line 460) | protected string GetNamedValueFromXml(XmlDocument Dom, string Key, str...
method GetXmlNamespaceInfo (line 479) | protected void GetXmlNamespaceInfo(XmlDocument Dom)
method CreateConfigSection (line 509) | private XmlNode CreateConfigSection(XmlDocument dom, string configSect...
method TypedValueToString (line 569) | static string TypedValueToString(object rawValue, CultureInfo culture ...
method StringToTypedValue (line 639) | static object StringToTypedValue(string sourceString, Type targetType,...
FILE: Westwind.Utilities/Configuration/Providers/ConfigurationProviderBase.cs
class ConfigurationProviderBase (line 49) | public abstract class ConfigurationProviderBase<TAppConfiguration> : ICo...
method Read (line 99) | public abstract T Read<T>()
method Read (line 109) | public abstract bool Read(AppConfiguration config);
method Write (line 117) | public abstract bool Write(AppConfiguration config);
method Read (line 128) | public virtual T Read<T>(string xml)
method Read (line 158) | public virtual bool Read(AppConfiguration config, string xml)
method WriteAsString (line 196) | public virtual string WriteAsString(AppConfiguration config)
method EncryptFields (line 223) | public virtual void EncryptFields(AppConfiguration config)
method DecryptFields (line 268) | public virtual void DecryptFields(AppConfiguration config)
method SetError (line 315) | protected virtual void SetError(string message)
method SetError (line 331) | protected virtual void SetError(Exception ex)
method CreateConfigurationInstance (line 343) | protected TAppConfiguration CreateConfigurationInstance()
FILE: Westwind.Utilities/Configuration/Providers/IConfigurationProvider.cs
type IConfigurationProvider (line 47) | public interface IConfigurationProvider
method Read (line 75) | T Read<T>()
method Read (line 83) | bool Read(AppConfiguration config);
method Read (line 84) | T Read<T>(string xml)
method Read (line 94) | bool Read(AppConfiguration config, string xml);
method Write (line 101) | bool Write(AppConfiguration config);
method WriteAsString (line 109) | string WriteAsString(AppConfiguration config);
method EncryptFields (line 115) | void EncryptFields(AppConfiguration config);
method DecryptFields (line 121) | void DecryptFields(AppConfiguration config);
FILE: Westwind.Utilities/Configuration/Providers/JsonFileConfigurationProvider.cs
class JsonFileConfigurationProvider (line 43) | public class JsonFileConfigurationProvider<TAppConfiguration> : Configur...
method Read (line 65) | public override bool Read(AppConfiguration config)
method Read (line 85) | public override TAppConfig Read<TAppConfig>()
method Write (line 99) | public override bool Write(AppConfiguration config)
FILE: Westwind.Utilities/Configuration/Providers/StringConfigurationProvider.cs
class StringConfigurationProvider (line 48) | public class StringConfigurationProvider<TAppConfiguration> : Configurat...
method Read (line 58) | public override T Read<T>()
method Read (line 68) | public override bool Read(AppConfiguration config)
method Write (line 78) | public override bool Write(AppConfiguration config)
FILE: Westwind.Utilities/Configuration/Providers/XmlFileConfigurationProvider.cs
class XmlFileConfigurationProvider (line 47) | public class XmlFileConfigurationProvider<TAppConfiguration> : Configura...
method Read (line 72) | public override bool Read(AppConfiguration config)
method Read (line 97) | public override TAppConfig Read<TAppConfig>()
method Write (line 111) | public override bool Write(AppConfiguration config)
FILE: Westwind.Utilities/Data/ValidationError.cs
class ValidationError (line 43) | public class ValidationError
method ValidationError (line 82) | public ValidationError() : base() {}
method ValidationError (line 84) | public ValidationError(string message)
method ValidationError (line 88) | public ValidationError(string message, string fieldName)
method ValidationError (line 93) | public ValidationError(string message, string fieldName, string id)
method ToString (line 101) | public override string ToString()
FILE: Westwind.Utilities/Data/ValidationErrorCollection.cs
class ValidationErrorCollection (line 10) | public class ValidationErrorCollection : CollectionBase
method Add (line 41) | public void Add(ValidationError error)
method Add (line 62) | public void Add(string message, string fieldName = "", string id = "")
method AddFormat (line 84) | public void AddFormat(string message, string fieldName, string id, par...
method Remove (line 93) | public void Remove(int index)
method Assert (line 118) | public bool Assert(bool condition, string message, string fieldName, s...
method Assert (line 138) | public bool Assert(bool condition, string message)
method Assert (line 161) | public bool Assert(bool condition, string message, string fieldName)
method Assert (line 180) | public bool Assert(bool condition, ValidationError error)
method ToString (line 194) | public override string ToString()
method ToString (line 216) | public string ToString(string prefixLine)
method ToHtml (line 236) | public string ToHtml()
FILE: Westwind.Utilities/InternetTools/HttpClient.cs
class HttpClient (line 57) | #if NET6_0_OR_GREATER
method HttpClient (line 303) | public HttpClient()
method CreateWebRequestObject (line 322) | public bool CreateWebRequestObject(string Url)
method ResetPostData (line 344) | public void ResetPostData()
method SetPostStream (line 350) | public void SetPostStream(Stream postStream)
method AddPostKey (line 366) | public void AddPostKey(string key, byte[] value)
method AddPostKey (line 410) | public void AddPostKey(string key, string value)
method AddPostKey (line 422) | public void AddPostKey(string fullPostBuffer)
method AddPostKey (line 432) | public void AddPostKey(byte[] fullPostBuffer)
method AddPostFile (line 444) | public bool AddPostFile(string key,string fileName, string contentType...
method GetPostBuffer (line 496) | public string GetPostBuffer()
method DownloadStream (line 513) | public StreamReader DownloadStream(string url)
method GetUrlResponse (line 565) | [Obsolete("Use DownloadResponse instead.")]
method DownloadResponseAsync (line 572) | public async Task<HttpWebResponse> DownloadResponseAsync(string url)
method DownloadResponse (line 783) | public HttpWebResponse DownloadResponse(string url)
method StreamPostBuffer (line 996) | protected void StreamPostBuffer(Stream PostData)
method GetUrl (line 1082) | [Obsolete("Use the DownloadString() method instead.")]
method DownloadString (line 1095) | public string DownloadString(string url, long bufferSize = 8192, Encod...
method DownloadStringAsync (line 1134) | public async Task<string> DownloadStringAsync(string url, long bufferS...
method GetUrlPartial (line 1176) | [Obsolete("Use DownloadStringPartial() instead.")]
method DownloadStringPartial (line 1193) | public string DownloadStringPartial(string url, int size)
method DownloadBytes (line 1218) | public byte[] DownloadBytes(string url, long bufferSize = 8192)
method DownloadBytesAsync (line 1333) | public async Task<byte[]> DownloadBytesAsync(string url, long bufferSi...
method GetUrlFile (line 1448) | [Obsolete("Use DownloadFile() instead.")]
method DownloadFile (line 1461) | public bool DownloadFile(string url,long bufferSize,string outputFile)
method CheckCertificateCallback (line 1508) | private static bool CheckCertificateCallback(object sender, X509Certif...
class ReceiveDataEventArgs (line 1532) | public class ReceiveDataEventArgs
method Dispose (line 1570) | public void Dispose()
type HttpPostMode (line 1587) | public enum HttpPostMode
class AcceptAllCertificatePolicy (line 1601) | internal class AcceptAllCertificatePolicy : ICertificatePolicy
method AcceptAllCertificatePolicy (line 1603) | public AcceptAllCertificatePolicy()
method CheckValidationResult (line 1607) | public bool CheckValidationResult(ServicePoint sPoint,
class HttpTimings (line 1616) | public class HttpTimings
method StartRequest (line 1622) | public void StartRequest()
method IsEmpty (line 1639) | public bool IsEmpty()
FILE: Westwind.Utilities/InternetTools/SmtpClientNative.cs
class SmtpClientNative (line 51) | public class SmtpClientNative : IDisposable
method AddHeader (line 245) | public void AddHeader(string headerName, string value)
method AddHeadersFromString (line 263) | public void AddHeadersFromString(string headers)
method LoadSmtpClient (line 282) | public SmtpClient LoadSmtpClient()
method Connect (line 332) | public bool Connect()
method Close (line 347) | public bool Close()
method SendMail (line 362) | public bool SendMail()
method SendMailAsync (line 404) | public void SendMailAsync()
method SendMailRun (line 413) | protected void SendMailRun()
method SendMessage (line 432) | public bool SendMessage(string recipient, string ccList, string bccList)
method GetMessage (line 469) | protected virtual MailMessage GetMessage()
method AssignMailAddresses (line 550) | private void AssignMailAddresses(MailAddressCollection address, string...
method GetEmailFromFullAddress (line 569) | string GetEmailFromFullAddress(string fullEmail)
method AddAlternateView (line 589) | public void AddAlternateView(AlternateView view)
method LogString (line 601) | protected void LogString(string message)
method SetError (line 620) | private void SetError(string errorMessage)
method Dispose (line 636) | public void Dispose()
FILE: Westwind.Utilities/Properties/Resources.Designer.cs
class Resources (line 22) | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resource...
method Resources (line 31) | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Mic...
FILE: Westwind.Utilities/SupportClasses/DelegateFactory.cs
class DelegateFactory (line 24) | public static class DelegateFactory
method Create (line 33) | public static LateBoundMethod Create(MethodInfo method)
method CreateParameterExpressions (line 51) | private static Expression[] CreateParameterExpressions(MethodInfo meth...
method Create (line 68) | public static LateBoundMethod Create(Type type, string methodName, par...
FILE: Westwind.Utilities/SupportClasses/Encryption.cs
class Encryption (line 23) | public static class Encryption
method EncryptBytes (line 53) | public static byte[] EncryptBytes(byte[] inputBytes, string encryption...
method EncryptBytes (line 69) | public static byte[] EncryptBytes(byte[] inputBytes, SecureString encr...
method EncryptBytes (line 85) | public static byte[] EncryptBytes(byte[] inputBytes, byte[] encryption...
method EncryptBytes (line 121) | public static byte[] EncryptBytes(string inputString, string encryptio...
method EncryptString (line 134) | public static string EncryptString(string inputString, byte[] encrypti...
method EncryptString (line 152) | public static string EncryptString(string inputString, string encrypti...
method EncryptString (line 171) | public static string EncryptString(string inputString,SecureString enc...
method DecryptBytes (line 191) | public static byte[] DecryptBytes(byte[] decryptBuffer, string encrypt...
method DecryptBytes (line 210) | public static byte[] DecryptBytes(byte[] decryptBuffer, SecureString e...
method DecryptBytes (line 227) | public static byte[] DecryptBytes(byte[] decryptBuffer, byte[] encrypt...
method DecryptBytes (line 268) | public static byte[] DecryptBytes(string decryptString, string encrypt...
method DecryptBytes (line 285) | public static byte[] DecryptBytes(string decryptString, SecureString e...
method DecryptString (line 305) | public static string DecryptString(string decryptString, string encryp...
method DecryptString (line 330) | public static string DecryptString(string decryptString, SecureString ...
method DecryptString (line 357) | public static string DecryptString(string decryptString, byte[] encryp...
method ProtectBytes (line 391) | public static byte[] ProtectBytes(byte[] encryptBytes, byte[] key, Dat...
method ProtectBytes (line 412) | public static byte[] ProtectBytes(byte[] encryptBytes, string key, Dat...
method ProtectString (line 434) | public static string ProtectString(string encryptString, string key, D...
method ProtectString (line 461) | public static string ProtectString(string encryptString, byte[] key, D...
method UnprotectBytes (line 487) | public static byte[] UnprotectBytes(byte[] encryptBytes, byte[] key, D...
method UnprotectBytes (line 508) | public static byte[] UnprotectBytes(byte[] encryptBytes, string key, D...
method UnprotectString (line 530) | public static string UnprotectString(string encryptString, string key,...
method UnprotectString (line 560) | public static string UnprotectString(string encryptString, byte[] key,...
method ComputeHash (line 614) | public static string ComputeHash(string plainText,
method ComputeHash (line 660) | public static string ComputeHash(string plainText,
method ComputeHash (line 706) | public static string ComputeHash(byte[] byteData,
method GZipMemory (line 791) | public static byte[] GZipMemory(byte[] buffer)
method GZipMemory (line 811) | public static byte[] GZipMemory(string input)
method GZipMemory (line 822) | public static byte[] GZipMemory(string filename, bool isFile)
method GZipFile (line 835) | public static bool GZipFile(string filename, string outputFile)
method GetChecksumFromFile (line 857) | public static string GetChecksumFromFile(string file, string mode = "S...
method GetChecksumFromBytes (line 912) | public static string GetChecksumFromBytes(byte[] fileData, string mode...
method BinaryToBinHex (line 963) | public static string BinaryToBinHex(byte[] data)
method BinHexToBinary (line 983) | public static byte[] BinHexToBinary(string hex)
method ParseHexChar (line 1000) | static int ParseHexChar(char c)
class SecureStringExtensions (line 1015) | public static class SecureStringExtensions
method GetString (line 1017) | public static string GetString(this SecureString source)
FILE: Westwind.Utilities/SupportClasses/Expando.cs
class Expando (line 61) | [Serializable]
method Expando (line 102) | public Expando()
method Expando (line 115) | public Expando(object instance)
method Expando (line 135) | public Expando(IDictionary<string, object> dict)
method InitializeAsDictionary (line 143) | private void InitializeAsDictionary(Expando expando, IDictionary<strin...
method Initialize (line 182) | protected void Initialize(object instance)
method GetDynamicMemberNames (line 197) | public override IEnumerable<string> GetDynamicMemberNames()
method TryGetMember (line 211) | public override bool TryGetMember(GetMemberBinder binder, out object r...
method TrySetMember (line 246) | public override bool TrySetMember(SetMemberBinder binder, object value)
method TryInvokeMember (line 277) | public override bool TryInvokeMember(InvokeMemberBinder binder, object...
method GetProperty (line 302) | protected bool GetProperty(object instance, string name, out object re...
method SetProperty (line 329) | protected bool SetProperty(object instance, string name, object value)
method InvokeMethod (line 355) | protected bool InvokeMethod(object instance, string name, object[] arg...
method GetProperties (line 442) | public IEnumerable<KeyValuePair<string,object>> GetProperties(bool inc...
method Contains (line 462) | public bool Contains(KeyValuePair<string, object> item, bool includeIn...
FILE: Westwind.Utilities/SupportClasses/ObjectFactory.cs
class ObjectFactory (line 16) | public class ObjectFactory<T>
method CreateObject (line 30) | public static T CreateObject(params object[] args)
method CreateThreadScopedObject (line 42) | public static T CreateThreadScopedObject(params object[] args)
method GetUniqueObjectKey (line 82) | public static string GetUniqueObjectKey(params object[] args)
FILE: Westwind.Utilities/SupportClasses/PropertyBag.cs
class PropertyBag (line 17) | [XmlRoot("properties")]
method CreateFromXml (line 25) | public new static PropertyBag CreateFromXml(string xml)
method GetSchema (line 51) | public System.Xml.Schema.XmlSchema GetSchema()
method WriteXml (line 67) | public void WriteXml(System.Xml.XmlWriter writer)
method ReadXml (line 137) | public void ReadXml(System.Xml.XmlReader reader)
method ToXml (line 187) | public string ToXml()
method FromXml (line 199) | public bool FromXml(string xml)
method CreateFromXml (line 229) | public static PropertyBag<TValue> CreateFromXml(string xml)
class PropertyBag (line 43) | [XmlRoot("properties")]
method CreateFromXml (line 25) | public new static PropertyBag CreateFromXml(string xml)
method GetSchema (line 51) | public System.Xml.Schema.XmlSchema GetSchema()
method WriteXml (line 67) | public void WriteXml(System.Xml.XmlWriter writer)
method ReadXml (line 137) | public void ReadXml(System.Xml.XmlReader reader)
method ToXml (line 187) | public string ToXml()
method FromXml (line 199) | public bool FromXml(string xml)
method CreateFromXml (line 229) | public static PropertyBag<TValue> CreateFromXml(string xml)
FILE: Westwind.Utilities/SupportClasses/Scheduler.cs
class Scheduler (line 14) | public class Scheduler : IDisposable
method Start (line 88) | public void Start(int checkFrequency)
method Start (line 102) | public void Start()
method Stop (line 114) | public void Stop()
method Cancel (line 131) | public void Cancel()
method Run (line 149) | private void Run()
method OnExecuteScheduledEvent (line 194) | protected virtual void OnExecuteScheduledEvent()
method OnError (line 219) | protected virtual void OnError(Exception ex)
method AddItem (line 235) | public void AddItem(object item)
method AddItem (line 247) | public void AddItem(SchedulerItem item)
method AddItem (line 257) | public void AddItem(string textData, string type = null)
method AddItem (line 270) | public void AddItem(byte[] data, string type = null)
method GetNextItem (line 284) | public object GetNextItem()
method PingServer (line 301) | public void PingServer(string url = null)
method Dispose (line 322) | public void Dispose()
class SchedulerItem (line 334) | public class SchedulerItem
FILE: Westwind.Utilities/SupportClasses/StringSerializer.cs
class StringSerializer (line 30) | public static class StringSerializer
method SerializeObject (line 47) | public static string SerializeObject(object objectToSerialize, string ...
method DeserializeObject (line 103) | public static object DeserializeObject(string serialized, Type type, s...
method Deserialize (line 163) | public static T Deserialize<T>(string serialized, string separator = n...
FILE: Westwind.Utilities/SupportClasses/UrlEncodingParser.cs
class UrlEncodingParser (line 22) | public class UrlEncodingParser : NameValueCollection
method UrlEncodingParser (line 63) | public UrlEncodingParser(string queryStringOrUrl = null, bool decodeSp...
method SetValues (line 79) | public void SetValues(string key, IEnumerable<string> values)
method Parse (line 94) | public NameValueCollection Parse(string query)
method ToString (line 140) | public override string ToString()
FILE: Westwind.Utilities/SupportClasses/UrlParser.cs
class UrlParser (line 49) | public class UrlParser
method ExpandUrls (line 61) | public static string ExpandUrls(string text, string target = null, boo...
method ExpandUrlsInternal (line 78) | private string ExpandUrlsInternal(string text)
method ExpandUrlsRegExEvaluator (line 114) | private string ExpandUrlsRegExEvaluator(System.Text.RegularExpressions...
method ExpandFormattedLinks (line 143) | private string ExpandFormattedLinks(System.Text.RegularExpressions.Mat...
FILE: Westwind.Utilities/Utilities/AsyncUtils.cs
class AsyncUtils (line 15) | public static class AsyncUtils
method RunSync (line 28) | public static void RunSync(Func<Task> task)
method RunSync (line 40) | public static void RunSync(Func<Task> task,
method RunSync (line 66) | public static TResult RunSync<TResult>(Func<Task<TResult>> task)
method RunSync (line 81) | public static TResult RunSync<TResult>(Func<Task<TResult>> func,
method FireAndForget (line 109) | public static void FireAndForget(this Task t)
method FireAndForget (line 126) | public static void FireAndForget(this Task t, Action<Exception> del)
method Timeout (line 140) | public static async Task<bool> Timeout(this Task task, int timeoutMs)
method TimeoutWithResult (line 160) | public static async Task<TResult> TimeoutWithResult<TResult>(this Task...
method DelayExecution (line 184) | public static void DelayExecution(int delayMs, Action action, Action<E...
method DelayExecution (line 214) | public static void DelayExecution<T>(int delayMs, Action<T> action, T ...
FILE: Westwind.Utilities/Utilities/ComObject.cs
class ComObject (line 17) | #if NET6_0_OR_GREATER
method ComObject (line 32) | public ComObject(object instance)
method CreateFromProgId (line 45) | public static ComObject CreateFromProgId(string progid)
method CreateFirstFrom (line 65) | public static ComObject CreateFirstFrom(Guid clsid)
method ComObject (line 85) | public ComObject(string progid)
method ComObject (line 94) | public ComObject(Guid clsid)
method Detach (line 103) | public object Detach()
method TryGetMember (line 113) | public override bool TryGetMember(GetMemberBinder binder, out object r...
method TrySetMember (line 128) | public override bool TrySetMember(SetMemberBinder binder, object value)
method TryInvokeMember (line 146) | public override bool TryInvokeMember(InvokeMemberBinder binder, object...
method TryGetIndex (line 160) | public override bool TryGetIndex(GetIndexBinder binder, object[] index...
method WrapIfRequired (line 187) | private static object WrapIfRequired(object obj)
method Dispose (line 190) | public void Dispose()
FILE: Westwind.Utilities/Utilities/DataUtils.cs
class DataUtils (line 54) | public static class DataUtils
method GenerateUniqueId (line 81) | public static string GenerateUniqueId(int stringSize = 8, string addit...
method GenerateUniqueNumericId (line 107) | public static long GenerateUniqueNumericId()
method GetRandomNumber (line 122) | public static int GetRandomNumber(int min, int max)
method IndexOfByteArray (line 139) | public static int IndexOfByteArray(byte[] buffer, byte[] bufferToFind)
method IndexOfByteArray (line 173) | public static int IndexOfByteArray(byte[] buffer, string stringToFind,...
method RemoveBytes (line 192) | public static byte[] RemoveBytes(byte[] buffer, byte[] bytesToRemove)
method CopyDataRow (line 244) | public static bool CopyDataRow(DataRow source, DataRow target)
method CopyObjectFromDataRow (line 268) | public static void CopyObjectFromDataRow(DataRow row, object targetObj...
method CopyObjectToDataRow (line 305) | public static bool CopyObjectToDataRow(DataRow row, object target)
method DataTableToTypedList (line 339) | public static List<T> DataTableToTypedList<T>(DataTable dsTable) where...
method CopyObjectData (line 362) | public static void CopyObjectData(object source, Object target)
method CopyObjectData (line 373) | public static void CopyObjectData(object source, Object target, Bindin...
method CopyObjectData (line 384) | public static void CopyObjectData(object source, Object target, string...
method CopyObjectData (line 400) | public static void CopyObjectData(object source, object target, string...
method DataTableToObjectList (line 450) | public static List<T> DataTableToObjectList<T>(DataTable dsTable) wher...
method DataReaderToObjectList (line 482) | public static List<T> DataReaderToObjectList<T>(IDataReader reader, st...
method DataReaderToIEnumerable (line 524) | public static IEnumerable<T> DataReaderToIEnumerable<T>(IDataReader re...
method DataReaderToList (line 550) | public static List<T> DataReaderToList<T>(IDataReader reader, string p...
method DataReaderToObject (line 595) | public static void DataReaderToObject(IDataReader reader, object insta...
method InitializeDataRowWithBlanks (line 671) | public static void InitializeDataRowWithBlanks(DataRow row)
method SqlTypeToDotNetType (line 713) | public static Type SqlTypeToDotNetType(SqlDbType sqlType)
method DbTypeToDotNetType (line 747) | public static Type DbTypeToDotNetType(DbType sqlType)
method DotNetTypeToDbType (line 782) | public static DbType DotNetTypeToDbType(Type type)
method DotNetTypeToSqlType (line 819) | public static SqlDbType DotNetTypeToSqlType(Type type)
type DataAccessProviderTypes (line 855) | public enum DataAccessProviderTypes
FILE: Westwind.Utilities/Utilities/DebugUtils.cs
class DebugUtils (line 45) | public static class DebugUtils
method GetInnerMostException (line 52) | [Obsolete("Use Exception.GetBaseException() instead")]
method GetInnerExceptions (line 70) | public static Exception[] GetInnerExceptions(Exception ex)
method GetTextWithLineNumbers (line 95) | public static string GetTextWithLineNumbers(string text, string lineFo...
method ParseStackTrace (line 129) | public static string ParseStackTrace(string stackTrace)
FILE: Westwind.Utilities/Utilities/ExensionMethods/DateTimeExtensions.cs
class DateTimeExtensions (line 5) | public static class DateTimeExtensions
method Between (line 14) | public static bool Between(this DateTime date, DateTime startDate, Dat...
method EndOfDay (line 27) | public static DateTime EndOfDay(this DateTime date)
method BeginningOfDay (line 38) | public static DateTime BeginningOfDay(this DateTime date)
method EndOfMonth (line 48) | public static DateTime EndOfMonth(this DateTime obj)
method BeginningOfMonth (line 58) | public static DateTime BeginningOfMonth(this DateTime obj)
FILE: Westwind.Utilities/Utilities/ExensionMethods/DictionaryExtensions.cs
class DictionaryExtensions (line 17) | public static class DictionaryExtensions
method ToXml (line 24) | public static string ToXml(this IDictionary items, string root = "root")
method FromXml (line 66) | public static void FromXml(this IDictionary items, string xml)
FILE: Westwind.Utilities/Utilities/ExensionMethods/LinqExtensions.cs
class LinqExtensions (line 8) | public static class LinqExtensions
method FlattenTree (line 24) | public static IEnumerable<T> FlattenTree<T>(
FILE: Westwind.Utilities/Utilities/ExensionMethods/MemoryStreamExtensions.cs
class MemoryStreamExtensions (line 10) | public static class MemoryStreamExtensions
method AsString (line 18) | public static string AsString(this MemoryStream ms, Encoding encoding ...
method FromString (line 32) | public static void FromString(this MemoryStream ms, string inputString...
class StreamExtensions (line 46) | public static class StreamExtensions
method AsString (line 55) | public static string AsString(this Stream s, Encoding encoding = null)
method AsBytes (line 70) | public static byte[] AsBytes(this Stream s)
method AsBytesAsync (line 91) | public static async Task<byte[]> AsBytesAsync(this Stream s)
FILE: Westwind.Utilities/Utilities/FileUtils.cs
class FileUtils (line 54) | public static class FileUtils
method GetPhysicalPath (line 71) | public static string GetPhysicalPath(string filename)
method GetRelativePath (line 95) | public static string GetRelativePath(string fullPath, string basePath )
method GetRelativeFilePath (line 130) | public static string GetRelativeFilePath(string filePath, string compa...
method ResolvePath (line 155) | public static string ResolvePath(string basePath, string relativeFile)
method IsRelativePath (line 173) | public static bool IsRelativePath(string path)
method GetShortPath (line 188) | public static string GetShortPath(string path)
method GetShortPathName (line 214) | [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
method GetWindowsLongFilename (line 240) | public static string GetWindowsLongFilename(string path)
method ExpandPathEnvironmentVariables (line 288) | public static string ExpandPathEnvironmentVariables(string path)
method TildefyUserPath (line 305) | public static string TildefyUserPath(string path)
method GetCompactPath (line 328) | public static string GetCompactPath(string path, int length = 70)
method GetTempFilenameWithExtension (line 368) | public static string GetTempFilenameWithExtension(string extension, st...
method BreakFilenameIntoWords (line 396) | public static string BreakFilenameIntoWords(string filename)
method NormalizePath (line 412) | public static string NormalizePath(string path)
method NormalizeDirectory (line 435) | public static string NormalizeDirectory(string path)
method AddTrailingSlash (line 450) | public static string AddTrailingSlash(string path)
method AddTrailingSlash (line 472) | public static string AddTrailingSlash(string path, char slashChar)
method FilePathAsUrl (line 493) | public static string FilePathAsUrl(string path)
method GetFileEncoding (line 514) | public static Encoding GetFileEncoding(string srcFile)
method GetChecksumFromFile (line 543) | public static string GetChecksumFromFile(string file, string hashAlgor...
method FindFileInHierarchy (line 592) | public static string FindFileInHierarchy( string currentPath, string s...
method FindFileInHierarchyInternal (line 621) | private static string FindFileInHierarchyInternal(string path, string ...
method FindFilesInHierarchy (line 663) | public static string[] FindFilesInHierarchy(string startPath, string s...
method FindFilesInHierarchyInternal (line 692) | private static string[] FindFilesInHierarchyInternal(string path, stri...
type FindFileInHierarchyDirection (line 720) | public enum FindFileInHierarchyDirection
method SafeFilename (line 739) | public static string SafeFilename(string fileName, string replacementS...
method CamelCaseSafeFilename (line 762) | public static string CamelCaseSafeFilename(string filename)
method HasInvalidPathCharacters (line 782) | public static bool HasInvalidPathCharacters(string path, params char[]...
method CopyStream (line 799) | public static void CopyStream(Stream source, Stream dest, int bufferSize)
method CopyStream (line 817) | public static void CopyStream(Stream source, Stream dest, int bufferSi...
method OpenStreamReaderWithEncoding (line 830) | public static StreamReader OpenStreamReaderWithEncoding(string srcFile)
method ReadAllTextAsync (line 846) | public static async Task<string> ReadAllTextAsync(string filename, Enc...
method ReadAllBytesAsync (line 862) | public static async Task<byte[]> ReadAllBytesAsync(string filename)
method WriteAllTextAsync (line 888) | public static async Task WriteAllTextAsync(string filename, string tex...
method WriteAllBytesAsync (line 908) | public static async Task WriteAllBytesAsync(string filename, byte[] by...
method CopyFileEnsureDirectory (line 933) | public static bool CopyFileEnsureDirectory(string sourceFilePath, stri...
method CopyDirectory (line 967) | public static void CopyDirectory(string sourceDirectory, string target...
method CopyDirectory (line 987) | public static void CopyDirectory(DirectoryInfo source, DirectoryInfo t...
method DeleteFiles (line 1030) | public static int DeleteFiles(string path, string filespec, bool recur...
method DeleteTimedoutFiles (line 1072) | public static void DeleteTimedoutFiles(string filespec, int seconds)
FILE: Westwind.Utilities/Utilities/GenericUtils.cs
class GenericUtils (line 8) | public static class GenericUtils
method InList (line 14) | public static bool InList<T>(this T item, params T[] list)
method InList (line 22) | public static bool InList<T>(this T item, IEnumerable<T> list)
method Inlist (line 38) | public static bool Inlist<T>(this T item, params T[] list)
method Inlist (line 51) | public static bool Inlist(this string item, bool caseSensitive, param...
FILE: Westwind.Utilities/Utilities/HtmlUtils.cs
class HtmlUtils (line 10) | public static class HtmlUtils
method FixHTMLForDisplay (line 17) | public static string FixHTMLForDisplay(string html)
method StripHtml (line 33) | public static string StripHtml(string html)
method DisplayMemo (line 51) | public static string DisplayMemo(string htmlText)
method DisplayMemoEncoded (line 69) | public static string DisplayMemoEncoded(string text)
method HtmlEncode (line 99) | [Obsolete("Use System.Net.WebUtility.HtmlEncode() instead.")]
method BinaryToEmbeddedBase64 (line 151) | public static string BinaryToEmbeddedBase64(byte[] imageBytes, string ...
method EmbeddedBase64ToBinary (line 165) | public static (byte[] bytes, string mimeType) EmbeddedBase64ToBinary(s...
method HtmlAbstract (line 189) | public static string HtmlAbstract(string html, int length)
method SanitizeHtml (line 224) | public static string SanitizeHtml(string html, string htmlTagBlacklist...
method Href (line 283) | public static string Href(string text, string url, string target = nul...
method Href (line 301) | public static string Href(string url)
method ImgRef (line 313) | public static string ImgRef(string imageUrl, string additionalMarkup =...
method ResolveUrl (line 342) | public static string ResolveUrl(string originalUrl)
method GetSiteBasePath (line 383) | public static string GetSiteBasePath(string url)
method GetRelativeUrlPath (line 395) | public static string GetRelativeUrlPath(string url, PathReturnOptions ...
type PathReturnOptions (line 417) | public enum PathReturnOptions
FILE: Westwind.Utilities/Utilities/HttpClientUtils.cs
class HttpClientUtils (line 23) | public class HttpClientUtils
method DownloadStringAsync (line 49) | public static async Task<string> DownloadStringAsync(HttpClientRequest...
method DownloadStringAsync (line 149) | public static async Task<string> DownloadStringAsync(string url, objec...
method DownloadString (line 176) | public static string DownloadString(HttpClientRequestSettings settings)
method DownloadString (line 274) | public static string DownloadString(string url, object data = null, st...
method DownloadFileAsync (line 309) | public static async Task<bool> DownloadFileAsync(HttpClientRequestSett...
method DownloadFileAsync (line 410) | public static Task<bool> DownloadFileAsync(string url, string filename)
method DownloadFile (line 431) | public static bool DownloadFile(HttpClientRequestSettings settings, st...
method DownloadFile (line 532) | public static bool DownloadFile(string url, string filename)
method DownloadImageToFileAsync (line 565) | public static async Task<string> DownloadImageToFileAsync(string image...
method DownloadImageToFileAsync (line 645) | public static async Task<string> DownloadImageToFileAsync( HttpClientR...
method DownloadImageToFile (line 669) | public static string DownloadImageToFile(string imageUrl = null, strin...
method DownloadImageToFile (line 749) | public static string DownloadImageToFile(HttpClientRequestSettings set...
method DownloadBytesAsync (line 764) | public static async Task<byte[]> DownloadBytesAsync(HttpClientRequestS...
method DownloadImageToFile (line 836) | public static string DownloadImageToFile(string imageUrl = null, strin...
method DownloadBytesAsync (line 903) | public static async Task<byte[]> DownloadBytesAsync(string url, object...
method DownloadBytes (line 931) | public static byte[] DownloadBytes(HttpClientRequestSettings settings)
method DownloadBytes (line 1017) | public static byte[] DownloadBytes(string url, object data = null, str...
method DownloadJsonAsync (line 1048) | public static async Task<TResult> DownloadJsonAsync<TResult>(HttpClien...
method DownloadJsonAsync (line 1078) | public static async Task<TResult> DownloadJsonAsync<TResult>(string ur...
method DownloadJson (line 1098) | public static TResult DownloadJson<TResult>(HttpClientRequestSettings ...
method DownloadJson (line 1136) | public static TResult DownloadJson<TResult>(string url, string verb = ...
method DownloadResponseMessageAsync (line 1157) | public static async Task<HttpResponseMessage> DownloadResponseMessageA...
method DownloadResponseMessage (line 1197) | public static HttpResponseMessage DownloadResponseMessage(HttpClientRe...
method GetHttpClient (line 1236) | public static HttpClient GetHttpClient(HttpClientHandler handler = null,
method ApplySettingsToRequest (line 1266) | public static void ApplySettingsToRequest(HttpClientRequestSettings se...
method SetHttpHeader (line 1330) | private static void SetHttpHeader(HttpRequestMessage req, string heade...
class HttpClientRequestSettings (line 1377) | public class HttpClientRequestSettings
method HttpClientRequestSettings (line 1559) | public HttpClientRequestSettings()
method ResetPostData (line 1585) | public void ResetPostData()
method SetPostStream (line 1591) | public void SetPostStream(Stream postStream)
method AddPostKey (line 1607) | public void AddPostKey(string key, byte[] value)
method AddPostKey (line 1652) | public void AddPostKey(string key, string value)
method AddPostKey (line 1664) | public void AddPostKey(string fullPostBuffer)
method AddPostKey (line 1674) | public void AddPostKey(byte[] fullPostBuffer)
method AddPostFile (line 1688) | public bool AddPostFile(string key, string filename, string contentTyp...
method GetPostBuffer (line 1744) | public string GetPostBuffer()
method GetPostBufferBytes (line 1770) | public byte[] GetPostBufferBytes()
method GetResponseStringAsync (line 1790) | public async Task<string> GetResponseStringAsync()
method GetResponseJson (line 1813) | public async Task<TResult> GetResponseJson<TResult>()
method GetResponseErrorMessage (line 1828) | public async Task<string> GetResponseErrorMessage()
method GetResponseDataAsync (line 1846) | public async Task<byte[]> GetResponseDataAsync()
method ToString (line 1864) | public override string ToString()
type HttpFormPostMode (line 1870) | public enum HttpFormPostMode
FILE: Westwind.Utilities/Utilities/HttpUtils.cs
class HttpUtils (line 14) | [Obsolete("Use HttpClientUtils if possible.")]
method HttpRequestString (line 24) | public static string HttpRequestString(string url)
method HttpRequestString (line 34) | public static string HttpRequestString(HttpRequestSettings settings)
method HttpRequestBytes (line 71) | public static byte[] HttpRequestBytes(string url)
method HttpRequestBytes (line 82) | public static byte[] HttpRequestBytes(HttpRequestSettings settings)
method HttpRequestStringAsync (line 117) | public static async Task<string> HttpRequestStringAsync(string url)
method HttpRequestStringAsync (line 128) | public static async Task<string> HttpRequestStringAsync(HttpRequestSet...
method HttpRequestBytesAsync (line 164) | public static async Task<byte[]> HttpRequestBytesAsync(string url)
method HttpRequestBytesAsync (line 174) | public static async Task<byte[]> HttpRequestBytesAsync(HttpRequestSett...
method JsonRequest (line 213) | public static TResultType JsonRequest<TResultType>(HttpRequestSettings...
method JsonRequestAsync (line 261) | public static async Task<TResultType> JsonRequestAsync<TResultType>(Ht...
method DownloadImageToFile (line 312) | public static string DownloadImageToFile(string imageUrl, string filen...
method DownloadImageToFileAsync (line 381) | public static async Task<string> DownloadImageToFileAsync(string image...
method CreateWebProxy (line 446) | public static IWebProxy CreateWebProxy(string proxyAddress = null, boo...
class HttpRequestSettings (line 472) | public class HttpRequestSettings
method HttpRequestSettings (line 594) | public HttpRequestSettings()
FILE: Westwind.Utilities/Utilities/HttpUtilsWebClient.cs
class HttpUtilsWebClient (line 12) | public class HttpUtilsWebClient : WebClient
method HttpUtilsWebClient (line 19) | public HttpUtilsWebClient(HttpRequestSettings settings = null)
method GetWebRequest (line 50) | protected override WebRequest GetWebRequest(Uri address)
method GetWebResponse (line 73) | protected override WebResponse GetWebResponse(WebRequest request)
method GetWebResponse (line 94) | protected override WebResponse GetWebResponse(WebRequest request, Syst...
FILE: Westwind.Utilities/Utilities/ImageUtils.cs
class ImageUtils (line 49) | public static class ImageUtils
method ResizeImage (line 64) | public static Bitmap ResizeImage(string filename, int width, int heigh...
method ResizeImage (line 88) | public static Bitmap ResizeImage(byte[] data, int width, int height, I...
method ResizeImage (line 115) | public static bool ResizeImage(string filename, string outputFilename,
method ResizeImage (line 145) | public static Bitmap ResizeImage(Bitmap bmp, int width, int height,
method AdjustImageToRatio (line 224) | public static Bitmap AdjustImageToRatio(Stream imageStream, decimal ra...
method AdjustImageToRatio (line 314) | public static Bitmap AdjustImageToRatio(byte[] imageContent, decimal r...
method SaveJpeg (line 332) | public static bool SaveJpeg(Bitmap bmp, string outputFileName, long jp...
method SaveJpeg (line 369) | public static bool SaveJpeg(Bitmap bmp, Stream imageStream, long jpegQ...
method RoateImage (line 406) | public static bool RoateImage(string filename, string outputFilename =...
method RoateImage (line 451) | public static byte[] RoateImage(byte[] data, RotateFlipType type = Rot...
method StripJpgExifData (line 495) | public static void StripJpgExifData(string imageFile, int imageQuality...
method NormalizeJpgImageRotation (line 517) | public static void NormalizeJpgImageRotation(string imageFile, int ima...
method GetImageFormatFromFilename (line 584) | public static ImageFormat GetImageFormatFromFilename(string filename)
method GetImageMediaTypeFromFilename (line 611) | public static string GetImageMediaTypeFromFilename(string file)
method GetExtensionFromMediaType (line 644) | public static string GetExtensionFromMediaType(string mediaType)
method IsImage (line 674) | public static bool IsImage(string filename)
method IsImage (line 700) | public static bool IsImage(byte[] data)
FILE: Westwind.Utilities/Utilities/JsonSerializationUtils.cs
class JsonSerializationUtils (line 52) | public static class JsonSerializationUtils
method Serialize (line 74) | public static string Serialize(object value, bool throwExceptions = fa...
method SerializeToFile (line 124) | public static bool SerializeToFile(object value, string fileName, bool...
method Deserialize (line 168) | public static object Deserialize(string jsonText, Type type, bool thro...
method Deserialize (line 206) | public static T Deserialize<T>(string jsonText, bool throwExceptions =...
method DeserializeFromFile (line 223) | public static object DeserializeFromFile(string fileName, Type objectT...
method DeserializeFromFile (line 265) | public static T DeserializeFromFile<T>(string fileName, bool throwExc...
method FormatJsonString (line 279) | public static string FormatJsonString(string json)
method CreateJsonNet (line 289) | public static JsonSerializer CreateJsonNet(bool throwExceptions = true...
FILE: Westwind.Utilities/Utilities/KnownFolders.cs
class KnownFolders (line 12) | public static class KnownFolders
method GetPath (line 22) | public static string GetPath(KnownFolder knownFolder)
method GetPath (line 38) | public static string GetPath(KnownFolder knownFolder, bool defaultUser)
method GetDefaultPath (line 51) | public static string GetDefaultPath(KnownFolder knownFolder)
method GetDefaultPath (line 66) | public static string GetDefaultPath(KnownFolder knownFolder, bool defa...
method Initialize (line 78) | public static void Initialize(KnownFolder knownFolder)
method Initialize (line 91) | public static void Initialize(KnownFolder knownFolder, bool defaultUser)
method GetPath (line 96) | private static string GetPath(KnownFolder knownFolder, KnownFolderFlag...
method SHGetKnownFolderPath (line 184) | [DllImport("Shell32.dll")]
type KnownFolderFlags (line 189) | [Flags]
type KnownFolder (line 230) | public enum KnownFolder
FILE: Westwind.Utilities/Utilities/LanguageUtils.cs
class LanguageUtils (line 6) | public static class LanguageUtils
method IgnoreErrors (line 15) | public static bool IgnoreErrors(Action operation)
method IgnoreErrors (line 39) | public static T IgnoreErrors<T>(Func<T> operation, T defaultValue = de...
FILE: Westwind.Utilities/Utilities/NetworkUtils.cs
class NetworkUtils (line 9) | public static class NetworkUtils
method GetBaseDomain (line 18) | public static string GetBaseDomain(string domainName)
method GetBaseDomain (line 39) | public static string GetBaseDomain(this Uri uri)
method IsLocalIpAddress (line 57) | public static bool IsLocalIpAddress(string hostOrIp)
method IsLocalIpAddress (line 100) | public static bool IsLocalIpAddress(Uri uri)
FILE: Westwind.Utilities/Utilities/PasswordScrubber.cs
class PasswordScrubber (line 17) | public class PasswordScrubber
method ScrubJsonValues (line 37) | public string ScrubJsonValues(string configString, params string[] jso...
method ScrubSqlConnectionStringValues (line 55) | public string ScrubSqlConnectionStringValues(string configString, para...
method ObscureValue (line 73) | public string ObscureValue(string value, int showUnobscuredCharacterCo...
FILE: Westwind.Utilities/Utilities/ReflectionUtils.cs
class ReflectionUtils (line 50) | public static class ReflectionUtils
method CreateInstanceFromType (line 75) | public static object CreateInstanceFromType(Type typeToCreate, params ...
method CreateInstanceFromString (line 95) | public static object CreateInstanceFromString(string typeName, params ...
method GetTypeFromName (line 130) | public static Type GetTypeFromName(string typeName, string assemblyName )
method GetTypeFromName (line 169) | public static Type GetTypeFromName(string typeName)
method CreateComInstance (line 180) | #if NET6_0_OR_GREATER
method LoadAssembly (line 198) | public static Assembly LoadAssembly(string assemblyName)
method ShallowClone (line 225) | public static object ShallowClone(object source)
method StringToTypedValue (line 257) | public static object StringToTypedValue(string sourceString, Type targ...
method StringToTypedValue (line 388) | public static T StringToTypedValue<T>(string sourceString, CultureInfo...
method TypedValueToString (line 402) | public static string TypedValueToString(object rawValue, CultureInfo c...
method CallMethod (line 463) | public static object CallMethod(object instance, string method, Type[]...
method CallMethod (line 489) | public static object CallMethod(object instance, string method, params...
method InvokeEvent (line 517) | public static void InvokeEvent(object instance, string eventName, para...
method GetProperty (line 541) | public static object GetProperty(object instance, string property)
method GetPropertyInternal (line 553) | private static object GetPropertyInternal(object Parent, string Property)
method GetPropertyInfoInternal (line 626) | public static PropertyInfo GetPropertyInfoInternal(object Parent, stri...
method GetField (line 648) | public static object GetField(object Object, string Property)
method SetProperty (line 661) | public static void SetProperty(object obj, string property, object value)
method SetPropertyInternal (line 672) | private static object SetPropertyInternal(object Parent, string Proper...
method SetField (line 756) | public static void SetField(object obj, string property, object value)
method GetEnumList (line 767) | public static List<KeyValuePair<string, string>> GetEnumList(Type enum...
method CallMethodEx (line 799) | public static object CallMethodEx(object parent, string method, params...
method GetPropertyEx (line 829) | public static object GetPropertyEx(object Parent, string Property)
method GetPropertyInfoEx (line 859) | public static PropertyInfo GetPropertyInfoEx(object Parent, string Pro...
method SetPropertyEx (line 896) | public static object SetPropertyEx(object parent, string property, obj...
method CallStaticMethod (line 929) | public static object CallStaticMethod(string typeName, string method, ...
method GetStaticProperty (line 957) | public static object GetStaticProperty(string typeName, string property)
method GetStaticProperty (line 972) | public static object GetStaticProperty(Type type, string property)
method GetPropertyCom (line 997) | public static object GetPropertyCom(object instance, string property)
method GetPropertyExCom (line 1010) | public static object GetPropertyExCom(object parent, string property)
method SetPropertyCom (line 1043) | public static void SetPropertyCom(object inst, string Property, object...
method SetPropertyExCom (line 1067) | public static object SetPropertyExCom(object parent, string property, ...
method CallMethodCom (line 1101) | public static object CallMethodCom(object instance, string method, par...
method CallMethodExCom (line 1113) | public static object CallMethodExCom(object parent, string method, par...
method IsAnonoymousType (line 1142) | public static bool IsAnonoymousType(object objectOrType)
FILE: Westwind.Utilities/Utilities/SecurityUtils.cs
class SecurityUtils (line 46) | public static class SecurityUtils
method LogonUser (line 57) | [DllImport("advapi32.dll", SetLastError = true)]
method CloseHandle (line 67) | [DllImport("kernel32.dll", SetLastError = true)]
method ImpersonateUser (line 83) | public static WindowsImpersonationContext ImpersonateUser(string usern...
method RevertImpersonation (line 113) | public static void RevertImpersonation(WindowsImpersonationContext con...
FILE: Westwind.Utilities/Utilities/SerializationUtils.cs
class SerializationUtils (line 51) | public static class SerializationUtils
method SerializeObject (line 61) | public static bool SerializeObject(object instance, string fileName, b...
method SerializeObject (line 132) | public static bool SerializeObject(object instance, XmlTextWriter writ...
method SerializeObject (line 169) | public static bool SerializeObject(object instance, out string xmlResu...
method SerializeObject (line 181) | public static bool SerializeObject(object instance, out string xmlResu...
method SerializeObject (line 209) | public static bool SerializeObject(object instance, out byte[] resultB...
method SerializeObjectToString (line 250) | public static string SerializeObjectToString(object instance, bool thr...
method SerializeObjectToByteArray (line 261) | public static byte[] SerializeObjectToByteArray(object instance, bool ...
method DeSerializeObject (line 280) | public static object DeSerializeObject(string fileName, Type objectTyp...
method DeSerializeObject (line 293) | public static object DeSerializeObject(string fileName, Type objectTyp...
method DeSerializeObject (line 366) | public static object DeSerializeObject(XmlReader reader, Type objectType)
method DeSerializeObject (line 375) | public static object DeSerializeObject(string xml, Type objectType)
method DeSerializeObject (line 389) | public static object DeSerializeObject(byte[] buffer, Type objectType,...
method ObjectToString (line 426) | public static string ObjectToString(object instanc, string separator, ...
type ObjectToStringTypes (line 466) | public enum ObjectToStringTypes
FILE: Westwind.Utilities/Utilities/ShellUtils.cs
class ShellUtils (line 50) | public static class ShellUtils
method ExecuteProcess (line 63) | public static int ExecuteProcess(string executable,
method ExecuteProcess (line 120) | public static int ExecuteProcess(string executable,
method ExecuteProcess (line 145) | public static int ExecuteProcess(string executable,
method ExecuteProcess (line 173) | private static int ExecuteProcess(string executable,
method GoUrl (line 273) | public static bool GoUrl(string url, string workingFolder = null)
method OpenUrl (line 310) | public static bool OpenUrl(string url)
method ShellExecute (line 374) | public static int ShellExecute(string url, string arguments = null,
method OpenFileInExplorer (line 399) | public static bool OpenFileInExplorer(string filename)
method OpenTerminal (line 433) | public static bool OpenTerminal(string folder, TerminalModes mode = Te...
method ExecuteCommandLine (line 477) | public static void ExecuteCommandLine(string fullCommandLine,
method ShowString (line 549) | public static bool ShowString(string text, string extension = null)
method ShowHtml (line 567) | public static bool ShowHtml(string htmlString)
method ShowText (line 578) | public static bool ShowText(string TextString)
method HttpGet (line 596) | public static string HttpGet(string url)
method HttpGet (line 608) | public static string HttpGet(string url, out string errorMessage)
method HttpGetBytes (line 637) | public static byte[] HttpGetBytes(string url)
method HttpGetBytes (line 650) | public static byte[] HttpGetBytes(string url, out string errorMessage)
type TerminalModes (line 673) | public enum TerminalModes
FILE: Westwind.Utilities/Utilities/StringUtils.cs
class StringUtils (line 53) | public static class StringUtils
method TrimStart (line 66) | public static string TrimStart(this string text, string textToTrim, bo...
method TrimEnd (line 94) | public static string TrimEnd(this string text, string textToTrim, bool...
method TrimTo (line 130) | [Obsolete("Please use the StringUtils.Truncate() method instead.")]
method Replicate (line 148) | public static string Replicate(string input, int charCount)
method Replicate (line 164) | public static string Replicate(char character, int charCount)
method IndexOfNth (line 176) | public static int IndexOfNth(this string source, string matchString, i...
method IndexOfNth (line 207) | public static int IndexOfNth(this string source, char matchChar, int c...
method LastIndexOfNth (line 237) | public static int LastIndexOfNth(this string source, string matchStrin...
method LastIndexOfNth (line 265) | public static int LastIndexOfNth(this string source, char matchChar, i...
method EqualsNoCase (line 294) | public static bool EqualsNoCase(this string text, string compareTo)
method ProperCase (line 309) | public static string ProperCase(string Input)
method ToCamelCase (line 321) | public static string ToCamelCase(string phrase)
method FromCamelCase (line 367) | public static string FromCamelCase(string camelCase)
method BreakIntoWords (line 399) | public static string BreakIntoWords(string text)
method ExtractString (line 449) | public static string ExtractString(this string source,
method StripAfter (line 505) | public static string StripAfter(this string value, string delimiter, b...
method ReplaceStringInstance (line 529) | public static string ReplaceStringInstance(string origString, string f...
method ReplaceString (line 569) | #if NET6_0_OR_GREATER
method ReplaceLastNthInstance (line 605) | public static string ReplaceLastNthInstance(string source, string oldV...
method Truncate (line 629) | public static string Truncate(this string text, int maxLength)
method TextAbstract (line 646) | public static string TextAbstract(string text, int length)
method TerminateString (line 676) | public static string TerminateString(string value, string terminatorSt...
method Right (line 695) | public static string Right(string full, int rightCharCount)
method StartsWithAny (line 712) | public static bool StartsWithAny(this string str, params string[] matc...
method StartsWithAny (line 733) | public static bool StartsWithAny(this string str, StringComparison com...
method ContainsAny (line 753) | public static bool ContainsAny(this string str, params string[] matchV...
method ContainsAny (line 774) | public static bool ContainsAny(this string str, StringComparison compa...
method ContainsAny (line 796) | public static bool ContainsAny(this string str, params char[] matchVal...
method ContainsAny (line 818) | public static bool ContainsAny(this string str, StringComparison compa...
method EqualsAny (line 841) | public static bool EqualsAny(this string str, params string[] matchVal...
method EqualsAny (line 866) | public static bool EqualsAny(this string str, StringComparison compare...
method ReplaceMany (line 893) | public static string ReplaceMany(this string str, string[] matchValues...
method ReplaceMany (line 919) | public static string ReplaceMany(this string str, string valuesToMatch...
method ReplaceMany (line 945) | public static string ReplaceMany(this string str, string[] matchValues...
method ReplaceMany (line 968) | public static string ReplaceMany(this string str, string valuesToMatch...
method Inlist (line 996) | public static bool Inlist(this string s, params string[] list)
method Inlist (line 1011) | public static bool Inlist(string s, StringComparison compare, params s...
method IsStringInList (line 1033) | public static bool IsStringInList(string stringList, string valueToFin...
method Contains (line 1055) | public static bool Contains(this string text, string searchFor, String...
method GetLines (line 1068) | public static string[] GetLines(this string s, int maxLines = 0)
method CountLines (line 1086) | public static int CountLines(this string s)
method Occurs (line 1102) | public static int Occurs(string source, char match)
method Occurs (line 1121) | public static int Occurs(string source, string match)
method GetMaxCharacters (line 1138) | public static string GetMaxCharacters(this string s, int maxCharacters...
method GetLastCharacters (line 1160) | public static string GetLastCharacters(this string s, int characterCount)
method StripNonNumber (line 1174) | public static string StripNonNumber(string input)
method TokenizeString (line 1201) | public static List<string> TokenizeString(ref string text, string star...
method DetokenizeString (line 1227) | public static string DetokenizeString(string text, IEnumerable<string>...
method ParseInt (line 1246) | public static int ParseInt(string input, int defaultValue = 0, IFormat...
method ParseDecimal (line 1271) | public static decimal ParseDecimal(string input, decimal defaultValue ...
method NewStringId (line 1293) | public static string NewStringId()
method RandomString (line 1304) | public static string RandomString(int size, bool includeNumbers = false)
method UrlEncode (line 1343) | public static string UrlEncode(string text)
method UrlEncodePathSafe (line 1357) | public static string UrlEncodePathSafe(string text)
method UrlDecode (line 1368) | public static string UrlDecode(string text)
method GetUrlEncodedKey (line 1385) | public static string GetUrlEncodedKey(string urlEncoded, string key)
method SetUrlEncodedKey (line 1412) | public static string SetUrlEncodedKey(string urlEncoded, string key, s...
method BinHexToBinary (line 1436) | public static byte[] BinHexToBinary(string hex)
method BinaryToBinHex (line 1460) | public static string BinaryToBinHex(byte[] data)
method StringToBytes (line 1484) | public static byte[] StringToBytes(string text, Encoding encoding = null)
method BytesToString (line 1501) | public static string BytesToString(byte[] buffer, Encoding encoding = ...
method ToBase64String (line 1518) | public static string ToBase64String(string text, Encoding encoding = n...
method FromBase64String (line 1533) | public static string FromBase64String(string base64, Encoding encoding...
method ParseHexChar (line 1542) | static int ParseHexChar(char c)
method Base36Encode (line 1565) | public static string Base36Encode(long value)
method Base36Decode (line 1586) | public static long Base36Decode(string input)
method NormalizeLineFeeds (line 1615) | public static string NormalizeLineFeeds(string text, LineFeedTypes typ...
method NormalizeIndentation (line 1641) | public static string NormalizeIndentation(string code)
method LogString (line 1692) | public static void LogString(string output, string filename, Encoding ...
method StringToStream (line 1715) | public static Stream StringToStream(string text, Encoding encoding = n...
method StreamToString (line 1734) | public static string StreamToString(Stream stream, Encoding encoding =...
method GetProperty (line 1754) | public static string GetProperty(string propertyString, string key)
method SetProperty (line 1769) | public static string SetProperty(string propertyString, string key, st...
method ToJsonString (line 1798) | public static string ToJsonString(string text)
type LineFeedTypes (line 1850) | public enum LineFeedTypes
FILE: Westwind.Utilities/Utilities/TimeUtils.cs
class TimeUtils (line 43) | public static class TimeUtils
method FriendlyDateString (line 54) | public static string FriendlyDateString(DateTime date, bool showTime =...
method ShortDateString (line 84) | public static string ShortDateString(DateTime date, bool showTime=fals...
method ShortDateString (line 102) | public static string ShortDateString(DateTime? date, bool ShowTime)
method ShortTimeString (line 115) | public static string ShortTimeString(DateTime date)
method FriendlyElapsedTimeString (line 128) | public static string FriendlyElapsedTimeString(int milliSeconds)
method FriendlyElapsedTimeString (line 141) | public static string FriendlyElapsedTimeString(double milliSeconds)
method FriendlyElapsedTimeString (line 175) | public static string FriendlyElapsedTimeString(TimeSpan elapsed)
method FractionalHoursToString (line 186) | public static string FractionalHoursToString(decimal hours, string for...
method FractionalHoursToString (line 204) | public static string FractionalHoursToString(decimal hours)
method RoundDateToMinuteInterval (line 215) | public static decimal RoundDateToMinuteInterval(decimal hours, int min...
method RoundDateToMinuteInterval (line 240) | public static DateTime RoundDateToMinuteInterval(DateTime time, int mi...
method DateTimeFromDateAndTime (line 282) | public static DateTime DateTimeFromDateAndTime(string Date, string Time)
method DateTimeFromDateAndTime (line 293) | public static DateTime DateTimeFromDateAndTime(DateTime Date, string T...
method MimeDateTime (line 302) | public static string MimeDateTime(DateTime Time)
method IsBetween (line 330) | public static bool IsBetween(this DateTime date, DateTime startDate, D...
method IsBetween (line 344) | public static bool IsBetween(this TimeSpan date, DateTime startDate, D...
method Truncate (line 358) | public static DateTime Truncate(DateTime date, DateTimeResolution reso...
method ToTimeZoneTime (line 390) | public static DateTime ToTimeZoneTime(this DateTime time, string timeZ...
method ToTimeZoneTime (line 403) | public static DateTime ToTimeZoneTime(this DateTime time, TimeZoneInfo...
type RoundingDirection (line 414) | public enum RoundingDirection
type DateTimeResolution (line 421) | public enum DateTimeResolution
FILE: Westwind.Utilities/Utilities/VersionUtils.cs
class VersionExtensions (line 8) | public static class VersionExtensions
method FormatVersion (line 21) | public static string FormatVersion(this Version version, int minTokens...
method FormatVersion (line 52) | public static string FormatVersion(string version, int minTokens = 2, ...
method CompareVersions (line 65) | public static int CompareVersions(string versionToCompare, string vers...
FILE: Westwind.Utilities/Utilities/XmlUtils.cs
class XmlUtils (line 47) | public static class XmlUtils
method XmlString (line 66) | public static string XmlString(string text, bool isAttribute = false)
method GetXmlNode (line 117) | public static XmlNode GetXmlNode(XmlNode node, string xPath, XmlNamesp...
method GetXmlString (line 129) | public static string GetXmlString(XmlNode node, string xPath = null, X...
method GetXmlEnum (line 151) | public static T GetXmlEnum<T>(XmlNode node, string xPath, XmlNamespace...
method GetXmlInt (line 166) | public static int GetXmlInt(XmlNode node, string XPath, XmlNamespaceMa...
method GetXmlDecimal (line 184) | public static decimal GetXmlDecimal(XmlNode node, string XPath, XmlNam...
method GetXmlBool (line 202) | public static bool GetXmlBool(XmlNode node, string xPath,XmlNamespaceM...
method GetXmlDateTime (line 221) | public static DateTime GetXmlDateTime(XmlNode node, string xPath, XmlN...
method GetXmlAttributeString (line 244) | public static string GetXmlAttributeString(XmlNode node, string attrib...
method GetXmlAttributeInt (line 260) | public static int GetXmlAttributeInt(XmlNode node, string attributeNam...
method GetXmlAttributeBool (line 277) | public static bool? GetXmlAttributeBool(XmlNode node, string attribute...
method MapTypeToXmlType (line 292) | public static string MapTypeToXmlType(Type type)
method MapXmlTypeToType (line 332) | public static Type MapXmlTypeToType(string xmlType)
method CreateXmlNamespaceManager (line 375) | public static XmlNamespaceManager CreateXmlNamespaceManager(XmlDocumen...
Condensed preview — 142 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,323K chars).
[
{
"path": ".gitattributes",
"chars": 2518,
"preview": "###############################################################################\n# Set default behavior to automatically "
},
{
"path": ".github/FUNDING.yml",
"chars": 177,
"preview": "github: RickStrahl\ncustom: \"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=K677THUA2MJSE&source=ur"
},
{
"path": ".gitignore",
"chars": 4352,
"preview": "## Ignore Visual Studio temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n\nTest/\n"
},
{
"path": "Changelog.md",
"chars": 24807,
"preview": "# Westwind.Utilities Changelog\n\n\n## 5.3\n\n* **HttpClientUtils.DownloadBytes/Async** \nAdded routine to easily download by"
},
{
"path": "LICENSE.md",
"chars": 1095,
"preview": "MIT License\n===========\n\nCopyright (c) 2012-2024 West Wind Technologies\n\nPermission is hereby granted, free of charge, t"
},
{
"path": "Readme.md",
"chars": 6308,
"preview": "# Westwind.Utilities \n\n\n\n\n| Library | Versions and Stats "
},
{
"path": "Westwind.Utilities/.gitignore",
"chars": 106,
"preview": "###############\n# folder #\n###############\n/**/DROP/\n/**/TEMP/\n/**/packages/\n/**/bin/\n/**/obj/\n_site\n"
},
{
"path": "Westwind.Utilities/Configuration/AppConfiguration.cd",
"chars": 2751,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ClassDiagram MajorVersion=\"1\" MinorVersion=\"1\">\n <Comment CommentText=\"<-- "
},
{
"path": "Westwind.Utilities/Configuration/AppConfiguration.cs",
"chars": 13755,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Configuration/Providers/ConfigurationFileConfigurationProvider.cs",
"chars": 29805,
"preview": "#if NETFULL\n\n#region License\n/*\n **************************************************************\n * Author: Rick Strahl "
},
{
"path": "Westwind.Utilities/Configuration/Providers/ConfigurationProviderBase.cs",
"chars": 12428,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Configuration/Providers/IConfigurationProvider.cs",
"chars": 4605,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Configuration/Providers/JsonFileConfigurationProvider.cs",
"chars": 4142,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Configuration/Providers/StringConfigurationProvider.cs",
"chars": 3143,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Configuration/Providers/XmlFileConfigurationProvider.cs",
"chars": 4478,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Data/ValidationError.cs",
"chars": 2736,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Data/ValidationErrorCollection.cs",
"chars": 9047,
"preview": "using System.Collections;\nusing System.Text;\n\nnamespace Westwind.Utilities\n{\n /// <summary>\n /// A collection of V"
},
{
"path": "Westwind.Utilities/InternetTools/HttpClient.cs",
"chars": 55151,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/InternetTools/SmtpClientNative.cs",
"chars": 21159,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/LICENSE.MD",
"chars": 1151,
"preview": "West Wind Utilities Library\n===========================\n\nMIT License\n-----------\nCopyright (c) 2019-2023 West Wind Techn"
},
{
"path": "Westwind.Utilities/Properties/Resources.Designer.cs",
"chars": 14544,
"preview": "//------------------------------------------------------------------------------\n// <auto-generated>\n// This code w"
},
{
"path": "Westwind.Utilities/Properties/Resources.resx",
"chars": 10166,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n <!-- \n Microsoft ResX Schema \n \n Version 2.0\n \n The prim"
},
{
"path": "Westwind.Utilities/SupportClasses/DelegateFactory.cs",
"chars": 3402,
"preview": "using System;\nusing System.Reflection;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Linq.Expression"
},
{
"path": "Westwind.Utilities/SupportClasses/Encryption.cs",
"chars": 41201,
"preview": "using System;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusi"
},
{
"path": "Westwind.Utilities/SupportClasses/Expando.cs",
"chars": 16503,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/SupportClasses/ObjectFactory.cs",
"chars": 3049,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Web;\nusing System.Th"
},
{
"path": "Westwind.Utilities/SupportClasses/PropertyBag.cs",
"chars": 8376,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Xml.Serialization;\nusing System.Xml;\nusing Westwind.Utiliti"
},
{
"path": "Westwind.Utilities/SupportClasses/Scheduler.cs",
"chars": 11263,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Net;\n\nnamespace Westwind.Utilities"
},
{
"path": "Westwind.Utilities/SupportClasses/StringSerializer.cs",
"chars": 6298,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\n\nnamespa"
},
{
"path": "Westwind.Utilities/SupportClasses/UrlEncodingParser.cs",
"chars": 5194,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\n\n\nnamespace Westwind.Utilities\n{\n"
},
{
"path": "Westwind.Utilities/SupportClasses/UrlParser.cs",
"chars": 5982,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Utilities/AsyncUtils.cs",
"chars": 9245,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Thr"
},
{
"path": "Westwind.Utilities/Utilities/ComObject.cs",
"chars": 6354,
"preview": "using System;\nusing System.Dynamic;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Runtime"
},
{
"path": "Westwind.Utilities/Utilities/DataUtils.cs",
"chars": 34584,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Utilities/DebugUtils.cs",
"chars": 5870,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Utilities/ExensionMethods/DateTimeExtensions.cs",
"chars": 2643,
"preview": "using System;\n\nnamespace Westwind.Utilities.Extensions\n{\n public static class DateTimeExtensions\n {\n /// <"
},
{
"path": "Westwind.Utilities/Utilities/ExensionMethods/DictionaryExtensions.cs",
"chars": 3607,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Linq;\nusing System.Xml.Linq;\nusing West"
},
{
"path": "Westwind.Utilities/Utilities/ExensionMethods/LinqExtensions.cs",
"chars": 1282,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Westwind.Utilities.Lin"
},
{
"path": "Westwind.Utilities/Utilities/ExensionMethods/MemoryStreamExtensions.cs",
"chars": 3389,
"preview": "using System.Text;\nusing System.IO;\nusing System.Threading.Tasks;\n\nnamespace System.IO\n{\n /// <summary>\n /// Memo"
},
{
"path": "Westwind.Utilities/Utilities/FileUtils.cs",
"chars": 40477,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Utilities/GenericUtils.cs",
"chars": 2000,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Westwind.Utilities\n{\n "
},
{
"path": "Westwind.Utilities/Utilities/HtmlUtils.cs",
"chars": 15524,
"preview": "using System;\nusing System.Text.RegularExpressions;\n\n\nnamespace Westwind.Utilities\n{\n /// <summary>\n /// Html stri"
},
{
"path": "Westwind.Utilities/Utilities/HttpClientUtils.cs",
"chars": 70134,
"preview": "using Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusi"
},
{
"path": "Westwind.Utilities/Utilities/HttpUtils.cs",
"chars": 23484,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Net;\nusing System.Text;\nusing System.Thre"
},
{
"path": "Westwind.Utilities/Utilities/HttpUtilsWebClient.cs",
"chars": 3455,
"preview": "using System;\nusing System.Net;\nusing System.Web;\n\nnamespace Westwind.Utilities\n{\n /// <summary>\n /// Customized v"
},
{
"path": "Westwind.Utilities/Utilities/ImageUtils.cs",
"chars": 28046,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Utilities/JsonSerializationUtils.cs",
"chars": 11587,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Utilities/KnownFolders.cs",
"chars": 13302,
"preview": "using System;\nusing System.Runtime.InteropServices;\nusing static System.Environment;\n\nnamespace Westwind.Utilities\n{\n "
},
{
"path": "Westwind.Utilities/Utilities/LanguageUtils.cs",
"chars": 1560,
"preview": "using System;\n\nnamespace Westwind.Utilities\n{\n\n public static class LanguageUtils\n {\n /// <summary>\n "
},
{
"path": "Westwind.Utilities/Utilities/NetworkUtils.cs",
"chars": 3693,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing System.Text;\n\nnamespace West"
},
{
"path": "Westwind.Utilities/Utilities/PasswordScrubber.cs",
"chars": 3328,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Text.RegularExpressi"
},
{
"path": "Westwind.Utilities/Utilities/ReflectionUtils.cs",
"chars": 45674,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Utilities/SecurityUtils.cs",
"chars": 4362,
"preview": "#if NETFULL\n\n#region License\n/*\n **************************************************************\n * Author: Rick Strahl "
},
{
"path": "Westwind.Utilities/Utilities/SerializationUtils.cs",
"chars": 16723,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Utilities/ShellUtils.cs",
"chars": 25310,
"preview": "#pragma warning disable SYSLIB0014\n\n#region \n/*\n **************************************************************\n * Aut"
},
{
"path": "Westwind.Utilities/Utilities/StringUtils.cs",
"chars": 68445,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Utilities/TimeUtils.cs",
"chars": 16711,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Utilities/VersionUtils.cs",
"chars": 2961,
"preview": "using System;\nusing System.Linq;\nusing System.Net;\n\nnamespace Westwind.Utilities\n{\n\n public static class VersionExte"
},
{
"path": "Westwind.Utilities/Utilities/XmlUtils.cs",
"chars": 13362,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities/Westwind.Utilities.csproj",
"chars": 4051,
"preview": "<Project Sdk=\"Microsoft.NET.Sdk\">\n\t<PropertyGroup>\n\t\t<TargetFrameworks>net10.0;net8.0;net472;netstandard2.0</TargetFram"
},
{
"path": "Westwind.Utilities/Westwind.Utilities.sln",
"chars": 1106,
"preview": "Microsoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 17\nVisualStudioVersion = 17.5.2.0\nMi"
},
{
"path": "Westwind.Utilities/publish-nuget.ps1",
"chars": 540,
"preview": "if (test-path ./nupkg) {\n remove-item ./nupkg -Force -Recurse\n} \n\ndotnet build -c Release\n\n$filename = Get-ChildIt"
},
{
"path": "Westwind.Utilities.Data/Configuration/SqlServerConfigurationProvider.cs",
"chars": 10207,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities.Data/ConnectionStringInfo.cs",
"chars": 4062,
"preview": "using System;\nusing System.Configuration;\nusing System.Data.Common;\n\n#if NETCORE\n using Microsoft.Data.SqlClient;\n#el"
},
{
"path": "Westwind.Utilities.Data/DataAccessBase.cs",
"chars": 80300,
"preview": "#region License\n//#define SupportWebRequestProvider\n/*\n **************************************************************\n"
},
{
"path": "Westwind.Utilities.Data/DataTableExtensions.cs",
"chars": 2914,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Data;\nusing System.C"
},
{
"path": "Westwind.Utilities.Data/DynamicDataReader.cs",
"chars": 2756,
"preview": "using System;\nusing System.Dynamic;\nusing System.Data;\nusing System.Data.Common;\n\nnamespace Westwind.Utilities.Data\n{\n\n"
},
{
"path": "Westwind.Utilities.Data/DynamicDataRow.cs",
"chars": 2202,
"preview": "using System;\nusing System.Dynamic;\nusing System.Data;\n\nnamespace Westwind.Utilities.Data\n{\n /// <summary>\n /// T"
},
{
"path": "Westwind.Utilities.Data/LICENSE.MD",
"chars": 1179,
"preview": "West Wind Utilities Data Support Library\n========================================\n\n\nMIT License\n-----------\n\nCopyright ("
},
{
"path": "Westwind.Utilities.Data/Security/UserTokenManager.cs",
"chars": 15504,
"preview": "using System;\nusing Westwind.Utilities.Properties;\n\nnamespace Westwind.Utilities.Data.Security\n{\n\n /// <summary>\n "
},
{
"path": "Westwind.Utilities.Data/SqlDataAccess.cs",
"chars": 3983,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities.Data/SqlUtils.cs",
"chars": 7805,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Configuration;\nusing System.Data;\nusing System.Data.Common"
},
{
"path": "Westwind.Utilities.Data/Westwind.Utilities.Data.csproj",
"chars": 3536,
"preview": "<Project Sdk=\"Microsoft.NET.Sdk\">\n\t<PropertyGroup>\n\t\t<TargetFrameworks>net10.0;net8.0;net472</TargetFrameworks>\n\t\t<Vers"
},
{
"path": "Westwind.Utilities.Data/publish-nuget.ps1",
"chars": 540,
"preview": "if (test-path ./nupkg) {\n remove-item ./nupkg -Force -Recurse\n} \n\ndotnet build -c Release\n\n$filename = Get-ChildIt"
},
{
"path": "Westwind.Utilities.Test/App.config",
"chars": 1706,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n <configSections>\n <section name=\"LogManager\" requirePermiss"
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/AutoConfigFileConfigurationTests.cs",
"chars": 8992,
"preview": "#if NETFULL\nusing System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.IO;\nusing System.Configurati"
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/AutoConfigFileConfiguration.cs",
"chars": 3224,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nna"
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/CustomConfigFileConfiguration.cs",
"chars": 2591,
"preview": "#if NETFULL\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threadi"
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/DatabaseConfiguration.cs",
"chars": 3074,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusi"
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/JsonFileConfiguration.cs",
"chars": 2282,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusi"
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/LicenseInformation.cs",
"chars": 577,
"preview": "namespace Westwind.Utilities.Configuration.Tests\n{\n /// <summary>\n /// Demonstration class for a complex type\n "
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/StringConfigFileConfiguration.cs",
"chars": 1913,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nna"
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/ConfigurationClasses/XmlFileConfiguration.cs",
"chars": 2346,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusi"
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/CustomConfigFileConfigurationTests.cs",
"chars": 7631,
"preview": "#if NETFULL\n\nusing System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.IO;\n\nnamespace Westwind.Uti"
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/DatabaseConfigurationTests.cs",
"chars": 3079,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.IO;\nusing Westwind.Data.Test;\nusing West"
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/JsonFileConfigurationTests.cs",
"chars": 5170,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.IO;\nusing Newtonsoft.Json;\nusing System."
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/StringConfigurationTests.cs",
"chars": 5199,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.IO;\n\nnamespace Westwind.Utilities.Config"
},
{
"path": "Westwind.Utilities.Test/AppConfiguration/XmlFileConfigurationTests.cs",
"chars": 4265,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.IO;\n\nnamespace Westwind.Utilities.Config"
},
{
"path": "Westwind.Utilities.Test/AsyncUtilsTests.cs",
"chars": 5516,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusi"
},
{
"path": "Westwind.Utilities.Test/DataUtilsTests.cs",
"chars": 5212,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.Data;\n\nusing System.Diagnostics;\nusing S"
},
{
"path": "Westwind.Utilities.Test/DynamicDataReaderTests.cs",
"chars": 4355,
"preview": "using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.Test"
},
{
"path": "Westwind.Utilities.Test/DynamicDataRowTests.cs",
"chars": 4293,
"preview": "using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.Test"
},
{
"path": "Westwind.Utilities.Test/EncryptionTests.cs",
"chars": 6522,
"preview": "using System;\nusing System.Linq;\nusing System.Text;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.Se"
},
{
"path": "Westwind.Utilities.Test/ExpandUrlsParserTest.cs",
"chars": 2995,
"preview": "using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.Test"
},
{
"path": "Westwind.Utilities.Test/ExpandoTests.cs",
"chars": 15978,
"preview": "using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.Test"
},
{
"path": "Westwind.Utilities.Test/FileUtilsTests.cs",
"chars": 12504,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.IO;\nusing System.Linq;\n\nnamespace Westwi"
},
{
"path": "Westwind.Utilities.Test/HttpClientTests.cs",
"chars": 2818,
"preview": "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Westwind.Utilities.InternetTools;\n\nusing Micr"
},
{
"path": "Westwind.Utilities.Test/HttpClientUtilsTests.cs",
"chars": 10948,
"preview": "\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing Newtonsoft.Json.Linq;\nusing System;\nusing System.Collections"
},
{
"path": "Westwind.Utilities.Test/HttpUtilsTests.cs",
"chars": 7771,
"preview": "using Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nus"
},
{
"path": "Westwind.Utilities.Test/ImagingTests.cs",
"chars": 3861,
"preview": "#if NETFULL\nusing System;\nusing System.Drawing.Imaging;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System"
},
{
"path": "Westwind.Utilities.Test/Models/Entities/Customer.cs",
"chars": 1004,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\nusing System.Linq;\nusing "
},
{
"path": "Westwind.Utilities.Test/Models/Entities/LineItem.cs",
"chars": 527,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Sy"
},
{
"path": "Westwind.Utilities.Test/Models/Entities/Order.cs",
"chars": 752,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.ComponentModel"
},
{
"path": "Westwind.Utilities.Test/Models/Entities/WebLogEntry.cs",
"chars": 9125,
"preview": "#region License\n/*\n **************************************************************\n * Author: Rick Strahl \n * "
},
{
"path": "Westwind.Utilities.Test/NetworkUtilsTests.cs",
"chars": 2759,
"preview": "using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.Test"
},
{
"path": "Westwind.Utilities.Test/ObjectFactoryTests.cs",
"chars": 3577,
"preview": "using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.Test"
},
{
"path": "Westwind.Utilities.Test/PasswordScrubberTests.cs",
"chars": 4151,
"preview": "using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.Test"
},
{
"path": "Westwind.Utilities.Test/PropertyBagTest.cs",
"chars": 7240,
"preview": "using System;\nusing System.Collections.Generic;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.Xml.Se"
},
{
"path": "Westwind.Utilities.Test/ReflectionUtilsTests.cs",
"chars": 2936,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.Reflection;\n\nnamespace Westwind.Utilitie"
},
{
"path": "Westwind.Utilities.Test/SanitizeHtmlTests.cs",
"chars": 4045,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing Westwind.Utilities;\n\nnamespace Westwind.Utiliti"
},
{
"path": "Westwind.Utilities.Test/ShellUtilsTests.cs",
"chars": 1577,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing Sys"
},
{
"path": "Westwind.Utilities.Test/SmtpClientNativeTests.cs",
"chars": 2174,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n"
},
{
"path": "Westwind.Utilities.Test/SqlDataAccessFoxProTests.cs",
"chars": 4933,
"preview": "// #define TEST_FOXPRO_DATA\n// IMPORTANT: For this to work the host project has to be targeting 32 bit Windows\n\nusing S"
},
{
"path": "Westwind.Utilities.Test/SqlDataAccessMySqlTests.cs",
"chars": 5989,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing Westwind.Utilities.Test;\n\nnamespace Westwind.Ut"
},
{
"path": "Westwind.Utilities.Test/SqlDataAccessSqlLiteTests.cs",
"chars": 5760,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing Westwind.Utilities.Test;\n\nnamespace Westwind.Ut"
},
{
"path": "Westwind.Utilities.Test/SqlDataAccessTests.cs",
"chars": 19179,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n"
},
{
"path": "Westwind.Utilities.Test/StrExtractTest.cs",
"chars": 4453,
"preview": "using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.Test"
},
{
"path": "Westwind.Utilities.Test/StringSerializerTests.cs",
"chars": 7480,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing Newtonsoft.Json;\nusing System.Diagnostics;\nusin"
},
{
"path": "Westwind.Utilities.Test/StringUtilsTests.cs",
"chars": 22125,
"preview": "using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.Test"
},
{
"path": "Westwind.Utilities.Test/SupportClasses/DebugModes.cs",
"chars": 283,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnam"
},
{
"path": "Westwind.Utilities.Test/SupportClasses/JsonNetSerializationUtilsTests.cs",
"chars": 7615,
"preview": "using System;\nusing System.Diagnostics;\nusing System.IO;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing Newt"
},
{
"path": "Westwind.Utilities.Test/SupportClasses/TestHelpers.cs",
"chars": 710,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.IO;\n\nnamespace Westwind.Utilities.Configu"
},
{
"path": "Westwind.Utilities.Test/SupportFiles/_MyJsonConfiguration.json",
"chars": 49,
"preview": "{\n \"MyString\": \"WhatEver!!\",\n \"SomeValue\": 0\n}\n"
},
{
"path": "Westwind.Utilities.Test/TimeUtilsTests.cs",
"chars": 1512,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.IO;\nusing System.Linq;\n\nnamespace Westwi"
},
{
"path": "Westwind.Utilities.Test/UrlEncodingParserTests.cs",
"chars": 5774,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n#if NETFRAMEWORK\nusing System.Web;\n#endif\n\nnamespace "
},
{
"path": "Westwind.Utilities.Test/UserTokenManagerTests.cs",
"chars": 3126,
"preview": "using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.IO;\nusing System.Linq;\nusing Westwind.Ut"
},
{
"path": "Westwind.Utilities.Test/VersionExtensionsTests.cs",
"chars": 2697,
"preview": "using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.Test"
},
{
"path": "Westwind.Utilities.Test/Westwind.Utilities.Test.csproj",
"chars": 2985,
"preview": "<Project Sdk=\"Microsoft.NET.Sdk\">\n\n\t<PropertyGroup>\n\t\t<TargetFrameworks>net10.0;net472</TargetFrameworks>\n\t\t<LangVersio"
},
{
"path": "Westwind.Utilities.Test/Westwind.Utilities.Test.dll.config",
"chars": 888,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <configSections>\n <section name=\"LogManager\" requirePermis"
},
{
"path": "Westwind.Utilities.Test/WindowsUtilsTests.cs",
"chars": 780,
"preview": "\nusing System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing Westwind.Utilities.Windows;\n\nnamespace Westwin"
},
{
"path": "Westwind.Utilities.Test/XmlUtilsTest.cs",
"chars": 3532,
"preview": "using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.Test"
},
{
"path": "Westwind.Utilities.Test/_TestConfigurationSettings.cs",
"chars": 766,
"preview": "\nnamespace Westwind.Utilities.Test\n{\n\tpublic class TestConfigurationSettings\n\t{\n\t\tpublic static string WestwindToolkitC"
},
{
"path": "Westwind.Utilities.Windows/LICENSE.MD",
"chars": 1151,
"preview": "West Wind Utilities Library\n===========================\n\nMIT License\n-----------\nCopyright (c) 2019-2023 West Wind Techn"
},
{
"path": "Westwind.Utilities.Windows/Utilities/ComObject.cs",
"chars": 6346,
"preview": "using System;\nusing System.Dynamic;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Runtime"
},
{
"path": "Westwind.Utilities.Windows/Utilities/HtmlUtils.cs",
"chars": 13764,
"preview": "using System;\nusing System.Runtime.Versioning;\nusing System.Text.RegularExpressions;\nusing System.Web;\n\nnamespace Westw"
},
{
"path": "Westwind.Utilities.Windows/Utilities/WindowsUtils.cs",
"chars": 9803,
"preview": "\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing Microsoft.Win32;\n\nnamespace"
},
{
"path": "Westwind.Utilities.Windows/Westwind.Utilities.Windows.csproj",
"chars": 3407,
"preview": "<Project Sdk=\"Microsoft.NET.Sdk\">\n\t<PropertyGroup>\n\t\t<TargetFrameworks>net10.0;net8.0;net6.0;net472;netstandard2.0</Tar"
},
{
"path": "Westwind.Utilities.Windows/Westwind.Utilities.Windows.sln",
"chars": 1122,
"preview": "Microsoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 17\nVisualStudioVersion = 17.5.2.0\nMi"
},
{
"path": "Westwind.Utilities.Windows/publish-nuget.ps1",
"chars": 540,
"preview": "if (test-path ./nupkg) {\n remove-item ./nupkg -Force -Recurse\n} \n\ndotnet build -c Release\n\n$filename = Get-ChildIt"
},
{
"path": "Westwind.Utilities.sln",
"chars": 3923,
"preview": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 17\nVisualStudioVersion = 17.5.3351"
},
{
"path": "Westwind.Utilities.slnx",
"chars": 504,
"preview": "<Solution>\n <Folder Name=\"/Solution Items/\">\n <File Path=\".gitignore\" />\n <File Path=\"Changelog.md\" />\n <File "
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the RickStrahl/Westwind.Utilities GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 142 files (1.2 MB), approximately 258.8k tokens, and a symbol index with 1235 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.