From: Ankit Jain Date: Mon, 22 Feb 2016 18:26:24 +0000 (-0500) Subject: Merge pull request #2646 from ludovic-henry/fix-processwatch-dispose X-Git-Url: http://wien.tomnetworks.com/gitweb/?a=commitdiff_plain;h=5317fbc0cd0146c84ffab2dc1776ec34cce859c0;hp=fb85e55a98a7df8c59b987f6dbb62f01aa4ec7c4;p=mono.git Merge pull request #2646 from ludovic-henry/fix-processwatch-dispose [Microsoft.Build] Fix XS build error + Fix expected output newline from ProcessWrapper.OutputStreamChanged and ProcessWrapper.ErrorStreamChanged --- diff --git a/README.md b/README.md index 8305cb08b3f..7a7f3639f28 100644 --- a/README.md +++ b/README.md @@ -181,7 +181,7 @@ while `mono-sgen` uses the Simple Generational GC. * `--with-gc=[included, boehm, none]` - Selects the default Boehm garbage collector engine to use. - * *included*: (*slighty modified Boehm GC*) This is the default + * *included*: (*slightly modified Boehm GC*) This is the default value for the Boehm GC, and it's the most feature complete, it will allow Mono to use typed allocations and support the debugger. diff --git a/configure.ac b/configure.ac index bf6208e5dd7..296c43c5431 100644 --- a/configure.ac +++ b/configure.ac @@ -2611,21 +2611,54 @@ if test "x$enable_llvm" = "xyes"; then if test "x$host_win32" = "xno"; then + # Should be something like '2.6' or '2.7svn' + llvm_version=`$LLVM_CONFIG --version` + llvm_api_version=`$LLVM_CONFIG --mono-api-version 2>/dev/null` + AC_MSG_CHECKING(LLVM version) + AC_MSG_RESULT($llvm_version $llvm_api_version) + if echo $llvm_version | grep -q 'mono'; then + if test "x$enable_llvm_version_check" == "xyes"; then + if test "$llvm_version" != "$expected_llvm_version"; then + AC_MSG_ERROR([Expected llvm version $expected_llvm_version, but llvm-config --version returned $llvm_version"]) + fi + fi + else + AC_MSG_ERROR([Compiling with stock LLVM is not supported, please use the Mono LLVM repo at https://github.com/mono/llvm, with the GIT branch which matches this version of mono, i.e. 'mono-2-10' for Mono 2.10.]) + fi + # The output of --cflags seems to include optimizations flags too - LLVM_CFLAGS=`$LLVM_CONFIG --cflags | sed -e 's/-O2//g' | sed -e 's/-O0//g' | sed -e 's/-fomit-frame-pointer//g' | sed -e 's/-fPIC//g'` - LLVM_CXXFLAGS=`$LLVM_CONFIG --cxxflags | sed -e 's/-O2//g' | sed -e 's/-O0//g' | sed -e 's/-fomit-frame-pointer//g' | sed -e 's/-fPIC//g'` + if test $llvm_api_version -gt 100; then + # The --cflags argument includes all kinds of warnings -pendantic etc. + LLVM_CFLAGS="-I$with_llvm/include -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS" + LLVM_CXXFLAGS="-I$with_llvm/include -std=c++11 -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS" + else + LLVM_CFLAGS=`$LLVM_CONFIG --cflags | sed -e 's/-O2//g' | sed -e 's/-O0//g' | sed -e 's/-fomit-frame-pointer//g' | sed -e 's/-fPIC//g'` + LLVM_CXXFLAGS=`$LLVM_CONFIG --cxxflags | sed -e 's/-O2//g' | sed -e 's/-O0//g' | sed -e 's/-fomit-frame-pointer//g' | sed -e 's/-fPIC//g'` + fi # LLVM is compiled with -fno-rtti, so we need this too, since our classes inherit # from LLVM classes. LLVM_CXXFLAGS="$LLVM_CXXFLAGS -fno-rtti -fexceptions" LLVM_LDFLAGS=`$LLVM_CONFIG --ldflags` # This might include empty lines LLVM_SYSTEM_LIBS=`$LLVM_CONFIG --system-libs 2>/dev/null | grep -- -` - if test "x$host" != "x$target"; then + llvm_jit_supported=yes + if test $llvm_api_version -gt 100; then + # Based on llvm 3.9, only aot is currently supported + llvm_jit_supported=no + elif test "x$host" != "x$target"; then + # No need for jit libs + llvm_jit_supported=no + fi + if test $llvm_jit_supported = no; then # No need for jit libs LLVM_LIBS=`$LLVM_CONFIG --libs analysis core bitwriter` else LLVM_LIBS=`$LLVM_CONFIG --libs analysis core bitwriter jit mcjit $llvm_codegen` fi + if test "x$LLVM_LIBS" == "x"; then + echo "$LLVM_CONFIG --libs failed." + exit 1 + fi LLVM_LIBS="$LLVM_LIBS $LLVM_LDFLAGS $LLVM_SYSTEM_LIBS" # The c++ standard library used by llvm doesn't show up in $LLVM_SYSTEM_LIBS so add it manually if echo $LLVM_CXXFLAGS | grep -q -- '-stdlib=libc++'; then @@ -2636,21 +2669,6 @@ if test "x$enable_llvm" = "xyes"; then expected_llvm_version="3.4svn-mono-mono/e656cac" - # Should be something like '2.6' or '2.7svn' - llvm_version=`$LLVM_CONFIG --version` - llvm_api_version=`$LLVM_CONFIG --mono-api-version 2>/dev/null` - AC_MSG_CHECKING(LLVM version) - AC_MSG_RESULT($llvm_version) - if echo $llvm_version | grep -q 'mono'; then - if test "x$enable_llvm_version_check" == "xyes"; then - if test "$llvm_version" != "$expected_llvm_version"; then - AC_MSG_ERROR([Expected llvm version $expected_llvm_version, but llvm-config --version returned $llvm_version"]) - fi - fi - else - AC_MSG_ERROR([Compiling with stock LLVM is not supported, please use the Mono LLVM repo at https://github.com/mono/llvm, with the GIT branch which matches this version of mono, i.e. 'mono-2-10' for Mono 2.10.]) - fi - else LLVM_CFLAGS="-I$with_llvm/include -DNDEBUG -D__NO_CTYPE_INLINE -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS" LLVM_CXXFLAGS="$LLVM_CFLAGS -std=gnu++11 -fvisibility-inlines-hidden -fno-rtti -Woverloaded-virtual -Wcast-qual" @@ -3020,6 +3038,7 @@ if test "x$host" != "x$target"; then arch_target=amd64; AC_DEFINE(TARGET_AMD64, 1, [...]) AC_DEFINE(TARGET_PS4, 1, [...]) + AC_DEFINE(DISABLE_HW_TRAPS, 1, [...]) CPPFLAGS="$CPPFLAGS" # Can't use tls, since it depends on the runtime detection of tls offsets # in mono-compiler.h diff --git a/external/referencesource b/external/referencesource index bf43bae316e..423e8998d55 160000 --- a/external/referencesource +++ b/external/referencesource @@ -1 +1 @@ -Subproject commit bf43bae316ec6216e79beb95b2ba25137d91908d +Subproject commit 423e8998d55f168e2aa5da2c0e00ec6dd1356cbf diff --git a/mcs/class/Mainsoft.Web/.gitattributes b/mcs/class/Mainsoft.Web/.gitattributes deleted file mode 100644 index 6c272b92163..00000000000 --- a/mcs/class/Mainsoft.Web/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -/makefile.build -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/.gitattributes b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/.gitattributes deleted file mode 100644 index 96015fec33e..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/.gitattributes +++ /dev/null @@ -1,3 +0,0 @@ -/Web.config -crlf -/Web.config.bak -crlf -/makefile.build -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_GlobalResources/.gitattributes b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_GlobalResources/.gitattributes deleted file mode 100644 index 0642a18bef4..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_GlobalResources/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -/GlobalResource.resx -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_GlobalResources/GlobalResource.resx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_GlobalResources/GlobalResource.resx deleted file mode 100644 index 000b0f9eff5..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_GlobalResources/GlobalResource.resx +++ /dev/null @@ -1,127 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Wildcard characters * and ? are permitted. - - - Welcome to the Web Site Administration Tool - - - \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/.gitattributes b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/.gitattributes deleted file mode 100644 index 506c9f54773..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/.gitattributes +++ /dev/null @@ -1,7 +0,0 @@ -/CreateRole.aspx.resx -crlf -/CreateUser.aspx.resx -crlf -/Default.aspx.resx -crlf -/EditUser.aspx.resx -crlf -/ManageRole.aspx.resx -crlf -/ManageUser.aspx.resx -crlf -/Util.Master.resx -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/CreateRole.aspx.resx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/CreateRole.aspx.resx deleted file mode 100644 index 3f10064a291..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/CreateRole.aspx.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - You can optionally add roles, or groups, that enable you to allow or deny groups of users access to specific folders in your Web site. For example, you might create roles such as "managers," "sales," or "members," each with different access to specific folders. - - - Create New Role - - - New role name: - - \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/CreateUser.aspx.resx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/CreateUser.aspx.resx deleted file mode 100644 index 7a8893a3b59..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/CreateUser.aspx.resx +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Active User - - - Add a user by entering a user name, password, and e-mail address on this page. - - \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/Default.aspx.resx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/Default.aspx.resx deleted file mode 100644 index a3a3199d596..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/Default.aspx.resx +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - You can use the Web Site Administration Tool to manage all the security settings for your application. You can set up users and passwords (authentication), create roles (groups of users), and create permissions (rules for controlling access to parts of your application). - - \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/EditUser.aspx.resx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/EditUser.aspx.resx deleted file mode 100644 index a33d331d425..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/EditUser.aspx.resx +++ /dev/null @@ -1,135 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Use this page to edit user information and to specify what roles a user belongs in. - - - Roles - - - You have successfully updated the user - - - You have successfully updated the user - - - User - - \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/ManageRole.aspx.resx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/ManageRole.aspx.resx deleted file mode 100644 index 1975602b4ac..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/ManageRole.aspx.resx +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Use this page to manage the members in the specified role. To add a user to the role, search for the user name and then select the User Is In Role check box for that user. - - - Role: - - - Search by : - - - Search for Users - - \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/ManageUser.aspx.resx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/ManageUser.aspx.resx deleted file mode 100644 index 9be80540a66..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/ManageUser.aspx.resx +++ /dev/null @@ -1,133 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Click Edit User to view or change the user's password or other properties. To assign roles to the selected user, select the appropriate check boxes on the right. To prevent users from logging in to your application while retaining their information in your database, set the status to inactive by clearing the check box. - - - - Roles - - - Search by : - - - Search for Users - - \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/Util.Master.resx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/Util.Master.resx deleted file mode 100644 index 5ea0895e324..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/App_LocalResources/Util.Master.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/.gitattributes b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/.gitattributes deleted file mode 100644 index 602d59b9180..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/.gitattributes +++ /dev/null @@ -1,5 +0,0 @@ -/Searcher.ascx -crlf -/Searcher.ascx.cs -crlf -/Searcher.ascx.cs.bak -crlf -/Searcher.ascx.designer.cs -crlf -/Searcher.ascx.designer.cs.bak -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx deleted file mode 100644 index 68daecefeca..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx +++ /dev/null @@ -1,34 +0,0 @@ -<%@ Control Language="C#" AutoEventWireup="true" EnableTheming="false" CodeBehind="Searcher.ascx.cs" Inherits="Mainsoft.Web.AspnetConfig.Searcher" %> -<%@ Register tagprefix="custom" namespace="Mainsoft.Web.AspnetConfig" Assembly="Mainsoft.Web.AspnetConfig" %> - - - - - - - - -
- Edit roles: -
- - - - - - - - - Edit roles for user : <%# User %> - - - - - - - - - -
\ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx.cs deleted file mode 100644 index 8d846ca7dd6..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Data; -using System.Configuration; -using System.Collections; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; - -namespace Mainsoft.Web.AspnetConfig -{ - public partial class Searcher : System.Web.UI.UserControl - { - public string User - { - get { return ViewState["User"] == null ? String.Empty : (string)ViewState["User"];} - set { ViewState["User"] = value; } - } - - protected void Page_Load(object sender, EventArgs e) - { - - } - - protected override void OnPreRender(EventArgs e) - { - if (User == String.Empty || (Membership.GetUser(User)==null)) - { - GridView1.DataSource = null; - } - else - { - GridView1.DataSource = RolesDS.SelectUsersRole(User); - } - GridView1.DataBind(); - base.OnPreRender(e); - } - - protected void Roles_Changed(object sender, EventArgs e) - { - String user_name = (string)ViewState["User"]; - if (((CheckBox)sender).Checked) - { - try { - Roles.AddUserToRole (user_name, ((CheckBox) sender).Text); - } - catch { - } - } - else - { - try { - Roles.RemoveUserFromRole (user_name, ((CheckBox) sender).Text); - } - catch { - } - } - } - } -} \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx.cs.bak b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx.cs.bak deleted file mode 100644 index 790c81da1bd..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx.cs.bak +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Data; -using System.Configuration; -using System.Collections; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; - -namespace Mainsoft.Web.Administration -{ - public partial class Searcher : System.Web.UI.UserControl - { - public string User - { - get { return ViewState["User"] == null ? String.Empty : (string)ViewState["User"];} - set { ViewState["User"] = value; } - } - - protected void Page_Load(object sender, EventArgs e) - { - - } - - protected override void OnPreRender(EventArgs e) - { - if (User == String.Empty || (Membership.GetUser(User)==null)) - { - GridView1.DataSource = null; - } - else - { - GridView1.DataSource = RolesDS.SelectUsersRole(User); - } - GridView1.DataBind(); - base.OnPreRender(e); - } - - protected void Roles_Changed(object sender, EventArgs e) - { - String user_name = (string)ViewState["User"]; - if (((CheckBox)sender).Checked) - { - try { - Roles.AddUserToRole (user_name, ((CheckBox) sender).Text); - } - catch { - } - } - else - { - try { - Roles.RemoveUserFromRole (user_name, ((CheckBox) sender).Text); - } - catch { - } - } - } - } -} \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx.designer.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx.designer.cs deleted file mode 100644 index 616d5c21310..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx.designer.cs +++ /dev/null @@ -1,16 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Mainsoft.Web.AspnetConfig { - - public partial class Searcher { - protected System.Web.UI.WebControls.GridView GridView1; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx.designer.cs.bak b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx.designer.cs.bak deleted file mode 100644 index a011c3edc8f..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Controls/Searcher.ascx.designer.cs.bak +++ /dev/null @@ -1,16 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Mainsoft.Web.Administration { - - public partial class Searcher { - protected System.Web.UI.WebControls.GridView GridView1; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Mainsoft.Web.AspnetConfig.csproj b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Mainsoft.Web.AspnetConfig.csproj deleted file mode 100644 index 063df5287b4..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Mainsoft.Web.AspnetConfig.csproj +++ /dev/null @@ -1,202 +0,0 @@ - - - Debug_Java - AnyCPU - 8.0.50727 - 2.0 - {724CABEB-39E5-47A7-9F72-4B81FFC56760} - {F6B19D50-1E2E-4e87-ADFB-10393B439DE0};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - Mainsoft.Web.AspnetConfig - 1.6.0 - 3 - runtime - 2.0 - Mainsoft.Web.AspnetConfig - ipa - tomcat - true - true - - - true - full - false - bin\ - TRACE;DEBUG;JAVA;TARGET_JVM - prompt - 4 - 285212672 - True - False - 0 - - - True - 1 - 1 - True - - - pdbonly - true - bin\ - TRACE;JAVA;TARGET_JVM - prompt - 4 - 285212672 - True - False - 0 - - - true - 1 - 1 - True - - - - - - - - - True - True - 2274 - / - - - False - - - - - - - - - - - - - - - - - - False - ..\..\lib\J2SE.Helpers.dll - - - - - CreateRole.aspx - ASPXCodeBehind - - - CreateRole.aspx - - - CreateUser.aspx - ASPXCodeBehind - - - CreateUser.aspx - - - Default.aspx - ASPXCodeBehind - - - Default.aspx - - - EditUser.aspx - ASPXCodeBehind - - - EditUser.aspx - - - Error.aspx - ASPXCodeBehind - - - Error.aspx - - - - - - ManageRole.aspx - ASPXCodeBehind - - - ManageRole.aspx - - - ManageUser.aspx - ASPXCodeBehind - - - ManageUser.aspx - - - - SecurError.aspx - ASPXCodeBehind - - - SecurError.aspx - - - - - Util.Master - ASPXCodeBehind - - - Util.Master - - - Searcher.ascx - ASPXCodeBehind - - - Searcher.ascx - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Properties/.gitattributes b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Properties/.gitattributes deleted file mode 100644 index 40887b8c7e5..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Properties/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -/AssemblyInfo.cs -crlf -/AssemblyInfo.cs.bak -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Properties/AssemblyInfo.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Properties/AssemblyInfo.cs deleted file mode 100644 index 7c3742f15ed..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Web.UI; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Mainsoft.Web.AspnetConfig")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Mainsoft.Web.AspnetConfig")] -[assembly: AssemblyCopyright("Copyright © 2006")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("3d5900ae-111a-45be-96b3-d9e4606ca793")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: WebResource ("Mainsoft.Web.AspnetConfig.resources.mainsoft.jpg", "image/jpeg")] -[assembly: WebResource ("Mainsoft.Web.AspnetConfig.resources.untitled.bmp", "image/jpeg")] -[assembly: WebResource ("Mainsoft.Web.AspnetConfig.aspnetconfig.Mainsoft.Web.AspnetConfig.css", "text/css")] - - - - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Properties/AssemblyInfo.cs.bak b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Properties/AssemblyInfo.cs.bak deleted file mode 100644 index 5e2c3bb5b0b..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Properties/AssemblyInfo.cs.bak +++ /dev/null @@ -1,43 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Web.UI; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Mainsoft.Web.Administration")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Mainsoft.Web.Administration")] -[assembly: AssemblyCopyright("Copyright © 2006")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("3d5900ae-111a-45be-96b3-d9e4606ca793")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: WebResource ("Mainsoft.Web.Administration.resources.mainsoft.jpg", "image/jpeg")] -[assembly: WebResource ("Mainsoft.Web.Administration.resources.untitled.bmp", "image/jpeg")] -[assembly: WebResource ("Mainsoft.Web.Administration.aspnetconfig.Mainsoft.Web.Administration.css", "text/css")] - - - - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/WEB-INF/.gitattributes b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/WEB-INF/.gitattributes deleted file mode 100644 index 54790099f9e..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/WEB-INF/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -/faces-config.xml -crlf -/web.xml -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/WEB-INF/faces-config.xml b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/WEB-INF/faces-config.xml deleted file mode 100755 index 7c89d00b9bc..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/WEB-INF/faces-config.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - Mainsoft.Web.Hosting.ServletFacesStateManager - Mainsoft.Web.Hosting.ServletFacesViewHandler - - - \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/WEB-INF/web.xml b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/WEB-INF/web.xml deleted file mode 100644 index 73c9a92f8c8..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/WEB-INF/web.xml +++ /dev/null @@ -1,134 +0,0 @@ - - - - Visual MainWin application - Visual MainWin application. - - EnableSessionPersistency - False - - - WebFileSystemAccess - Virtual - - - javax.faces.STATE_SAVING_METHOD - client - - - javax.faces.application.CONFIG_FILES - /WEB-INF/faces-config.xml - - - javax.faces.DEFAULT_SUFFIX - .aspx - - - org.apache.myfaces.webapp.StartupServletContextListener - - - system.Web.GH.SessionListener - - - VmwIncludeHelperServlet - system.Web.GH.IncludeHelperServlet - - - VmwDynamicServlet - GhDynamicHttpServlet - - - VmwStaticServlet - GhStaticHttpServlet - - - VmwDynamicServlet - *.aspx - - - VmwDynamicServlet - *.asmx - - - VmwDynamicServlet - *.ashx - - - VmwDynamicServlet - *.invoke - - - VmwDynamicServlet - *.soap - - - VmwDynamicServlet - *.rem - - - VmwDynamicServlet - *.axd - - - VmwIncludeHelperServlet - /servletincludehelper - - - VmwStaticServlet - *.gif - - - VmwStaticServlet - *.jpeg - - - VmwStaticServlet - *.jpg - - - VmwStaticServlet - *.png - - - VmwStaticServlet - *.html - - - VmwStaticServlet - *.htm - - - VmwStaticServlet - *.bmp - - - VmwStaticServlet - *.css - - - VmwStaticServlet - *.js - - - VmwStaticServlet - *.vbs - - - VmwStaticServlet - *.inc - - - VmwStaticServlet - *.swf - - - VmwStaticServlet - *.htc - - - 20 - - - Default.aspx - - \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Web.config b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Web.config deleted file mode 100644 index aaa267b992e..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Web.config +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Web.config.bak b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Web.config.bak deleted file mode 100644 index bd9b8f57a4e..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/Web.config.bak +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/.gitattributes b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/.gitattributes deleted file mode 100644 index 130d95bd912..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/.gitattributes +++ /dev/null @@ -1,32 +0,0 @@ -/CreateRole.aspx -crlf -/CreateRole.aspx.cs -crlf -/CreateRole.aspx.designer.cs -crlf -/CreateUser.aspx -crlf -/CreateUser.aspx.cs -crlf -/CreateUser.aspx.designer.cs -crlf -/Default.aspx -crlf -/Default.aspx.cs -crlf -/Default.aspx.designer.cs -crlf -/EditUser.aspx -crlf -/EditUser.aspx.cs -crlf -/EditUser.aspx.designer.cs -crlf -/Error.aspx -crlf -/Error.aspx.cs -crlf -/Error.aspx.designer.cs -crlf -/GridButton.cs -crlf -/GridCheckBox.cs -crlf -/Mainsoft.Web.AspnetConfig.css -crlf -/ManageRole.aspx -crlf -/ManageRole.aspx.cs -crlf -/ManageRole.aspx.designer.cs -crlf -/ManageUser.aspx -crlf -/ManageUser.aspx.cs -crlf -/ManageUser.aspx.designer.cs -crlf -/RolesDS.cs -crlf -/SecurError.aspx -crlf -/SecurError.aspx.cs -crlf -/SecurError.aspx.designer.cs -crlf -/StrUtils.cs -crlf -/Util.Master -crlf -/Util.Master.cs -crlf -/Util.Master.designer.cs -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateRole.aspx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateRole.aspx deleted file mode 100644 index 85905e9ca53..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateRole.aspx +++ /dev/null @@ -1,125 +0,0 @@ -<%-- -// Mainsoft.Web.AspnetConfig - Site administration utility -// Authors: -// Klain Yoni -// -// Mainsoft.Web.AspnetConfig - Site administration utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. --%> -<%@ Page Language="C#" AutoEventWireup="true" EnableTheming="false" MasterPageFile="~/aspnetconfig/Util.Master" CodeBehind="CreateRole.aspx.cs" Inherits="Mainsoft.Web.AspnetConfig.CreateRole" %> -<%@ Register TagPrefix="custom" Assembly="Mainsoft.Web.AspnetConfig" Namespace="Mainsoft.Web.AspnetConfig" %> - -Home - >> -Create\Manage roles - - - - - - - - - - - - - - - -
- You can optionally add roles, or groups, that enable you to allow or deny groups of users access to specific folders in your Web site. For example, you might create roles such as "managers," "sales," or "members," each with different access to specific folders.

-
- - - - - - - - - - -
- Create New Role -
- New role name:     -     - -
- -

-
-
- - - - - - - - - - - - - - Delete - - - - - - - - - - - - - - - -
-
- - - - - - - - -
-
-   - Are you sure you want to delete the role: "<%= Role %>"? -
-
- - -
-
-
-
- \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateRole.aspx.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateRole.aspx.cs deleted file mode 100644 index 46c484296a0..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateRole.aspx.cs +++ /dev/null @@ -1,107 +0,0 @@ -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. - -using System; -using System.Data; -using System.Configuration; -using System.Collections; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; -using System.Threading; -using System.Text; - -namespace Mainsoft.Web.AspnetConfig -{ - public partial class CreateRole : System.Web.UI.Page - { - public string Role - { - get { return ViewState["Role"] == null ? String.Empty : (string) ViewState["Role"]; } - set { ViewState["Role"] = value; } - } - - - protected override void OnPreRender (EventArgs e) - { - if (mv.ActiveViewIndex == 1) { - ((Button) Master.FindControl ("Back")).Visible = false; - } - else { - ((Button) Master.FindControl ("Back")).Visible = true; - } - - base.OnPreRender (e); - Roles_gv.DataBind (); - } - - protected override void OnInit (EventArgs e) - { - Img.ImageUrl = this.Page.ClientScript.GetWebResourceUrl (typeof (CreateRole), "Mainsoft.Web.AspnetConfig.resources.untitled.bmp"); - base.OnInit (e); - } - - protected void Page_Load (object sender, EventArgs e) - { - Button bt = Master.FindControl ("Back") as Button; - if (bt != null) { - bt.PostBackUrl = "Default.aspx"; - } - } - - protected void gridbtn_click (object sender, EventArgs e) - { - Role = ((GridButton) sender).User; - mv.ActiveViewIndex = 1; - } - - protected void roleName_bt_Click (object sender, EventArgs e) - { - if (roleName_txb.Text != "") { - try { - Roles.CreateRole (roleName_txb.Text); - error_lb.Text = ""; - } - catch (Exception ex) { - error_lb.Text = ex.Message; - } - finally { - } - } - else { - error_lb.Text = "Role name cannot be empty!"; - } - } - - protected void Click_No (object sender, EventArgs e) - { - mv.ActiveViewIndex = 0; - } - - protected void Click_Yes (object sender, EventArgs e) - { - RolesDS.Delete (Role); - mv.ActiveViewIndex = 0; - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateRole.aspx.designer.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateRole.aspx.designer.cs deleted file mode 100644 index 059f968f98c..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateRole.aspx.designer.cs +++ /dev/null @@ -1,26 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Mainsoft.Web.AspnetConfig { - - public partial class CreateRole { - protected System.Web.UI.WebControls.MultiView mv; - protected System.Web.UI.WebControls.View grid; - protected System.Web.UI.WebControls.TextBox roleName_txb; - protected System.Web.UI.WebControls.Button roleName_bt; - protected System.Web.UI.WebControls.Label error_lb; - protected System.Web.UI.WebControls.GridView Roles_gv; - protected System.Web.UI.WebControls.ObjectDataSource ObjectDataSource1; - protected System.Web.UI.WebControls.View yesno; - protected System.Web.UI.WebControls.Image Img; - protected System.Web.UI.WebControls.Button yes; - protected System.Web.UI.WebControls.Button no; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateUser.aspx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateUser.aspx deleted file mode 100644 index c31608e5808..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateUser.aspx +++ /dev/null @@ -1,195 +0,0 @@ -<%-- -// Mainsoft.Web.AspnetConfig - Site administration utility -// Authors: -// Klain Yoni -// -// Mainsoft.Web.AspnetConfig - Site administration utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. --%> -<%@ Page Language="C#" AutoEventWireup="true" EnableTheming="false" MasterPageFile="~/aspnetconfig/Util.Master" CodeBehind="CreateUser.aspx.cs" Inherits="Mainsoft.Web.AspnetConfig.CreateUser" %> - -Home - >> -Create user - - - - - - - - - - - - - -
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- Sign Up for Your New Account
- User Name: - - * -
- Password: - - * -
- Confirm Password: - - * -
- E-mail: - - * -
- Security Question: - - * -
- Security Answer: - - * -
- -
- -
- -
-
-
- - - - - - - - - - - - -
- Create User
-          -
-                        -    Complete.
-      Your account has been successfully created.
- -
-
-
-
- - - - - - - - -
-
- - - - - - - -
- Roles -
-   -
-
- Active User - -
-
diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateUser.aspx.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateUser.aspx.cs deleted file mode 100644 index b6a51d08bc2..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateUser.aspx.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. - -using System; -using System.Data; -using System.Configuration; -using System.Collections; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; - -namespace Mainsoft.Web.AspnetConfig -{ - public partial class CreateUser : System.Web.UI.Page - { - protected override void OnPreRender (EventArgs e) - { - roles_lst.DataBind (); - base.OnPreRender (e); - if (CreateUserWizard1.ActiveStepIndex != 0) { - text_lbl.Visible = false; - ((Button) Master.FindControl ("Back")).Visible = false; - active_chb.Enabled = false; - } - } - - protected void Page_Load (object sender, EventArgs e) - { - if (!IsPostBack) { - roles_lst.DataValueField = "Role"; - roles_lst.DataSource = RolesDS.Select (); - } - CreateUserWizard1.CreatingUser += new LoginCancelEventHandler (CreateUserWizard1_CreatingUser); - CreateUserWizard1.CreatedUser += new EventHandler (CreateUserWizard1_CreatedUser); - Button bt = Master.FindControl ("Back") as Button; - if (bt != null) { - bt.PostBackUrl = "Default.aspx"; - } - } - - public void CreateUserWizard1_CreatedUser (object sender, EventArgs e) - { - MembershipUser user = Membership.GetUser (((CreateUserWizard) sender).UserName); - roles_lst.Enabled = false; - - int i = 0; - while (i < roles_lst.Items.Count) { - if (roles_lst.Items[i].Selected) { - try { - Roles.AddUserToRole (((CreateUserWizard) sender).UserName, roles_lst.Items[i].Text); - } - catch (Exception ex) { - ((CreateUserWizard) sender).UnknownErrorMessage = ex.Message; - } - } - i++; - } - } - - public void CreateUserWizard1_CreatingUser (object sender, LoginCancelEventArgs e) - { - ((CreateUserWizard) sender).DisableCreatedUser = !active_chb.Checked; - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateUser.aspx.designer.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateUser.aspx.designer.cs deleted file mode 100644 index ed805984c6c..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/CreateUser.aspx.designer.cs +++ /dev/null @@ -1,21 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Mainsoft.Web.AspnetConfig { - - public partial class CreateUser { - protected System.Web.UI.WebControls.Label text_lbl; - protected System.Web.UI.WebControls.CreateUserWizard CreateUserWizard1; - protected System.Web.UI.WebControls.CreateUserWizardStep CreateUserWizardStep1; - protected System.Web.UI.WebControls.CompleteWizardStep CompleteWizardStep1; - protected System.Web.UI.WebControls.CheckBoxList roles_lst; - protected System.Web.UI.WebControls.CheckBox active_chb; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Default.aspx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Default.aspx deleted file mode 100644 index 37ef6b2b98a..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Default.aspx +++ /dev/null @@ -1,88 +0,0 @@ -<%-- -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// Authors: -// Klain Yoni -// -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. --%> -<%@ Page Language="C#" AutoEventWireup="true" EnableTheming="false" MasterPageFile="~/aspnetconfig/Util.Master" CodeBehind="Default.aspx.cs" Inherits="Mainsoft.Web.AspnetConfig.Default" %> - -Home - - - - - - - - - - - - -
- You can use the Web Site Administration Tool to manage all the security settings for your application. You can set up users and passwords (authentication), and create roles (groups of users). By default, user information is stored in a Cloudscape database in the Data folder of your Web project. If you want to store user information in a different database, you may configure a different provider in the web.config file. -


-
- - - - - - - - - - - - - -
- Users -
- <%= User_count %> -
- Create user -
- Manage users -
-


-
- - - - - - - - - - -
- Roles -
- <%= Roles_count %> -
- Create or manage roles -
-


-
-
\ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Default.aspx.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Default.aspx.cs deleted file mode 100644 index 4531e7532e1..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Default.aspx.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// Authors: -// Klain Yoni -// -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. - -using System; -using System.Data; -using System.Configuration; -using System.Collections; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; - - -namespace Mainsoft.Web.AspnetConfig -{ - public partial class Default : System.Web.UI.Page - { - private bool IsPortalRoleProvider; - private bool IsPortalMembershipProvider; - protected override void OnInit (EventArgs e) - { - try { - IsPortalRoleProvider = (Roles.Provider).GetType ().ToString () == "Mainsoft.Web.Security.WPGroupsRoleProvider"; - } - catch{ - } - IsPortalMembershipProvider = (Membership.Provider).GetType().ToString () == "Mainsoft.Web.Security.WPMembershipProvider"; - } - - protected void Page_Load (object sender, EventArgs e) - { - Button bt = Master.FindControl ("Back") as Button; - if (bt != null) { - bt.Enabled = false; - } - } - - public string User_count - { - get - { - if (IsPortalMembershipProvider) { - return "You cannot create or manage users when WPMembershipProvider is configured as the default provider."; - } - else { - MembershipUserCollection user_collection = Membership.GetAllUsers (); - return "Created users :" + user_collection.Count.ToString (); - } - } - } - - public string Roles_count - { - get - { - if (IsPortalRoleProvider) { - return @"You cannot create or manage roles when WPGroupsRoleProvider is configured as the default provider."; - } - else if (Roles.Enabled) { - string[] list = Roles.GetAllRoles (); - return "Existing roles :" + list.Length.ToString (); - } - else - return @"In order to create or manage roles, the roleManger key must be enabled. To enable roleManager, please modify your Web.config file as follows:
-   <configuration xmlns=""http://schemas.microsoft.com/.NetConfiguration/v2.0"">
-    <system.web>
-     <roleManager enabled=""true"" />
-    </system.web>
-   </configuration>"; - } - } - - protected void HyperLink1_Load (object sender, EventArgs e) - { - if (!Roles.Enabled || IsPortalRoleProvider) - ((HyperLink) sender).Visible = false; - } - - protected void UsersLinks_Load (object sender, EventArgs e) - { - if (IsPortalMembershipProvider) { - ((HyperLink) sender).Visible = false; - } - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Default.aspx.designer.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Default.aspx.designer.cs deleted file mode 100644 index f1b438b9bec..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Default.aspx.designer.cs +++ /dev/null @@ -1,18 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Mainsoft.Web.AspnetConfig { - - public partial class Default { - protected System.Web.UI.WebControls.HyperLink HyperLink1; - protected System.Web.UI.WebControls.HyperLink HyperLink2; - protected System.Web.UI.WebControls.HyperLink HyperLink3; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/EditUser.aspx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/EditUser.aspx deleted file mode 100644 index adec8b84232..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/EditUser.aspx +++ /dev/null @@ -1,126 +0,0 @@ -<%-- -// Mainsoft.Web.AspnetConfig - Site administration utility -// Authors: -// Klain Yoni -// -// Mainsoft.Web.AspnetConfig - Site administration utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. --%> -<%@ Page Language="C#" AutoEventWireup="true" EnableTheming="false" MasterPageFile="~/aspnetconfig/Util.Master" CodeBehind="EditUser.aspx.cs" Inherits="Mainsoft.Web.AspnetConfig.EditUser" %> -<%@ Register TagPrefix="custom" TagName="searcher" Src="~/Controls/Searcher.ascx" %> - -Home - >> -Manage user - >> -Edit user - - - - -
- - - - - - - - - - - -
- Use this page to edit user information and to specify what roles a user belongs in. -


-
- - - - - - - - - - - - - - - - - - - -
- User -
- User ID: - - - -   -
- * E-mail address: - - - - Active user -
- Description: - - [not set] - - -
-
- -
- (*)Required field

- - -
-
-
- -
- - - - - - - - - - -
- User Management -
- You have successfully updated the user -


-
- -
-
-
-
-
diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/EditUser.aspx.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/EditUser.aspx.cs deleted file mode 100644 index 7c0c39ec9ac..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/EditUser.aspx.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. - -using System; -using System.Data; -using System.Configuration; -using System.Collections; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; - -namespace Mainsoft.Web.AspnetConfig -{ - public partial class EditUser : System.Web.UI.Page - { - String user_name; - protected void Page_Load (object sender, EventArgs e) - { - user_name = Request.QueryString["User"]; - srch.User = user_name; - if (!IsPostBack) { - FillUserData (user_name); - name_lbl.Text = user_name; - } - - Button bt = Master.FindControl ("Back") as Button; - if (bt != null) { - bt.PostBackUrl = "ManageUser.aspx"; - } - } - - protected override void OnPreRender (EventArgs e) - { - if (IsPostBack) { - if (MultiView1.ActiveViewIndex == 1) { - ((Button) Master.FindControl ("Back")).Visible = false; - } - else { - ((Button) Master.FindControl ("Back")).Visible = true; - } - } - base.OnPreRender (e); - } - - void FillUserData (string user_name) - { - MembershipUser user = Membership.GetUser (user_name); - userid_txb.Text = user.UserName; - email_txb.Text = user.Email; - active_chb.Checked = user.IsApproved; - desc_txb.Text = user.Comment; - } - - protected void roles_lst_DataBound (object sender, EventArgs e) - { - foreach (ListItem item in ((CheckBoxList) sender).Items) { - item.Selected = Boolean.Parse (item.Value); - } - } - - protected void save_bt_Click (object sender, EventArgs e) - { - MembershipUser user = Membership.GetUser (user_name); - user.IsApproved = active_chb.Checked; - user.Email = email_txb.Text; - user.Comment = desc_txb.Text; - Membership.UpdateUser (user); - MultiView1.ActiveViewIndex = 1; - } - - protected void success_btn_Click (object sender, EventArgs e) - { - Server.Transfer ("ManageUser.aspx"); - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/EditUser.aspx.designer.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/EditUser.aspx.designer.cs deleted file mode 100644 index 56d3186b6f2..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/EditUser.aspx.designer.cs +++ /dev/null @@ -1,28 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Mainsoft.Web.AspnetConfig { - - public partial class EditUser { - protected System.Web.UI.WebControls.MultiView MultiView1; - protected System.Web.UI.WebControls.View updateUser; - protected System.Web.UI.WebControls.TextBox userid_txb; - protected System.Web.UI.WebControls.TextBox email_txb; - protected System.Web.UI.WebControls.CheckBox active_chb; - protected System.Web.UI.WebControls.TextBox desc_txb; - protected System.Web.UI.WebControls.Button save_bt; - protected Mainsoft.Web.AspnetConfig.Searcher srch; - protected System.Web.UI.WebControls.RequiredFieldValidator required_email_validator; - protected System.Web.UI.WebControls.RegularExpressionValidator RegularExpressionValidator1; - protected System.Web.UI.WebControls.View successupdate; - protected System.Web.UI.WebControls.Label name_lbl; - protected System.Web.UI.WebControls.Button success_btn; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Error.aspx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Error.aspx deleted file mode 100644 index 6861f885d8f..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Error.aspx +++ /dev/null @@ -1,44 +0,0 @@ -<%-- -// Mainsoft.Web.AspnetConfig - Site administration utility -// Authors: -// Klain Yoni -// -// Mainsoft.Web.AspnetConfig - Site administration utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. --%> - -<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Error.aspx.cs" Theme="" StylesheetTheme="" Inherits="Mainsoft.Web.AspnetConfig.Error" %> - - - - - ASP.Net Web Application Administration - - -
-
- Error occured on this request ! Please try again ! -
-
- Administration utility home page -
-
- - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Error.aspx.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Error.aspx.cs deleted file mode 100644 index 26c4c271557..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Error.aspx.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Data; -using System.Configuration; -using System.Collections; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.WebControls.WebParts; -using System.Web.UI.HtmlControls; - -namespace Mainsoft.Web.AspnetConfig -{ - public partial class Error : System.Web.UI.Page - { - protected void Page_Load (object sender, EventArgs e) - { - - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Error.aspx.designer.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Error.aspx.designer.cs deleted file mode 100644 index cb5c3f68bc1..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Error.aspx.designer.cs +++ /dev/null @@ -1,17 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Mainsoft.Web.AspnetConfig { - - public partial class Error { - protected System.Web.UI.HtmlControls.HtmlForm form1; - protected System.Web.UI.WebControls.HyperLink HyperLink1; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/GridButton.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/GridButton.cs deleted file mode 100644 index 9e81ae21073..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/GridButton.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. - -using System; -using System.Data; -using System.Configuration; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; -using System.ComponentModel; - -namespace Mainsoft.Web.AspnetConfig -{ - public class GridButton : LinkButton - { - [Bindable (true)] - public string User - { - get { return ViewState["User"] == null ? String.Empty : (string) ViewState["User"]; } - set { ViewState["User"] = value; } - } - } -} \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/GridCheckBox.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/GridCheckBox.cs deleted file mode 100644 index a4f6592d572..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/GridCheckBox.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// Authors: -// Klain Yoni -// -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// -// 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. - -using System; -using System.Data; -using System.Configuration; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; -using System.ComponentModel; - -namespace Mainsoft.Web.AspnetConfig -{ - public class GridCheckBox : CheckBox - { - [Bindable (true)] - public string User - { - get { return ViewState["User"] == null ? String.Empty : (string) ViewState["User"]; } - set { ViewState["User"] = value; } - } - - [Bindable (true)] - public string Role - { - get { return ViewState["Role"] == null ? String.Empty : (string) ViewState["Role"]; } - set { ViewState["Role"] = value; } - } - - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/HandlerFactoryConfiguration.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/HandlerFactoryConfiguration.cs deleted file mode 100644 index 353393af8e4..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/HandlerFactoryConfiguration.cs +++ /dev/null @@ -1,247 +0,0 @@ -// -// System.Web.Configuration.HandlerFactoryConfiguration.cs -// -// -// Authors: -// Miguel de Icaza (miguel@novell.com) -// Gonzalo Paniagua Javier (gonzalo@novell.com) -// -// (C) 2005 Novell, Inc (http://www.novell.com) -// - -// -// 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. -// - -using System; -using System.Collections; -using System.Web.Util; -using System.Text.RegularExpressions; - -namespace System.Web.Configuration { - - class FileMatchingInfo { - public string MatchExact; - public string MatchExpr; - - // If set, we can fast-path the patch with string.EndsWith (FMI.EndsWith) - public string EndsWith; - public Regex RegExp; - - public FileMatchingInfo (string s) - { - MatchExpr = s; - - if (s[0] == '*' && (s.IndexOf ('*', 1) == -1)) - EndsWith = s.Substring (1); - - if (s.IndexOf ('*') == -1) - MatchExact = "/" + s; - - if (MatchExpr != "*") { - string expr = MatchExpr.Replace(".", "\\.").Replace("?", "\\?").Replace("*", ".*"); - if (expr.Length > 0 && expr [0] =='/') - expr = expr.Substring (1); - - expr += "\\z"; - RegExp = new Regex (expr); - } - } - } - - class HttpHandler { - // If `null', we are the "*" match - public string OriginalVerb; - public string OriginalPath; - - public string [] Verbs; - public FileMatchingInfo [] files; - - // To support lazy loading we keep the name around. - public string TypeName; - Type type; - - object instance; - - public HttpHandler (string verb, string path, string typename, Type t) - { - OriginalVerb = verb; - OriginalPath = path; - - if (verb != "*") - Verbs = verb.Split (','); - string [] paths = path.Split (','); - files = new FileMatchingInfo [paths.Length]; - - int i = 0; - foreach (string s in paths) - files [i++] = new FileMatchingInfo (s); - - this.TypeName = typename; - type = t; - } - - // - // Loads the a type by name and verifies that it implements - // IHttpHandler or IHttpHandlerFactory - // - public static Type LoadType (string type_name) - { - Type t; - - try { - t = Type.GetType (type_name, true); - } catch (Exception e) { - throw new HttpException (String.Format ("Failed to load httpHandler type `{0}'", type_name)); - } - - if (typeof (IHttpHandler).IsAssignableFrom (t) || - typeof (IHttpHandlerFactory).IsAssignableFrom (t)) - return t; - - throw new HttpException (String.Format ("Type {0} does not implement IHttpHandler or IHttpHandlerFactory", type_name)); - } - - public bool PathMatches (string p) - { - int slash = p.LastIndexOf ('/'); - string orig = p; - if (slash != -1) - p = p.Substring (slash); - - for (int j = files.Length; j > 0; ){ - j--; - FileMatchingInfo fm = files [j]; - - if (fm.MatchExact != null) - return fm.MatchExact.Length == p.Length && StrUtils.EndsWith (p, fm.MatchExact); - - if (fm.EndsWith != null) - return StrUtils.EndsWith (p, fm.EndsWith); - - if (fm.MatchExpr == "*") - return true; - - /* convert to regexp */ - return fm.RegExp.IsMatch (orig); - } - return false; - } - - // Loads the handler, possibly delay-loaded. - public object GetHandlerInstance () - { - IHttpHandler ihh = instance as IHttpHandler; - - if (instance == null || (ihh != null && !ihh.IsReusable)){ - if (type == null) - type = LoadType (TypeName); - - instance = Activator.CreateInstance (type); - } - - return instance; - } - } - - class HandlerFactoryConfiguration { - ArrayList handlers; - HandlerFactoryConfiguration parent; - int parent_items; - - public HandlerFactoryConfiguration (HandlerFactoryConfiguration parent) - { - this.parent = parent; - - if (parent != null) { - handlers = new ArrayList (parent.handlers); - parent_items = handlers.Count; - } else { - handlers = new ArrayList (); - } - } - - public void Clear () - { - handlers.Clear (); - } - - public void Add (string verb, string path, string type_name, bool validate) - { - Type type; - - if (validate){ - type = HttpHandler.LoadType (type_name); - if (type == null) - throw new HttpException (String.Format ("Can not load {0}", type_name)); - } else - type = null; - - handlers.Add (new HttpHandler (verb, path, type_name, type)); - } - - public bool Remove (string verb, string path) - { - for (int i = handlers.Count - 1; i >= 0; i--) { - HttpHandler handler = (HttpHandler) handlers [i]; - - if (verb == handler.OriginalVerb && path == handler.OriginalPath){ - handlers.RemoveAt (i); - return true; - } - } - - return false; - } - - public object LocateHandler (string verb, string filepath) - { - int start, end; - int count = handlers.Count; - for (int k = 0; k < 2; k++) { - // First iteration searches for the mapping in the items added to this - // instance. The second one searches through the parent items if any. - start = (k == 0) ? parent_items : 0; - end = (k == 0) ? count : parent_items; - for (int i = start; i < end; i++) { - HttpHandler handler = (HttpHandler) handlers [i]; - - if (handler.Verbs == null){ - if (handler.PathMatches (filepath)) - return handler.GetHandlerInstance (); - continue; - } - - string [] verbs = handler.Verbs; - for (int j = verbs.Length; j > 0; ){ - j--; - if (verbs [j] != verb) - continue; - if (handler.PathMatches (filepath)) - return handler.GetHandlerInstance (); - } - } - } - - return null; - } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/HttpHandlersSectionHandler.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/HttpHandlersSectionHandler.cs deleted file mode 100644 index 0d7aab8069a..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/HttpHandlersSectionHandler.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -// System.Web.Configuration.HttpHandlersSectionHandler -// -// Authors: -// Gonzalo Paniagua Javier (gonzalo@ximian.com) -// -// (C) 2002 Ximian, Inc (http://www.ximian.com) -// - -// -// 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. -// - -using System.Collections; -using System.Configuration; -using System.Xml; -using System.Globalization; -using System; - -namespace Mainsoft.Web.Configuration -{ - - - internal class HandlersUtil - { - private HandlersUtil () - { - } - - static internal string ExtractAttributeValue (string attKey, XmlNode node) - { - return ExtractAttributeValue (attKey, node, false); - } - - static internal string ExtractAttributeValue (string attKey, XmlNode node, bool optional) - { - return ExtractAttributeValue (attKey, node, optional, false); - } - - static internal string ExtractAttributeValue (string attKey, XmlNode node, bool optional, - bool allowEmpty) - { - if (node.Attributes == null) { - if (optional) - return null; - - ThrowException ("Required attribute not found: " + attKey, node); - } - - XmlNode att = node.Attributes.RemoveNamedItem (attKey); - if (att == null) { - if (optional) - return null; - ThrowException ("Required attribute not found: " + attKey, node); - } - - string value = att.Value; - if (!allowEmpty && value == String.Empty) { - string opt = optional ? "Optional" : "Required"; - ThrowException (opt + " attribute is empty: " + attKey, node); - } - - return value; - } - - static internal void ThrowException (string msg, XmlNode node) - { - if (node != null && node.Name != String.Empty) - msg = msg + " (node name: " + node.Name + ") "; - throw new ConfigurationException (msg, node); - } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Mainsoft.Web.AspnetConfig.css b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Mainsoft.Web.AspnetConfig.css deleted file mode 100644 index b211386067b..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Mainsoft.Web.AspnetConfig.css +++ /dev/null @@ -1,72 +0,0 @@ - -.appHeader -{ - background-image: url(Images/mainsoft.jpg); - background-repeat :no-repeat; - height: 139px; - width: 100%; - border-bottom: 1 solid #7daad4; - background-color:White; - width: 100%; - height: 133px; -} - -.controlheader { - text-align: center; - background-color: #5D7B9D; - font-weight:bold; - font-size:0.9em; - color:White; - text-align:center; - height: 25px; -} - -.maintable { - border-right: thin solid; - padding-right: 2px; - border-top: thin solid; - padding-left: 2px; - padding-bottom: 2px; - border-left: thin solid; - padding-top: 2px; - border-bottom: thin solid; - width: 100%; -} - -.innertable -{ - background-color: #f7f6f3; - border-right: #e6e2d8 1px solid; - border-top: #e6e2d8 1px solid; - border-left: #e6e2d8 1px solid; - border-bottom: #e6e2d8 1px solid; -} - -.h1{ - font-size: 25px; - vertical-align: middle; - color: #6699ff; - text-align: center; -} - -.bordredtable -{ - border-right: #6699ff 5px solid; - padding-right: 40px; - border-top: #6699ff 5px solid; - padding-left: 40px; - padding-bottom: 40px; - border-left: #6699ff 5px solid; - padding-top: 40px; - border-bottom: #6699ff 5px solid; - width: 90%; - height: 500px; - margin:5%; -} - - -BODY,TABLE,TR,TD -{ - font-family: Arial; - font-size: 11pt; -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageRole.aspx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageRole.aspx deleted file mode 100644 index 68d6e2dec81..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageRole.aspx +++ /dev/null @@ -1,106 +0,0 @@ -<%-- -// Mainsoft.Web.AspnetConfig - Site administration utility -// Authors: -// Klain Yoni -// -// Mainsoft.Web.AspnetConfig - Site administration utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. --%> -<%@ Page Language="C#" AutoEventWireup="true" EnableTheming="false" MasterPageFile="~/aspnetconfig/Util.Master" CodeBehind="ManageRole.aspx.cs" Inherits="Mainsoft.Web.AspnetConfig.MenageRole" %> -<%@ Register tagprefix="custom" namespace="Mainsoft.Web.AspnetConfig" Assembly="Mainsoft.Web.AspnetConfig" %> - -Home - >> -Create\Manage roles - >> -Manage roles - - - - - - - - - - -
- Use this page to manage the members in the specified role. To add a user to the role, search for the user name and then select the User Is In Role check box for that user. -
- Role: -
-
- - - - - - - - - - -
- Search for Users -
- Search for Users     - - User Name - E-Mail -     -   -
- Wildcard characters * and ? are permitted.

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
\ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageRole.aspx.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageRole.aspx.cs deleted file mode 100644 index c6422861964..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageRole.aspx.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. --> - - -using System; -using System.Data; -using System.Configuration; -using System.Collections; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; - -namespace Mainsoft.Web.AspnetConfig -{ - public partial class MenageRole : System.Web.UI.Page - { - String role; - protected void Page_Load (object sender, EventArgs e) - { - role = Request.QueryString["Role"]; - if (!Roles.RoleExists (role)) { - Server.Transfer ("Error.aspx"); - } - role_lbl.Text = role; - Button bt = Master.FindControl ("Back") as Button; - if (bt != null) { - bt.PostBackUrl = "CreateRole.aspx"; - } - } - - protected override void OnPreRender (EventArgs e) - { - Roles_gv.DataBind (); - base.OnPreRender (e); - } - - public void CheckBox_CheckedChanged (object sender, EventArgs e) - { - string user = ((GridCheckBox) sender).User; - if (((GridCheckBox) sender).Checked) { - try { - Roles.AddUserToRole (user, role); - } - catch { - } - } - else { - try { - Roles.RemoveUserFromRole (user, role); - } - catch { - } - } - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageRole.aspx.designer.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageRole.aspx.designer.cs deleted file mode 100644 index 08527bd71dc..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageRole.aspx.designer.cs +++ /dev/null @@ -1,21 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Mainsoft.Web.AspnetConfig { - - public partial class MenageRole { - protected System.Web.UI.WebControls.Label role_lbl; - protected System.Web.UI.WebControls.DropDownList searchBy_dl; - protected System.Web.UI.WebControls.TextBox user_txt; - protected System.Web.UI.WebControls.Button searchUser_bt; - protected System.Web.UI.WebControls.GridView Roles_gv; - protected System.Web.UI.WebControls.ObjectDataSource ObjectDataSource1; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageUser.aspx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageUser.aspx deleted file mode 100644 index e2a9f675054..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageUser.aspx +++ /dev/null @@ -1,153 +0,0 @@ -<%-- -// Mainsoft.Web.AspnetConfig - Site administration utility -// Authors: -// Klain Yoni -// -// Mainsoft.Web.AspnetConfig - Site administration utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. --%> -<%@ Page Language="C#" AutoEventWireup="true" EnableTheming="false" MasterPageFile="~/aspnetconfig/Util.Master" CodeBehind="ManageUser.aspx.cs" Inherits="Mainsoft.Web.AspnetConfig.ManageUser" %> -<%@ Register tagprefix="custom" namespace="Mainsoft.Web.AspnetConfig" Assembly="Mainsoft.Web.AspnetConfig" %> -<%@ Register TagPrefix="custom" TagName="searcher" Src="~/Controls/Searcher.ascx" %> - - -Home - >> -Manage user - - - - - - - - - - - - - - -
- Click Edit User to view or change the user's password or other properties. To assign roles to the selected user, select the appropriate check boxes on the right. To prevent users from logging in to your application while retaining their information in your database, set the status to inactive by clearing the check box. -


-
- - - - - - - - - - - -
- Search for Users -
- Search by :     - - User Name - E-Mail -     -   -
- Wildcard characters * and ? are permitted.

-
- - - - - - - - - - - - - - - - - - - - Delete User - - - - - Edit roles - - - - - - - - - - - - - - - - - - - - - -
-

-
- Create new user -
-
- - - - - - - - -
-
-   - Are you sure you want to delete the user: "<%= User_name %>"?
- All information for this user will be deleted, including the user name, the user's membership in roles, and any profile property values associated with this user. -


-
- - -
-
-
-
diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageUser.aspx.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageUser.aspx.cs deleted file mode 100644 index 25a070cd1f8..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageUser.aspx.cs +++ /dev/null @@ -1,138 +0,0 @@ -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// Authors: -// Klain Yoni -// -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. - - -using System; -using System.Data; -using System.Configuration; -using System.Collections; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; - -namespace Mainsoft.Web.AspnetConfig -{ - public partial class ManageUser : System.Web.UI.Page - { - public string User_name - { - get { return ViewState["User"] == null ? String.Empty : (string) ViewState["User"]; } - set { ViewState["User"] = value; } - } - - protected void Page_Load (object sender, EventArgs e) - { - Button bt = Master.FindControl ("Back") as Button; - if (bt != null) { - bt.PostBackUrl = "Default.aspx"; - } - } - - protected override void OnInit (EventArgs e) - { - Img.ImageUrl = this.Page.ClientScript.GetWebResourceUrl (typeof (ManageUser), "Mainsoft.Web.AspnetConfig.resources.untitled.bmp"); - base.OnInit (e); - } - - protected override void OnPreRender (EventArgs e) - { - if (IsPostBack) { - Roles_gv.DataBind (); - if (mv.ActiveViewIndex == 1) { - ((Button) Master.FindControl ("Back")).Visible = false; - } - else { - ((Button) Master.FindControl ("Back")).Visible = true; - } - } - base.OnPreRender (e); - } - - public void CheckBox_CheckedChanged (object sender, EventArgs e) - { - string user_name = ((GridCheckBox) sender).User; - MembershipUser user = Membership.GetUser (user_name); - if (((GridCheckBox) sender).Checked) { - user.IsApproved = true; - Membership.UpdateUser (user); - } - else { - user.IsApproved = false; - Membership.UpdateUser (user); - } - } - - protected void gridbtn_click (object sender, EventArgs e) - { - srch.User = ((GridButton) sender).User; - } - - protected void Roles_Changed (object sender, EventArgs e) - { - String user_name = (string) ViewState["User_name"]; - if (((CheckBox) sender).Checked) { - try { - Roles.AddUserToRole (user_name, ((CheckBox) sender).Text); - } - catch { - } - } - else { - try { - Roles.RemoveUserFromRole (user_name, ((CheckBox) sender).Text); - } - catch { - } - } - } - - protected void Click_No (object sender, EventArgs e) - { - mv.ActiveViewIndex = 0; - } - - protected void Click_Yes (object sender, EventArgs e) - { - RolesDS.DeleteUser (User_name); - //Roles_gv.DataBind (); - mv.ActiveViewIndex = 0; - } - - protected void Delete_Click (object sender, EventArgs e) - { - User_name = ((GridButton) sender).User; - mv.ActiveViewIndex = 1; - } - - protected void gridbtn_load (object sender, EventArgs e) - { - if (!Roles.Enabled) { - ((GridButton)sender).Enabled = false; - } - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageUser.aspx.designer.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageUser.aspx.designer.cs deleted file mode 100644 index 33dab35f4b3..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/ManageUser.aspx.designer.cs +++ /dev/null @@ -1,28 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Mainsoft.Web.AspnetConfig { - - public partial class ManageUser { - protected System.Web.UI.WebControls.MultiView mv; - protected System.Web.UI.WebControls.View manage; - protected System.Web.UI.WebControls.DropDownList searchBy_lbx; - protected System.Web.UI.WebControls.TextBox user_txt; - protected System.Web.UI.WebControls.Button searchUser_bt; - protected System.Web.UI.WebControls.GridView Roles_gv; - protected System.Web.UI.WebControls.ObjectDataSource ObjectDataSource1; - protected Mainsoft.Web.AspnetConfig.Searcher srch; - protected System.Web.UI.WebControls.HyperLink HyperLink1; - protected System.Web.UI.WebControls.View quest; - protected System.Web.UI.WebControls.Image Img; - protected System.Web.UI.WebControls.Button yes; - protected System.Web.UI.WebControls.Button no; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/RolesDS.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/RolesDS.cs deleted file mode 100644 index 4b5949a27ef..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/RolesDS.cs +++ /dev/null @@ -1,301 +0,0 @@ -// Mainsoft.Web.AspnetConfig - Site AspnetConfig utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. - - -using System; -using System.Data; -using System.Configuration; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; -using System.Text.RegularExpressions; - -namespace Mainsoft.Web.AspnetConfig -{ - public class RolesDS - { - public static DataTable Select() - { - return CreateDataTable(); - } - - public static DataTable SelectUser() - { - return CreateUserDataTable(); - } - - public static DataTable SelectUser(string searchtag, string searchby) - { - return CreateUserDataTable(searchtag, searchby); - } - - public static DataTable SelectUsersRole(string user) - { - return CreateUsersRoles(user); - } - - public static DataTable CreateUsersRoles(string user) - { - DataTable aTable = new DataTable("A"); - DataColumn dtCol; - DataColumn dtCol1; - DataRow dtRow; - - - // Create User Name column and add to the table - dtCol = new DataColumn(); - dtCol.DataType = Type.GetType("System.String"); - dtCol.ColumnName = "Role"; - dtCol.AutoIncrement = false; - dtCol.ReadOnly = false; - dtCol.Unique = true; - aTable.Columns.Add(dtCol); - - dtCol1 = new DataColumn(); - dtCol1.DataType = Type.GetType("System.Boolean"); - dtCol1.ColumnName = "IsInRole"; - dtCol1.AutoIncrement = false; - dtCol1.ReadOnly = false; - dtCol1.Unique = false; - aTable.Columns.Add(dtCol1); - - if (Roles.Enabled) { - // Create rows to the table - foreach (String role in Roles.GetAllRoles ()) { - dtRow = aTable.NewRow (); - dtRow["Role"] = role; - dtRow["IsInRole"] = Roles.IsUserInRole (user, role); - aTable.Rows.Add (dtRow); - } - } - aTable.PrimaryKey = new DataColumn[] { aTable.Columns["Role"] }; - return aTable; - } - - public static DataTable Delete(string Role) - { - if (Roles.RoleExists(Role)) - { - Roles.DeleteRole(Role,false); - } - return Select(); - } - - public static DataTable DeleteUser(string User) - { - Membership.DeleteUser(User, true); - return SelectUser(); - } - - public static DataTable CreateUserDataTable() - { - DataTable aTable = new DataTable("A"); - DataColumn dtCol; - DataColumn dtCol1; - DataRow dtRow; - - // Create User Name column and add to the table - dtCol = new DataColumn(); - dtCol.DataType = Type.GetType("System.String"); - dtCol.ColumnName = "User"; - dtCol.AutoIncrement = false; - dtCol.ReadOnly = false; - dtCol.Unique = true; - aTable.Columns.Add(dtCol); - - dtCol1 = new DataColumn(); - dtCol1.DataType = Type.GetType("System.Boolean"); - dtCol1.ColumnName = "Active"; - dtCol1.AutoIncrement = false; - dtCol1.ReadOnly = false; - dtCol1.Unique = false; - aTable.Columns.Add(dtCol1); - - // Create rows to the table - foreach (MembershipUser user in Membership.GetAllUsers()) - { - dtRow = aTable.NewRow(); - dtRow["User"] = user.UserName; - dtRow["Active"] = user.IsApproved; - aTable.Rows.Add(dtRow); - } - - aTable.PrimaryKey = new DataColumn[] { aTable.Columns["User"] }; - return aTable; - } - - public static DataTable CreateUserDataTable(string searchtag, string searchby) - { - DataTable aTable = new DataTable("A"); - DataColumn dtCol; - DataColumn dtCol1; - DataRow dtRow; - - dtCol = new DataColumn(); - dtCol.DataType = Type.GetType("System.String"); - dtCol.ColumnName = "User"; - dtCol.AutoIncrement = false; - dtCol.ReadOnly = false; - dtCol.Unique = true; - aTable.Columns.Add(dtCol); - - dtCol1 = new DataColumn(); - dtCol1.DataType = Type.GetType("System.Boolean"); - dtCol1.ColumnName = "Active"; - dtCol1.AutoIncrement = false; - dtCol1.ReadOnly = false; - dtCol1.Unique = false; - aTable.Columns.Add(dtCol1); - - string text = searchtag; - text = text.Replace("*", "%"); - text = text.Replace("?", "_"); - - if (text.Trim() == "\"\"") - text = "%"; - - if (searchby == "Name") - { - foreach (MembershipUser user in Membership.FindUsersByName(text)) - { - dtRow = aTable.NewRow(); - dtRow["User"] = user.UserName; - dtRow["Active"] = user.IsApproved; - aTable.Rows.Add(dtRow); - } - } - else // Mail - { - foreach (MembershipUser user in Membership.FindUsersByEmail(text)) - { - dtRow = aTable.NewRow(); - dtRow["User"] = user.UserName; - dtRow["Active"] = user.IsApproved; - aTable.Rows.Add(dtRow); - } - } - - aTable.PrimaryKey = new DataColumn[] { aTable.Columns["User"] }; - return aTable; - } - - public static DataTable CreateDataTable() - { - DataTable aTable = new DataTable("A"); - DataColumn dtCol; - DataRow dtRow; - - // Create Name column and add to the table - dtCol = new DataColumn(); - dtCol.DataType = Type.GetType("System.String"); - dtCol.ColumnName = "Role"; - dtCol.AutoIncrement = false; - dtCol.Caption = "Role Name"; - dtCol.ReadOnly = false; - dtCol.Unique = false; - aTable.Columns.Add(dtCol); - - if (Roles.Enabled) { - // Create rows to the table - foreach (string str in Roles.GetAllRoles ()) { - dtRow = aTable.NewRow (); - dtRow["Role"] = str; - aTable.Rows.Add (dtRow); - } - } - - aTable.PrimaryKey = new DataColumn[] { aTable.Columns["Role"] }; - return aTable; - } - - public static DataTable CreateManageRoleTable(string role, string searchtag, string searchby) - { - DataTable aTable = new DataTable("A"); - DataColumn dtCol; - DataColumn dtCol1; - DataRow dtRow; - - // Create UserName column and add to the table - dtCol = new DataColumn(); - dtCol.DataType = Type.GetType("System.String"); - dtCol.ColumnName = "User"; - dtCol.AutoIncrement = false; - dtCol.Caption = "User Name"; - dtCol.ReadOnly = false; - dtCol.Unique = true; - aTable.Columns.Add(dtCol); - - // Create User in role bool column and add to the table - dtCol1 = new DataColumn(); - dtCol1.DataType = Type.GetType("System.Boolean"); - dtCol1.ColumnName = "InRole"; - dtCol1.AutoIncrement = false; - dtCol1.Caption = "User Is In Role"; - dtCol1.ReadOnly = false; - dtCol1.Unique = false; - aTable.Columns.Add(dtCol1); - - string text = searchtag; - text = text.Replace("*", "%"); - text = text.Replace("?", "_"); - - if (text.Trim() == "\"\"") - text = "%"; - - if (searchby == "Name") - { - foreach (MembershipUser user in Membership.FindUsersByName(text)) - { - dtRow = aTable.NewRow(); - dtRow["User"] = user.UserName; - if (Roles.Enabled) { - dtRow["InRole"] = Roles.IsUserInRole (user.UserName, role); - } - else { - dtRow["InRole"] = false; - } - aTable.Rows.Add(dtRow); - } - } - else // Mail - { - foreach (MembershipUser user in Membership.FindUsersByEmail(text)) - { - dtRow = aTable.NewRow(); - dtRow["User"] = user.UserName; - if (Roles.Enabled) { - dtRow["InRole"] = Roles.IsUserInRole (user.UserName, role); - } - else { - dtRow["InRole"] = false; - } - aTable.Rows.Add(dtRow); - } - } - aTable.PrimaryKey = new DataColumn[] { aTable.Columns["User"] }; - return aTable; - } - } -} - - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/SecurError.aspx b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/SecurError.aspx deleted file mode 100644 index 04d64d73a85..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/SecurError.aspx +++ /dev/null @@ -1,47 +0,0 @@ -<%-- -// Mainsoft.Web.AspnetConfig - Site administration utility -// Authors: -// Klain Yoni -// -// Mainsoft.Web.AspnetConfig - Site administration utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. --%> -<%@ Page Language="C#" AutoEventWireup="true" Theme="" StylesheetTheme="" CodeBehind="SecurError.aspx.cs" Inherits="Mainsoft.Web.AspnetConfig.SecurError" %> - - - - - ASP.Net Web Application Administration - - -
-
- By default, the Web Site Administration Tool may only be accessed locally. - To enable accessing it from a remote computer, open the Web.config file, add the key
- allowRemoteConfiguration to the appSettings section, and set its value to true:
-
-        < appSettings > 
-              </ add key="allowRemoteConfiguration" value="True" /> 
-        </ appSettings >
-        
-
-
- - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/SecurError.aspx.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/SecurError.aspx.cs deleted file mode 100644 index 8b2a60b3c5c..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/SecurError.aspx.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Data; -using System.Configuration; -using System.Collections; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.WebControls.WebParts; -using System.Web.UI.HtmlControls; - -namespace Mainsoft.Web.AspnetConfig -{ - public partial class SecurError : System.Web.UI.Page - { - protected void Page_Load (object sender, EventArgs e) - { - - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/SecurError.aspx.designer.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/SecurError.aspx.designer.cs deleted file mode 100644 index 8771cea6ba8..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/SecurError.aspx.designer.cs +++ /dev/null @@ -1,16 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Mainsoft.Web.AspnetConfig { - - public partial class SecurError { - protected System.Web.UI.HtmlControls.HtmlForm form1; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/StrUtils.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/StrUtils.cs deleted file mode 100644 index debcf68113d..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/StrUtils.cs +++ /dev/null @@ -1,101 +0,0 @@ -// -// System.Web.Util.StrUtils -// -// Author(s): -// Gonzalo Paniagua Javier (gonzalo@ximian.com) -// -// (C) 2005 Novell, Inc, (http://www.novell.com) -// - -// -// 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. -// - -using System; -using System.Globalization; -using System.Text; - -namespace Mainsoft.Web.Util -{ - internal sealed class StrUtils { - static CultureInfo invariant = CultureInfo.InvariantCulture; - private StrUtils () { } - - public static bool StartsWith (string str1, string str2) - { - return StartsWith (str1, str2, false); - } - - public static bool StartsWith (string str1, string str2, bool ignore_case) - { - int l2 = str2.Length; - if (l2 == 0) - return true; - - int l1 = str1.Length; - if (l2 > l1) - return false; - - return (0 == String.Compare (str1, 0, str2, 0, l2, ignore_case, invariant)); - } - - public static bool EndsWith (string str1, string str2) - { - return EndsWith (str1, str2, false); - } - - public static bool EndsWith (string str1, string str2, bool ignore_case) - { - int l2 = str2.Length; - if (l2 == 0) - return true; - - int l1 = str1.Length; - if (l2 > l1) - return false; - - return (0 == String.Compare (str1, l1 - l2, str2, 0, l2, ignore_case, invariant)); - } - - public static string EscapeQuotesAndBackslashes (string attributeValue) - { - StringBuilder sb = null; - for (int i = 0; i < attributeValue.Length; i++) { - char ch = attributeValue [i]; - if (ch == '\'' || ch == '"' || ch == '\\') { - if (sb == null) { - sb = new StringBuilder (); - sb.Append (attributeValue.Substring (0, i)); - } - sb.Append ('\\'); - sb.Append (ch); - } - else { - if (sb != null) - sb.Append (ch); - } - } - if (sb != null) - return sb.ToString (); - return attributeValue; - } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/UrlUtils.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/UrlUtils.cs deleted file mode 100644 index f8aa0a23ba1..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/UrlUtils.cs +++ /dev/null @@ -1,265 +0,0 @@ -// -// System.Web.UrlUtils.cs -// -// Authors: -// Gonzalo Paniagua (gonzalo@ximian.com) -// Jackson Harper (jackson@ximian.com) -// - -// -// Copyright (C) 2005 Novell, Inc (http://www.novell.com) -// -// 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. -// - -using System.Web.SessionState; -using System.Web; -using System; - -namespace Mainsoft.Web.Util { - - internal class UrlUtils { - - // appRoot + SessionID + vpath - internal static string InsertSessionId (string id, string path) - { - string dir = GetDirectory (path); - if (!dir.EndsWith ("/")) - dir += "/"; - - string appvpath = HttpRuntime.AppDomainAppVirtualPath; - if (!appvpath.EndsWith ("/")) - appvpath += "/"; - - if (path.StartsWith (appvpath)) - path = path.Substring (appvpath.Length); - - if (path [0] == '/') - path = path.Length > 1 ? path.Substring (1) : ""; - - return Canonic (appvpath + "(" + id + ")/" + path); - } -#if false - internal static string GetSessionId (string path) - { - string appvpath = HttpRuntime.AppDomainAppVirtualPath; - if (path.Length <= appvpath.Length) - return null; - - path = path.Substring (appvpath.Length); - if (path.Length == 0 || path [0] != '/') - path = '/' + path; - - int len = path.Length; - if ((len < SessionId.IdLength + 3) || (path [1] != '(') || - (path [SessionId.IdLength + 2] != ')')) - return null; - - return path.Substring (2, SessionId.IdLength); - } -#endif - internal static string RemoveSessionId (string base_path, string file_path) - { - // Caller did a GetSessionId first - int idx = base_path.IndexOf ("/("); - string dir = base_path.Substring (0, idx + 1); - if (!dir.EndsWith ("/")) - dir += "/"; - - idx = base_path.IndexOf (")/"); - if (idx != -1 && base_path.Length > idx + 2) { - string dir2 = base_path.Substring (idx + 2); - if (!dir2.EndsWith ("/")) - dir2 += "/"; - - dir += dir2; - } - - return Canonic (dir + GetFile (file_path)); - } - - public static string Combine (string basePath, string relPath) - { - if (relPath == null) - throw new ArgumentNullException ("relPath"); - - int rlength = relPath.Length; - if (rlength == 0) - return ""; - - relPath = relPath.Replace ("\\", "/"); - if (IsRooted (relPath)) - return Canonic (relPath); - - char first = relPath [0]; - if (rlength < 3 || first == '~' || first == '/' || first == '\\') { - if (basePath == null || (basePath.Length == 1 && basePath [0] == '/')) - basePath = String.Empty; - - string slash = (first == '/') ? "" : "/"; - if (first == '~') { - if (rlength == 1) { - relPath = ""; - } else if (rlength > 1 && relPath [1] == '/') { - relPath = relPath.Substring (2); - slash = "/"; - } - - string appvpath = HttpRuntime.AppDomainAppVirtualPath; - if (appvpath.EndsWith ("/")) - slash = ""; - - return Canonic (appvpath + slash + relPath); - } - - return Canonic (basePath + slash + relPath); - } - - if (basePath == null || basePath == "" || basePath [0] == '~') - basePath = HttpRuntime.AppDomainAppVirtualPath; - - if (basePath.Length <= 1) - basePath = String.Empty; - - return Canonic (basePath + "/" + relPath); - } - - static char [] path_sep = {'\\', '/'}; - - internal static string Canonic (string path) - { - string [] parts = path.Split (path_sep); - int end = parts.Length; - - int dest = 0; - - for (int i = 0; i < end; i++) { - string current = parts [i]; - if (current == "." ) - continue; - - if (current == "..") { - if (dest == 0) { - if (i == 1) // see bug 52599 - continue; - - throw new HttpException ("Invalid path."); - } - - dest --; - continue; - } - - parts [dest++] = current; - } - - if (dest == 0) - return "/"; - - return String.Join ("/", parts, 0, dest); - } - - internal static string GetDirectory (string url) - { - url = url.Replace('\\','/'); - int last = url.LastIndexOf ('/'); - - if (last > 0) { - return RemoveDoubleSlashes (url.Substring (0, last)); - } - - return "/"; - } - - internal static string RemoveDoubleSlashes (string input) - { - // MS VirtualPathUtility removes duplicate '/' - string str = input; - string x; - while ((x = str.Replace ("//", "/")) != str) { - str = x; - } - - return str; - } - - internal static string GetFile (string url) - { - url = url.Replace('\\','/'); - int last = url.LastIndexOf ('/'); - if (last >= 0) { - if (url.Length == 1) // Empty file name instead of ArgumentOutOfRange - return ""; - return url.Substring (last+1); - } - - throw new Exception (String.Format ("GetFile: `{0}' does not contain a /", url)); - } - - internal static bool IsRooted (string path) - { - if (path == null || path == "") - return true; - - char c = path [0]; - if (c == '/' || c == '\\') - return true; - - return false; - } - - internal static bool IsRelativeUrl (string path) - { - return (path [0] != '/' && path.IndexOf (':') == -1); - } - - public static string ResolveVirtualPathFromAppAbsolute (string path) - { - if (path [0] != '~') return path; - - if (path.Length == 1) - return HttpRuntime.AppDomainAppVirtualPath; - - if (path [1] == '/' || path [1] == '\\') { - string appPath = HttpRuntime.AppDomainAppVirtualPath; - if (appPath.Length > 1) - return appPath + "/" + path.Substring (2); - return "/" + path.Substring (2); - } - return path; - } - - public static string ResolvePhysicalPathFromAppAbsolute (string path) - { - if (path [0] != '~') return path; - - if (path.Length == 1) - return HttpRuntime.AppDomainAppPath; - - if (path [1] == '/' || path [1] == '\\') { - string appPath = HttpRuntime.AppDomainAppPath; - if (appPath.Length > 1) - return appPath + "/" + path.Substring (2); - return "/" + path.Substring (2); - } - return path; - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Util.Master b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Util.Master deleted file mode 100644 index baf3a656c7d..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Util.Master +++ /dev/null @@ -1,91 +0,0 @@ -<%-- -// Mainsoft.Web.AspnetConfig - Site administration utility -// Authors: -// Klain Yoni -// -// Mainsoft.Web.AspnetConfig - Site administration utility -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// 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. --%> -<%@ Master Language="C#" AutoEventWireup="true" EnableTheming="false" CodeBehind="Util.master.cs" Inherits="Mainsoft.Web.AspnetConfig.Util" %> -<%@ Register TagPrefix="Custom" Namespace="Mainsoft.Web.AspnetConfig" Assembly="Mainsoft.Web.AspnetConfig" %> - - - - - - " rel="stylesheet" type="text/css" /> - ASP.Net Web Application Administration - - - -
-
- - - - - - - - - - -
-    -
- Web Site Administration Tool -
- - - - - - - - - - -
- - - - - -
Current page :   - - - - -
-
-
- - -
- - <%--style="padding-right: 1px; padding-left: 1px; font-weight: bold; padding-bottom: 1px; margin: 1px; color: yellow; padding-top: 1px; background-color: #6699ff"--%> -
-
-
-
- - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Util.Master.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Util.Master.cs deleted file mode 100644 index cda1f014e12..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Util.Master.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Resources; -using System.Data; -using System.Configuration; -using System.Collections; -using System.Web; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; - -namespace Mainsoft.Web.AspnetConfig -{ - public partial class Util : System.Web.UI.MasterPage - { - bool allowRemoteConfiguration // Default is false - { - get - { - if (System.Configuration.ConfigurationSettings.AppSettings["allowRemoteConfiguration"] != null) { - return bool.Parse (System.Configuration.ConfigurationSettings.AppSettings["allowRemoteConfiguration"]); - } - else { - return false; - } - } - } - - public String Backurl - { - get { return ViewState["BackUrl"] == null ? String.Empty : (string) ViewState["BackUrl"]; } - set { ViewState["BackUrl"] = value; } - } - - protected override void OnInit (EventArgs e) - { - if (!(allowRemoteConfiguration || Request.IsLocal)) { - Server.Transfer ("~/aspnetconfig/SecurError.aspx"); - } - - - base.OnInit (e); - } - - protected void Page_Load (object sender, EventArgs e) - { - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Util.Master.designer.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Util.Master.designer.cs deleted file mode 100644 index 5b695866173..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/aspnetconfig/Util.Master.designer.cs +++ /dev/null @@ -1,20 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.42 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Mainsoft.Web.AspnetConfig { - - public partial class Util { - protected System.Web.UI.HtmlControls.HtmlHead Head1; - protected System.Web.UI.HtmlControls.HtmlForm form1; - protected System.Web.UI.WebControls.ContentPlaceHolder SiteMapLinks; - protected System.Web.UI.WebControls.ContentPlaceHolder Main; - protected System.Web.UI.WebControls.Button Back; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/makefile.build b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/makefile.build deleted file mode 100755 index 8a930c5dacf..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/makefile.build +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/nomd5 b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/nomd5 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/resources/mainsoft.jpg b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/resources/mainsoft.jpg deleted file mode 100644 index 3bf06981cf7..00000000000 Binary files a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/resources/mainsoft.jpg and /dev/null differ diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/resources/untitled.bmp b/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/resources/untitled.bmp deleted file mode 100644 index e92ef9f7fdc..00000000000 Binary files a/mcs/class/Mainsoft.Web/Mainsoft.Web.AspnetConfig/resources/untitled.bmp and /dev/null differ diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/.gitattributes b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/.gitattributes deleted file mode 100644 index 2932b7b4b8a..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/.gitattributes +++ /dev/null @@ -1,18 +0,0 @@ -/AbstractAttributeMap.cs -crlf -/AspNetFacesContext.cs -crlf -/BaseExternalContext.cs -crlf -/BaseFacesPageHandlerFactory.cs -crlf -/BaseFacesStateManager.cs -crlf -/BaseFacesViewHandler.cs -crlf -/IExtendedViewHandler.cs -crlf -/OutputStreamWrapper.cs -crlf -/RequestParameterMap.cs -crlf -/RequestParameterValuesMap.cs -crlf -/ServletFacesContext.cs -crlf -/ServletFacesPageHandler.cs -crlf -/ServletFacesPageHandlerFactory.cs -crlf -/ServletFacesStateManager.cs -crlf -/ServletFacesViewHandler.cs -crlf -/ServletIncludeUtils.cs -crlf -/ServletResourceLoader.cs -crlf -/SessionWrapper.cs -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/AbstractAttributeMap.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/AbstractAttributeMap.cs deleted file mode 100644 index 475b14db796..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/AbstractAttributeMap.cs +++ /dev/null @@ -1,333 +0,0 @@ -// -// Mainsoft.Web.Hosting.AbstractAttributeMap.cs -// -// Authors: -// Konstantin Triger -// -// (C) 2008 Mainsoft Co. (http://www.mainsoft.com) -// - -// -// 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. -// - -using java.util; -using System; - -namespace Mainsoft.Web.Hosting -{ - partial class BaseExternalContext - { - public abstract class AbstractAttributeMap : AbstractMap - { - private Set _keySet; - private Collection _values; - private Set _entrySet; - - public override void clear () { - List names = new ArrayList (); - for (Enumeration e = getAttributeNames (); e.hasMoreElements (); ) { - names.add (e.nextElement ()); - } - - for (Iterator it = names.iterator (); it.hasNext (); ) { - removeAttribute ((String) it.next ()); - } - } - - public override bool containsKey (Object key) { - return getAttribute (key.ToString ()) != null; - } - - public override bool containsValue (Object findValue) { - if (findValue == null) { - return false; - } - - for (Enumeration e = getAttributeNames (); e.hasMoreElements (); ) { - Object value = getAttribute ((String) e.nextElement ()); - if (findValue.Equals (value)) { - return true; - } - } - - return false; - } - - public override Set entrySet () { - return (_entrySet != null) ? _entrySet : (_entrySet = new EntrySet (this)); - } - - public override Object get (Object key) { - return getAttribute (key.ToString ()); - } - - public override bool isEmpty () { - return !getAttributeNames ().hasMoreElements (); - } - - public override Set keySet () { - return (_keySet != null) ? _keySet : (_keySet = new KeySet (this)); - } - - public override Object put (Object key, Object value) { - String key_ = key.ToString (); - Object retval = getAttribute (key_); - setAttribute (key_, value); - return retval; - } - - public override void putAll (Map t) { - for (Iterator it = t.entrySet ().iterator (); it.hasNext (); ) { - Map.Entry entry = (Map.Entry) it.next (); - setAttribute (entry.getKey ().ToString (), entry.getValue ()); - } - } - - public override Object remove (Object key) { - String key_ = key.ToString (); - Object retval = getAttribute (key_); - removeAttribute (key_); - return retval; - } - - public override int size () { - int size = 0; - for (Enumeration e = getAttributeNames (); e.hasMoreElements (); ) { - size++; - e.nextElement (); - } - return size; - } - - public override Collection values () { - return (_values != null) ? _values : (_values = new Values (this)); - } - - - abstract protected Object getAttribute (string key); - - abstract protected void setAttribute (string key, Object value); - - abstract protected void removeAttribute (string key); - - abstract protected Enumeration getAttributeNames (); - - - private class KeySet : AbstractSet - { - protected readonly AbstractAttributeMap _owner; - public KeySet (AbstractAttributeMap owner) { - _owner = owner; - } - - public override Iterator iterator () { - return new KeyIterator (_owner); - } - - public override bool isEmpty () { - return _owner.isEmpty (); - } - - public override int size () { - return _owner.size (); - } - - public override bool contains (Object o) { - return _owner.containsKey (o); - } - - public override bool remove (Object o) { - return _owner.remove (o) != null; - } - - public override void clear () { - _owner.clear (); - } - } - - private class KeyIterator : Iterator - { - protected readonly AbstractAttributeMap _owner; - protected readonly Enumeration _e; - - public KeyIterator (AbstractAttributeMap owner) { - _owner = owner; - _e = _owner.getAttributeNames (); - } - - protected Object _currentKey; - - public virtual void remove () { - // remove() may cause ConcurrentModificationException. - // We could throw an exception here, but not throwing an exception - // allows one call to remove() to succeed - if (_currentKey == null) { - throw new NoSuchElementException ( - "You must call next() at least once"); - } - _owner.remove (_currentKey); - } - - public bool hasNext () { - return _e.hasMoreElements (); - } - - public virtual Object next () { - return _currentKey = _e.nextElement (); - } - } - - private class Values : KeySet - { - - public Values (AbstractAttributeMap owner) - : base (owner) { - } - - public override Iterator iterator () { - return new ValuesIterator (_owner); - } - - public override bool contains (Object o) { - return _owner.containsValue (o); - } - - public override bool remove (Object o) { - if (o == null) { - return false; - } - - for (Iterator it = iterator (); it.hasNext (); ) { - if (o.Equals (it.next ())) { - it.remove (); - return true; - } - } - - return false; - } - } - - private class ValuesIterator : KeyIterator - { - public ValuesIterator (AbstractAttributeMap owner) - : base (owner) { } - public override Object next () { - base.next (); - return _owner.get (_currentKey); - } - } - - private class EntrySet : KeySet - { - public EntrySet (AbstractAttributeMap owner) : base (owner) { } - - public override Iterator iterator () { - return new EntryIterator (_owner); - } - - public override bool contains (Object o) { - if (!(o is Map.Entry)) { - return false; - } - - Map.Entry entry = (Map.Entry) o; - Object key = entry.getKey (); - Object value = entry.getValue (); - if (key == null || value == null) { - return false; - } - - return value.Equals (_owner.get (key)); - } - - public override bool remove (Object o) { - if (!(o is Map.Entry)) { - return false; - } - - Map.Entry entry = (Map.Entry) o; - Object key = entry.getKey (); - Object value = entry.getValue (); - if (key == null || value == null - || !value.Equals (_owner.get (key))) { - return false; - } - - return _owner.remove (((Map.Entry) o).getKey ()) != null; - } - } - - /** - * Not very efficient since it generates a new instance of Entry - * for each element and still internaly uses the KeyIterator. - * It is more efficient to use the KeyIterator directly. - */ - private class EntryIterator : KeyIterator - { - public EntryIterator (AbstractAttributeMap owner) : base (owner) { } - public override Object next () { - base.next (); - // Must create new Entry every time--value of the entry must stay - // linked to the same attribute name - return new EntrySetEntry (_currentKey); - } - } - - private class EntrySetEntry : Map.Entry - { - readonly AbstractAttributeMap _owner; - - public EntrySetEntry (AbstractAttributeMap owner) { - _owner = owner; - } - - private readonly Object _currentKey; - - public EntrySetEntry (Object currentKey) { - _currentKey = currentKey; - } - - public Object getKey () { - return _currentKey; - } - - public Object getValue () { - return _owner.get (_currentKey); - } - - public Object setValue (Object value) { - return _owner.put (_currentKey, value); - } - - public int hashCode () { - return _currentKey == null ? 0 : _currentKey.GetHashCode (); - } - - public bool equals (Object obj) { - if (!(obj is EntrySetEntry)) - return false; - return _currentKey != null && _currentKey.Equals (obj); - } - } - } - } -} \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/AspNetFacesContext.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/AspNetFacesContext.cs deleted file mode 100644 index 5474dd0779a..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/AspNetFacesContext.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using javax.faces.context; -using System.Web; -using System.Web.UI; -using javax.servlet; -using javax.faces.lifecycle; - -namespace Mainsoft.Web.Hosting -{ - public abstract class AspNetFacesContext : FacesContext - { - readonly FacesContext _oldFacesContex; - readonly FacesContext _facesContex; - readonly HttpContext _httpContext; - readonly ExternalContext _externalContext; - - public HttpContext Context { - get { return _httpContext; } - } - - protected AspNetFacesContext (FacesContext wrappedFacesContex, ExternalContext externalContext, HttpContext httpContext, FacesContext oldFacesContex) { - _facesContex = wrappedFacesContex; - _httpContext = httpContext; - _oldFacesContex = oldFacesContex; - _externalContext = externalContext; - setCurrentInstance (this); - } - - public bool IsProcessingInclude () { - if (_oldFacesContex == null) - return false; - - if (getViewRoot ().getChildCount () == 0) - throw new InvalidOperationException (); - - Page page = (Page) getViewRoot ().getChildren ().get (0); - return !page.IsPostBack; - } - - public override void addMessage (string __p1, javax.faces.application.FacesMessage __p2) { - _facesContex.addMessage (__p1, __p2); - } - - public override javax.faces.application.Application getApplication () { - return _facesContex.getApplication (); - } - - public override java.util.Iterator getClientIdsWithMessages () { - return _facesContex.getClientIdsWithMessages (); - } - - public override ExternalContext getExternalContext () { - return _externalContext; - } - - public override javax.faces.application.FacesMessage.Severity getMaximumSeverity () { - return _facesContex.getMaximumSeverity (); - } - - public override java.util.Iterator getMessages (string __p1) { - return _facesContex.getMessages (__p1); - } - - public override java.util.Iterator getMessages () { - return _facesContex.getMessages (); - } - - public override javax.faces.render.RenderKit getRenderKit () { - return _facesContex.getRenderKit (); - } - - public override bool getRenderResponse () { - return _facesContex.getRenderResponse (); - } - - public override bool getResponseComplete () { - return _facesContex.getResponseComplete (); - } - - public override ResponseStream getResponseStream () { - return _facesContex.getResponseStream (); - } - - public override ResponseWriter getResponseWriter () { - return _facesContex.getResponseWriter (); - } - - public override javax.faces.component.UIViewRoot getViewRoot () { - return _facesContex.getViewRoot (); - } - - public override void release () { - _facesContex.release (); - FacesContext.setCurrentInstance (_oldFacesContex); - } - - public override void renderResponse () { - _facesContex.renderResponse (); - } - - public override void responseComplete () { - _facesContex.responseComplete (); - } - - public override void setResponseStream (ResponseStream __p1) { - _facesContex.setResponseStream (__p1); - } - - public override void setResponseWriter (ResponseWriter __p1) { - _facesContex.setResponseWriter (__p1); - } - - public override void setViewRoot (javax.faces.component.UIViewRoot __p1) { - _facesContex.setViewRoot (__p1); - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseExternalContext.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseExternalContext.cs deleted file mode 100644 index 515f011cb95..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseExternalContext.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -// Mainsoft.Web.Hosting.BaseExternalContext.cs -// -// Authors: -// Konstantin Triger -// -// (C) 2008 Mainsoft Co. (http://www.mainsoft.com) -// - -// -// 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. -// - -using System; -using System.Collections.Generic; -using System.Text; -using javax.faces.context; -using System.Web; -using java.util; - -namespace Mainsoft.Web.Hosting -{ - public abstract partial class BaseExternalContext : ExternalContext - { - readonly HttpContext _httpContext; - readonly string _executionFilePath; - - private Map _requestParameterMap; - private Map _requestParameterValuesMap; - - protected BaseExternalContext (HttpContext httpContext, string executionFilePath) { - _httpContext = httpContext; - _executionFilePath = executionFilePath; - } - - protected HttpContext Context { - get { return _httpContext; } - } - - public override Map getRequestParameterMap () { - return _requestParameterMap ?? (_requestParameterMap = new RequestParameterMap (Context.Request.Form)); - } - - public override Iterator getRequestParameterNames () { - return new IEnumeratorIteratorImpl (Context.Request.Form.Keys.GetEnumerator ()); - } - - public override Map getRequestParameterValuesMap () { - return _requestParameterValuesMap ?? (_requestParameterValuesMap = new RequestParameterValuesMap (Context.Request.Form)); - } - - public override string getRequestPathInfo () { - return _executionFilePath.Substring (getRequestContextPath ().Length); - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseFacesPageHandlerFactory.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseFacesPageHandlerFactory.cs deleted file mode 100644 index c26eca76b1d..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseFacesPageHandlerFactory.cs +++ /dev/null @@ -1,46 +0,0 @@ -// -// (C) 2007 Mainsoft Corporation (http://www.mainsoft.com) -// Author: Igor Zelmanovich -// - -// -// 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. -// - -using System; -using System.Collections.Generic; -using System.Text; -using System.Web; -using javax.faces.context; -using javax.faces.lifecycle; -using javax.servlet; -using javax.faces; -using javax.faces.webapp; - -namespace Mainsoft.Web.Hosting -{ - public abstract class BaseFacesPageHandlerFactory : IHttpHandlerFactory - { - public abstract IHttpHandler GetHandler (HttpContext context, string requestType, string url, string pathTranslated); - - public virtual void ReleaseHandler (IHttpHandler handler) { - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseFacesStateManager.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseFacesStateManager.cs deleted file mode 100644 index 09004e34183..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseFacesStateManager.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using javax.faces.application; -using javax.faces.component; -using javax.faces.context; -using System.Diagnostics; -using System.Web.UI; -using javax.faces.render; -using javax.faces; - -namespace Mainsoft.Web.Hosting -{ - public abstract class BaseFacesStateManager : StateManager - { - protected static readonly string VIEWSTATE = "__VIEWSTATE"; - protected static readonly RenderKitFactory RenderKitFactory = (RenderKitFactory) FactoryFinder.getFactory (FactoryFinder.RENDER_KIT_FACTORY); - - public override StateManager.SerializedView saveSerializedView (FacesContext facesContext) { - Object treeStruct = getTreeStructureToSave (facesContext); - Object compStates = getComponentStateToSave (facesContext); - SerializedView serializedView = new SerializedView (this, treeStruct, compStates); - return serializedView; - } - - protected override sealed Object getTreeStructureToSave (FacesContext facesContext) { - return String.Empty; - } - - public override UIViewRoot restoreView (FacesContext facesContext, - String viewId, - String renderKitId) { - - UIViewRoot uiViewRoot = restoreTreeStructure (facesContext, viewId, renderKitId); - Page page = (Page) uiViewRoot.getChildren ().get (0); - if (page.IsPostBack || page.IsCallback) - restoreComponentState (facesContext, uiViewRoot, renderKitId); - else - facesContext.renderResponse (); - return uiViewRoot; - } - - protected override sealed UIViewRoot restoreTreeStructure (FacesContext facesContext, string viewId, string renderKitId) { - return facesContext.getApplication ().getViewHandler ().createView (facesContext, viewId); - } - - protected override Object getComponentStateToSave (FacesContext facesContext) { - Trace.WriteLine ("Entering getComponentStateToSave"); - - UIViewRoot viewRoot = facesContext.getViewRoot (); - if (viewRoot.isTransient ()) { - return null; - } - - Object serializedComponentStates = ((UIComponent) viewRoot.getChildren ().get (0)).processSaveState (facesContext); - //Locale is a state attribute of UIViewRoot and need not be saved explicitly - Trace.WriteLine ("Exiting getComponentStateToSave"); - return serializedComponentStates; - } - - protected void SaveStateInClient (FacesContext facesContext, StateManager.SerializedView serializedView) { - //UIViewRoot uiViewRoot = facesContext.getViewRoot (); - ////save state in response (client-side: full state; server-side: sequence) - //RenderKit renderKit = RenderKitFactory.getRenderKit (facesContext, uiViewRoot.getRenderKitId ()); - //// not us. - //renderKit.getResponseStateManager ().writeState (facesContext, serializedView); - - java.io.ByteArrayOutputStream bytearrayoutputstream = new java.io.ByteArrayOutputStream (); - java.io.ObjectOutputStream objectoutputstream = new java.io.ObjectOutputStream (bytearrayoutputstream); - - //ignore tree structure - //objectoutputstream.writeObject (serializedView.getStructure ()); - objectoutputstream.writeObject (serializedView.getState ()); - objectoutputstream.close (); - bytearrayoutputstream.close (); - - string s = -@"
- -
"; - facesContext.getResponseWriter ().write (s); - } - - protected object GetStateFromClient (FacesContext facesContext, String viewId, String renderKitId) { - //RenderKit renderKit = RenderKitFactory.getRenderKit (facesContext, renderKitId); - //ResponseStateManager responseStateManager = renderKit.getResponseStateManager (); - //responseStateManager.getTreeStructureToRestore (facesContext, viewId); //ignore result. Must call for compatibility with sun implementation. - //return responseStateManager.getComponentStateToRestore (facesContext); - - java.util.Map map = facesContext.getExternalContext ().getRequestParameterMap (); - string s1 = (string) map.get (VIEWSTATE); - - byte [] buffer = Convert.FromBase64String (s1); - java.io.ByteArrayInputStream bytearrayinputstream = new java.io.ByteArrayInputStream (vmw.common.TypeUtils.ToSByteArray (buffer)); - java.io.ObjectInputStream inputStream = new java.io.ObjectInputStream (bytearrayinputstream); - //ignore tree structure - //inputStream.readObject (); - object state = inputStream.readObject (); - inputStream.close (); - bytearrayinputstream.close (); - - return state; - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseFacesViewHandler.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseFacesViewHandler.cs deleted file mode 100644 index c0e95321d10..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseFacesViewHandler.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using javax.faces.application; -using java.util; -using javax.faces.context; -using javax.faces.component; -using javax.faces.render; -using System.Web.UI; -using System.Web; -using System.Diagnostics; - -namespace Mainsoft.Web.Hosting -{ - public abstract class BaseFacesViewHandler : ViewHandler, IExtendedViewHandler - { - readonly ViewHandler _viewHandler; - public static readonly string NAMESPACE = "__NAMESPACE"; - - public BaseFacesViewHandler (ViewHandler viewHandler) { - _viewHandler = viewHandler; - } - - public override string getActionURL (FacesContext facesContext, string viewId) { - return _viewHandler.getActionURL (facesContext, viewId); - } - - public override Locale calculateLocale (FacesContext facesContext) { - return _viewHandler.calculateLocale (facesContext); - } - - public override String calculateRenderKitId (FacesContext facesContext) { - return _viewHandler.calculateRenderKitId (facesContext); - } - - public override UIViewRoot createView (FacesContext facesContext, String viewId) { - - // create instance of Page by viewId - StringBuilder sb = new StringBuilder (); - sb.Append (facesContext.getExternalContext ().getRequestContextPath ()); - sb.Append (viewId); - IHttpHandler page = PageParser.GetCompiledPageInstance (sb.ToString (), null, ((AspNetFacesContext) facesContext).Context); - - HttpContext context = ((AspNetFacesContext) facesContext).Context; - page.ProcessRequest (context); - - UIViewRoot uiViewRoot = _viewHandler.createView (facesContext, viewId); - uiViewRoot.getChildren ().add (0, (UIComponent) page); - - Trace.WriteLine ("Created view " + viewId); - return uiViewRoot; - } - - public override String getResourceURL (FacesContext facesContext, String path) { - return _viewHandler.getResourceURL (facesContext, path); - } - - public override void renderView (FacesContext facesContext, UIViewRoot viewToRender) { - if (viewToRender == null) - throw new ArgumentNullException ("viewToRender", "viewToRender must not be null"); - ((UIComponent) viewToRender.getChildren ().get (0)).encodeChildren (facesContext); - } - - - public override UIViewRoot restoreView (FacesContext facesContext, String viewId) { - return _viewHandler.restoreView (facesContext, viewId); - } - - public override void writeState (FacesContext facesContext) { - StateManager manager = facesContext.getApplication ().getStateManager (); - StateManager.SerializedView serializedView = manager.saveSerializedView (facesContext); - manager.writeState (facesContext, serializedView); - } - - public virtual string EncodeNamespace (FacesContext facesContext, string value) { - return value; - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseHttpServlet.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseHttpServlet.cs deleted file mode 100644 index 18d0c7c7dc2..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseHttpServlet.cs +++ /dev/null @@ -1,396 +0,0 @@ -// -// (C) 2005 Mainsoft Corporation (http://www.mainsoft.com) -// - -// -// 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. -// - -using System; - -using System.Configuration; -using System.Web; -using System.Web.Configuration; -using System.Threading; -using System.Web.Hosting; -using System.IO; - -using javax.servlet; -using javax.servlet.http; -using vmw.common; -using java.util; -using vmw.@internal; -using java.lang.reflect; -using java.net; -using System.Globalization; -using System.Diagnostics; -using javax.faces; -using javax.faces.context; -using javax.faces.lifecycle; -using javax.faces.webapp; -using javax.faces.render; - -namespace Mainsoft.Web.Hosting -{ - public interface IJDBCDriverDeregisterer - { - void DeregisterDriver (java.sql.Driver driver); - } - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public class BaseHttpServlet : HttpServlet, IJDBCDriverDeregisterer - { - bool _appVirDirInited = false; - - static FacesContextFactory _facesContextFactory; - static Lifecycle _lifecycle; - static RenderKitFactory _renderKitFactory; - - public BaseHttpServlet() - { - } - - public static RenderKitFactory RenderKitFactory { - get { return _renderKitFactory; } - } - - public static FacesContextFactory FacesContextFactory { - get { return _facesContextFactory; } - } - - public static Lifecycle Lifecycle { - get { return _lifecycle; } - } - - override public void init(ServletConfig config) - { - base.init(config); - InitRuntime (config, this); - } - - public static void InitRuntime (ServletConfig config, object evidence) { - - ServletContext context = config.getServletContext (); - - if (context.getAttribute (J2EEConsts.APP_DOMAIN) != null) - return; - - _facesContextFactory = (FacesContextFactory) FactoryFinder.getFactory (FactoryFinder.FACES_CONTEXT_FACTORY); - //TODO: null-check for Weblogic, that tries to initialize Servlet before ContextListener - - //Javadoc says: Lifecycle instance is shared across multiple simultaneous requests, it must be implemented in a thread-safe manner. - //So we can acquire it here once: - LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory (FactoryFinder.LIFECYCLE_FACTORY); - _lifecycle = lifecycleFactory.getLifecycle (context.getInitParameter (FacesServlet.LIFECYCLE_ID_ATTR) ?? LifecycleFactory.DEFAULT_LIFECYCLE); - - _renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory (FactoryFinder.RENDER_KIT_FACTORY); - - AppDomain servletDomain = createServletDomain (config); - vmw.@internal.EnvironmentUtils.setAppDomain (servletDomain); - - try { - //GH Infromation Initizalization - long currentTime = java.lang.System.currentTimeMillis (); - servletDomain.SetData (".domainId", currentTime.ToString ("x")); - currentTime = ~currentTime; - servletDomain.SetData (".appId", currentTime.ToString ("x")); - servletDomain.SetData (".appName", servletDomain.SetupInformation.ApplicationName); - - servletDomain.SetData (J2EEConsts.CLASS_LOADER, java.lang.Thread.currentThread ().getContextClassLoader ()); - //servletDomain.SetData (J2EEConsts.CLASS_LOADER, vmw.common.TypeUtils.ToClass (evidence).getClassLoader ()); - //servletDomain.SetData(J2EEConsts.SERVLET_CONFIG, config); - servletDomain.SetData (J2EEConsts.RESOURCE_LOADER, new ServletResourceLoader (context)); - - lock (evidence) { - if (context.getAttribute (J2EEConsts.APP_DOMAIN) == null) - context.setAttribute (J2EEConsts.APP_DOMAIN, servletDomain); - } - //config.getServletContext ().setAttribute (J2EEConsts.CURRENT_SERVLET, this); - } - finally { - vmw.@internal.EnvironmentUtils.cleanTLS (); - vmw.@internal.EnvironmentUtils.clearAppDomain (); - } - } - - protected override void service (HttpServletRequest req, HttpServletResponse resp) - { - const string assemblies = "/assemblies"; - const string getping = "getping"; - const string setping = "setping"; - const string version = "2.2"; - string servletPath = req.getServletPath (); - - if (String.CompareOrdinal (assemblies, 0, servletPath, 0, assemblies.Length) == 0) { - if (servletPath.Length == assemblies.Length || - servletPath [assemblies.Length] == '/') { - string requestURI = req.getRequestURI (); - bool getp = requestURI.EndsWith (getping, StringComparison.Ordinal); - if (!getp && requestURI.EndsWith (setping, StringComparison.Ordinal)) { - getServletContext().setAttribute(getping, version); - getp = true; - } - - if (getp) { - string ping = (string) getServletContext ().getAttribute (getping); - if (ping == null) - ping = "0"; - resp.getOutputStream ().print (ping); - return; - } - } - } - resp.setContentType ("text/html"); - - try - { - // Very important - to update Virtual Path!!! - AppDomain servletDomain = (AppDomain)this.getServletContext().getAttribute(J2EEConsts.APP_DOMAIN); - if (!_appVirDirInited) { - string appVPath = req.getContextPath (); - if (appVPath == null || appVPath.Length == 0) - appVPath = "/"; - servletDomain.SetData (IAppDomainConfig.APP_VIRT_DIR, appVPath); - servletDomain.SetData (".hostingVirtualPath", req.getContextPath ()); - _appVirDirInited = true; - } - - // Put to the TLS current AppDomain of the servlet, so anyone can use it. - vmw.@internal.EnvironmentUtils.setAppDomain(servletDomain); - - // put request to the TLS - //Thread.SetData(_servletRequestSlot, req); - //// put response to the TLS - //Thread.SetData(_servletResponseSlot, resp); - //// put the servlet object to the TLS - //Thread.SetData(_servletSlot, this); - - resp.setHeader("X-Powered-By", "ASP.NET"); - resp.setHeader("X-AspNet-Version", "1.1.4322"); - - HttpWorkerRequest gwr = new ServletWorkerRequest (this, req, resp); - CultureInfo culture = (CultureInfo) vmw.@internal.EnvironmentUtils.getCultureInfoFromLocale (req.getLocale ()); - Thread currentTread = Thread.CurrentThread; - currentTread.CurrentCulture = culture; - currentTread.CurrentUICulture = culture; - HttpRuntime.ProcessRequest(gwr); - } - finally - { - HttpContext.Current = null; - //Thread.SetData(_servletRequestSlot, null); - //Thread.SetData(_servletResponseSlot, null); - //Thread.SetData(_servletSlot, null); - vmw.@internal.EnvironmentUtils.clearAppDomain(); - } - } - - override public void destroy() - { - base.destroy(); - DestroyRuntime (getServletContext (), this); - } - - public static void DestroyRuntime (ServletContext context, IJDBCDriverDeregisterer evidence) { - AppDomain servletDomain = (AppDomain) context.getAttribute (J2EEConsts.APP_DOMAIN); - if (servletDomain == null) - return; - - try { - vmw.@internal.EnvironmentUtils.setAppDomain (servletDomain); - Debug.WriteLine ("Destroy of GhHttpServlet"); - HttpRuntime.Close (); - vmw.@internal.EnvironmentUtils.cleanAllBeforeServletDestroy (evidence); - context.removeAttribute (J2EEConsts.APP_DOMAIN); - try { - FactoryFinder.releaseFactories (); - } - catch (FacesException) { } - - java.lang.ClassLoader appClassLoader = vmw.common.TypeUtils.ToClass (evidence).getClassLoader (); - - IJDBCDriverDeregisterer dereg = evidence; - - java.util.Enumeration en = java.sql.DriverManager.getDrivers (); - while (en.hasMoreElements ()) { - Object o = en.nextElement (); - if (vmw.common.TypeUtils.ToClass (o).getClassLoader () == appClassLoader) - dereg.DeregisterDriver ((java.sql.Driver) o); - } - - java.lang.Thread.currentThread ().setContextClassLoader (null); - } - catch (Exception e) { - Debug.WriteLine (String.Format ("ERROR in Servlet Destroy {0},{1}", e.GetType (), e.Message)); - Debug.WriteLine (e.StackTrace); - } - finally { - vmw.@internal.EnvironmentUtils.clearAppDomain (); - } - } - - private static AppDomain createServletDomain(ServletConfig config) - { - string rootPath = J2EEUtils.GetApplicationRealPath(config.getServletContext ()); - AppDomainSetup domainSetup = new AppDomainSetup(); - string name = config.getServletName();//.getServletContextName(); - if (name == null) - name = "GH Application"; - domainSetup.ApplicationName = name; - domainSetup.ConfigurationFile = Path.Combine (rootPath, "Web.config"); - domainSetup.PrivateBinPath = Path.Combine (rootPath, "WEB-INF/lib"); - - AppDomain servletDomain = AppDomain.CreateDomain(name, null, domainSetup); - - - - - - //servletDomain.SetData(IAppDomainConfig.APP_PHYS_DIR, J2EEUtils.GetApplicationPhysicalPath(config)); - //servletDomain.SetData(IAppDomainConfig.WEB_APP_DIR, rootPath); - - servletDomain.SetData(IAppDomainConfig.APP_PHYS_DIR, J2EEUtils.GetApplicationPhysicalPath(config.getServletContext ())); - servletDomain.SetData(IAppDomainConfig.WEB_APP_DIR, rootPath); - servletDomain.SetData(IAppDomainConfig.SERVLET_CONFIG, config); - - //Set DataDirectory substitution string (http://blogs.msdn.com/dataaccess/archive/2005/10/28/486273.aspx) - string dataDirectory = config.getServletContext ().getInitParameter ("DataDirectory"); - if (dataDirectory == null) - dataDirectory = "App_Data"; - - if (!Path.IsPathRooted (dataDirectory)) { - java.io.InputStream inputStream = config.getServletContext ().getResourceAsStream ("/WEB-INF/classes/appData.properties"); - string root; - if (inputStream != null) { - try { - Properties props = new Properties (); - props.load (inputStream); - root = props.getProperty ("root.folder"); - } - finally { - inputStream.close (); - } - } - else - root = config.getServletContext ().getRealPath ("/"); - - if (root == null) - root = String.Empty; - - dataDirectory = Path.Combine (root, dataDirectory); - } - - if (dataDirectory [dataDirectory.Length - 1] != Path.DirectorySeparatorChar) - dataDirectory += Path.DirectorySeparatorChar; - - servletDomain.SetData ("DataDirectory", dataDirectory); - - if (config.getServletContext ().getRealPath ("/") == null) - servletDomain.SetData(".appStartTime", DateTime.UtcNow); - - // The BaseDir is the full path to the physical dir of the app - // and allows the application to modify files in the case of - // open deployment. - string webApp_baseDir = config.getServletContext().getRealPath(""); - if (webApp_baseDir == null || webApp_baseDir == "") - webApp_baseDir = rootPath; - servletDomain.SetData(IAppDomainConfig.APP_BASE_DIR , webApp_baseDir); - Debug.WriteLine("Initialization of webapp " + webApp_baseDir); - //servletDomain.SetData(".hostingVirtualPath", "/"); - //servletDomain.SetData(".hostingInstallDir", "/"); - return servletDomain; - } - - #region IJDBCDriverDeregisterer Members - - public void DeregisterDriver (java.sql.Driver driver) { - java.sql.DriverManager.deregisterDriver (driver); - } - - #endregion - } -} - -namespace System.Web.GH -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public class BaseHttpServlet : Mainsoft.Web.Hosting.BaseHttpServlet - { - } - -} - -namespace System.Web.J2EE -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public class BaseHttpServlet : Mainsoft.Web.Hosting.BaseHttpServlet - { - } - -} - -public class GhDynamicHttpServlet : System.Web.GH.BaseHttpServlet -{ -} - -public class GhStaticHttpServlet : System.Web.GH.BaseStaticHttpServlet -{ -} - -public class GhHttpServlet : System.Web.GH.BaseHttpServlet -{ - GhStaticHttpServlet staticServlet; - - public GhHttpServlet () { - staticServlet = new GhStaticHttpServlet (); - } - - override public void init (ServletConfig config) { - base.init (config); - staticServlet.init (config); - } - - override protected void service (HttpServletRequest req, HttpServletResponse resp) { - string pathInfo = req.getRequestURI (); - string contextPath = req.getContextPath (); - if (pathInfo.Equals (contextPath) || - ((pathInfo.Length - contextPath.Length) == 1) && - pathInfo [pathInfo.Length - 1] == '/' && pathInfo.StartsWith (contextPath)) - pathInfo = contextPath + req.getServletPath (); - if (pathInfo.EndsWith (".aspx") || - pathInfo.EndsWith (".asmx") || - pathInfo.EndsWith (".invoke")) { - base.service (req, resp); - } - else { - staticServlet.service (req, resp); - } - } - - override public void destroy () { - staticServlet.destroy (); - base.destroy (); - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseStaticHttpServlet.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseStaticHttpServlet.cs deleted file mode 100644 index d6ebfd73015..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/BaseStaticHttpServlet.cs +++ /dev/null @@ -1,186 +0,0 @@ -// -// (C) 2005 Mainsoft Corporation (http://www.mainsoft.com) -// - -// -// 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. -// - -using System; -using System.IO; -using System.Configuration; -using System.Web; -using System.Threading; - -using javax.servlet; -using javax.servlet.http; -using vmw.common; -using System.Diagnostics; - -namespace Mainsoft.Web.Hosting -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public class BaseStaticHttpServlet : HttpServlet - { - public BaseStaticHttpServlet() - { - } - - override public void init(ServletConfig config) - { - base.init(config); - AppDir = config.getServletContext ().getInitParameter (IAppDomainConfig.APP_DIR_NAME); - if (AppDir != null) { - AppDir = AppDir.Replace('\\', '/'); - if (AppDir[AppDir.Length - 1] != '/') - AppDir += '/'; - } - } - - override protected void service(HttpServletRequest req, HttpServletResponse resp) - { - resp.setHeader("X-Powered-By", "ASP.NET"); - resp.setHeader("X-AspNet-Version", "1.1.4322"); - - String filename = getServletContext().getRealPath(req.getServletPath()); - ServletOutputStream hos; - try { - hos = resp.getOutputStream(); - } - catch (java.lang.IllegalStateException e) - { - string mimeType = getServletContext().getMimeType(filename); - if (mimeType == null || mimeType.StartsWith("text")) { - sendFileUsingWriter(resp, filename); - return; - } - else - throw e; - } - try - { - string mimeType = this.getServletContext().getMimeType(filename); - if (mimeType == null) - mimeType = "text/plain"; - - resp.setContentType(mimeType); - - FileStream fis = null; - try { - fis = new FileStream(filename,FileMode.Open,FileAccess.Read); - byte[] buf = new byte[4 * 1024]; // 4K buffer - int bytesRead; - while ((bytesRead = fis.Read(buf,0,buf.Length)) != -1 && - bytesRead != 0) { - hos.write(TypeUtils.ToSByteArray(buf), 0, bytesRead); - } - } - finally { - if (fis != null) fis.Close(); - } - } - catch (System.IO.FileNotFoundException e) - { - resp.setStatus(404,"Object Not Found."); - HttpException myExp = new HttpException (404, "File '" + filename + "' not found."); - hos.print(((HttpException) myExp).GetHtmlErrorMessage ()); - hos.flush(); - } - catch(Exception e) - { - Trace.WriteLine (String.Format ("ERROR in Static File Reading {0},{1}", e.GetType (), e.Message)); - resp.setStatus(500); - HttpException myExp = new HttpException ("Exception in Reading static file", e); - hos.print(((HttpException) myExp).GetHtmlErrorMessage ()); - hos.flush(); - } - } - - void sendFileUsingWriter(HttpServletResponse resp, string filename) - { - java.io.PrintWriter writer = resp.getWriter(); - try - { - resp.setContentType(this.getServletContext().getMimeType(filename)); - StreamReader fis = null; - char[] buf = new char[4 * 1024]; // 4K buffer - try { - fis = new StreamReader(filename); - int charsRead; - while ((charsRead = fis.Read(buf,0,buf.Length)) != -1 && - charsRead != 0) { - writer.write(buf, 0, charsRead); - } - } - finally { - if (fis != null) fis.Close(); - } - } - catch (System.IO.FileNotFoundException e) - { - resp.setStatus(404,"Object Not Found."); - HttpException myExp = new HttpException (404, "File '" + filename + "' not found."); - writer.print(((HttpException) myExp).GetHtmlErrorMessage ()); - writer.flush(); - } - catch(Exception e) - { - Trace.WriteLine (String.Format ("ERROR in Static File Reading {0},{1}", e.GetType (), e.Message)); - resp.setStatus(500); - HttpException myExp = new HttpException ("Exception in Reading static file", e); - writer.print(((HttpException) myExp).GetHtmlErrorMessage ()); - writer.flush(); - } - } - - override public void destroy() - { - base.destroy(); - } - - private string AppDir; - } -} - -namespace System.Web.J2EE -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public class BaseStaticHttpServlet : Mainsoft.Web.Hosting.BaseStaticHttpServlet - { - } - -} - - -namespace System.Web.GH -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public class BaseStaticHttpServlet : Mainsoft.Web.Hosting.BaseStaticHttpServlet - { - } - -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/IExtendedViewHandler.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/IExtendedViewHandler.cs deleted file mode 100644 index bb76590e4ea..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/IExtendedViewHandler.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using javax.faces.context; - -namespace Mainsoft.Web.Hosting -{ - public interface IExtendedViewHandler - { - string EncodeNamespace (FacesContext facesContext, string value); - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/IncludeHelperServlet.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/IncludeHelperServlet.cs deleted file mode 100644 index a2e47e1dd2e..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/IncludeHelperServlet.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -// Mainsoft.Web.Hosting.IncludeHelperServlet -// -// Authors: -// Eyal Alaluf (eyala@mainsoft.com) -// -// (C) 2006 Mainsoft Co. (http://www.mainsoft.com) -// - -// -// 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. -// - -using System; -using System.IO; -using System.Web.UI; -using java.io; -using javax.servlet; -using javax.servlet.http; - -namespace Mainsoft.Web.Hosting -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public class IncludeHelperServlet : HttpServlet - { - public IncludeHelperServlet() - { - } - - override protected void service(HttpServletRequest req, HttpServletResponse resp) - { - string servletPath = ServletIncludeUtils.getServletPath(req); - TextWriter writer = (TextWriter)ServletIncludeUtils.getTextWriter(req); - RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(servletPath); - HttpServletResponseWrapper wrapper = new AspxResponseWrapper(resp, writer); - dispatcher.include(req, wrapper); - } - - sealed class AspxResponseWrapper : HttpServletResponseWrapper - { - public AspxResponseWrapper(HttpServletResponse resp, TextWriter writer) : base (resp) - { - jwriter = new PrintWriter(new JavaWriterFromTextWriter(writer)); - } - - public override PrintWriter getWriter() - { - return jwriter; - } - - readonly PrintWriter jwriter; - } - - sealed class JavaWriterFromTextWriter : Writer - { - public JavaWriterFromTextWriter(TextWriter writer) - { - this.writer = writer; - } - - public override void flush() - { - writer.Flush (); - } - - public override void write(char[] buffer, int offset, int count) - { - writer.Write(buffer, offset, count); - } - - public override void write(String s) - { - writer.Write(s); - } - - public override void write(string s, int start, int count) - { - if (start == 0 && count == s.Length) - writer.Write(s); - else - writer.Write(s.Substring(start, count)); - } - - public override void close() - { - // Ignore close as we don't own here the writer. - } - - readonly TextWriter writer; - } - } -} - -namespace System.Web.GH -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public class IncludeHelperServlet : Mainsoft.Web.Hosting.IncludeHelperServlet - { - } - -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/OutputStreamWrapper.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/OutputStreamWrapper.cs deleted file mode 100644 index 878f771ecd3..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/OutputStreamWrapper.cs +++ /dev/null @@ -1,188 +0,0 @@ -// -// Mainsoft.Web.Hosting.OutputStreamWrapper -// -// Authors: -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// (C) 2006 Mainsoft -// -// -// 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. -// - -using System; -using System.Web; -using System.Collections.Generic; -using System.Text; - -using java.io; -using vmw.common; - - -namespace Mainsoft.Web.Hosting -{ - /// - /// - /// - public sealed class OutputStreamWrapper : java.io.Writer - { - enum OutputMode - { - CharWriter, - ByteStream, - } - - readonly PrintWriter _printWriter; - readonly OutputStream _outputStream; - readonly OutputMode _outputMode; - - private byte [] _bytebuffer; - private char [] _charBuffer; - //sbyte [] _oneByte = new sbyte [1]; - - Encoding _encoding = null; - - /// - /// Ctor from writer - /// - /// - public OutputStreamWrapper (PrintWriter writer) - { - _printWriter = writer; - _outputMode = OutputMode.CharWriter; - } - - /// - /// Ctor from stream - /// - /// - public OutputStreamWrapper (OutputStream outputStream) - { - _outputStream = outputStream; - _outputMode = OutputMode.ByteStream; - } - - /// - /// - /// - public override void close () - { - // BUGBUG - // on WPS, closing the writer causes - // any portlets rendered after us to be not shown... - //_writer.close(); - } - - /// - /// Flushes servers stream - /// - public override void flush () - { - if (_outputMode == OutputMode.CharWriter) - _printWriter.flush (); - else - _outputStream.flush(); - } - - /// - /// Writes char array - /// - /// - /// - /// - public override void write (char [] chars, int index, int count) - { - if (_outputMode == OutputMode.CharWriter) { - _printWriter.write (chars, index, count); - } - else { - int length = Encoding.GetMaxByteCount (count); - byte [] bytebuffer = GetByteBuffer (length); - int realLength = Encoding.GetBytes (chars, index, count, bytebuffer, 0); - - _outputStream.write (TypeUtils.ToSByteArray (bytebuffer), 0, realLength); - } - - } - - /// - /// Writes byte array - /// - /// - /// - /// - public void write (sbyte [] sbytes, int index, int count) - { - if (_outputMode == OutputMode.ByteStream) - _outputStream.write (sbytes, index, count); - else { - int length = Encoding.GetMaxCharCount (count); - char [] charbuffer = GetCharBuffer (length); - int realLength = Encoding.GetChars ((byte []) TypeUtils.ToByteArray (sbytes), index, count, charbuffer, 0); - - _printWriter.write (charbuffer, 0, realLength); - } - } - - private char [] GetCharBuffer (int length) - { - // We will reuse the buffer if its size is < 32K - if (_charBuffer != null && _charBuffer.Length >= length) - return _charBuffer; - - if (length > 32 * 1024) - return new char [length]; - - if (length < 1024) - length = 1024; - - _charBuffer = new char [length]; - return _charBuffer; - } - - private byte [] GetByteBuffer (int length) - { - // We will reuse the buffer if its size is < 32K - if (_bytebuffer != null && _bytebuffer.Length >= length) - return _bytebuffer; - - if (length > 32 * 1024) - return new byte [length]; - - if (length < 1024) - length = 1024; - - _bytebuffer = new byte [length]; - return _bytebuffer; - } - - private Encoding Encoding - { - get - { - if (_encoding == null) { - HttpContext current = HttpContext.Current; - _encoding = (current != null) ? current.Response.ContentEncoding : Encoding.UTF8; - } - return _encoding; - } - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/RequestParameterMap.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/RequestParameterMap.cs deleted file mode 100644 index 51a975e019a..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/RequestParameterMap.cs +++ /dev/null @@ -1,118 +0,0 @@ -// -// Mainsoft.Web.Hosting.RequestParameterMap.cs -// -// Authors: -// Konstantin Triger -// -// (C) 2008 Mainsoft Co. (http://www.mainsoft.com) -// - -// -// 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. -// - -using System; -using java.util; -using System.Collections.Specialized; -using System.Collections; -namespace Mainsoft.Web.Hosting -{ - partial class BaseExternalContext - { - abstract class BaseRequestParameterMap : AbstractAttributeMap - { - readonly NameValueCollection _form; - - protected BaseRequestParameterMap (NameValueCollection form) { - _form = form; - } - - protected NameValueCollection Form { - get { return _form; } - } - - protected override void setAttribute (String key, Object value) { - throw new NotSupportedException ( - "Cannot set Request Parameter"); - } - - protected override void removeAttribute (String key) { - throw new NotSupportedException ( - "Cannot remove Request Parameter"); - } - - protected override Enumeration getAttributeNames () { - return new EnumerationImpl (_form.Keys.GetEnumerator ()); - } - - sealed class EnumerationImpl : Enumeration - { - readonly IEnumerator _en; - public EnumerationImpl (IEnumerator en) { - _en = en; - } - - #region Enumeration Members - - public bool hasMoreElements () { - return _en.MoveNext (); - } - - public object nextElement () { - return _en.Current; - } - - #endregion - } - } - - sealed class RequestParameterMap : BaseRequestParameterMap - { - public RequestParameterMap (NameValueCollection form) - : base (form) { - } - - protected override Object getAttribute (String key) { - return Form [key]; - } - } - - sealed class IEnumeratorIteratorImpl : Iterator - { - readonly private IEnumerator _en; - - public IEnumeratorIteratorImpl (IEnumerator en) { - _en = en; - } - - public bool hasNext () { - return _en.MoveNext (); - } - - public Object next () { - return _en.Current; - } - - public void remove () { - throw new NotSupportedException (GetType ().Name + " UnsupportedOperationException"); - } - } - } -} \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/RequestParameterValuesMap.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/RequestParameterValuesMap.cs deleted file mode 100644 index e9fa9b40c3e..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/RequestParameterValuesMap.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// Mainsoft.Web.Hosting.RequestParameterValuesMap.cs -// -// Authors: -// Konstantin Triger -// -// (C) 2008 Mainsoft Co. (http://www.mainsoft.com) -// - -// -// 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. -// - -using System; -using java.util; -using System.Collections.Specialized; -namespace Mainsoft.Web.Hosting -{ - partial class BaseExternalContext - { - sealed class RequestParameterValuesMap : BaseRequestParameterMap - { - public RequestParameterValuesMap (NameValueCollection form) - : base (form) { - } - - protected override Object getAttribute (String key) { - return Form.GetValues (key); - } - } - } -} \ No newline at end of file diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesContext.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesContext.cs deleted file mode 100644 index ef2ebc074a9..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesContext.cs +++ /dev/null @@ -1,167 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using javax.faces.context; -using System.Web; -using System.Web.UI; -using javax.servlet; -using javax.faces.lifecycle; -using javax.faces.application; - -namespace Mainsoft.Web.Hosting -{ - public class ServletFacesContext : AspNetFacesContext - { - protected ServletFacesContext (FacesContext wrappedFacesContext, ExternalContext externalContext, HttpContext httpContext, FacesContext oldFacesContext) - : base (wrappedFacesContext, externalContext, httpContext, oldFacesContext) { - } - - public static ServletFacesContext GetFacesContext (FacesContextFactory facesContextFactory, - ServletContext servletContext, - ServletRequest servletRequest, - ServletResponse servletResponse, - Lifecycle lifecycle, - HttpContext httpContext, - string executionFilePath) { - FacesContext oldFacesContex = FacesContext.getCurrentInstance (); - FacesContext wrappedFacesContex = facesContextFactory.getFacesContext (servletContext, servletRequest, servletResponse, lifecycle); - ExternalContext externalContext = new ServletExternalContext (wrappedFacesContex.getExternalContext (), httpContext, executionFilePath); - ServletFacesContext context = new ServletFacesContext (wrappedFacesContex, externalContext, httpContext, oldFacesContex); - return context; - } - - } - #region ServletExternalContext - - public class ServletExternalContext : BaseExternalContext - { - readonly ExternalContext _externalContext; - - public ServletExternalContext (ExternalContext externalContext, HttpContext httpContext, string executionFilePath) - : base (httpContext, executionFilePath) { - _externalContext = externalContext; - } - - public override void dispatch (string __p1) { - _externalContext.dispatch (__p1); - } - - public override string encodeActionURL (string __p1) { - return _externalContext.encodeActionURL (__p1); - } - - public override string encodeNamespace (string __p1) { - return _externalContext.encodeNamespace (__p1); - } - - public override string encodeResourceURL (string __p1) { - return _externalContext.encodeResourceURL (__p1); - } - - public override java.util.Map getApplicationMap () { - return _externalContext.getApplicationMap (); - } - - public override string getAuthType () { - return _externalContext.getAuthType (); - } - - public override object getContext () { - return _externalContext.getContext (); - } - - public override string getInitParameter (string __p1) { - return _externalContext.getInitParameter (__p1); - } - - public override java.util.Map getInitParameterMap () { - return _externalContext.getInitParameterMap (); - } - - public override string getRemoteUser () { - return _externalContext.getRemoteUser (); - } - - public override object getRequest () { - return _externalContext.getRequest (); - } - - public override string getRequestContextPath () { - return _externalContext.getRequestContextPath (); - } - - public override java.util.Map getRequestCookieMap () { - return _externalContext.getRequestCookieMap (); - } - - public override java.util.Map getRequestHeaderMap () { - return _externalContext.getRequestHeaderMap (); - } - - public override java.util.Map getRequestHeaderValuesMap () { - return _externalContext.getRequestHeaderValuesMap (); - } - - public override java.util.Locale getRequestLocale () { - return _externalContext.getRequestLocale (); - } - - public override java.util.Iterator getRequestLocales () { - return _externalContext.getRequestLocales (); - } - - public override java.util.Map getRequestMap () { - return _externalContext.getRequestMap (); - } - - public override string getRequestServletPath () { - return _externalContext.getRequestServletPath (); - } - - public override java.net.URL getResource (string __p1) { - return _externalContext.getResource (__p1); - } - - public override java.io.InputStream getResourceAsStream (string __p1) { - return _externalContext.getResourceAsStream (__p1); - } - - public override java.util.Set getResourcePaths (string __p1) { - return _externalContext.getResourcePaths (__p1); - } - - public override object getResponse () { - return _externalContext.getResponse (); - } - - public override object getSession (bool __p1) { - return _externalContext.getSession (__p1); - } - - public override java.util.Map getSessionMap () { - return _externalContext.getSessionMap (); - } - - public override java.security.Principal getUserPrincipal () { - return _externalContext.getUserPrincipal (); - } - - public override bool isUserInRole (string __p1) { - return _externalContext.isUserInRole (__p1); - } - - public override void log (string __p1, Exception __p2) { - _externalContext.log (__p1, __p2); - } - - public override void log (string __p1) { - _externalContext.log (__p1); - } - - public override void redirect (string __p1) { - _externalContext.redirect (__p1); - } - } - - #endregion -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesPageHandler.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesPageHandler.cs deleted file mode 100644 index fc9a5c7c6af..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesPageHandler.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Web; -using javax.faces.component; -using System.Web.UI; -using javax.faces.context; -using javax.faces.lifecycle; -using javax.faces; -using javax.servlet; -using javax.faces.webapp; -using javax.servlet.http; -using vmw.common; -using System.Diagnostics; -using javax.faces.render; -using System.IO; - -namespace Mainsoft.Web.Hosting -{ - public abstract class BaseFacesPageHandler - { - static protected void SetupResponseWriter (AspNetFacesContext facesContext, string contentType, string characterEncoding) { - RenderKit renderKit = BaseHttpServlet.RenderKitFactory.getRenderKit (facesContext, facesContext.getViewRoot ().getRenderKitId ()); - ResponseWriter writer = renderKit.createResponseWriter (new AspNetResponseWriter (facesContext.Context.Response.Output), contentType, characterEncoding); - facesContext.setResponseWriter (writer); - } - - #region AspNetResponseWriter - private sealed class AspNetResponseWriter : java.io.Writer - { - readonly TextWriter _writer; - public AspNetResponseWriter (TextWriter writer) { - _writer = writer; - } - public override void close () { - _writer.Close (); - } - - public override void flush () { - _writer.Flush (); - } - - public override void write (char [] __p1, int __p2, int __p3) { - _writer.Write (__p1, __p2, __p3); - } - - public override void write (int __p1) { - _writer.Write ((char) __p1); - } - - public override void write (char [] __p1) { - _writer.Write (__p1); - } - - public override void write (string __p1) { - _writer.Write (__p1); - } - - public override void write (string __p1, int __p2, int __p3) { - _writer.Write (__p1, __p2, __p3); - } - } - #endregion - } - - public class ServletFacesPageHandler : BaseFacesPageHandler, IHttpHandler, IServiceProvider - { - readonly FacesContextFactory _facesContextFactory; - readonly Lifecycle _lifecycle; - readonly string _executionFilePath; - readonly Type _pageType; - Page _page; - - public bool IsReusable { - get { return false; } - } - - public ServletFacesPageHandler (string executionFilePath, Type pageType, FacesContextFactory facesContextFactory, Lifecycle lifecycle) { - _facesContextFactory = facesContextFactory; - _lifecycle = lifecycle; - _executionFilePath = executionFilePath; - _pageType = pageType; - } - - protected virtual ServletFacesContext GetFacesContext (FacesContextFactory facesContextFactory, - ServletContext servletContext, - ServletRequest servletRequest, - ServletResponse servletResponse, - Lifecycle lifecycle, - HttpContext httpContext, - string executionFilePath) { - return ServletFacesContext.GetFacesContext (facesContextFactory, servletContext, servletRequest, servletResponse, lifecycle, httpContext, executionFilePath); - } - - public void ProcessRequest (HttpContext context) { - ServletWorkerRequest wr = (ServletWorkerRequest) ((IServiceProvider) context).GetService (typeof (HttpWorkerRequest)); - ServletContext servletContext = wr.GetContext (); - HttpServletRequest request = wr.ServletRequest; - HttpServletResponse response = wr.ServletResponse; - - ServletFacesContext facesContext = GetFacesContext (_facesContextFactory, servletContext, request, response, _lifecycle, context, _executionFilePath); - try { - try { - try { - Trace.WriteLine ("FacesPageHandler: before execute"); - _lifecycle.execute (facesContext); - Trace.WriteLine ("FacesPageHandler: after execute"); - } - finally { - UIViewRoot viewRoot = facesContext.getViewRoot (); - if (viewRoot != null && viewRoot.getChildCount () > 0) - _page = (Page) viewRoot.getChildren ().get (0); - } - Trace.WriteLine ("FacesPageHandler: before render"); - SetupResponseWriter (facesContext, response.getContentType (), response.getCharacterEncoding ()); - _lifecycle.render (facesContext); - Trace.WriteLine ("FacesPageHandler: after render"); - } - catch (FacesException fex) { - Exception inner = fex.InnerException; - if (inner != null) - TypeUtils.Throw (inner); - throw; - } - } - finally { - facesContext.release (); - } - } - - public object GetService (Type serviceType) { - if (serviceType == typeof (Type)) - return _pageType; - if (serviceType == typeof (Page)) - return _page; - return null; - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesPageHandlerFactory.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesPageHandlerFactory.cs deleted file mode 100644 index af1398c42b8..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesPageHandlerFactory.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Web; -using System.Web.Compilation; -using System.Web.UI; -using javax.faces.component; -using javax.servlet; -using javax.faces.context; -using javax.faces.lifecycle; -using javax.servlet.http; -using System; -using javax.faces.webapp; -using javax.faces; -using System.Web.J2EE; - -namespace Mainsoft.Web.Hosting -{ - public sealed class ServletFacesPageHandlerFactory : BaseFacesPageHandlerFactory - { - public override IHttpHandler GetHandler (HttpContext context, string requestType, string url, string path) { - Type pageType = PageMapper.GetObjectType (context, url); - IHttpHandler handler = new ServletFacesPageHandler (url, pageType, BaseHttpServlet.FacesContextFactory, BaseHttpServlet.Lifecycle); - return SessionWrapper.WrapHandler (handler); - } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesStateManager.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesStateManager.cs deleted file mode 100644 index 1da99bde9dd..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesStateManager.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Web.UI; - -using javax.faces; -using javax.faces.application; -using javax.faces.render; -using javax.faces.component; -using javax.faces.context; -using System.Web.Hosting; -using System.Web; -using java.util; -using System.Diagnostics; -using javax.servlet.http; - -namespace Mainsoft.Web.Hosting -{ - public sealed class ServletFacesStateManager : BaseFacesStateManager - { - public override void writeState (FacesContext facesContext, StateManager.SerializedView serializedView) { - Trace.WriteLine ("Entering writeState"); - - if (serializedView != null) { - if (isSavingStateInClient (facesContext)) { - SaveStateInClient (facesContext, serializedView); - } - else { - HttpSession session = (HttpSession) facesContext.getExternalContext ().getSession (true); - string key = ((IExtendedViewHandler) facesContext.getApplication ().getViewHandler ()).EncodeNamespace (facesContext, VIEWSTATE); - session.setAttribute (key, serializedView); - } - } - - Trace.WriteLine ("Exiting writeState"); - } - - protected override void restoreComponentState (FacesContext facesContext, - javax.faces.component.UIViewRoot uiViewRoot, - String renderKitId) { - - Trace.WriteLine ("Entering restoreComponentState"); - - Object serializedComponentStates; - if (isSavingStateInClient (facesContext)) { - serializedComponentStates = GetStateFromClient (facesContext, uiViewRoot.getViewId(), renderKitId); - } - else { - HttpSession session = (HttpSession) facesContext.getExternalContext ().getSession (false); - if (session == null) - serializedComponentStates = null; - else { - string key = ((IExtendedViewHandler) facesContext.getApplication ().getViewHandler ()).EncodeNamespace (facesContext, VIEWSTATE); - SerializedView serializedView = session.getAttribute (key) as SerializedView; - if (serializedView == null) - serializedComponentStates = null; - else - serializedComponentStates = serializedView.getState (); - } - } - ((UIComponent) uiViewRoot.getChildren ().get (0)).processRestoreState (facesContext, serializedComponentStates); - - Trace.WriteLine ("Exiting restoreComponentState"); - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesViewHandler.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesViewHandler.cs deleted file mode 100644 index 596577fdbe7..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletFacesViewHandler.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using javax.faces.application; -using javax.servlet.http; -using java.util; -using javax.faces.context; -using javax.faces.component; -using java.lang; -using javax.faces.render; - -namespace Mainsoft.Web.Hosting -{ - public class ServletFacesViewHandler : BaseFacesViewHandler - { - public ServletFacesViewHandler (ViewHandler viewHandler) - : base (viewHandler) { - } - - public override string getActionURL (FacesContext facesContext, string viewId) { - if (viewId.Length > 0 && viewId [0] == '/') { - return facesContext.getExternalContext ().getRequestContextPath () + viewId; - } - else { - return viewId; - } - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletIncludeUtils.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletIncludeUtils.cs deleted file mode 100644 index d7cc5c518a1..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletIncludeUtils.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using javax.servlet; -using System.Web; -using javax.servlet.http; - -namespace Mainsoft.Web.Hosting -{ - public class ServletIncludeUtils - { - public static void includeServlet (String servletPath, Object writer, Object aspPage, Object [] servletParams) { - // Need to define logic for resolving the servletPath. Share code with portlet createRenderUrl. - HttpContext context = HttpContext.Current; - HttpWorkerRequest wr = (HttpWorkerRequest) ((IServiceProvider) context).GetService (typeof (HttpWorkerRequest)); - RequestDispatcher dispatcher = ((ServletContext) ((IServiceProvider) wr).GetService (typeof (ServletContext))).getRequestDispatcher (SERVLET_INCLUDE_HELPER_PATH); - ServletResponse response = (ServletResponse) ((IServiceProvider) wr).GetService (typeof (ServletResponse)); - ServletRequest request = (ServletRequest) ((IServiceProvider) wr).GetService (typeof (ServletRequest)); - - // Setup params for the include call. - String oldServletPath = (String) setAttribute (request, SERVLET_PATH_ATTRIBUTE_NAME, servletPath); - Object oldAspPage = setAttribute (request, ASPPAGE_ATTRIBUTE_NAME, aspPage); - Object [] oldServletParams = (Object []) setAttribute (request, SERVLET_PARAMS_ATTRIBUTE_NAME, servletParams); - Object oldWriter = setAttribute (request, TEXT_WRITER_ATTRIBUTE_NAME, writer); - - // Do the include call. - dispatcher.include (request, response); - - // Restore previous attribute values after the call. - request.setAttribute (SERVLET_PATH_ATTRIBUTE_NAME, oldServletPath); - request.setAttribute (ASPPAGE_ATTRIBUTE_NAME, oldAspPage); - request.setAttribute (SERVLET_PARAMS_ATTRIBUTE_NAME, oldServletParams); - request.setAttribute (TEXT_WRITER_ATTRIBUTE_NAME, oldWriter); - } - - public static String getServletPath (ServletRequest request) { - return (String) request.getAttribute (SERVLET_PATH_ATTRIBUTE_NAME); - } - public static Object getAspPage (ServletRequest request) { - return request.getAttribute (ASPPAGE_ATTRIBUTE_NAME); - } - public static Object [] getServletParams (ServletRequest request) { - return (Object []) request.getAttribute (SERVLET_PARAMS_ATTRIBUTE_NAME); - } - public static Object getTextWriter (ServletRequest request) { - return request.getAttribute (TEXT_WRITER_ATTRIBUTE_NAME); - } - - private static Object setAttribute (ServletRequest request, String attrname, Object newval) { - Object oldval = request.getAttribute (attrname); - request.setAttribute (attrname, newval); - return oldval; - } - - public static readonly String SERVLET_INCLUDE_HELPER_PATH = "/servletincludehelper"; - public static readonly String ASPPAGE_ATTRIBUTE_NAME = "vmw.servlet.include.asppage"; - public static readonly String SERVLET_PATH_ATTRIBUTE_NAME = "vmw.servlet.include.servlet.path"; - public static readonly String SERVLET_PARAMS_ATTRIBUTE_NAME = "vmw.servlet.include.servlet.params"; - public static readonly String TEXT_WRITER_ATTRIBUTE_NAME = "vmw.servlet.include.text.writer"; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletResourceLoader.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletResourceLoader.cs deleted file mode 100644 index 82d4a90b10a..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletResourceLoader.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using vmw.@internal.io; -using javax.servlet; -using java.io; -using java.net; - -namespace Mainsoft.Web.Hosting -{ - class ServletResourceLoader : IResourceLoader - { - ServletContext _context; - - public ServletResourceLoader (ServletContext context) { - _context = context; - } - - public URL getResource (String resourceName) { - if (resourceName == null) - throw new ArgumentNullException ("resourceName"); - - if (!resourceName.StartsWith ("/")) - resourceName = "/" + resourceName; - - return _context.getResource (resourceName); - } - - public InputStream getResourceAsStream (String resourceName) { - if (resourceName == null) - throw new ArgumentNullException ("resourceName"); - - if (!resourceName.StartsWith ("/")) - resourceName = "/" + resourceName; - - return _context.getResourceAsStream (resourceName); - } - - public java.util.Set getResourcePaths (String path) { - if (path == null) - throw new ArgumentNullException ("path"); - - if (!path.StartsWith ("/")) - path = "/" + path; - - return _context.getResourcePaths (path); - } - } - -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletWorkerRequest.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletWorkerRequest.cs deleted file mode 100644 index 6cff989c788..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletWorkerRequest.cs +++ /dev/null @@ -1,202 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using javax.servlet.http; -using java.security; -using javax.servlet; - -namespace Mainsoft.Web.Hosting -{ - public sealed class ServletWorkerRequest : BaseWorkerRequest - { - readonly HttpServlet _HttpServlet; - readonly HttpServletRequest _HttpServletRequest; - readonly HttpServletResponse _HttpServletResponse; - OutputStreamWrapper _outputStream; - - public ServletWorkerRequest (HttpServlet servlet, HttpServletRequest req, HttpServletResponse resp) - : base (req.getContextPath(), req.getServletPath (), req.getRequestURI ()) { - - _HttpServlet = servlet; - _HttpServletRequest = req; - _HttpServletResponse = resp; - - } - - static readonly Type typeOfHttpServletRequest = typeof (HttpServletRequest); - static readonly Type typeOfHttpServletResponse = typeof (HttpServletResponse); - static readonly Type typeOfHttpServlet = typeof (HttpServlet); - static readonly Type typeOfHttpSession = typeof (HttpSession); - static readonly Type typeOfServletContext = typeof (ServletContext); - static readonly Type typeOfServletConfig = typeof (ServletConfig); - public override object GetService (Type serviceType) { - if (serviceType == typeOfHttpServlet || - serviceType == typeOfServletConfig) - return _HttpServlet; - if (serviceType == typeOfHttpServletRequest) - return _HttpServletRequest; - if (serviceType == typeOfHttpServletResponse) - return _HttpServletResponse; - if (serviceType == typeOfHttpSession) - return GetSession (false); - if (serviceType == typeOfServletContext) - return _HttpServlet.getServletContext (); - return base.GetService (serviceType); - } - - public HttpServlet Servlet { - get { - return _HttpServlet; - } - } - - public HttpServletRequest ServletRequest { - get { - return _HttpServletRequest; - } - } - - public HttpServletResponse ServletResponse { - get { - return _HttpServletResponse; - } - } - - public override string GetHttpVerbName () { - return _HttpServletRequest.getMethod (); - } - - public override string GetHttpVersion () { - return _HttpServletRequest.getProtocol (); - } - - public override string GetLocalAddress () { - return _HttpServletRequest.getLocalAddr (); - } - - public override int GetLocalPort () { - return _HttpServletRequest.getServerPort (); - } - - public override string GetPathInfo () { - return base.GetPathInfo () ?? String.Empty; - } - - public override string GetQueryString () { - return _HttpServletRequest.getQueryString (); - } - - public override string GetRemoteAddress () { - return _HttpServletRequest.getRemoteAddr (); - } - - public override string GetRemoteName () { - return _HttpServletRequest.getRemoteHost (); - } - - - public override int GetRemotePort () { - try { - return _HttpServletRequest.getRemotePort (); - } - catch (Exception e) { - // if servlet API is 2.3 and below - there is no method getRemotePort - // in ServletRequest interface... should be described as limitation. - return 0; - } - } - - public override string GetProtocol () { - return _HttpServletRequest.getScheme (); - } - - public override string GetServerName () { - return _HttpServletRequest.getServerName (); - } - - public override bool IsSecure () { - return _HttpServletRequest.isSecure (); - } - - public override void SendStatus (int statusCode, string statusDescription) { - // setStatus(int, string) is deprecated - _HttpServletResponse.setStatus (statusCode/*, statusDescription*/); - } - - public override void SendUnknownResponseHeader (string name, string value) { - if (HeadersSent ()) - return; - - _HttpServletResponse.addHeader (name, value); - } - - public override bool HeadersSent () { - return _HttpServletResponse.isCommitted (); - } - - public override void SendCalculatedContentLength (int contentLength) { - _HttpServletResponse.setContentLength (contentLength); - } - - public override string GetAuthType () { - return _HttpServletRequest.getAuthType (); - } - - protected override int getContentLength () { - return _HttpServletRequest.getContentLength (); - } - - protected override string getContentType () { - return _HttpServletRequest.getContentType (); - } - - public override string GetRemoteUser () { - return _HttpServletRequest.getRemoteUser (); - } - - protected override java.util.Enumeration getHeaderNames () { - return _HttpServletRequest.getHeaderNames (); - } - - protected override string getHeader (string name) { - return _HttpServletRequest.getHeader (name); - } - - protected override java.io.InputStream getInputStream () { - return _HttpServletRequest.getInputStream (); - } - - public override javax.servlet.ServletContext GetContext () { - return _HttpServlet.getServletContext (); - } - - protected override OutputStreamWrapper CreateOutputStream (bool binary) { - return _outputStream ?? (_outputStream = binary ? - new OutputStreamWrapper (_HttpServletResponse.getOutputStream ()) : - new OutputStreamWrapper (_HttpServletResponse.getWriter ())); - } - - public override HttpSession GetSession (bool create) { - return _HttpServletRequest.getSession (create); - } - - public override bool IsRequestedSessionIdValid () { - return _HttpServletRequest.isRequestedSessionIdValid (); - } - public override string GetRequestedSessionId () { - return _HttpServletRequest.getRequestedSessionId (); - } - - public override bool IsUserInRole (string name) { - return _HttpServletRequest.isUserInRole (name); - } - - public override Principal GetUserPrincipal () { - return _HttpServletRequest.getUserPrincipal (); - } - - public override BaseHttpContext CreateContext (System.Web.HttpContext context) { - return new ServletHttpContext (context); - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletWorkerRequest.jvm.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletWorkerRequest.jvm.cs deleted file mode 100644 index 60037a316d3..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/ServletWorkerRequest.jvm.cs +++ /dev/null @@ -1,430 +0,0 @@ -// -// (C) 2005 Mainsoft Corporation (http://www.mainsoft.com) -// - -// -// 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. -// -using System; -using System.IO; -using System.Text; -using System.Runtime.InteropServices; -using System.Web.Util; -using System.Web.J2EE; -using System.Collections; -using System.Web; -using javax.servlet; -using javax.servlet.http; -using System.Collections.Specialized; -using System.Globalization; -using System.Web.Hosting; -using vmw.common; -using InputStream=java.io.InputStream; -using java.security; - -namespace Mainsoft.Web.Hosting { - [MonoTODO("Implement security demands on the path usage functions (and review)")] - [ComVisible (false)] - public abstract class BaseWorkerRequest : HttpWorkerRequest, IHttpExtendedWorkerRequest, IServiceProvider - { - OutputStreamWrapper _OutputStream; - - readonly string _contextPath; - readonly string _requestUri; - readonly string _pathInfo; - - static readonly StringDictionary _srvVarsToHeaderMap; - - private string [][] unknownHeaders; - string _rawUrl; - - private HttpWorkerRequest.EndOfSendNotification _endOfSendCallback; - private object _endOfSendArgs; - - enum KnownServerVariable { - AUTH_TYPE, - CONTENT_LENGTH, - CONTENT_TYPE, - QUERY_STRING, - REMOTE_ADDR, - REMOTE_HOST, - REMOTE_USER, - REQUEST_METHOD, - REQUEST_URI, - SCRIPT_NAME, - SERVER_NAME, - SERVER_PORT, - SERVER_PROTOCOL, - SERVER_SOFTWARE, - PATH_INFO - }; - - static readonly Hashtable KnownServerVariableMap; - - static BaseWorkerRequest() { - _srvVarsToHeaderMap = new StringDictionary(); - _srvVarsToHeaderMap.Add("HTTP_ACCEPT", "Accept"); - _srvVarsToHeaderMap.Add("HTTP_REFERER", "Referer"); - _srvVarsToHeaderMap.Add("HTTP_ACCEPT_LANGUAGE", "Accept-Language"); - _srvVarsToHeaderMap.Add("HTTP_ACCEPT_ENCODING", "Accept-Encoding"); - _srvVarsToHeaderMap.Add("HTTP_CONNECTION", "Connection"); - _srvVarsToHeaderMap.Add("HTTP_HOST", "Host"); - _srvVarsToHeaderMap.Add("HTTP_USER_AGENT", "User-Agent"); - _srvVarsToHeaderMap.Add("HTTP_SOAPACTION", "SOAPAction"); - - string[] knownServerVariableNames = Enum.GetNames(typeof(KnownServerVariable)); - KnownServerVariableMap = CollectionsUtil.CreateCaseInsensitiveHashtable(knownServerVariableNames.Length); - for (int i = 0; i < knownServerVariableNames.Length; i++) - KnownServerVariableMap[knownServerVariableNames[i]] = (KnownServerVariable)i; - } - - public BaseWorkerRequest (string contextPath, string servletPath, string requestURI) { - - - _contextPath = contextPath; - - //string contextPath = req.getContextPath(); - //string servletPath = req.getServletPath (); - //string requestURI = req.getRequestURI (); - // servletPath - Returns the part of this request's URL that calls the servlet. - // so it contains default page. - // requestURI - Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. - // so it contains what the user passed. - // - // the one containing more information wins. - if (contextPath.Length + servletPath.Length > requestURI.Length) - requestURI = contextPath + servletPath; - else { - int contextPos = requestURI.IndexOf(contextPath, StringComparison.Ordinal); - if (contextPos > 0) - requestURI = requestURI.Substring (contextPos); - } - - _requestUri = Uri.UnescapeDataString(requestURI); - const int dotInvokeLength = 7; //".invoke".Length - if (_requestUri.Length > dotInvokeLength && - String.CompareOrdinal(".invoke", 0, _requestUri, - _requestUri.Length - dotInvokeLength, dotInvokeLength) == 0) { - - _requestUri = _requestUri.Substring(0, _requestUri.Length - dotInvokeLength); - - int paramNameStart = _requestUri.LastIndexOf('/'); - _pathInfo = _requestUri.Substring(paramNameStart, _requestUri.Length - paramNameStart); - } - - const int aspnetconfigLength = 12; //"aspnetconfig".Length - int endingSlash = _requestUri [_requestUri.Length - 1] == '/' ? 1 : 0; - if (_requestUri.Length > aspnetconfigLength && - String.CompareOrdinal ("aspnetconfig", 0, _requestUri, - _requestUri.Length - aspnetconfigLength - endingSlash, aspnetconfigLength) == 0) { - - if (endingSlash == 0) - _requestUri += "/"; - _requestUri += "Default.aspx"; - } - } - - static readonly Type typeOfWriter = typeof (java.io.Writer); - public virtual object GetService (Type serviceType) - { - if (serviceType == typeOfWriter) - return CreateOutputStream (false); - return null; - } - - [MonoTODO("Implement security")] - public override string MachineInstallDirectory { - get { - return "."; - } - } - - public override string MachineConfigPath { - get { return "."; } - } - - public override void EndOfRequest () { - if (_endOfSendCallback != null) - _endOfSendCallback(this, _endOfSendArgs); - _OutputStream = null; - } - - public override void FlushResponse (bool finalFlush) { - //kostat - //IPortletActionResponse resp =_HttpServletResponse as IPortletActionResponse; - //if (_OutputStream == null || resp != null && resp.isRedirected()) - // return; - if (_OutputStream == null) - return; - - _OutputStream.flush(); - if (finalFlush) - _OutputStream.close(); - } - - public override string GetAppPath () { - return _contextPath; - } - - public override string GetFilePath () { - string uri = GetUriPath(); - string pathInfo = GetPathInfo(); - if (pathInfo != null && pathInfo.Length > 0) - uri = uri.Substring (0, uri.Length - pathInfo.Length); - - return uri; - } - - public override string GetFilePathTranslated () { - string page = GetFilePath (); - - if (Path.DirectorySeparatorChar != '/') - page = page.Replace ('/', Path.DirectorySeparatorChar); - - if (page [0] == Path.DirectorySeparatorChar) - page = page.Substring (1); - - return Path.Combine (GetAppPathTranslated (), page); - } - - public override string GetPathInfo () { - return _pathInfo; - } - - public override string GetRawUrl () { - if (_rawUrl == null) { - StringBuilder builder = new StringBuilder(); - builder.Append(GetUriPath()); - string pathInfo = GetPathInfo(); - string query = GetQueryString(); - if (query != null && query.Length > 0) { - builder.Append('?'); - builder.Append(query); - } - - _rawUrl = builder.ToString(); - } - - return _rawUrl; - } - - public override string GetServerVariable(string name) { - // FIXME: We need to make a proper mapping between the standard server - // variables and java equivalent. probably we have to have a configuration file - // which associates between the two. Pay a special attention on GetUnknownRequestHeader/s - // while implementing. Ensure that system web "common" code correctly calls each method. - - string headerName = _srvVarsToHeaderMap[name]; - - if (headerName != null) - return getHeader( headerName ); - - object knownVariable = KnownServerVariableMap[name]; - if (knownVariable != null) - return GetKnownServerVariable((KnownServerVariable)knownVariable); - - return getHeader( name ); - } - - public abstract string GetAuthType (); - protected abstract int getContentLength (); - protected abstract string getContentType (); - public abstract string GetRemoteUser (); - protected abstract string getHeader (string name); - protected abstract java.util.Enumeration getHeaderNames (); - protected abstract InputStream getInputStream (); - public abstract ServletContext GetContext (); - protected abstract OutputStreamWrapper CreateOutputStream (bool binary); - - public abstract HttpSession GetSession (bool create); - public abstract bool IsRequestedSessionIdValid (); - public abstract string GetRequestedSessionId (); - public abstract bool IsUserInRole (string name); - public abstract Principal GetUserPrincipal (); - - string GetKnownServerVariable(KnownServerVariable index) { - switch (index) { - case KnownServerVariable.AUTH_TYPE : return GetAuthType(); - case KnownServerVariable.CONTENT_LENGTH : return Convert.ToString(getContentLength()); - case KnownServerVariable.CONTENT_TYPE : return getContentType(); - case KnownServerVariable.QUERY_STRING : return GetQueryString(); - case KnownServerVariable.REMOTE_ADDR : return GetRemoteAddress(); - case KnownServerVariable.REMOTE_HOST : return GetRemoteName(); - case KnownServerVariable.REMOTE_USER : return GetRemoteUser(); - case KnownServerVariable.REQUEST_METHOD : return GetHttpVerbName (); - case KnownServerVariable.REQUEST_URI : return GetUriPath(); - case KnownServerVariable.SCRIPT_NAME : return GetFilePath (); - case KnownServerVariable.SERVER_NAME : return GetServerName(); - case KnownServerVariable.SERVER_PORT : return Convert.ToString(GetLocalPort()); - case KnownServerVariable.SERVER_PROTOCOL : return GetHttpVersion (); - case KnownServerVariable.SERVER_SOFTWARE : return GetContext().getServerInfo(); - case KnownServerVariable.PATH_INFO : return GetPathInfo(); - default: throw new IndexOutOfRangeException("index"); - } - } - - public override string GetUriPath() { - return _requestUri; - } - - public override IntPtr GetUserToken() { - return IntPtr.Zero; - } - - public override string GetAppPathTranslated () { - return J2EEUtils.GetApplicationRealPath (GetContext ()); - } - - public override string MapPath (string virtualPath) { - if (virtualPath == null) - throw new ArgumentNullException ("virtualPath"); - - ServletContext context = GetContext (); - - string contextPath = GetAppPath (); - if ((virtualPath.Length > contextPath.Length && virtualPath [contextPath.Length] != '/') || - string.Compare (contextPath, 0, virtualPath, 0, contextPath.Length, StringComparison.OrdinalIgnoreCase) != 0) { - - for (int appVirtualPathIndex = 0; appVirtualPathIndex > 0 && virtualPath.Length > appVirtualPathIndex; ) { - appVirtualPathIndex = virtualPath.IndexOf ('/', appVirtualPathIndex + 1); - string crossContextPath = appVirtualPathIndex > 0 ? - virtualPath.Remove (appVirtualPathIndex) : virtualPath; - ServletContext other = context.getContext (crossContextPath); - if (other != null) { - string appVirtualPath = appVirtualPathIndex > 0 ? - virtualPath.Substring (appVirtualPathIndex) : String.Empty; - return other.getRealPath (appVirtualPath); - } - } - - throw new HttpException ( - String.Format ("MapPath: Mapping across applications is not allowed. ApplicationPath is '{0}', VirtualPath is '{1}'.", - contextPath, virtualPath)); - } - - string thisAppVirtualPath = virtualPath.Length > contextPath.Length ? virtualPath.Substring (contextPath.Length) : String.Empty; - return J2EEUtils.GetApplicationRealPath (context, thisAppVirtualPath); - - } - - public override void SendResponseFromFile (IntPtr handle, long offset, long length) { - throw new NotSupportedException(); - } - - public override void SendResponseFromFile (string filename, long offset, long length) { - using (FileStream fs = File.OpenRead (filename)) { - byte [] buffer = new byte [4 * 1024]; - - if (offset != 0) - fs.Position = offset; - - long remain = length; - int n; - while (remain > 0 && (n = fs.Read (buffer, 0, (int) Math.Min (remain, buffer.Length))) != 0){ - remain -= n; - SendResponseFromMemory(buffer, n); - } - } - } - - //kostat - //private OutputStreamWrapper CreateOutputStream (bool binary) - //{ - // IPortletActionResponse resp = _HttpServletResponse as IPortletActionResponse; - // if (resp != null) - // return null; // no output stream while processAction - - // if (_OutputStream != null) - // return _OutputStream; - - // if (_HttpServletResponse != null) { - // if (binary) - // _OutputStream = new OutputStreamWrapper (_HttpServletResponse.getOutputStream ()); - // else - // _OutputStream = new OutputStreamWrapper (_HttpServletResponse.getWriter ()); - // } - - // return _OutputStream; - //} - - public override void SendResponseFromMemory (byte [] data, int length) { - _OutputStream = CreateOutputStream (true); - - if (_OutputStream == null) - return; - - sbyte [] sdata = vmw.common.TypeUtils.ToSByteArray(data); - _OutputStream.write(sdata, 0 , length); - } - - public override void SendKnownResponseHeader (int index, string value) { - SendUnknownResponseHeader (GetKnownResponseHeaderName (index), value); - } - - public override string GetKnownRequestHeader (int index) { - return GetUnknownRequestHeader(GetKnownRequestHeaderName (index)); - } - - public override string GetUnknownRequestHeader (string name) { - return getHeader(name); - } - - public override string [][] GetUnknownRequestHeaders () { - if (unknownHeaders == null) { - ArrayList pairs = new ArrayList (); - for (java.util.Enumeration he = getHeaderNames(); he.hasMoreElements() ;) { - string key = (string) he.nextElement(); - int index = HttpWorkerRequest.GetKnownRequestHeaderIndex (key); - if (index != -1) - continue; - pairs.Add (new string [] {key, getHeader(key)}); - } - - if (pairs.Count != 0) { - unknownHeaders = new string [pairs.Count][]; - for (int i = 0; i < pairs.Count; i++) - unknownHeaders [i] = (string []) pairs [i]; - } - } - if (unknownHeaders == null) unknownHeaders = new string [0][]; - - return unknownHeaders; - } - - public override int ReadEntityBody (byte [] buffer, int size) { - if (buffer == null || size == 0) - return 0; - sbyte [] sbuffer = vmw.common.TypeUtils.ToSByteArray(buffer); - InputStream inp = getInputStream(); - if (inp == null) - return 0; - int r = inp.read (sbuffer, 0, size); - return r < 0 ? 0 : r; - } - - public override void SetEndOfSendNotification(System.Web.HttpWorkerRequest.EndOfSendNotification callback, object extraData) { - _endOfSendCallback = callback; - _endOfSendArgs = extraData; - } - - public abstract BaseHttpContext CreateContext (HttpContext context); - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/SessionWrapper.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/SessionWrapper.cs deleted file mode 100644 index 5af48a48123..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Hosting/SessionWrapper.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Web; -using System.Web.J2EE; -using System.Web.SessionState; - -namespace Mainsoft.Web.Hosting -{ - public static class SessionWrapper - { - static readonly Type IRequiresSessionStateType = typeof (IRequiresSessionState); - static readonly Type IReadOnlySessionStateType = typeof (IReadOnlySessionState); - - public static IHttpHandler WrapHandler (IHttpHandler handler) { - Type type = (Type) ((IServiceProvider) handler).GetService (typeof (Type)); - - if (IRequiresSessionStateType.IsAssignableFrom (type)) - return IReadOnlySessionStateType.IsAssignableFrom (type) ? - (handler is IHttpExtendedHandler ? (IHttpHandler) new ReadOnlySessionWrapperExtendedHandler ((IHttpExtendedHandler) handler) : new ReadOnlySessionWrapperHandler (handler)) : - (handler is IHttpExtendedHandler ? new SessionWrapperExtendedHandler ((IHttpExtendedHandler) handler) : new SessionWrapperHandler (handler)); - return handler; - } - - #region SessionWrappers - - class SessionWrapperHandler : IHttpHandler, IRequiresSessionState, IServiceProvider - { - protected readonly IHttpHandler _handler; - - public SessionWrapperHandler (IHttpHandler handler) { - _handler = handler; - } - - public bool IsReusable { - get { return _handler.IsReusable; } - } - - public void ProcessRequest (HttpContext context) { - _handler.ProcessRequest (context); - } - - public object GetService (Type serviceType) { - return ((IServiceProvider) _handler).GetService (serviceType); - } - } - - sealed class ReadOnlySessionWrapperHandler : SessionWrapperHandler, IReadOnlySessionState - { - public ReadOnlySessionWrapperHandler (IHttpHandler handler) : base (handler) { } - } - - #endregion - - #region ExtendedSessionWrappers - - class SessionWrapperExtendedHandler : SessionWrapperHandler, IHttpExtendedHandler - { - public SessionWrapperExtendedHandler (IHttpExtendedHandler handler) - : base (handler) { - } - - public bool IsCompleted { - get { return ((IHttpExtendedHandler) _handler).IsCompleted; } - } - } - - sealed class ReadOnlySessionWrapperExtendedHandler : SessionWrapperExtendedHandler, IReadOnlySessionState - { - public ReadOnlySessionWrapperExtendedHandler (IHttpExtendedHandler handler) : base (handler) { } - } - - #endregion - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.J2EE.csproj b/mcs/class/Mainsoft.Web/Mainsoft.Web.J2EE.csproj deleted file mode 100644 index daf6b865013..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.J2EE.csproj +++ /dev/null @@ -1,150 +0,0 @@ - - - Debug_Java - AnyCPU - 8.0.50727 - 2.0 - {77DE6DDE-B8D4-4710-ADB3-4D5C3F4058C8} - Library - Properties - Mainsoft.Web - 1.4.2 - 1 - 2.0 - Mainsoft.Web - iap2 - - - {F6B19D50-1E2E-4e87-ADFB-10393B439DE0};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - - bin\Release_Java\ - JAVA;NET_2_0 - 285212672 - true - pdbonly - AnyCPU - prompt - false - false - 1 - false - - - - - 2.0 - 1.4.2 - iap2 - 0 - bin\Release_Java\Mainsoft.Web.XML - - - true - bin\Debug_Java\ - TRACE;DEBUG;JAVA;NET_2_0 - 285212672 - full - AnyCPU - prompt - True - False - 1 - false - - - - - 2.0 - 1.4.2 - iap2 - 0 - bin\Debug_Java\Mainsoft.Web.XML - - - - - - - - - - - - ..\lib\J2SE.Helpers.dll - False - - - - - - - - - - - - - MonoTODOAttribute.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {FBFDAD51-74B6-4660-81C0-9C8B6C8D3B47} - System.Web.Phantom - False - - - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Profile/.gitattributes b/mcs/class/Mainsoft.Web/Mainsoft.Web.Profile/.gitattributes deleted file mode 100644 index 4f3bf364d1b..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Profile/.gitattributes +++ /dev/null @@ -1,3 +0,0 @@ -/CloudscapeProfileProvider.cs -crlf -/DerbyProfileHelper.cs -crlf -/DerbyProfileProvider.cs -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Profile/CloudscapeProfileProvider.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Profile/CloudscapeProfileProvider.cs deleted file mode 100644 index 34eac6ebe24..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Profile/CloudscapeProfileProvider.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// Mainsoft.Web.Profile.CloudscapeProfileProvider -// -// Authors: -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// (C) 2006 Mainsoft -// -// 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. -// - -using System; -using System.Collections.Specialized; -using System.Text; - -namespace Mainsoft.Web.Profile -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - [Obsolete] - public class CloudscapeProfileProvider : DerbyProfileProvider - { - public override void Initialize (string name, NameValueCollection config) - { - if (string.IsNullOrEmpty (name)) - name = "CloudscapeProfileProvider"; - - base.Initialize (name, config); - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Profile/DerbyProfileHelper.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Profile/DerbyProfileHelper.cs deleted file mode 100644 index f67a38b42f8..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Profile/DerbyProfileHelper.cs +++ /dev/null @@ -1,288 +0,0 @@ -// -// Mainsoft.Web.Profile.DerbyProfileHelper -// -// Authors: -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// (C) 2006 Mainsoft -// -// 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. -// - - -using System; -using System.Web.Security; -using System.Web.Configuration; -using System.Data; -using System.Data.OleDb; -using System.Data.Common; -using System.Collections.Generic; -using System.Text; - -using Mainsoft.Web.Security; - -namespace Mainsoft.Web.Profile -{ - class DerbyProfileHelper - { - private static OleDbParameter AddParameter (OleDbCommand command, string paramName, object paramValue) - { - OleDbParameter prm = new OleDbParameter (paramName, paramValue); - command.Parameters.Add (prm); - return prm; - } - - public static int Profile_DeleteInactiveProfiles(DbConnection connection, string applicationName, int profileAuthOptions, DateTime inactiveSinceDate) - { - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return 0; - - string queryDelete = @"DELETE FROM aspnet_Profile WHERE UserId IN ( " + - "SELECT UserId FROM aspnet_Users WHERE ApplicationId = ? AND LastActivityDate <= ? " + - GetProfileAuthOptions (profileAuthOptions) + ")"; - OleDbCommand cmdDelete = new OleDbCommand (queryDelete, (OleDbConnection) connection); - AddParameter (cmdDelete, "ApplicationId", appId); - AddParameter (cmdDelete, "LastActivityDate", inactiveSinceDate); - - return cmdDelete.ExecuteNonQuery (); - } - - public static int Profile_DeleteProfiles(DbConnection connection, string applicationName, string [] userNames) - { - int deletedUsers = 0; - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return 0; - - OleDbTransaction trans = (OleDbTransaction) connection.BeginTransaction (); - try { - foreach (string username in userNames) { - string userId = GetUserId (connection, trans, appId, username); - if (userId == null) - continue; - - string queryDelete = "DELETE FROM aspnet_Profile WHERE UserId = ?"; - OleDbCommand cmdDelete = new OleDbCommand (queryDelete, (OleDbConnection) connection); - cmdDelete.Transaction = trans; - AddParameter (cmdDelete, "UserId", userId); - cmdDelete.Transaction = trans; - deletedUsers += cmdDelete.ExecuteNonQuery (); - } - trans.Commit (); - return deletedUsers; - } - catch (Exception e) { - trans.Rollback (); - throw e; - } - } - - public static int Profile_GetNumberOfInactiveProfiles (DbConnection connection, string applicationName, int profileAuthOptions, DateTime inactiveSinceDate) - { - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return 0; - - string querySelect = @"SELECT COUNT(*) FROM aspnet_Users usr, aspnet_Profile prf WHERE ApplicationId = ? " + - "AND usr.UserId = prf.UserId AND LastActivityDate <= ? " + GetProfileAuthOptions(profileAuthOptions); - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "ApplicationId", appId); - AddParameter (cmdSelect, "LastActivityDate", inactiveSinceDate); - - using (OleDbDataReader reader = cmdSelect.ExecuteReader ()) { - if (reader.Read ()) - return reader.GetInt32 (0); - } - return 0; - } - - public static int Profile_GetInactiveProfiles (DbConnection connection, string applicationName, int profileAuthOptions, int pageIndex, int pageSize, string userNameToMatch, DateTime inactiveSinceDate, out DbDataReader reader) - { - reader = null; - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return -1; - - string querySelect = @"SELECT usr.UserName, usr.IsAnonymous, usr.LastActivityDate, prf.LastUpdatedDate, " + - "LENGTH(prf.PropertyNames) + LENGTH(prf.PropertyValuesString) + LENGTH(prf.PropertyValuesBinary)" + - "FROM aspnet_Users usr, aspnet_Profile prf WHERE usr.ApplicationId = ? AND usr.UserId = prf.UserId " + - "AND usr.LastActivityDate <= ? " + GetProfileAuthOptions (profileAuthOptions) + - (string.IsNullOrEmpty(userNameToMatch) ? "" : " AND usr.LoweredUserName LIKE ?"); - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "ApplicationId", appId); - AddParameter (cmdSelect, "LastActivityDate", inactiveSinceDate); - if (!string.IsNullOrEmpty (userNameToMatch)) - AddParameter (cmdSelect, "LoweredUserName", userNameToMatch.ToLowerInvariant()); - reader = cmdSelect.ExecuteReader (); - return 0; - } - - public static int Profile_GetProfiles (DbConnection connection, string applicationName, int profileAuthOptions, int pageIndex, int pageSize, string userNameToMatch, out DbDataReader reader) - { - reader = null; - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return -1; - - string querySelect = @"SELECT usr.UserName, usr.IsAnonymous, usr.LastActivityDate, prf.LastUpdatedDate, " + - "LENGTH(prf.PropertyNames) + LENGTH(prf.PropertyValuesString) + LENGTH(prf.PropertyValuesBinary)" + - "FROM aspnet_Users usr, aspnet_Profile prf WHERE ApplicationId = ? AND usr.UserId = prf.UserId " + - GetProfileAuthOptions (profileAuthOptions) + - (string.IsNullOrEmpty (userNameToMatch) ? "" : " AND usr.LoweredUserName LIKE ?"); - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "ApplicationId", appId); - if (!string.IsNullOrEmpty (userNameToMatch)) - AddParameter (cmdSelect, "LoweredUserName", userNameToMatch.ToLowerInvariant ()); - reader = cmdSelect.ExecuteReader (); - return 0; - } - - public static int Profile_GetProperties (DbConnection connection, string applicationName, string username, DateTime currentTimeUtc, out DbDataReader reader) - { - reader = null; - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return -1; - - string userId = GetUserId (connection, null, appId, username); - if (userId == null) - return -1; - - string queryUpdUser = @"UPDATE aspnet_Users SET LastActivityDate = ? WHERE UserId = ?"; - OleDbCommand cmdUpdUser = new OleDbCommand (queryUpdUser, (OleDbConnection) connection); - AddParameter (cmdUpdUser, "LastActivityDate", currentTimeUtc); - AddParameter (cmdUpdUser, "UserId", userId); - cmdUpdUser.ExecuteNonQuery (); - - string querySelect = @"SELECT PropertyNames, PropertyValuesString, PropertyValuesBinary FROM aspnet_Profile WHERE UserId = ?"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "UserId", userId); - reader = cmdSelect.ExecuteReader (); - return 0; - } - - public static int Profile_SetProperties (DbConnection connection, string applicationName, string propertyNames, string propertyValuesString, byte [] propertyValuesBinary, string username, bool isUserAnonymous, DateTime currentTimeUtc) - { - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) { - object newAppId = DerbyApplicationsHelper.Applications_CreateApplication (connection, applicationName); - appId = newAppId as string; - if (appId == null) - return -1; - } - - OleDbTransaction trans = (OleDbTransaction) connection.BeginTransaction (); - try { - string userId = GetUserId (connection, trans, appId, username); - if (userId == null) { - object newUserId = null; - DerbyMembershipHelper.Users_CreateUser (connection, trans, appId, username, true, currentTimeUtc, ref newUserId); - userId = newUserId as string; - if (userId == null) { - trans.Rollback (); - return -1; - } - } - - string queryUpdUser = @"UPDATE aspnet_Users SET LastActivityDate=? WHERE UserId = ?"; - OleDbCommand cmdUpdUser = new OleDbCommand (queryUpdUser, (OleDbConnection) connection); - cmdUpdUser.Transaction = trans; - AddParameter (cmdUpdUser, "LastActivityDate", currentTimeUtc); - AddParameter (cmdUpdUser, "UserId", userId); - cmdUpdUser.ExecuteNonQuery (); - - string querySelect = @"SELECT * FROM aspnet_Profile WHERE UserId = ?"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - cmdSelect.Transaction = trans; - AddParameter (cmdSelect, "UserId", userId); - bool userHasRecords = false; - using (OleDbDataReader reader = cmdSelect.ExecuteReader ()) { - userHasRecords = reader.HasRows; - } - - if (userHasRecords) { - string queryUpdate = @"UPDATE aspnet_Profile SET PropertyNames = ?, PropertyValuesString = ?, " + - "PropertyValuesBinary = ?, LastUpdatedDate = ? WHERE UserId = ?"; - OleDbCommand cmdUpdate = new OleDbCommand (queryUpdate, (OleDbConnection) connection); - cmdUpdate.Transaction = trans; - AddParameter (cmdUpdate, "PropertyNames", propertyNames); - AddParameter (cmdUpdate, "PropertyValuesString", propertyValuesString); - AddParameter (cmdUpdate, "PropertyValuesBinary", propertyValuesBinary); - AddParameter (cmdUpdate, "LastUpdatedDate", currentTimeUtc); - AddParameter (cmdUpdate, "UserId", userId); - cmdUpdate.ExecuteNonQuery (); - } - else { - string queryInsert = @"INSERT INTO aspnet_Profile(UserId, PropertyNames, PropertyValuesString, " + - "PropertyValuesBinary, LastUpdatedDate) VALUES (?, ?, ?, ?, ?)"; - OleDbCommand cmdInsert = new OleDbCommand (queryInsert, (OleDbConnection) connection); - cmdInsert.Transaction = trans; - AddParameter (cmdInsert, "UserId", userId); - AddParameter (cmdInsert, "PropertyNames", propertyNames); - AddParameter (cmdInsert, "PropertyValuesString", propertyValuesString); - AddParameter (cmdInsert, "PropertyValuesBinary", propertyValuesBinary); - AddParameter (cmdInsert, "LastUpdatedDate", currentTimeUtc); - cmdInsert.ExecuteNonQuery (); - } - trans.Commit (); - } - catch (Exception e) { - trans.Rollback (); - throw e; - } - return 0; - } - - private static string GetUserId (DbConnection connection, DbTransaction trans, string applicationId, string username) - { - if (username == null) - return null; - - string selectQuery = "SELECT UserId FROM aspnet_Users WHERE LoweredUserName = ? AND ApplicationId = ?"; - - OleDbCommand selectCmd = new OleDbCommand (selectQuery, (OleDbConnection) connection); - if (trans != null) - selectCmd.Transaction = (OleDbTransaction) trans; - - AddParameter (selectCmd, "LoweredUserName", username.ToLowerInvariant ()); - AddParameter (selectCmd, "ApplicationId", applicationId); - using (OleDbDataReader reader = selectCmd.ExecuteReader ()) { - if (reader.Read ()) - return reader.GetString (0); - } - - return null; - } - - private static string GetProfileAuthOptions (int profileAuthOptions) - { - switch (profileAuthOptions) { - case 1: - return "AND IsAnonymous = 0"; - - case 2: - return "AND IsAnonymous = 1"; - } - return string.Empty; - } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Profile/DerbyProfileProvider.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Profile/DerbyProfileProvider.cs deleted file mode 100644 index 95a4a89ac05..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Profile/DerbyProfileProvider.cs +++ /dev/null @@ -1,471 +0,0 @@ -// -// Mainsoft.Web.Profile.DerbyProfileProvider -// -// Authors: -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// (C) 2006 Mainsoft -// -// 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. -// - - -using System; -using System.Data.OleDb; -using System.Data.Common; -using System.Collections; -using System.Configuration; -using System.Globalization; -using System.Web.Profile; -using System.Web.Configuration; -using System.Collections.Specialized; -using System.Text; -using System.IO; - -using Mainsoft.Web.Security; -using System.Configuration.Provider; - -namespace Mainsoft.Web.Profile -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// Manages storage of profile information for an ASP.NET application in a Derby database. - /// - public class DerbyProfileProvider : ProfileProvider - { - ConnectionStringSettings _connectionString; - string _applicationName = string.Empty; - bool _schemaChecked = false; - DerbyUnloadManager.DerbyShutDownPolicy _shutDownPolicy = DerbyUnloadManager.DerbyShutDownPolicy.Default; - - public DerbyProfileProvider () - { - } - - public override string ApplicationName - { - get { return _applicationName; } - set { _applicationName = value; } - } - - DbConnection CreateConnection () - { - if (!_schemaChecked) { - DerbyDBSchema.CheckSchema (_connectionString.ConnectionString); - _schemaChecked = true; - - DerbyUnloadManager.RegisterUnloadHandler (_connectionString.ConnectionString, _shutDownPolicy); - } - - OleDbConnection connection = new OleDbConnection (_connectionString.ConnectionString); - connection.Open (); - return connection; - } - - public override int DeleteInactiveProfiles (ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) - { - using (DbConnection connection = CreateConnection ()) { - return DerbyProfileHelper.Profile_DeleteInactiveProfiles (connection, ApplicationName, (int) authenticationOption, userInactiveSinceDate); - } - } - - public override int DeleteProfiles (ProfileInfoCollection profiles) - { - if (profiles == null) - throw new ArgumentNullException ("profiles"); - if (profiles.Count == 0) - throw new ArgumentException ("profiles"); - - string [] usernames = new string [profiles.Count]; - - int i = 0; - foreach (ProfileInfo pi in profiles) { - if (pi.UserName == null) - throw new ArgumentNullException ("element in profiles collection is null"); - - if (pi.UserName.Length == 0 || pi.UserName.Length > 256 || pi.UserName.IndexOf (",") != -1) - throw new ArgumentException ("element in profiles collection in illegal format"); - - usernames [i++] = pi.UserName; - } - - return DeleteProfilesInternal (usernames); - } - - public override int DeleteProfiles (string [] usernames) - { - if (usernames == null) - throw new ArgumentNullException ("usernames"); - - Hashtable users = new Hashtable (); - foreach (string username in usernames) { - if (username == null) - throw new ArgumentNullException ("element in usernames array is null"); - - if (username.Length == 0 || username.Length > 256 || username.IndexOf (",") != -1) - throw new ArgumentException ("element in usernames array in illegal format"); - - if (users.ContainsKey (username)) - throw new ArgumentException ("duplicate element in usernames array"); - - users.Add (username, username); - } - - return DeleteProfilesInternal (usernames); - } - - private int DeleteProfilesInternal (string[] usernames) - { - using (DbConnection connection = CreateConnection ()) { - return DerbyProfileHelper.Profile_DeleteProfiles (connection, ApplicationName, usernames); - } - } - - public override ProfileInfoCollection FindInactiveProfilesByUserName (ProfileAuthenticationOption authenticationOption, - string usernameToMatch, - DateTime userInactiveSinceDate, - int pageIndex, - int pageSize, - out int totalRecords) - { - CheckParam ("usernameToMatch", usernameToMatch, 256); - if (pageIndex < 0) - throw new ArgumentException ("pageIndex is less than zero"); - if (pageSize < 1) - throw new ArgumentException ("pageIndex is less than one"); - if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue) - throw new ArgumentException ("pageIndex and pageSize are too large"); - - DbDataReader reader = null; - using (DbConnection connection = CreateConnection ()) { - totalRecords = DerbyProfileHelper.Profile_GetInactiveProfiles (connection, ApplicationName, (int) authenticationOption, pageIndex, pageSize, usernameToMatch, userInactiveSinceDate, out reader); - - using (reader) { - return BuildProfileInfoCollection (reader, pageIndex, pageSize, out totalRecords); - } - } - } - - public override ProfileInfoCollection FindProfilesByUserName (ProfileAuthenticationOption authenticationOption, - string usernameToMatch, - int pageIndex, - int pageSize, - out int totalRecords) - { - CheckParam ("usernameToMatch", usernameToMatch, 256); - if (pageIndex < 0) - throw new ArgumentException ("pageIndex is less than zero"); - if (pageSize < 1) - throw new ArgumentException ("pageIndex is less than one"); - if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue) - throw new ArgumentException ("pageIndex and pageSize are too large"); - - DbDataReader reader = null; - using (DbConnection connection = CreateConnection ()) { - totalRecords = DerbyProfileHelper.Profile_GetProfiles (connection, ApplicationName, (int) authenticationOption, pageIndex, pageSize, usernameToMatch, out reader); - - using (reader) { - return BuildProfileInfoCollection (reader, pageIndex, pageSize, out totalRecords); - } - } - } - - public override ProfileInfoCollection GetAllInactiveProfiles (ProfileAuthenticationOption authenticationOption, - DateTime userInactiveSinceDate, - int pageIndex, - int pageSize, - out int totalRecords) - { - if (pageIndex < 0) - throw new ArgumentException ("pageIndex is less than zero"); - if (pageSize < 1) - throw new ArgumentException ("pageIndex is less than one"); - if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue) - throw new ArgumentException ("pageIndex and pageSize are too large"); - - DbDataReader reader = null; - using (DbConnection connection = CreateConnection ()) { - totalRecords = DerbyProfileHelper.Profile_GetInactiveProfiles ( - connection, ApplicationName, (int) authenticationOption, - pageIndex, pageSize, null, userInactiveSinceDate, out reader); - - using (reader) { - return BuildProfileInfoCollection (reader, pageIndex, pageSize, out totalRecords); - } - } - } - - public override ProfileInfoCollection GetAllProfiles (ProfileAuthenticationOption authenticationOption, - int pageIndex, - int pageSize, - out int totalRecords) - { - if (pageIndex < 0) - throw new ArgumentException ("pageIndex is less than zero"); - if (pageSize < 1) - throw new ArgumentException ("pageIndex is less than one"); - if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue) - throw new ArgumentException ("pageIndex and pageSize are too large"); - - DbDataReader reader = null; - using (DbConnection connection = CreateConnection ()) { - totalRecords = DerbyProfileHelper.Profile_GetProfiles ( - connection, ApplicationName, (int) authenticationOption, - pageIndex, pageSize, null, out reader); - - using (reader) { - return BuildProfileInfoCollection (reader, pageIndex, pageSize, out totalRecords); - } - } - } - - public override int GetNumberOfInactiveProfiles (ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) - { - using (DbConnection connection = CreateConnection ()) { - return DerbyProfileHelper.Profile_GetNumberOfInactiveProfiles ( - connection, ApplicationName, (int) authenticationOption, userInactiveSinceDate); - } - } - - public override SettingsPropertyValueCollection GetPropertyValues (SettingsContext sc, SettingsPropertyCollection properties) - { - SettingsPropertyValueCollection settings = new SettingsPropertyValueCollection (); - - if (properties.Count == 0) - return settings; - - foreach (SettingsProperty property in properties) { - if (property.SerializeAs == SettingsSerializeAs.ProviderSpecific) - if (property.PropertyType.IsPrimitive || property.PropertyType == typeof (String)) - property.SerializeAs = SettingsSerializeAs.String; - else - property.SerializeAs = SettingsSerializeAs.Xml; - - settings.Add (new SettingsPropertyValue (property)); - } - - string username = (string) sc ["UserName"]; - - DbDataReader reader; - using (DbConnection connection = CreateConnection ()) { - DerbyProfileHelper.Profile_GetProperties (connection, ApplicationName, username, DateTime.UtcNow, out reader); - if (reader != null) { - using (reader) { - if (reader.Read ()) { - string allnames = reader.GetString (0); - string allvalues = reader.GetString (1); - int binaryLen = (int) reader.GetBytes (2, 0, null, 0, 0); - byte [] binaryvalues = new byte [binaryLen]; - reader.GetBytes (2, 0, binaryvalues, 0, binaryLen); - - DecodeProfileData (allnames, allvalues, binaryvalues, settings); - } - } - } - } - return settings; - } - - public override void SetPropertyValues (SettingsContext sc, SettingsPropertyValueCollection properties) - { - string username = (string) sc ["UserName"]; - bool authenticated = (bool) sc ["IsAuthenticated"]; - - string names = String.Empty; - string values = String.Empty; - byte [] buf = null; - - EncodeProfileData (ref names, ref values, ref buf, properties, authenticated); - - using (DbConnection connection = CreateConnection ()) { - DerbyProfileHelper.Profile_SetProperties ( - connection, _applicationName, names, values, - buf, username, authenticated, DateTime.UtcNow); - } - } - - public override void Initialize (string name, NameValueCollection config) - { - if (config == null) - throw new ArgumentNullException ("config"); - - if (string.IsNullOrEmpty (name)) - name = "DerbyProfileProvider"; - - if (string.IsNullOrEmpty (config ["description"])) { - config.Remove ("description"); - config.Add ("description", "Derby profile provider"); - } - base.Initialize (name, config); - - _applicationName = GetStringConfigValue (config, "applicationName", "/"); - - ProfileSection profileSection = (ProfileSection) WebConfigurationManager.GetSection ("system.web/profile"); - string connectionStringName = config ["connectionStringName"]; - _connectionString = WebConfigurationManager.ConnectionStrings [connectionStringName]; - if (_connectionString == null) - throw new ProviderException (String.Format ("The connection name '{0}' was not found in the applications configuration or the connection string is empty.", connectionStringName)); - - string shutdown = config ["shutdown"]; - if (!String.IsNullOrEmpty (shutdown)) - _shutDownPolicy = (DerbyUnloadManager.DerbyShutDownPolicy) Enum.Parse (typeof (DerbyUnloadManager.DerbyShutDownPolicy), shutdown, true); - } - - private ProfileInfoCollection BuildProfileInfoCollection (DbDataReader reader, int pageIndex, int pageSize, out int totalRecords) - { - int num_read = 0; - int num_added = 0; - int num_to_skip = pageIndex * pageSize; - ProfileInfoCollection pic = new ProfileInfoCollection (); - - while (reader.Read ()) { - if (num_read >= num_to_skip && num_added < pageSize) { - ProfileInfo pi = ReadProfileInfo (reader); - if (pi != null) { - pic.Add (pi); - num_added++; - } - } - num_read++; - } - totalRecords = num_read; - return pic; - } - - private ProfileInfo ReadProfileInfo (DbDataReader reader) - { - string username = reader.GetString (0); - bool anonymous = reader.GetInt32 (1) > 0; - DateTime lastUpdate = reader.GetDateTime (2); - DateTime lastActivity = reader.GetDateTime (3); - int size = reader.GetInt32 (4); - - return new ProfileInfo (username, anonymous, lastActivity, lastUpdate, size); - } - - // Helper methods - private void DecodeProfileData (string allnames, string values, byte [] buf, SettingsPropertyValueCollection properties) - { - if (allnames == null || values == null || buf == null || properties == null) - return; - - string [] names = allnames.Split (':'); - for (int i = 0; i < names.Length; i += 4) { - string name = names [i]; - SettingsPropertyValue pp = properties [name]; - - if (pp == null) - continue; - - int pos = Int32.Parse (names [i + 2], CultureInfo.InvariantCulture); - int len = Int32.Parse (names [i + 3], CultureInfo.InvariantCulture); - - if (len == -1 && !pp.Property.PropertyType.IsValueType) { - pp.PropertyValue = null; - pp.IsDirty = false; - pp.Deserialized = true; - } - else if (names [i + 1] == "S" && pos >= 0 && len > 0 && values.Length >= pos + len) { - pp.SerializedValue = values.Substring (pos, len); - } - else if (names [i + 1] == "B" && pos >= 0 && len > 0 && buf.Length >= pos + len) { - byte [] buf2 = new byte [len]; - Buffer.BlockCopy (buf, pos, buf2, 0, len); - pp.SerializedValue = buf2; - } - } - } - - private void EncodeProfileData (ref string allNames, ref string allValues, ref byte [] buf, SettingsPropertyValueCollection properties, bool userIsAuthenticated) - { - StringBuilder names = new StringBuilder (); - StringBuilder values = new StringBuilder (); - MemoryStream stream = new MemoryStream (); - - try { - foreach (SettingsPropertyValue pp in properties) { - if (!userIsAuthenticated && !(bool) pp.Property.Attributes ["AllowAnonymous"]) - continue; - - if (!pp.IsDirty && pp.UsingDefaultValue) - continue; - - int len = 0, pos = 0; - string propValue = null; - - if (pp.Deserialized && pp.PropertyValue == null) - len = -1; - else { - object sVal = pp.SerializedValue; - - if (sVal == null) - len = -1; - else if (sVal is string) { - propValue = (string) sVal; - len = propValue.Length; - pos = values.Length; - } - else { - byte [] b2 = (byte []) sVal; - pos = (int) stream.Position; - stream.Write (b2, 0, b2.Length); - stream.Position = pos + b2.Length; - len = b2.Length; - } - } - - names.Append (pp.Name + ":" + ((propValue != null) ? "S" : "B") + ":" + pos.ToString (CultureInfo.InvariantCulture) + ":" + len.ToString (CultureInfo.InvariantCulture) + ":"); - - if (propValue != null) - values.Append (propValue); - } - - buf = stream.ToArray (); - } - finally { - if (stream != null) - stream.Close (); - } - - allNames = names.ToString (); - allValues = values.ToString (); - } - - string GetStringConfigValue (NameValueCollection config, string name, string def) - { - string rv = def; - string val = config [name]; - if (val != null) - rv = val; - return rv; - } - - void CheckParam (string pName, string p, int length) - { - if (p == null) - throw new ArgumentNullException (pName); - if (p.Length == 0 || p.Length > length || p.IndexOf (",") != -1) - throw new ArgumentException (String.Format ("invalid format for {0}", pName)); - } - - - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/.gitattributes b/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/.gitattributes deleted file mode 100644 index dc336de8ef1..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/.gitattributes +++ /dev/null @@ -1,7 +0,0 @@ -/CloudscapeMembershipProvider.cs -crlf -/CloudscapeRoleProvider.cs -crlf -/DerbyApplicationsHelper.cs -crlf -/DerbyMembershipHelper.cs -crlf -/DerbyMembershipProvider.cs -crlf -/DerbyRoleProvider.cs -crlf -/DerbyRolesHelper.cs -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/CloudscapeMembershipProvider.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/CloudscapeMembershipProvider.cs deleted file mode 100644 index f5957cd8ee2..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/CloudscapeMembershipProvider.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// Mainsoft.Web.Security.CloudscapeMembershipProvider -// -// Authors: -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// (C) 2006 Mainsoft -// -// 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. -// - -using System; -using System.Collections.Specialized; -using System.Text; - -namespace Mainsoft.Web.Security -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - [Obsolete] - public class CloudscapeMembershipProvider : DerbyMembershipProvider - { - public override void Initialize (string name, NameValueCollection config) - { - if (string.IsNullOrEmpty (name)) - name = "CloudscapeMembershipProvider"; - - base.Initialize (name, config); - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/CloudscapeRoleProvider.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/CloudscapeRoleProvider.cs deleted file mode 100644 index 8e0fb05f1e8..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/CloudscapeRoleProvider.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// Mainsoft.Web.Security.CloudscapeRoleProvider -// -// Authors: -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// (C) 2006 Mainsoft -// -// 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. -// - -using System; -using System.Collections.Specialized; -using System.Text; - -namespace Mainsoft.Web.Security -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - [Obsolete] - public class CloudscapeRoleProvider : DerbyRoleProvider - { - public override void Initialize (string name, NameValueCollection config) - { - if (string.IsNullOrEmpty (name)) - name = "CloudscapeRoleProvider"; - - base.Initialize (name, config); - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyApplicationsHelper.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyApplicationsHelper.cs deleted file mode 100644 index 28cf3e63cd5..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyApplicationsHelper.cs +++ /dev/null @@ -1,87 +0,0 @@ -// -// Mainsoft.Web.Security.DerbyApplicationsHelper -// -// Authors: -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// (C) 2006 Mainsoft -// -// 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. -// - - -using System; -using System.Web.Security; -using System.Data; -using System.Data.OleDb; -using System.Data.Common; -using System.Collections.Generic; -using System.Text; - -namespace Mainsoft.Web.Security -{ - static class DerbyApplicationsHelper - { - private static OleDbParameter AddParameter (OleDbCommand command, string paramName, object paramValue) - { - OleDbParameter prm = new OleDbParameter (paramName, paramValue); - command.Parameters.Add (prm); - return prm; - } - - public static object Applications_CreateApplication (DbConnection connection, string applicationName) - { - string selectQuery = "SELECT ApplicationId FROM aspnet_Applications WHERE LoweredApplicationName = ?"; - string insertQuery = "INSERT INTO aspnet_Applications (ApplicationId, ApplicationName, LoweredApplicationName) VALUES (?, ?, ?)"; - - OleDbCommand selectCmd = new OleDbCommand (selectQuery, (OleDbConnection) connection); - AddParameter (selectCmd, "LoweredApplicationName", applicationName.ToLowerInvariant ()); - - using (OleDbDataReader reader = selectCmd.ExecuteReader ()) { - if (reader.Read ()) - return reader.GetString (0); - } - - string applicationId = Guid.NewGuid ().ToString (); - OleDbCommand insertCmd = new OleDbCommand (insertQuery, (OleDbConnection) connection); - AddParameter (insertCmd, "ApplicationId", applicationId); - AddParameter (insertCmd, "ApplicationName", applicationName); - AddParameter (insertCmd, "LoweredApplicationName", applicationName.ToLowerInvariant ()); - insertCmd.ExecuteNonQuery (); - - return applicationId; - } - - public static string GetApplicationId (DbConnection connection, string applicationName) - { - string selectQuery = "SELECT ApplicationId FROM aspnet_Applications WHERE LoweredApplicationName = ?"; - - OleDbCommand selectCmd = new OleDbCommand (selectQuery, (OleDbConnection) connection); - AddParameter (selectCmd, "LoweredApplicationName", applicationName.ToLowerInvariant ()); - using (OleDbDataReader reader = selectCmd.ExecuteReader ()) { - if (reader.Read ()) - return reader.GetString (0); - } - - return null; - } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyDBSchema.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyDBSchema.cs deleted file mode 100644 index 3866f8c579e..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyDBSchema.cs +++ /dev/null @@ -1,312 +0,0 @@ -// -// Mainsoft.Web.Security.DerbyDBSchema -// -// Authors: -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// (C) 2006 Mainsoft -// -// 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. -// - - -using System; -using System.Data; -using System.Data.OleDb; -using System.Collections.Generic; -using System.Text; -using System.Configuration.Provider; -using System.Diagnostics; -using Mainsoft.Web.Hosting; - -namespace Mainsoft.Web.Security -{ - internal class DerbyDBSchema - { - const string _currentSchemaVersion = "1.0"; - static readonly object _lock = new object (); - - #region schema string array - static string [] schemaElements = new string [] { - // Applications table - @"CREATE TABLE aspnet_Applications ( - ApplicationId char(36) NOT NULL PRIMARY KEY, - ApplicationName varchar(256) NOT NULL UNIQUE, - LoweredApplicationName varchar(256) NOT NULL UNIQUE, - Description varchar(256) - )", - @"CREATE INDEX aspnet_App_Idx ON aspnet_Applications(LoweredApplicationName)", - - // Users table - @"CREATE TABLE aspnet_Users ( - ApplicationId char(36) NOT NULL, - UserId char(36) NOT NULL PRIMARY KEY, - UserName varchar(256) NOT NULL, - LoweredUserName varchar(256) NOT NULL, - MobileAlias varchar(16) DEFAULT NULL, - IsAnonymous int NOT NULL DEFAULT 0, - LastActivityDate timestamp NOT NULL, - - CONSTRAINT Users_AppId_PK FOREIGN KEY (ApplicationId) REFERENCES aspnet_Applications(ApplicationId) - )", - @"CREATE UNIQUE INDEX aspnet_Usr_Idx ON aspnet_Users(ApplicationId, LoweredUserName)", - @"CREATE INDEX aspnet_Usr_Idx2 ON aspnet_Users(ApplicationId, LastActivityDate)", - - // Membership table - @"CREATE TABLE aspnet_Membership ( - ApplicationId char(36) NOT NULL, - UserId char(36) NOT NULL PRIMARY KEY, - Password varchar(128) NOT NULL, - PasswordFormat int NOT NULL DEFAULT 0, - PasswordSalt varchar(128) NOT NULL, - MobilePIN varchar(16), - Email varchar(256), - LoweredEmail varchar(256), - PasswordQuestion varchar(256), - PasswordAnswer varchar(128), - IsApproved int NOT NULL, - IsLockedOut int NOT NULL, - CreateDate timestamp NOT NULL, - LastLoginDate timestamp NOT NULL, - LastPasswordChangedDate timestamp NOT NULL, - LastLockoutDate timestamp NOT NULL, - FailedPasswordAttemptCount int NOT NULL, - FailedPwdAttemptWindowStart timestamp NOT NULL, - FailedPwdAnswerAttemptCount int NOT NULL, - FailedPwdAnswerAttWindowStart timestamp NOT NULL, - Comment varchar(256), - - CONSTRAINT Member_AppId_PK FOREIGN KEY (ApplicationId) REFERENCES aspnet_Applications(ApplicationId), - CONSTRAINT UserId_PK FOREIGN KEY (UserId) REFERENCES aspnet_Users(UserId) - )", - @"CREATE INDEX aspnet_Mbr_idx ON aspnet_Membership(ApplicationId, LoweredEmail)", - - // Roles table - @"CREATE TABLE aspnet_Roles ( - ApplicationId char(36) NOT NULL, - RoleId char(36) NOT NULL PRIMARY KEY, - RoleName varchar(256) NOT NULL, - LoweredRoleName varchar(256) NOT NULL, - Description varchar(256), - - CONSTRAINT Roles_AppId_PK FOREIGN KEY (ApplicationId) REFERENCES aspnet_Applications(ApplicationId) - )", - @"CREATE UNIQUE INDEX aspnet_Rls_idx ON aspnet_Roles(ApplicationId, LoweredRoleName)", - - // UsersInRoles table - @"CREATE TABLE aspnet_UsersInRoles ( - UserId char(36) NOT NULL, - RoleId char(36) NOT NULL, - - CONSTRAINT RoleId_UserId_PK FOREIGN KEY (UserId) REFERENCES aspnet_Users (UserId), - CONSTRAINT UserId_RoleId_PK FOREIGN KEY (RoleId) REFERENCES aspnet_Roles (RoleId) - )", - @"ALTER TABLE aspnet_UsersInRoles ADD PRIMARY KEY (UserId, RoleId)", - @"CREATE INDEX aspnet_UsrRls_idx ON aspnet_UsersInRoles(RoleId)", - - // Profile table - @"CREATE TABLE aspnet_Profile ( - UserId char(36) NOT NULL PRIMARY KEY, - PropertyNames long varchar NOT NULL, - PropertyValuesString long varchar NOT NULL, - PropertyValuesBinary blob NOT NULL, - LastUpdatedDate timestamp NOT NULL, - - CONSTRAINT Profile_UserId_PK FOREIGN KEY (UserId) REFERENCES aspnet_Users (UserId) - )", - - // Pathes table - //@"CREATE TABLE aspnet_Paths ( - // ApplicationId char(36) NOT NULL, - // PathId char(36) NOT NULL PRIMARY KEY, - // Path varchar(256) NOT NULL, - // LoweredPath varchar(256) NOT NULL, - // - // CONSTRAINT Paths_AppId_FK FOREIGN KEY (ApplicationId) REFERENCES aspnet_Applications(ApplicationId) - //)", - //@"CREATE UNIQUE INDEX aspnet_Pth_idx ON aspnet_Paths(ApplicationId, LoweredPath)", - - // Personalization tables - //@"CREATE TABLE aspnet_PersonalizationAllUsers ( - // PathId char(36) NOT NULL PRIMARY KEY, - // PageSettings blob NOT NULL, - // LastUpdatedDate timestamp NOT NULL, - // - // CONSTRAINT PrsUsr_PathId_PK FOREIGN KEY (PathId) REFERENCES aspnet_Paths (PathId) - //)", - //@"CREATE TABLE aspnet_PersonalizationPerUser ( - // Id char(36) NOT NULL PRIMARY KEY, - // PathId char(36) NOT NULL, - // UserId char(36) NOT NULL, - // PageSettings blob NOT NULL, - // LastUpdatedDate timestamp NOT NULL, - // - // CONSTRAINT PrsPUser_PathId_FK FOREIGN KEY (PathId) REFERENCES aspnet_Paths (PathId), - // CONSTRAINT PrsPUser_UserId_FK FOREIGN KEY (UserId) REFERENCES aspnet_Users (UserId) - //)", - //@"CREATE UNIQUE INDEX PrsPUser_idx1 ON aspnet_PersonalizationPerUser(PathId,UserId)", - //@"CREATE UNIQUE INDEX PrsPUser_idx2 ON aspnet_PersonalizationPerUser(UserId,PathId)" - - // Version table - @"CREATE TABLE aspnet_Version ( - SchemaVersion varchar(10) NOT NULL - )", - @"CREATE INDEX aspnet_Version_Idx ON aspnet_Version(SchemaVersion)", - @"INSERT INTO aspnet_Version VALUES ('1.0')" - }; - #endregion - - public static void CheckSchema (string connectionString) { - string schemaVersion = GetSchemaVersion (connectionString); - if (schemaVersion != null) { - if (string.CompareOrdinal (schemaVersion, _currentSchemaVersion) == 0) - return; - } - else { - lock (_lock) { - schemaVersion = GetSchemaVersion (connectionString); - if (schemaVersion == null) { - InitializeSchema (connectionString); - return; - } - } - } - - throw new ProviderException (String.Format ("Incorrect aspnetdb schema version: found '{0}', expected '{1}'.", schemaVersion, _currentSchemaVersion)); - } - - static string GetSchemaVersion (string connectionString) - { - OleDbConnection connection = new OleDbConnection (connectionString); - - connection.Open (); - - using (connection) { - OleDbCommand cmd = new OleDbCommand ("SELECT SchemaVersion FROM aspnet_Version", connection); - - try { - using (OleDbDataReader reader = cmd.ExecuteReader ()) { - if (reader.Read ()) - return reader.GetString (0); - } - } - catch { } - - return null; - } - } - - static void InitializeSchema (string connectionString) - { - OleDbConnection connection = new OleDbConnection (); - connection.ConnectionString = connectionString; - - connection.Open (); - - using (connection) { - for (int i = 0; i < schemaElements.Length; i++) { - OleDbCommand cmd = new OleDbCommand (schemaElements [i], connection); - cmd.ExecuteNonQuery (); - } - } - } - } - - internal class DerbyUnloadManager - { - public enum DerbyShutDownPolicy - { - Default, - Never, - Database, - System - } - - readonly string _connectionString; - readonly DerbyShutDownPolicy _policy; - - DerbyUnloadManager (string connectionString, DerbyShutDownPolicy policy) { - _connectionString = connectionString; - _policy = policy; - } - - public static void RegisterUnloadHandler (string connectionString, DerbyShutDownPolicy policy) { - if (policy == DerbyShutDownPolicy.Never) - return; - - if (connectionString.IndexOf("org.apache.derby.jdbc.EmbeddedDriver", StringComparison.Ordinal) < 0) - return; - - DerbyUnloadManager derbyMan = new DerbyUnloadManager (connectionString, policy); - AppDomain.CurrentDomain.DomainUnload += new EventHandler (derbyMan.UnloadHandler); - } - - public void UnloadHandler (object sender, EventArgs e) - { - string shutUrl; - - switch (_policy) { - case DerbyShutDownPolicy.Never: - return; - case DerbyShutDownPolicy.Database: - shutUrl = GetConnectionProperty (_connectionString, "JdbcURL"); - break; - case DerbyShutDownPolicy.System: - shutUrl = "JdbcURL=jdbc:derby:"; - break; - default: - case DerbyShutDownPolicy.Default: - java.lang.ClassLoader contextLoader = (java.lang.ClassLoader) AppDomain.CurrentDomain.GetData (J2EEConsts.CLASS_LOADER); - java.lang.Class klass = contextLoader.loadClass ("org.apache.derby.jdbc.EmbeddedDriver"); - if (klass == null) - return; - - shutUrl = (klass.getClassLoader () == contextLoader) ? - "JdbcURL=jdbc:derby:" : GetConnectionProperty (_connectionString, "JdbcURL"); - - break; - } - - const string shuttingConnection = "JdbcDriverClassName=org.apache.derby.jdbc.EmbeddedDriver;{0};shutdown=true"; - - if (!String.IsNullOrEmpty (shutUrl)) { - try { - new OleDbConnection (String.Format (shuttingConnection, shutUrl)).Open (); - } - catch (Exception ex) { - Trace.Write (ex.ToString ()); - } - } - } - - static string GetConnectionProperty (string connectionString, string name) { - if (String.IsNullOrEmpty (connectionString)) - return null; - - string [] parts = connectionString.Split (';'); - foreach (string part in parts) - if (part.StartsWith (name, StringComparison.OrdinalIgnoreCase)) - return part; - - return null; - } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyMembershipHelper.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyMembershipHelper.cs deleted file mode 100644 index 7a8e5b3e3d6..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyMembershipHelper.cs +++ /dev/null @@ -1,739 +0,0 @@ -// -// Mainsoft.Web.Security.DerbyMembershipHelper -// -// Authors: -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// (C) 2006 Mainsoft -// -// 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. -// - - -using System; -using System.Web.Security; -using System.Data; -using System.Data.OleDb; -using System.Data.Common; -using System.Collections.Generic; -using System.Text; - -namespace Mainsoft.Web.Security -{ - static class DerbyMembershipHelper - { - static readonly DateTime DefaultDateTime = new DateTime (1754, 1, 1).ToUniversalTime (); - - private static OleDbParameter AddParameter (OleDbCommand command, string paramName, object paramValue) - { - OleDbParameter prm = new OleDbParameter (paramName, paramValue); - command.Parameters.Add (prm); - return prm; - } - - public static int Membership_ChangePasswordQuestionAndAnswer (DbConnection connection, string applicationName, string username, string newPwdQuestion, string newPwdAnswer) - { - string updateQuery = "UPDATE aspnet_Membership SET PasswordQuestion = ?, PasswordAnswer = ? WHERE UserId = ?"; - - string userId = GetUserId (connection, applicationName, username); - if (userId == null) - return 1; // user not found - - OleDbCommand updateCmd = new OleDbCommand (updateQuery, (OleDbConnection) connection); - AddParameter (updateCmd, "PasswordQuestion", newPwdQuestion); - AddParameter (updateCmd, "PasswordAnswer", newPwdAnswer); - AddParameter (updateCmd, "UserId", userId); - updateCmd.ExecuteNonQuery (); - return 0; - } - - public static int Membership_CreateUser (DbConnection connection, string applicationName, string username, string password, string passwordSalt, string email, string pwdQuestion, string pwdAnswer, bool isApproved, DateTime currentTimeUtc, DateTime createDate, bool uniqueEmail, int passwordFormat, ref object userId) - { - string applicationId = (string) DerbyApplicationsHelper.Applications_CreateApplication (connection, applicationName); - string newUserId = (string) userId; - - OleDbTransaction trans = (OleDbTransaction) connection.BeginTransaction (); - - try { - int returnValue = Users_CreateUser (connection, trans, applicationId, username, false, createDate, ref userId); - if (returnValue == 1) { - // the user exists in users table, this can occure when user - // does not have membership information, but has other information - // like roles, etc. - if (userId != null && newUserId != null && newUserId != (string) userId) { - trans.Rollback (); - return 9; // wrong userid provided - } - } - else if (returnValue == 2) { - // another user with provided id already exists - trans.Rollback (); - return 10; // wrong userid provided - } - newUserId = (string) userId; - - string selectQueryMbrUserId = "SELECT UserId FROM aspnet_Membership WHERE UserId = ?"; - OleDbCommand selectCmdMbrUserId = new OleDbCommand (selectQueryMbrUserId, (OleDbConnection) connection); - selectCmdMbrUserId.Transaction = trans; - AddParameter (selectCmdMbrUserId, "UserId", newUserId); - using (OleDbDataReader reader = selectCmdMbrUserId.ExecuteReader ()) { - if (reader.Read ()) { - trans.Rollback (); - return 2; // user with such userId already exists - } - } - - if (uniqueEmail) { - string queryMbrEmail = "SELECT * FROM aspnet_Membership WHERE ApplicationId = ? AND LoweredEmail = ?"; - OleDbCommand cmdMbrEmail = new OleDbCommand (queryMbrEmail, (OleDbConnection) connection); - cmdMbrEmail.Transaction = trans; - AddParameter (cmdMbrEmail, "ApplicationId", applicationId); - AddParameter (cmdMbrEmail, "LoweredEmail", email.ToLowerInvariant ()); - using (OleDbDataReader reader = cmdMbrEmail.ExecuteReader ()) { - if (reader.Read ()) { - trans.Rollback (); - return 3; // user with such email already exists - } - } - } - - if (returnValue == 1) { - // if user was not created, but found existing and correct - // update it's activity (membership create) time. - string queryUpdActivity = "UPDATE aspnet_Users SET LastActivityDate = ? WHERE UserId = ?"; - OleDbCommand cmdUpdActivity = new OleDbCommand (queryUpdActivity, (OleDbConnection) connection); - cmdUpdActivity.Transaction = trans; - AddParameter (cmdUpdActivity, "LastActivityDate", createDate); - AddParameter (cmdUpdActivity, "UserId", newUserId); - cmdUpdActivity.ExecuteNonQuery (); - } - - string queryInsertMbr = "INSERT INTO aspnet_Membership (ApplicationId, UserId, Password, PasswordFormat, PasswordSalt, Email, " + - "LoweredEmail, PasswordQuestion, PasswordAnswer, IsApproved, IsLockedOut, CreateDate, LastLoginDate, " + - "LastPasswordChangedDate, LastLockoutDate, FailedPasswordAttemptCount, FailedPwdAttemptWindowStart, " + - "FailedPwdAnswerAttemptCount, FailedPwdAnswerAttWindowStart) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - OleDbCommand cmdInsertMbr = new OleDbCommand (queryInsertMbr, (OleDbConnection) connection); - cmdInsertMbr.Transaction = trans; - AddParameter (cmdInsertMbr, "ApplicationId", applicationId); - AddParameter (cmdInsertMbr, "UserId", newUserId); - AddParameter (cmdInsertMbr, "Password", password); - AddParameter (cmdInsertMbr, "PasswordFormat", passwordFormat); - AddParameter (cmdInsertMbr, "PasswordSalt", passwordSalt); - AddParameter (cmdInsertMbr, "Email", email); - AddParameter (cmdInsertMbr, "LoweredEmail", email != null ? email.ToLowerInvariant () : null); - AddParameter (cmdInsertMbr, "PasswordQuestion", pwdQuestion); - AddParameter (cmdInsertMbr, "PasswordAnswer", pwdAnswer); - AddParameter (cmdInsertMbr, "IsApproved", isApproved); - AddParameter (cmdInsertMbr, "IsLockedOut", 0); - AddParameter (cmdInsertMbr, "CreateDate", createDate); - AddParameter (cmdInsertMbr, "LastLoginDate", DefaultDateTime); - AddParameter (cmdInsertMbr, "LastPasswordChangedDate", createDate); - AddParameter (cmdInsertMbr, "LastLockoutDate", DefaultDateTime); - AddParameter (cmdInsertMbr, "FailedPasswordAttemptCount", 0); - AddParameter (cmdInsertMbr, "FailedPwdAttemptWindowStart", DefaultDateTime); - AddParameter (cmdInsertMbr, "FailedPwdAnswerAttemptCount", 0); - AddParameter (cmdInsertMbr, "FailedPwdAnswerAttWindowStart", DefaultDateTime); - cmdInsertMbr.ExecuteNonQuery (); - - trans.Commit (); - } - catch (Exception e) { - trans.Rollback (); - throw e; - } - - return 0; - } - - public static int Membership_FindUsersByEmail (DbConnection connection, string applicationName, string emailToMatch, int pageIndex, int pageSize, out DbDataReader reader) - { - string querySelect = "SELECT usr.UserName, mbr.UserId, mbr.Email, mbr.PasswordQuestion, mbr.Comment, mbr.IsApproved, " + - "mbr.IsLockedOut, mbr.CreateDate, mbr.LastLoginDate, usr.LastActivityDate, mbr.LastPasswordChangedDate, mbr.LastLockoutDate " + - "FROM aspnet_Membership mbr, aspnet_Users usr " + - "WHERE usr.UserId = mbr.UserId AND mbr.LoweredEmail LIKE ? ORDER BY usr.LoweredUserName"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "LoweredEmail", emailToMatch.ToLowerInvariant ()); - reader = cmdSelect.ExecuteReader (); - return 0; - } - - public static int Membership_FindUsersByName (DbConnection connection, string applicationName, string userNameToMatch, int pageIndex, int pageSize, out DbDataReader reader) - { - string querySelect = "SELECT usr.UserName, mbr.UserId, mbr.Email, mbr.PasswordQuestion, mbr.Comment, mbr.IsApproved, " + - "mbr.IsLockedOut, mbr.CreateDate, mbr.LastLoginDate, usr.LastActivityDate, mbr.LastPasswordChangedDate, mbr.LastLockoutDate " + - "FROM aspnet_Membership mbr, aspnet_Users usr " + - "WHERE usr.UserId = mbr.UserId AND usr.LoweredUserName LIKE ? ORDER BY usr.LoweredUserName"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "LoweredUserName", userNameToMatch.ToLowerInvariant ()); - reader = cmdSelect.ExecuteReader (); - return 0; - } - - public static int Membership_GetAllUsers (DbConnection connection, string applicationName, int pageIndex, int pageSize, out DbDataReader reader) - { - string querySelect = "SELECT usr.UserName, mbr.UserId, mbr.Email, mbr.PasswordQuestion, mbr.Comment, mbr.IsApproved, " + - "mbr.IsLockedOut, mbr.CreateDate, mbr.LastLoginDate, usr.LastActivityDate, mbr.LastPasswordChangedDate, mbr.LastLockoutDate " + - "FROM aspnet_Membership mbr, aspnet_Users usr " + - "WHERE usr.UserId = mbr.UserId ORDER BY usr.LoweredUserName"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - reader = cmdSelect.ExecuteReader (); - return 0; - } - - public static int Membership_GetNumberOfUsersOnline (DbConnection connection, string applicationName, int minutesSinceLastInActive, DateTime currentTimeUtc) - { - string queryUsersActive = "SELECT COUNT(*) FROM aspnet_Users usr, aspnet_Applications app, aspnet_Membership mbr " + - "WHERE usr.ApplicationId = app.ApplicationId AND usr.LastActivityDate > ? AND " + - "app.LoweredApplicationName = ? AND usr.UserId = mbr.UserId"; - - - OleDbCommand cmdUsersActive = new OleDbCommand (queryUsersActive, (OleDbConnection) connection); - AddParameter (cmdUsersActive, "LastActivityDate", currentTimeUtc.AddMinutes (-minutesSinceLastInActive)); - AddParameter (cmdUsersActive, "LoweredApplicationName", applicationName.ToLowerInvariant ()); - using (OleDbDataReader reader = cmdUsersActive.ExecuteReader ()) { - if (reader.Read ()) - return reader.GetInt32 (0); - } - return 0; - } - - public static int Membership_GetPassword (DbConnection connection, string applicationName, string username, string passwordAnswer, int maxInvalidPasswordAttempts, int passwordAttemptWindow, DateTime currentTimeUtc, out string password) - { - string querySelect = "SELECT usr.UserId, mbr.Password, mbr.PasswordAnswer, mbr.IsLockedOut, " + - "mbr.LastLockoutDate, mbr.FailedPwdAnswerAttemptCount, mbr.FailedPwdAnswerAttWindowStart " + - "FROM aspnet_Applications app, aspnet_Users usr, aspnet_Membership mbr " + - "WHERE app.LoweredApplicationName = ? AND usr.ApplicationId = app.ApplicationId " + - "AND usr.UserId = mbr.UserId AND usr.LoweredUserName = ?"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "LoweredApplicationName", applicationName.ToLowerInvariant ()); - AddParameter (cmdSelect, "LoweredUserName", username.ToLowerInvariant ()); - - password = null; - string dbUserId = null; - string dbPassword = null; - string dbPasswordAns = null; - bool dbLockedOut = false; - DateTime dbLastLockoutDate; - int dbFailedPasswordAnswerAttemptCount = 0; - DateTime dbFailedPasswordAnswerAttemptWindowStart; - - using (OleDbDataReader reader = cmdSelect.ExecuteReader ()) { - if (reader.Read ()) { - dbUserId = reader.GetString (0); - dbPassword = reader.GetString (1); - dbPasswordAns = reader.GetString (2); - dbLockedOut = reader.GetInt32 (3) > 0; - dbLastLockoutDate = reader.GetDateTime (4); - dbFailedPasswordAnswerAttemptCount = reader.GetInt32 (5); - dbFailedPasswordAnswerAttemptWindowStart = reader.GetDateTime (6); - } - else { - return 1; // user not found - } - } - - if (dbLockedOut) - return 2; // locked out - - if (dbPasswordAns != passwordAnswer) { - if (currentTimeUtc > dbFailedPasswordAnswerAttemptWindowStart.AddMinutes (passwordAttemptWindow)) { - dbFailedPasswordAnswerAttemptWindowStart = currentTimeUtc; - dbFailedPasswordAnswerAttemptCount = 1; - } - else { - dbFailedPasswordAnswerAttemptWindowStart = currentTimeUtc; - dbFailedPasswordAnswerAttemptCount++; - } - - if (dbFailedPasswordAnswerAttemptCount > maxInvalidPasswordAttempts) { - dbLockedOut = true; - dbLastLockoutDate = currentTimeUtc; - } - return 3; // wrong password answer - } - else { - dbFailedPasswordAnswerAttemptCount = 0; - dbFailedPasswordAnswerAttemptWindowStart = DefaultDateTime; - password = dbPassword; - } - - string queryUpdate = "UPDATE aspnet_Membership SET IsLockedOut = ?, LastLockoutDate = ?, " + - "FailedPwdAnswerAttemptCount = ?, FailedPwdAnswerAttWindowStart = ? " + - "WHERE UserId = ?"; - OleDbCommand cmdUpdate = new OleDbCommand (queryUpdate, (OleDbConnection) connection); - AddParameter (cmdUpdate, "IsLockedOut", dbLockedOut); - AddParameter (cmdUpdate, "LastLockoutDate", dbLastLockoutDate); - AddParameter (cmdUpdate, "FailedPwdAnswerAttemptCount", dbFailedPasswordAnswerAttemptCount); - AddParameter (cmdUpdate, "FailedPwdAnswerAttWindowStart", dbFailedPasswordAnswerAttemptWindowStart); - AddParameter (cmdUpdate, "UserId", dbUserId); - cmdUpdate.ExecuteNonQuery (); - - return 0; - } - - public static int Membership_GetPasswordWithFormat (DbConnection connection, string applicationName, string username, bool updateLastActivity, DateTime currentTimeUtc, out DbDataReader reader) - { - string querySelect = "SELECT usr.UserId, mbr.IsLockedOut, mbr.IsApproved, mbr.Password, mbr.PasswordFormat, mbr.PasswordSalt, " + - "mbr.FailedPasswordAttemptCount, mbr.FailedPwdAnswerAttemptCount, mbr.LastLoginDate, usr.LastActivityDate " + - "FROM aspnet_Applications app, aspnet_Users usr, aspnet_Membership mbr " + - "WHERE app.LoweredApplicationName = ? AND usr.ApplicationId = app.ApplicationId " + - "AND usr.UserId = mbr.UserId AND usr.LoweredUserName = ?"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "LoweredApplicationName", applicationName.ToLowerInvariant ()); - AddParameter (cmdSelect, "LoweredUserName", username.ToLowerInvariant ()); - reader = cmdSelect.ExecuteReader (); - return 0; - } - - public static int Membership_GetUserByEmail (DbConnection connection, string applicationName, string email, out string username) - { - string querySelect = "SELECT usr.UserName FROM aspnet_Applications app, aspnet_Users usr, aspnet_Membership mbr " + - "WHERE app.LoweredApplicationName = ? AND usr.ApplicationId = app.ApplicationId AND " + - "usr.UserId = mbr.UserId AND mbr.LoweredEmail " + (email == null ? "IS NULL" : "= ?"); - - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "LoweredApplicationName", applicationName.ToLowerInvariant ()); - if (email != null) - AddParameter (cmdSelect, "LoweredEmail", email.ToLowerInvariant ()); - - username = null; - using (OleDbDataReader reader = cmdSelect.ExecuteReader ()) { - if (reader.Read ()) { - username = reader.GetString (0); - if (reader.Read ()) - return 2; // more that one user found with this email - } - else - return 1; // no users found - return 0; - } - } - - public static int Membership_GetUserByName (DbConnection connection, string applicationName, string username, bool updateLastActivity, DateTime currentTimeUtc, out DbDataReader reader) - { - reader = null; - object userId = GetUserId (connection, applicationName, username); - if (userId == null) - return 1; // user not found - - if (updateLastActivity) { - string queryUpdate = "UPDATE aspnet_Users SET LastActivityDate = ? WHERE UserId = ?"; - OleDbCommand cmdUpdate = new OleDbCommand (queryUpdate, (OleDbConnection) connection); - AddParameter (cmdUpdate, "LastActivityDate", currentTimeUtc); - AddParameter (cmdUpdate, "UserId", userId); - int records = cmdUpdate.ExecuteNonQuery (); - if (records == 0) - return -1; // unknown error - } - - return Membership_GetUserByUserId (connection, userId, updateLastActivity, currentTimeUtc, out reader); - } - - public static int Membership_GetUserByUserId (DbConnection connection, object userId, bool updateLastActivity, DateTime currentTimeUtc, out DbDataReader reader) - { - reader = null; - if (updateLastActivity) { - string queryUpdate = "UPDATE aspnet_Users SET LastActivityDate = ? WHERE UserId = ?"; - OleDbCommand cmdUpdate = new OleDbCommand (queryUpdate, (OleDbConnection) connection); - AddParameter (cmdUpdate, "LastActivityDate", currentTimeUtc); - AddParameter (cmdUpdate, "UserId", userId); - int recordsAffected = cmdUpdate.ExecuteNonQuery (); - if (recordsAffected == 0) - return 1; // user not found - } - - string querySelect = "SELECT usr.UserName, mbr.UserId, mbr.Email, mbr.PasswordQuestion, mbr.Comment, mbr.IsApproved, " + - "mbr.IsLockedOut, mbr.CreateDate, mbr.LastLoginDate, usr.LastActivityDate, mbr.LastPasswordChangedDate, mbr.LastLockoutDate " + - "FROM aspnet_Users usr, aspnet_Membership mbr " + - "WHERE usr.UserId = ? AND usr.UserId = mbr.UserId"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "UserId", userId); - reader = cmdSelect.ExecuteReader (); - return 0; - } - - public static int Membership_ResetPassword (DbConnection connection, string applicationName, string username, string newPassword, string passwordAnswer, int passwordFormat, string passwordSalt, int maxInvalidPasswordAttempts, int passwordAttemptWindow, DateTime currentTimeUtc) - { - string querySelect = "SELECT usr.UserId, mbr.Password, mbr.PasswordAnswer, mbr.IsLockedOut, " + - "mbr.LastLockoutDate, mbr.FailedPwdAnswerAttemptCount, mbr.FailedPwdAnswerAttWindowStart " + - "FROM aspnet_Applications app, aspnet_Users usr, aspnet_Membership mbr " + - "WHERE app.LoweredApplicationName = ? AND usr.ApplicationId = app.ApplicationId " + - "AND usr.UserId = mbr.UserId AND usr.LoweredUserName = ?"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "LoweredApplicationName", applicationName.ToLowerInvariant ()); - AddParameter (cmdSelect, "LoweredUserName", username.ToLowerInvariant ()); - - string dbUserId = null; - string dbPassword = null; - string dbPasswordAns = null; - bool dbLockedOut = false; - DateTime dbLastLockoutDate; - int dbFailedPasswordAnswerAttemptCount = 0; - DateTime dbFailedPasswordAnswerAttemptWindowStart; - - using (OleDbDataReader reader = cmdSelect.ExecuteReader ()) { - if (reader.Read ()) { - dbUserId = reader.GetString (0); - dbPassword = reader.GetString (1); - dbPasswordAns = reader.GetString (2); - dbLockedOut = reader.GetInt32 (3) > 0; - dbLastLockoutDate = reader.GetDateTime (4); - dbFailedPasswordAnswerAttemptCount = reader.GetInt32 (5); - dbFailedPasswordAnswerAttemptWindowStart = reader.GetDateTime (6); - } - else { - return 1; // user not found - } - } - - if (dbLockedOut) - return 2; // locked out - - if (dbPasswordAns != passwordAnswer) { - if (currentTimeUtc > dbFailedPasswordAnswerAttemptWindowStart.AddMinutes (passwordAttemptWindow)) { - dbFailedPasswordAnswerAttemptWindowStart = currentTimeUtc; - dbFailedPasswordAnswerAttemptCount = 1; - } - else { - dbFailedPasswordAnswerAttemptWindowStart = currentTimeUtc; - dbFailedPasswordAnswerAttemptCount++; - } - - if (dbFailedPasswordAnswerAttemptCount > maxInvalidPasswordAttempts) { - dbLockedOut = true; - dbLastLockoutDate = currentTimeUtc; - } - return 3; // passwrod answer is wrong - } - else { - dbFailedPasswordAnswerAttemptCount = 0; - dbFailedPasswordAnswerAttemptWindowStart = DefaultDateTime; - } - - return Membership_SetPasswordUserId (connection, dbUserId, newPassword, passwordSalt, passwordFormat, currentTimeUtc); - } - - public static int Membership_SetPassword (DbConnection connection, string applicationName, string username, string newPassword, int passwordFormat, string passwordSalt, DateTime currentTimeUtc) - { - string userId = GetUserId (connection, applicationName, username); - if (userId == null) - return 1; // user not found - - return Membership_SetPasswordUserId (connection, userId, newPassword, passwordSalt, passwordFormat, currentTimeUtc); - } - - private static int Membership_SetPasswordUserId (DbConnection connection, string userId, string newPassword, string passwordSalt, int passwordFormat, DateTime currentTimeUtc) - { - string queryUpdate = "UPDATE aspnet_Membership SET Password = ?, PasswordFormat = ?, PasswordSalt = ?, " + - "LastPasswordChangedDate = ? WHERE UserId = ?"; - OleDbCommand cmdUpdate = new OleDbCommand (queryUpdate, (OleDbConnection) connection); - AddParameter (cmdUpdate, "Password", newPassword); - AddParameter (cmdUpdate, "PasswordFormat", passwordFormat); - AddParameter (cmdUpdate, "PasswordSalt", passwordSalt); - AddParameter (cmdUpdate, "LastPasswordChangedDate", currentTimeUtc); - AddParameter (cmdUpdate, "UserId", userId); - - cmdUpdate.ExecuteNonQuery (); - return 0; - } - - public static int Membership_UnlockUser (DbConnection connection, string applicationName, string username) - { - string userId = GetUserId (connection, applicationName, username); - if (userId == null) - return 1; // user not found - - string queryUnlock = "UPDATE aspnet_Membership SET IsLockedOut = 0, " + - "FailedPasswordAttemptCount = 0, FailedPwdAttemptWindowStart = ?, " + - "FailedPwdAnswerAttemptCount = 0, FailedPwdAnswerAttWindowStart = ?, " + - "LastLockoutDate = ? WHERE UserId = ?"; - OleDbCommand cmdUnlock = new OleDbCommand (queryUnlock, (OleDbConnection) connection); - AddParameter (cmdUnlock, "FailedPwdAttemptWindowStart", DefaultDateTime); - AddParameter (cmdUnlock, "FailedPwdAnswerAttWindowStart", DefaultDateTime); - AddParameter (cmdUnlock, "LastLockoutDate", DefaultDateTime); - AddParameter (cmdUnlock, "UserId", userId); - - cmdUnlock.ExecuteNonQuery (); - return 0; - } - - public static int Membership_UpdateUser (DbConnection connection, string applicationName, string username, string email, string comment, bool isApproved, bool uniqueEmail, DateTime lastLoginDate, DateTime lastActivityDate, DateTime currentTimeUtc) - { - string userId = GetUserId (connection, applicationName, username); - if (userId == null) - return 1; // user not found - - if (uniqueEmail) { - string queryUniqueMail = "SELECT * FROM aspnet_Membership WHERE ApplicationId = ? " + - "AND UserId <> ? AND LoweredEmail = ?"; - OleDbCommand cmdUniqueMail = new OleDbCommand (queryUniqueMail, (OleDbConnection) connection); - AddParameter (cmdUniqueMail, "ApplicationId", email); - AddParameter (cmdUniqueMail, "UserId", userId); - using (OleDbDataReader reader = cmdUniqueMail.ExecuteReader ()) { - if (reader.Read ()) - return 2; // duplicate email - } - } - string queryUpdateUser = "UPDATE aspnet_Users SET LastActivityDate = ? WHERE UserId = ?"; - OleDbCommand cmdUpdateUser = new OleDbCommand (queryUpdateUser, (OleDbConnection) connection); - AddParameter (cmdUpdateUser, "LastActivityDate", lastActivityDate); - AddParameter (cmdUpdateUser, "UserId", userId); - cmdUpdateUser.ExecuteNonQuery (); - - string queryUpdateMember = "UPDATE aspnet_Membership SET Email = ?, LoweredEmail = ?, Comment = ?, " + - "IsApproved = ?, LastLoginDate = ? WHERE UserId = ?"; - OleDbCommand cmdUpdateMember = new OleDbCommand (queryUpdateMember, (OleDbConnection) connection); - AddParameter (cmdUpdateMember, "Email", email); - AddParameter (cmdUpdateMember, "LoweredEmail", email.ToLowerInvariant ()); - AddParameter (cmdUpdateMember, "Comment", comment); - AddParameter (cmdUpdateMember, "IsApproved", isApproved); - AddParameter (cmdUpdateMember, "LastLoginDate", lastLoginDate); - AddParameter (cmdUpdateMember, "UserId", userId); - cmdUpdateMember.ExecuteNonQuery (); - - return 0; - } - - public static int Membership_UpdateUserInfo (DbConnection connection, string applicationName, string username, bool isPasswordCorrect, bool updateLastLoginActivityDate, int maxInvalidPasswordAttempts, int passwordAttemptWindow, DateTime currentTimeUtc, DateTime lastLoginDate, DateTime lastActivityDate) - { - string querySelect = "SELECT usr.UserId, mbr.IsApproved, mbr.IsLockedOut, mbr.LastLockoutDate, " + - "mbr.FailedPasswordAttemptCount, mbr.FailedPwdAttemptWindowStart " + - "FROM aspnet_Applications app, aspnet_Users usr, aspnet_Membership mbr " + - "WHERE app.LoweredApplicationName = ? AND usr.ApplicationId = app.ApplicationId " + - "AND usr.UserId = mbr.UserId AND usr.LoweredUserName = ?"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "LoweredApplicationName", applicationName.ToLowerInvariant ()); - AddParameter (cmdSelect, "LoweredUserName", username.ToLowerInvariant ()); - - string dbUserId = string.Empty; - bool dbIsApproved = false; - bool dbLockedOut = false; - DateTime dbLastLockoutDate; - int dbFailedPasswordAttemptCount = 0; - DateTime dbFailedPasswordAttemptWindowStart; - - using (OleDbDataReader reader = cmdSelect.ExecuteReader ()) { - if (reader.Read ()) { - dbUserId = reader.GetString (0); - dbIsApproved = reader.GetInt32 (1) > 0; - dbLockedOut = reader.GetInt32 (2) > 0; - dbLastLockoutDate = reader.GetDateTime (3); - dbFailedPasswordAttemptCount = reader.GetInt32 (4); - dbFailedPasswordAttemptWindowStart = reader.GetDateTime (5); - } - else { - return 1; // user not found - } - } - - if (dbLockedOut) - return 2; // locked out - - if (!isPasswordCorrect) { - if (currentTimeUtc > dbFailedPasswordAttemptWindowStart.AddMinutes (passwordAttemptWindow)) { - dbFailedPasswordAttemptWindowStart = currentTimeUtc; - dbFailedPasswordAttemptCount = 1; - } - else { - dbFailedPasswordAttemptWindowStart = currentTimeUtc; - dbFailedPasswordAttemptCount++; - } - - if (dbFailedPasswordAttemptCount > maxInvalidPasswordAttempts) { - dbLockedOut = true; - dbLastLockoutDate = currentTimeUtc; - } - } - else { - dbFailedPasswordAttemptCount = 0; - dbFailedPasswordAttemptWindowStart = DefaultDateTime; - } - - if (updateLastLoginActivityDate) { - string queryUpdUserActivity = "UPDATE aspnet_Users SET LastActivityDate = ? WHERE UserId = ?"; - OleDbCommand cmdUpdUserActivity = new OleDbCommand (queryUpdUserActivity, (OleDbConnection) connection); - AddParameter (cmdUpdUserActivity, "LastActivityDate", currentTimeUtc); - AddParameter (cmdUpdUserActivity, "UserId", dbUserId); - cmdUpdUserActivity.ExecuteNonQuery (); - - string queryUpdMemberActivity = "UPDATE aspnet_Membership SET LastLoginDate = ? WHERE UserId = ?"; - OleDbCommand cmdUpdMemberActivity = new OleDbCommand (queryUpdMemberActivity, (OleDbConnection) connection); - AddParameter (cmdUpdMemberActivity, "LastLoginDate", currentTimeUtc); - AddParameter (cmdUpdMemberActivity, "UserId", dbUserId); - cmdUpdMemberActivity.ExecuteNonQuery (); - } - - string queryUpdate = "UPDATE aspnet_Membership SET IsLockedOut = ?, LastLockoutDate = ?, " + - "FailedPasswordAttemptCount = ?, FailedPwdAttemptWindowStart = ? " + - "WHERE UserId = ?"; - OleDbCommand cmdUpdate = new OleDbCommand (queryUpdate, (OleDbConnection) connection); - AddParameter (cmdUpdate, "IsLockedOut", dbLockedOut); - AddParameter (cmdUpdate, "LastLockoutDate", dbLastLockoutDate); - AddParameter (cmdUpdate, "FailedPasswordAttemptCount", dbFailedPasswordAttemptCount); - AddParameter (cmdUpdate, "FailedPwdAttemptWindowStart", dbFailedPasswordAttemptWindowStart); - AddParameter (cmdUpdate, "UserId", dbUserId); - cmdUpdate.ExecuteNonQuery (); - return 0; - } - - public static int Users_CreateUser (DbConnection connection, DbTransaction trans, string applicationId, string username, bool isAnonymous, DateTime lastActivityDate, ref object userId) - { - string selectQuery = "SELECT UserId FROM aspnet_Users WHERE LoweredUserName = ? AND ApplicationId = ?"; - OleDbCommand selectCmd = new OleDbCommand (selectQuery, (OleDbConnection) connection); - AddParameter (selectCmd, "LoweredUserName", username.ToLowerInvariant ()); - AddParameter (selectCmd, "ApplicationId", applicationId); - if (trans != null) - selectCmd.Transaction = (OleDbTransaction) trans; - - string existingUserId = null; - using (OleDbDataReader reader = selectCmd.ExecuteReader ()) { - if (reader.Read ()) - existingUserId = reader.GetString (0); - } - - if (existingUserId != null && existingUserId.Length > 0) { - userId = existingUserId; - return 1; // user with such username and appid already exists - } - - if (userId != null) { - string querySelectUserId = "SELECT UserId FROM aspnet_Users WHERE UserId = ?"; - OleDbCommand cmdSelectUserId = new OleDbCommand (querySelectUserId, (OleDbConnection) connection); - AddParameter (cmdSelectUserId, "UserId", userId); - if (trans != null) - cmdSelectUserId.Transaction = (OleDbTransaction) trans; - - using (OleDbDataReader reader = cmdSelectUserId.ExecuteReader ()) { - if (reader.Read ()) - return 2; // user with such userId already exists - } - } - - if (userId == null) - userId = Guid.NewGuid ().ToString (); - - string insertQuery = "INSERT INTO aspnet_Users (ApplicationId, UserId, UserName, LoweredUserName, IsAnonymous, LastActivityDate) VALUES (?, ?, ?, ?, ?, ?)"; - OleDbCommand insertCmd = new OleDbCommand (insertQuery, (OleDbConnection) connection); - AddParameter (insertCmd, "ApplicationId", applicationId); - AddParameter (insertCmd, "UserId", userId); - AddParameter (insertCmd, "UserName", username); - AddParameter (insertCmd, "LoweredUserName", username.ToLowerInvariant ()); - AddParameter (insertCmd, "IsAnonymous", isAnonymous); - AddParameter (insertCmd, "LastActivityDate", lastActivityDate); - if (trans != null) - insertCmd.Transaction = (OleDbTransaction) trans; - - insertCmd.ExecuteNonQuery (); - return 0; - } - - public static int Users_DeleteUser (DbConnection connection, string applicationName, string username, int tablesToDeleteFrom, ref int numTablesDeletedFrom) - { - string userId = GetUserId (connection, applicationName, username); - if (userId == null) - return 1; // user not found - - numTablesDeletedFrom = 0; - OleDbTransaction trans = (OleDbTransaction) connection.BeginTransaction (); - - try { - if ((tablesToDeleteFrom & 1) == 1) { - string queryDelete = "DELETE FROM aspnet_Membership WHERE UserId = ?"; - OleDbCommand cmdDelete = new OleDbCommand (queryDelete, (OleDbConnection) connection); - AddParameter (cmdDelete, "UserId", userId); - cmdDelete.Transaction = trans; - cmdDelete.ExecuteNonQuery (); - - numTablesDeletedFrom++; - } - - if ((tablesToDeleteFrom & 2) == 2) { - string queryDelete = "DELETE FROM aspnet_UsersInRoles WHERE UserId = ?"; - OleDbCommand cmdDelete = new OleDbCommand (queryDelete, (OleDbConnection) connection); - AddParameter (cmdDelete, "UserId", userId); - cmdDelete.Transaction = trans; - cmdDelete.ExecuteNonQuery (); - - numTablesDeletedFrom++; - } - - if ((tablesToDeleteFrom & 4) == 4) { - string queryDelete = "DELETE FROM aspnet_Profile WHERE UserId = ?"; - OleDbCommand cmdDelete = new OleDbCommand (queryDelete, (OleDbConnection) connection); - AddParameter (cmdDelete, "UserId", userId); - cmdDelete.Transaction = trans; - cmdDelete.ExecuteNonQuery (); - - numTablesDeletedFrom++; - } - - // this table was removed from schema - //if ((tablesToDeleteFrom & 8) == 8) { - // string queryDelete = "DELETE FROM aspnet_PersonalizationPerUser WHERE UserId = ?"; - // OleDbCommand cmdDelete = new OleDbCommand (queryDelete, (OleDbConnection) connection); - // AddParameter (cmdDelete, "UserId", userId); - // cmdDelete.Transaction = trans; - // cmdDelete.ExecuteNonQuery (); - - // numTablesDeletedFrom++; - //} - - if ((tablesToDeleteFrom & 15) == 15) { - string queryDelete = "DELETE FROM aspnet_Users WHERE UserId = ?"; - OleDbCommand cmdDelete = new OleDbCommand (queryDelete, (OleDbConnection) connection); - AddParameter (cmdDelete, "UserId", userId); - cmdDelete.Transaction = trans; - cmdDelete.ExecuteNonQuery (); - - numTablesDeletedFrom++; - } - - trans.Commit (); - } - catch (Exception e) { - trans.Rollback (); - throw e; - } - - return 0; - } - - private static string GetUserId (DbConnection connection, string applicationName, string username) - { - string selectQuery = "SELECT usr.UserId FROM aspnet_Membership mbr, aspnet_Users usr, aspnet_Applications app WHERE " + - "usr.LoweredUserName = ? AND app.LoweredApplicationName = ? " + - "AND usr.ApplicationId = app.ApplicationId " + - "AND usr.UserId = mbr.UserId"; - - OleDbCommand selectCmd = new OleDbCommand (selectQuery, (OleDbConnection) connection); - AddParameter (selectCmd, "LoweredUserName", username.ToLowerInvariant ()); - AddParameter (selectCmd, "PasswordAnswer", applicationName.ToLowerInvariant ()); - - using (OleDbDataReader reader = selectCmd.ExecuteReader ()) { - if (reader.Read ()) - return reader.GetString (0); - } - - return null; // user not found - } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyMembershipProvider.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyMembershipProvider.cs deleted file mode 100644 index 0c575a6375d..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyMembershipProvider.cs +++ /dev/null @@ -1,1002 +0,0 @@ -// -// Mainsoft.Web.Security.DerbyMembershipProvider -// -// Authors: -// Ben Maurer (bmaurer@users.sourceforge.net) -// Chris Toshok (toshok@ximian.com) -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// -// 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. -// - - -using System; -using System.Collections; -using System.Collections.Specialized; -using System.Configuration; -using System.Configuration.Provider; -using System.Data; -using System.Data.OleDb; -using System.Data.Common; -using System.Text; -using System.Web.Configuration; -using System.Security; -using System.Security.Cryptography; -using System.Web; -using System.Web.Security; - -namespace Mainsoft.Web.Security { - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// Manages storage of membership information for an ASP.NET application in a Derby database. - /// - public class DerbyMembershipProvider : MembershipProvider - { - const int SALT_BYTES = 16; - - bool enablePasswordReset; - bool enablePasswordRetrieval; - int maxInvalidPasswordAttempts; - MembershipPasswordFormat passwordFormat; - bool requiresQuestionAndAnswer; - bool requiresUniqueEmail; - int minRequiredNonAlphanumericCharacters; - int minRequiredPasswordLength; - int passwordAttemptWindow; - string passwordStrengthRegularExpression; - TimeSpan userIsOnlineTimeWindow; - ConnectionStringSettings connectionString; - bool schemaChecked = false; - DerbyUnloadManager.DerbyShutDownPolicy shutDownPolicy = DerbyUnloadManager.DerbyShutDownPolicy.Default; - - string applicationName; - - DbConnection CreateConnection () - { - if (!schemaChecked) { - DerbyDBSchema.CheckSchema (connectionString.ConnectionString); - schemaChecked = true; - - DerbyUnloadManager.RegisterUnloadHandler (connectionString.ConnectionString, shutDownPolicy); - } - - OleDbConnection connection = new OleDbConnection (connectionString.ConnectionString); - connection.Open (); - return connection; - } - - void CheckParam (string pName, string p, int length) - { - if (p == null) - throw new ArgumentNullException (pName); - if (p.Length == 0 || p.Length > length || p.IndexOf (",") != -1) - throw new ArgumentException (String.Format ("invalid format for {0}", pName)); - } - - public override bool ChangePassword (string username, string oldPwd, string newPwd) - { - if (username != null) username = username.Trim (); - if (oldPwd != null) oldPwd = oldPwd.Trim (); - if (newPwd != null) newPwd = newPwd.Trim (); - - CheckParam ("username", username, 256); - CheckParam ("oldPwd", oldPwd, 128); - CheckParam ("newPwd", newPwd, 128); - - if (!CheckPassword (newPwd)) - throw new ArgumentException (string.Format ( - "New Password invalid. New Password length minimum: {0}. Non-alphanumeric characters required: {1}.", - MinRequiredPasswordLength, - MinRequiredNonAlphanumericCharacters)); - - using (DbConnection connection = CreateConnection ()) { - PasswordInfo pi = ValidateUsingPassword (username, oldPwd); - - if (pi != null) { - EmitValidatingPassword (username, newPwd, false); - string db_password = EncodePassword (newPwd, pi.PasswordFormat, pi.PasswordSalt); - - int st = DerbyMembershipHelper.Membership_SetPassword (connection, ApplicationName, username, db_password, (int) pi.PasswordFormat, pi.PasswordSalt, DateTime.UtcNow); - - if (st == 0) - return true; - } - return false; - } - } - - public override bool ChangePasswordQuestionAndAnswer (string username, string password, string newPwdQuestion, string newPwdAnswer) - { - if (username != null) username = username.Trim (); - if (newPwdQuestion != null) newPwdQuestion = newPwdQuestion.Trim (); - if (newPwdAnswer != null) newPwdAnswer = newPwdAnswer.Trim (); - - CheckParam ("username", username, 256); - if (RequiresQuestionAndAnswer) - CheckParam ("newPwdQuestion", newPwdQuestion, 128); - if (RequiresQuestionAndAnswer) - CheckParam ("newPwdAnswer", newPwdAnswer, 128); - - using (DbConnection connection = CreateConnection ()) { - PasswordInfo pi = ValidateUsingPassword (username, password); - - if (pi != null) { - string db_passwordAnswer = EncodePassword (newPwdAnswer, pi.PasswordFormat, pi.PasswordSalt); - - int st = DerbyMembershipHelper.Membership_ChangePasswordQuestionAndAnswer (connection, ApplicationName, username, newPwdQuestion, db_passwordAnswer); - - if (st == 0) - return true; - } - return false; - } - } - - public override MembershipUser CreateUser (string username, - string password, - string email, - string pwdQuestion, - string pwdAnswer, - bool isApproved, - object providerUserKey, - out MembershipCreateStatus status) - { - if (username != null) username = username.Trim (); - if (password != null) password = password.Trim (); - if (email != null) email = email.Trim (); - if (pwdQuestion != null) pwdQuestion = pwdQuestion.Trim (); - if (pwdAnswer != null) pwdAnswer = pwdAnswer.Trim (); - - /* some initial validation */ - if (username == null || username.Length == 0 || username.Length > 256 || username.IndexOf (",") != -1) { - status = MembershipCreateStatus.InvalidUserName; - return null; - } - if (password == null || password.Length == 0 || password.Length > 128) { - status = MembershipCreateStatus.InvalidPassword; - return null; - } - - if (!CheckPassword (password)) { - status = MembershipCreateStatus.InvalidPassword; - return null; - } - EmitValidatingPassword (username, password, true); - - if (RequiresUniqueEmail && (email == null || email.Length == 0)) { - status = MembershipCreateStatus.InvalidEmail; - return null; - } - if (RequiresQuestionAndAnswer && - (pwdQuestion == null || - pwdQuestion.Length == 0 || pwdQuestion.Length > 256)) { - status = MembershipCreateStatus.InvalidQuestion; - return null; - } - if (RequiresQuestionAndAnswer && - (pwdAnswer == null || - pwdAnswer.Length == 0 || pwdAnswer.Length > 128)) { - status = MembershipCreateStatus.InvalidAnswer; - return null; - } - if (providerUserKey != null && !(providerUserKey is Guid)) { - status = MembershipCreateStatus.InvalidProviderUserKey; - return null; - } - - /* encode our password/answer using the - * "passwordFormat" configuration option */ - string passwordSalt = ""; - - RandomNumberGenerator rng = RandomNumberGenerator.Create (); - byte [] salt = new byte [SALT_BYTES]; - rng.GetBytes (salt); - passwordSalt = Convert.ToBase64String (salt); - - password = EncodePassword (password, PasswordFormat, passwordSalt); - if (RequiresQuestionAndAnswer) - pwdAnswer = EncodePassword (pwdAnswer, PasswordFormat, passwordSalt); - - /* make sure the hashed/encrypted password and - * answer are still under 128 characters. */ - if (password.Length > 128) { - status = MembershipCreateStatus.InvalidPassword; - return null; - } - - if (RequiresQuestionAndAnswer) { - if (pwdAnswer.Length > 128) { - status = MembershipCreateStatus.InvalidAnswer; - return null; - } - } - status = MembershipCreateStatus.Success; - - using (DbConnection connection = CreateConnection ()) { - try { - - object helperUserKey = providerUserKey != null ? providerUserKey.ToString () : null; - DateTime Now = DateTime.UtcNow; - int st = DerbyMembershipHelper.Membership_CreateUser (connection, ApplicationName, username, password, passwordSalt, email, - pwdQuestion, pwdAnswer, isApproved, Now, Now, RequiresUniqueEmail, (int) PasswordFormat, ref helperUserKey); - - providerUserKey = new Guid ((string) helperUserKey); - if (st == 0) - return GetUser (providerUserKey, false); - else if (st == 2) - status = MembershipCreateStatus.DuplicateUserName; - else if (st == 3) - status = MembershipCreateStatus.DuplicateEmail; - else if (st == 9) - status = MembershipCreateStatus.InvalidProviderUserKey; - else if (st == 10) - status = MembershipCreateStatus.DuplicateProviderUserKey; - else - status = MembershipCreateStatus.ProviderError; - - return null; - } - catch (Exception) { - status = MembershipCreateStatus.ProviderError; - return null; - } - } - } - - private bool CheckPassword (string password) - { - if (password.Length < MinRequiredPasswordLength) - return false; - - if (MinRequiredNonAlphanumericCharacters > 0) { - int nonAlphanumeric = 0; - for (int i = 0; i < password.Length; i++) { - if (!Char.IsLetterOrDigit (password [i])) - nonAlphanumeric++; - } - return nonAlphanumeric >= MinRequiredNonAlphanumericCharacters; - } - return true; - } - - public override bool DeleteUser (string username, bool deleteAllRelatedData) - { - CheckParam ("username", username, 256); - - DeleteUserTableMask deleteBitmask = DeleteUserTableMask.MembershipUsers; - - if (deleteAllRelatedData) - deleteBitmask |= - DeleteUserTableMask.Profiles | - DeleteUserTableMask.UsersInRoles | - DeleteUserTableMask.WebPartStateUser; - - int num = 0; - using (DbConnection connection = CreateConnection ()) { - int st = DerbyMembershipHelper.Users_DeleteUser (connection, ApplicationName, username, (int) deleteBitmask, ref num); - - if (num == 0) - return false; - - if (st == 0) - return true; - - return false; - } - } - - public virtual string GeneratePassword () - { - return Membership.GeneratePassword (MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters); - } - - public override MembershipUserCollection FindUsersByEmail (string emailToMatch, int pageIndex, int pageSize, out int totalRecords) - { - CheckParam ("emailToMatch", emailToMatch, 256); - - if (pageIndex < 0) - throw new ArgumentException ("pageIndex must be >= 0"); - if (pageSize < 0) - throw new ArgumentException ("pageSize must be >= 0"); - if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue) - throw new ArgumentException ("pageIndex and pageSize are too large"); - - totalRecords = 0; - using (DbConnection connection = CreateConnection ()) { - DbDataReader reader = null; - - DerbyMembershipHelper.Membership_FindUsersByEmail (connection, ApplicationName, emailToMatch, pageSize, pageIndex, out reader); - if (reader == null) - return null; - - using (reader) { - return BuildMembershipUserCollection (reader, pageIndex, pageSize, out totalRecords); - } - } - } - - public override MembershipUserCollection FindUsersByName (string nameToMatch, int pageIndex, int pageSize, out int totalRecords) - { - CheckParam ("nameToMatch", nameToMatch, 256); - - if (pageIndex < 0) - throw new ArgumentException ("pageIndex must be >= 0"); - if (pageSize < 0) - throw new ArgumentException ("pageSize must be >= 0"); - if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue) - throw new ArgumentException ("pageIndex and pageSize are too large"); - - totalRecords = 0; - using (DbConnection connection = CreateConnection ()) { - DbDataReader reader = null; - - DerbyMembershipHelper.Membership_FindUsersByName (connection, ApplicationName, nameToMatch, pageSize, pageIndex, out reader); - if (reader == null) - return null; - - using (reader) { - return BuildMembershipUserCollection (reader, pageIndex, pageSize, out totalRecords); - } - } - } - - public override MembershipUserCollection GetAllUsers (int pageIndex, int pageSize, out int totalRecords) - { - if (pageIndex < 0) - throw new ArgumentException ("pageIndex must be >= 0"); - if (pageSize < 0) - throw new ArgumentException ("pageSize must be >= 0"); - if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue) - throw new ArgumentException ("pageIndex and pageSize are too large"); - - using (DbConnection connection = CreateConnection ()) { - DbDataReader reader = null; - totalRecords = DerbyMembershipHelper.Membership_GetAllUsers (connection, ApplicationName, pageIndex, pageSize, out reader); - return BuildMembershipUserCollection (reader, pageIndex, pageSize, out totalRecords); - } - } - - MembershipUserCollection BuildMembershipUserCollection (DbDataReader reader, int pageIndex, int pageSize, out int totalRecords) - { - int num_read = 0; - int num_added = 0; - int num_to_skip = pageIndex * pageSize; - MembershipUserCollection users = new MembershipUserCollection (); - try { - while (reader.Read ()) { - if (num_read >= num_to_skip) { - if (num_added < pageSize) { - users.Add (GetUserFromReader (reader)); - num_added++; - } - } - num_read++; - } - totalRecords = num_read; - return users; - } - catch (Exception) { - totalRecords = 0; - return null; /* should we let the exception through? */ - } - finally { - if (reader != null) - reader.Close (); - } - } - - public override int GetNumberOfUsersOnline () - { - using (DbConnection connection = CreateConnection ()) { - return DerbyMembershipHelper.Membership_GetNumberOfUsersOnline (connection, ApplicationName, userIsOnlineTimeWindow.Minutes, DateTime.UtcNow); - } - } - - public override string GetPassword (string username, string answer) - { - if (!EnablePasswordRetrieval) - throw new NotSupportedException ("this provider has not been configured to allow the retrieval of passwords"); - - CheckParam ("username", username, 256); - if (RequiresQuestionAndAnswer) - CheckParam ("answer", answer, 128); - - PasswordInfo pi = GetPasswordInfo (username); - if (pi == null) - throw new ProviderException ("An error occurred while retrieving the password from the database"); - - string user_answer = EncodePassword (answer, pi.PasswordFormat, pi.PasswordSalt); - string password = null; - - using (DbConnection connection = CreateConnection ()) { - int st = DerbyMembershipHelper.Membership_GetPassword (connection, ApplicationName, username, user_answer, MaxInvalidPasswordAttempts, PasswordAttemptWindow, DateTime.UtcNow, out password); - - if (st == 1) - throw new ProviderException ("User specified by username is not found in the membership database"); - - if (st == 2) - throw new MembershipPasswordException ("The membership user identified by username is locked out"); - - if (st == 3) - throw new MembershipPasswordException ("Password Answer is invalid"); - - return DecodePassword (password, pi.PasswordFormat); - } - } - - MembershipUser GetUserFromReader (DbDataReader reader) - { - return new MembershipUser ( - this.Name, /* XXX is this right? */ - reader.GetString (0), /* name */ - new Guid (reader.GetString (1)), /* providerUserKey */ - reader.IsDBNull (2) ? null : reader.GetString (2), /* email */ - reader.IsDBNull (3) ? null : reader.GetString (3), /* passwordQuestion */ - reader.IsDBNull (4) ? null : reader.GetString (4), /* comment */ - reader.GetInt32 (5) > 0, /* isApproved */ - reader.GetInt32 (6) > 0, /* isLockedOut */ - reader.GetDateTime (7).ToLocalTime (), /* creationDate */ - reader.GetDateTime (8).ToLocalTime (), /* lastLoginDate */ - reader.GetDateTime (9).ToLocalTime (), /* lastActivityDate */ - reader.GetDateTime (10).ToLocalTime (), /* lastPasswordChangedDate */ - reader.GetDateTime (11).ToLocalTime () /* lastLockoutDate */); - } - - public override MembershipUser GetUser (string username, bool userIsOnline) - { - if (username.Length == 0) - return null; - - CheckParam ("username", username, 256); - - using (DbConnection connection = CreateConnection ()) { - DbDataReader reader = null; - int st = DerbyMembershipHelper.Membership_GetUserByName (connection, ApplicationName, username, userIsOnline, DateTime.UtcNow, out reader); - using (reader) { - if (st == 0 && reader != null) { - MembershipUser u = GetUserFromReader (reader); - return u; - } - } - } - return null; - } - - public override MembershipUser GetUser (object providerUserKey, bool userIsOnline) - { - if (providerUserKey == null) - throw new ArgumentNullException ("providerUserKey"); - - if (!(providerUserKey is Guid)) - throw new ArgumentException ("providerUserKey is not of type Guid", "providerUserKey"); - - using (DbConnection connection = CreateConnection ()) { - DbDataReader reader = null; - int st = DerbyMembershipHelper.Membership_GetUserByUserId (connection, providerUserKey.ToString (), userIsOnline, DateTime.UtcNow, out reader); - using (reader) { - if (st == 0 && reader != null) { - MembershipUser u = GetUserFromReader (reader); - return u; - } - } - } - return null; - } - - public override string GetUserNameByEmail (string email) - { - CheckParam ("email", email, 256); - - string username = null; - - using (DbConnection connection = CreateConnection ()) { - int st = DerbyMembershipHelper.Membership_GetUserByEmail (connection, ApplicationName, email, out username); - - if (st == 1) - return null; - - if (st == 2 && RequiresUniqueEmail) - throw new ProviderException ("More than one user with the same e-mail address exists in the database and RequiresUniqueEmail is true"); - } - return username; - } - - bool GetBoolConfigValue (NameValueCollection config, string name, bool def) - { - bool rv = def; - string val = config [name]; - if (val != null) { - try { rv = Boolean.Parse (val); } - catch (Exception e) { - throw new ProviderException (String.Format ("{0} must be true or false", name), e); - } - } - return rv; - } - - int GetIntConfigValue (NameValueCollection config, string name, int def) - { - int rv = def; - string val = config [name]; - if (val != null) { - try { rv = Int32.Parse (val); } - catch (Exception e) { - throw new ProviderException (String.Format ("{0} must be an integer", name), e); - } - } - return rv; - } - - int GetEnumConfigValue (NameValueCollection config, string name, Type enumType, int def) - { - int rv = def; - string val = config [name]; - if (val != null) { - try { rv = (int) Enum.Parse (enumType, val); } - catch (Exception e) { - throw new ProviderException (String.Format ("{0} must be one of the following values: {1}", name, String.Join (",", Enum.GetNames (enumType))), e); - } - } - return rv; - } - - string GetStringConfigValue (NameValueCollection config, string name, string def) - { - string rv = def; - string val = config [name]; - if (val != null) - rv = val; - return rv; - } - - void EmitValidatingPassword (string username, string password, bool isNewUser) - { - ValidatePasswordEventArgs args = new ValidatePasswordEventArgs (username, password, isNewUser); - OnValidatingPassword (args); - - /* if we're canceled.. */ - if (args.Cancel) { - if (args.FailureInformation == null) - throw new ProviderException ("Password validation canceled"); - else - throw args.FailureInformation; - } - } - - public override void Initialize (string name, NameValueCollection config) - { - if (config == null) - throw new ArgumentNullException ("config"); - - base.Initialize (name, config); - - applicationName = GetStringConfigValue (config, "applicationName", "/"); - enablePasswordReset = GetBoolConfigValue (config, "enablePasswordReset", true); - enablePasswordRetrieval = GetBoolConfigValue (config, "enablePasswordRetrieval", false); - requiresQuestionAndAnswer = GetBoolConfigValue (config, "requiresQuestionAndAnswer", true); - requiresUniqueEmail = GetBoolConfigValue (config, "requiresUniqueEmail", false); - passwordFormat = (MembershipPasswordFormat) GetEnumConfigValue (config, "passwordFormat", typeof (MembershipPasswordFormat), - (int) MembershipPasswordFormat.Hashed); - maxInvalidPasswordAttempts = GetIntConfigValue (config, "maxInvalidPasswordAttempts", 5); - minRequiredPasswordLength = GetIntConfigValue (config, "minRequiredPasswordLength", 7); - minRequiredNonAlphanumericCharacters = GetIntConfigValue (config, "minRequiredNonAlphanumericCharacters", 1); - passwordAttemptWindow = GetIntConfigValue (config, "passwordAttemptWindow", 10); - passwordStrengthRegularExpression = GetStringConfigValue (config, "passwordStrengthRegularExpression", ""); - - MembershipSection section = (MembershipSection) WebConfigurationManager.GetSection ("system.web/membership"); - - userIsOnlineTimeWindow = section.UserIsOnlineTimeWindow; - - /* we can't support password retrieval with hashed passwords */ - if (passwordFormat == MembershipPasswordFormat.Hashed && enablePasswordRetrieval) - throw new ProviderException ("password retrieval cannot be used with hashed passwords"); - - string connectionStringName = config ["connectionStringName"]; - - if (applicationName.Length > 256) - throw new ProviderException ("The ApplicationName attribute must be 256 characters long or less."); - if (connectionStringName == null || connectionStringName.Length == 0) - throw new ProviderException ("The ConnectionStringName attribute must be present and non-zero length."); - - connectionString = WebConfigurationManager.ConnectionStrings [connectionStringName]; - if (connectionString == null) - throw new ProviderException (String.Format ("The connection name '{0}' was not found in the applications configuration or the connection string is empty.", connectionStringName)); - - if (connectionString == null) - throw new ProviderException (String.Format ("The connection name '{0}' was not found in the applications configuration or the connection string is empty.", connectionStringName)); - - string shutdown = config ["shutdown"]; - if (!String.IsNullOrEmpty (shutdown)) - shutDownPolicy = (DerbyUnloadManager.DerbyShutDownPolicy) Enum.Parse (typeof (DerbyUnloadManager.DerbyShutDownPolicy), shutdown, true); - } - - public override string ResetPassword (string username, string answer) - { - if (!EnablePasswordReset) - throw new NotSupportedException ("this provider has not been configured to allow the resetting of passwords"); - - CheckParam ("username", username, 256); - - if (RequiresQuestionAndAnswer) - CheckParam ("answer", answer, 128); - - using (DbConnection connection = CreateConnection ()) { - PasswordInfo pi = GetPasswordInfo (username); - if (pi == null) - throw new ProviderException (username + "is not found in the membership database"); - - string newPassword = GeneratePassword (); - EmitValidatingPassword (username, newPassword, false); - - string db_password = EncodePassword (newPassword, pi.PasswordFormat, pi.PasswordSalt); - string db_answer = EncodePassword (answer, pi.PasswordFormat, pi.PasswordSalt); - - int st = DerbyMembershipHelper.Membership_ResetPassword (connection, ApplicationName, username, db_password, db_answer, (int) pi.PasswordFormat, pi.PasswordSalt, MaxInvalidPasswordAttempts, PasswordAttemptWindow, DateTime.UtcNow); - - if (st == 0) - return newPassword; - else if (st == 1) - throw new ProviderException (username + " is not found in the membership database"); - else if (st == 2) - throw new MembershipPasswordException ("The user account is currently locked out"); - else if (st == 3) - throw new MembershipPasswordException ("Password Answer is invalid"); - else - throw new ProviderException ("Failed to reset password"); - } - } - - public override void UpdateUser (MembershipUser user) - { - if (user == null) - throw new ArgumentNullException ("user"); - - if (user.UserName == null) - throw new ArgumentNullException ("user.UserName"); - - if (RequiresUniqueEmail && user.Email == null) - throw new ArgumentNullException ("user.Email"); - - CheckParam ("user.UserName", user.UserName, 256); - - if (user.Email.Length > 256 || (RequiresUniqueEmail && user.Email.Length == 0)) - throw new ArgumentException ("invalid format for user.Email"); - - using (DbConnection connection = CreateConnection ()) { - int st = DerbyMembershipHelper.Membership_UpdateUser (connection, ApplicationName, user.UserName, user.Email, user.Comment, user.IsApproved, RequiresUniqueEmail, user.LastLoginDate, DateTime.UtcNow, DateTime.UtcNow); - - if (st == 1) - throw new ProviderException ("The UserName property of user was not found in the database."); - if (st == 2) - throw new ProviderException ("The Email property of user was equal to an existing e-mail address in the database and RequiresUniqueEmail is set to true."); - if (st != 0) - throw new ProviderException ("Failed to update user"); - } - } - - public override bool ValidateUser (string username, string password) - { - if (username.Length == 0) - return false; - - CheckParam ("username", username, 256); - EmitValidatingPassword (username, password, false); - - PasswordInfo pi = ValidateUsingPassword (username, password); - if (pi != null) { - pi.LastLoginDate = DateTime.UtcNow; - UpdateUserInfo (username, pi, true, true); - return true; - } - return false; - } - - public override bool UnlockUser (string username) - { - CheckParam ("username", username, 256); - - using (DbConnection connection = CreateConnection ()) { - try { - int st = DerbyMembershipHelper.Membership_UnlockUser (connection, ApplicationName, username); - - if (st == 0) - return true; - } - catch (Exception e) { - throw new ProviderException ("Failed to unlock user", e); - } - } - return false; - } - - void UpdateUserInfo (string username, PasswordInfo pi, bool isPasswordCorrect, bool updateLoginActivity) - { - CheckParam ("username", username, 256); - - using (DbConnection connection = CreateConnection ()) { - try { - int st = DerbyMembershipHelper.Membership_UpdateUserInfo (connection, ApplicationName, username, isPasswordCorrect, updateLoginActivity, - MaxInvalidPasswordAttempts, PasswordAttemptWindow, DateTime.UtcNow, pi.LastLoginDate, pi.LastActivityDate); - - if (st == 0) - return; - } - catch (Exception e) { - throw new ProviderException ("Failed to update Membership table", e); - } - - } - } - - PasswordInfo ValidateUsingPassword (string username, string password) - { - MembershipUser user = GetUser (username, true); - if (user == null) - return null; - - if (!user.IsApproved || user.IsLockedOut) - return null; - - PasswordInfo pi = GetPasswordInfo (username); - - if (pi == null) - return null; - - /* do the actual validation */ - string user_password = EncodePassword (password, pi.PasswordFormat, pi.PasswordSalt); - - if (user_password != pi.Password) { - UpdateUserInfo (username, pi, false, false); - return null; - } - - return pi; - } - - private PasswordInfo GetPasswordInfo (string username) - { - using (DbConnection connection = CreateConnection ()) { - DbDataReader reader = null; - DerbyMembershipHelper.Membership_GetPasswordWithFormat (connection, ApplicationName, username, false, DateTime.UtcNow, out reader); - - PasswordInfo pi = null; - if (reader == null) - return null; - - using (reader) { - if (reader.Read ()) { - int isLockedOut = reader.GetInt32 (1); - if (isLockedOut > 0) - return null; - - pi = new PasswordInfo ( - reader.GetString (3), - (MembershipPasswordFormat) reader.GetInt32 (4), - reader.GetString (5), - reader.GetInt32 (6), - reader.GetInt32 (7), - reader.GetInt32 (2) > 0, - reader.GetDateTime (8), - reader.GetDateTime (9)); - } - } - return pi; - } - } - - private string EncodePassword (string password, MembershipPasswordFormat passwordFormat, string salt) - { - byte [] password_bytes; - byte [] salt_bytes; - - switch (passwordFormat) { - case MembershipPasswordFormat.Clear: - return password; - case MembershipPasswordFormat.Hashed: - password_bytes = Encoding.Unicode.GetBytes (password); - salt_bytes = Convert.FromBase64String (salt); - - byte [] hashBytes = new byte [salt_bytes.Length + password_bytes.Length]; - - Buffer.BlockCopy (salt_bytes, 0, hashBytes, 0, salt_bytes.Length); - Buffer.BlockCopy (password_bytes, 0, hashBytes, salt_bytes.Length, password_bytes.Length); - - MembershipSection section = (MembershipSection) WebConfigurationManager.GetSection ("system.web/membership"); - string alg_type = section.HashAlgorithmType; - if (alg_type == "") { - MachineKeySection keysection = (MachineKeySection) WebConfigurationManager.GetSection ("system.web/machineKey"); - alg_type = keysection.Validation.ToString (); - } - using (HashAlgorithm hash = HashAlgorithm.Create (alg_type)) { - hash.TransformFinalBlock (hashBytes, 0, hashBytes.Length); - return Convert.ToBase64String (hash.Hash); - } - case MembershipPasswordFormat.Encrypted: - password_bytes = Encoding.Unicode.GetBytes (password); - salt_bytes = Convert.FromBase64String (salt); - - byte [] buf = new byte [password_bytes.Length + salt_bytes.Length]; - - Array.Copy (salt_bytes, 0, buf, 0, salt_bytes.Length); - Array.Copy (password_bytes, 0, buf, salt_bytes.Length, password_bytes.Length); - - return Convert.ToBase64String (EncryptPassword (buf)); - default: - /* not reached.. */ - return null; - } - } - - private string DecodePassword (string password, MembershipPasswordFormat passwordFormat) - { - switch (passwordFormat) { - case MembershipPasswordFormat.Clear: - return password; - case MembershipPasswordFormat.Hashed: - throw new ProviderException ("Hashed passwords cannot be decoded."); - case MembershipPasswordFormat.Encrypted: - return Encoding.Unicode.GetString (DecryptPassword (Convert.FromBase64String (password))); - default: - /* not reached.. */ - return null; - } - } - - public override string ApplicationName - { - get { return applicationName; } - set { applicationName = value; } - } - - public override bool EnablePasswordReset - { - get { return enablePasswordReset; } - } - - public override bool EnablePasswordRetrieval - { - get { return enablePasswordRetrieval; } - } - - public override MembershipPasswordFormat PasswordFormat - { - get { return passwordFormat; } - } - - public override bool RequiresQuestionAndAnswer - { - get { return requiresQuestionAndAnswer; } - } - - public override bool RequiresUniqueEmail - { - get { return requiresUniqueEmail; } - } - - public override int MaxInvalidPasswordAttempts - { - get { return maxInvalidPasswordAttempts; } - } - - public override int MinRequiredNonAlphanumericCharacters - { - get { return minRequiredNonAlphanumericCharacters; } - } - - public override int MinRequiredPasswordLength - { - get { return minRequiredPasswordLength; } - } - - public override int PasswordAttemptWindow - { - get { return passwordAttemptWindow; } - } - - public override string PasswordStrengthRegularExpression - { - get { return passwordStrengthRegularExpression; } - } - - [Flags] - private enum DeleteUserTableMask - { - MembershipUsers = 1, - UsersInRoles = 2, - Profiles = 4, - WebPartStateUser = 8 - } - - private sealed class PasswordInfo - { - private string _password; - private MembershipPasswordFormat _passwordFormat; - private string _passwordSalt; - private int _failedPasswordAttemptCount; - private int _failedPasswordAnswerAttemptCount; - private bool _isApproved; - private DateTime _lastLoginDate; - private DateTime _lastActivityDate; - - internal PasswordInfo ( - string password, - MembershipPasswordFormat passwordFormat, - string passwordSalt, - int failedPasswordAttemptCount, - int failedPasswordAnswerAttemptCount, - bool isApproved, - DateTime lastLoginDate, - DateTime lastActivityDate) - { - _password = password; - _passwordFormat = passwordFormat; - _passwordSalt = passwordSalt; - _failedPasswordAttemptCount = failedPasswordAttemptCount; - _failedPasswordAnswerAttemptCount = failedPasswordAnswerAttemptCount; - _isApproved = isApproved; - _lastLoginDate = lastLoginDate; - _lastActivityDate = lastActivityDate; - } - - public string Password - { - get { return _password; } - set { _password = value; } - } - public MembershipPasswordFormat PasswordFormat - { - get { return _passwordFormat; } - set { _passwordFormat = value; } - } - public string PasswordSalt - { - get { return _passwordSalt; } - set { _passwordSalt = value; } - } - public int FailedPasswordAttemptCount - { - get { return _failedPasswordAttemptCount; } - set { _failedPasswordAttemptCount = value; } - } - public int FailedPasswordAnswerAttemptCount - { - get { return _failedPasswordAnswerAttemptCount; } - set { _failedPasswordAnswerAttemptCount = value; } - } - public bool IsApproved - { - get { return _isApproved; } - set { _isApproved = value; } - } - public DateTime LastLoginDate - { - get { return _lastLoginDate; } - set { _lastLoginDate = value; } - } - public DateTime LastActivityDate - { - get { return _lastActivityDate; } - set { _lastActivityDate = value; } - } - } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyRoleProvider.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyRoleProvider.cs deleted file mode 100644 index 0f488be366e..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyRoleProvider.cs +++ /dev/null @@ -1,374 +0,0 @@ -// -// Mainsoft.Web.Security.DerbyRoleProvider -// -// Authors: -// Ben Maurer (bmaurer@users.sourceforge.net) -// Chris Toshok (toshok@ximian.com) -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// -// 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. -// - - -using System; -using System.Collections; -using System.Collections.Specialized; -using System.Data; -using System.Data.OleDb; -using System.Data.Common; -using System.Configuration; -using System.Configuration.Provider; -using System.Web.Configuration; -using System.Web.Security; - -namespace Mainsoft.Web.Security -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// Manages storage of role membership information for an ASP.NET application in a Derby database. - /// - public class DerbyRoleProvider : RoleProvider - { - ConnectionStringSettings connectionString; - string applicationName; - bool schemaChecked = false; - DerbyUnloadManager.DerbyShutDownPolicy shutDownPolicy = DerbyUnloadManager.DerbyShutDownPolicy.Default; - - DbConnection CreateConnection () - { - if (!schemaChecked) { - DerbyDBSchema.CheckSchema (connectionString.ConnectionString); - schemaChecked = true; - - DerbyUnloadManager.RegisterUnloadHandler (connectionString.ConnectionString, shutDownPolicy); - } - - OleDbConnection connection = new OleDbConnection (connectionString.ConnectionString); - connection.Open (); - return connection; - } - - public override void AddUsersToRoles (string [] usernames, string [] rolenames) - { - Hashtable h = new Hashtable (); - - foreach (string u in usernames) { - if (u == null) - throw new ArgumentNullException ("null element in usernames array"); - if (h.ContainsKey (u)) - throw new ArgumentException ("duplicate element in usernames array"); - if (u.Length == 0 || u.Length > 256 || u.IndexOf (",") != -1) - throw new ArgumentException ("element in usernames array in illegal format"); - h.Add (u, u); - } - - h = new Hashtable (); - foreach (string r in rolenames) { - if (r == null) - throw new ArgumentNullException ("null element in rolenames array"); - if (h.ContainsKey (r)) - throw new ArgumentException ("duplicate element in rolenames array"); - if (r.Length == 0 || r.Length > 256 || r.IndexOf (",") != -1) - throw new ArgumentException ("element in rolenames array in illegal format"); - h.Add (r, r); - } - - using (DbConnection connection = CreateConnection ()) { - int returnValue = DerbyRolesHelper.UsersInRoles_AddUsersToRoles (connection, ApplicationName, usernames, rolenames, DateTime.UtcNow); - - if (returnValue == 0) - return; - else if (returnValue == 2) - throw new ProviderException ("One or more of the specified role names was not found."); - else if (returnValue == 3) - throw new ProviderException ("One or more of the specified user names is already associated with one or more of the specified role names."); - else - throw new ProviderException ("Failed to create new user/role association."); - } - } - - public override void CreateRole (string rolename) - { - if (rolename == null) - throw new ArgumentNullException ("rolename"); - - if (rolename.Length == 0 || rolename.Length > 256 || rolename.IndexOf (",") != -1) - throw new ArgumentException ("rolename is in invalid format"); - - using (DbConnection connection = CreateConnection ()) { - int returnValue = DerbyRolesHelper.Roles_CreateRole (connection, ApplicationName, rolename); - - if (returnValue == 2) - throw new ProviderException (rolename + " already exists in the database"); - else - return; - } - } - - public override bool DeleteRole (string rolename, bool throwOnPopulatedRole) - { - if (rolename == null) - throw new ArgumentNullException ("rolename"); - - if (rolename.Length == 0 || rolename.Length > 256 || rolename.IndexOf (",") != -1) - throw new ArgumentException ("rolename is in invalid format"); - - using (DbConnection connection = CreateConnection ()) { - int returnValue = DerbyRolesHelper.Roles_DeleteRole (connection, ApplicationName, rolename, throwOnPopulatedRole); - - if (returnValue == 0) - return true; - if (returnValue == 2) - return false; //role does not exist - else if (returnValue == 3 && throwOnPopulatedRole) - throw new ProviderException (rolename + " is not empty"); - else - return false; - } - } - - public override string [] FindUsersInRole (string roleName, string usernameToMatch) - { - if (roleName == null) - throw new ArgumentNullException ("roleName"); - if (usernameToMatch == null) - throw new ArgumentNullException ("usernameToMatch"); - if (roleName.Length == 0 || roleName.Length > 256 || roleName.IndexOf (",") != -1) - throw new ArgumentException ("roleName is in invalid format"); - if (usernameToMatch.Length == 0 || usernameToMatch.Length > 256) - throw new ArgumentException ("usernameToMatch is in invalid format"); - - using (DbConnection connection = CreateConnection ()) { - DbDataReader reader; - ArrayList userList = new ArrayList (); - int returnValue = DerbyRolesHelper.UsersInRoles_FindUsersInRole (connection, applicationName, roleName, usernameToMatch, out reader); - - if (returnValue == 2) - throw new ProviderException ("The role '" + roleName + "' was not found."); - - using (reader) { - if (reader == null) - return new string [] { }; - - while (reader.Read ()) - userList.Add (reader.GetString (0)); - } - return (string []) userList.ToArray (typeof (string)); - } - } - - public override string [] GetAllRoles () - { - using (DbConnection connection = CreateConnection ()) { - DbDataReader reader; - ArrayList roleList = new ArrayList (); - DerbyRolesHelper.Roles_GetAllRoles (connection, applicationName, out reader); - using (reader) { - if (reader == null) - return new string [] { }; - - while (reader.Read ()) - roleList.Add (reader.GetString (0)); - } - return (string []) roleList.ToArray (typeof (string)); - } - } - - public override string [] GetRolesForUser (string username) - { - if (username == null) - throw new ArgumentNullException ("rolename"); - - if (username.Length == 0 || username.Length > 256 || username.IndexOf (",") != -1) - throw new ArgumentException ("username is in invalid format"); - - using (DbConnection connection = CreateConnection ()) { - DbDataReader reader; - ArrayList roleList = new ArrayList (); - int returnValue = DerbyRolesHelper.UsersInRoles_GetRolesForUser (connection, applicationName, username, out reader); - - if (returnValue == 2) - throw new ProviderException ("username was not found in the database"); - - using (reader) { - if (reader == null) - return new string [] { }; - - while (reader.Read ()) - roleList.Add (reader.GetString (0)); - } - return (string []) roleList.ToArray (typeof (string)); - } - } - - public override string [] GetUsersInRole (string rolename) - { - if (rolename == null) - throw new ArgumentNullException ("rolename"); - - if (rolename.Length == 0 || rolename.Length > 256 || rolename.IndexOf (",") != -1) - throw new ArgumentException ("rolename is in invalid format"); - - using (DbConnection connection = CreateConnection ()) { - DbDataReader reader; - ArrayList roleList = new ArrayList (); - int returnValue = DerbyRolesHelper.UsersInRoles_GetUsersInRoles (connection, applicationName, rolename, out reader); - - if (returnValue == 2) - throw new ProviderException ("The role '" + rolename + "' was not found."); - - using (reader) { - if (reader == null) - return new string [] { }; - - while (reader.Read ()) - roleList.Add (reader.GetString (0)); - } - return (string []) roleList.ToArray (typeof (string)); - } - } - - string GetStringConfigValue (NameValueCollection config, string name, string def) - { - string rv = def; - string val = config [name]; - if (val != null) - rv = val; - return rv; - } - - public override void Initialize (string name, NameValueCollection config) - { - if (config == null) - throw new ArgumentNullException ("config"); - - base.Initialize (name, config); - - applicationName = config ["applicationName"]; - string connectionStringName = config ["connectionStringName"]; - - if (applicationName.Length > 256) - throw new ProviderException ("The ApplicationName attribute must be 256 characters long or less."); - if (connectionStringName == null || connectionStringName.Length == 0) - throw new ProviderException ("The ConnectionStringName attribute must be present and non-zero length."); - - // XXX check connectionStringName and commandTimeout - - connectionString = WebConfigurationManager.ConnectionStrings [connectionStringName]; - if (connectionString == null) - throw new ProviderException (String.Format("The connection name '{0}' was not found in the applications configuration or the connection string is empty.", connectionStringName)); - - string shutdown = config ["shutdown"]; - if (!String.IsNullOrEmpty (shutdown)) - shutDownPolicy = (DerbyUnloadManager.DerbyShutDownPolicy) Enum.Parse (typeof (DerbyUnloadManager.DerbyShutDownPolicy), shutdown, true); - } - - public override bool IsUserInRole (string username, string rolename) - { - if (username == null) - throw new ArgumentNullException ("rolename"); - if (username.Length == 0 || username.Length > 256 || username.IndexOf (",") != -1) - throw new ArgumentException ("username is in invalid format"); - if (rolename == null) - throw new ArgumentNullException ("rolename"); - if (rolename.Length == 0 || rolename.Length > 256 || rolename.IndexOf (",") != -1) - throw new ArgumentException ("rolename is in invalid format"); - - using (DbConnection connection = CreateConnection ()) { - int returnValue = DerbyRolesHelper.UsersInRoles_IsUserInRole (connection, ApplicationName, username, rolename); - - if (returnValue == 4) - return true; - - return false; - } - } - - public override void RemoveUsersFromRoles (string [] usernames, string [] rolenames) - { - Hashtable h = new Hashtable (); - - foreach (string u in usernames) { - if (u == null) - throw new ArgumentNullException ("null element in usernames array"); - if (h.ContainsKey (u)) - throw new ArgumentException ("duplicate element in usernames array"); - if (u.Length == 0 || u.Length > 256 || u.IndexOf (",") != -1) - throw new ArgumentException ("element in usernames array in illegal format"); - h.Add (u, u); - } - - h = new Hashtable (); - foreach (string r in rolenames) { - if (r == null) - throw new ArgumentNullException ("null element in rolenames array"); - if (h.ContainsKey (r)) - throw new ArgumentException ("duplicate element in rolenames array"); - if (r.Length == 0 || r.Length > 256 || r.IndexOf (",") != -1) - throw new ArgumentException ("element in rolenames array in illegal format"); - h.Add (r, r); - } - - using (DbConnection connection = CreateConnection ()) { - int returnValue = DerbyRolesHelper.UsersInRoles_RemoveUsersFromRoles (connection, ApplicationName, usernames, rolenames); - - if (returnValue == 0) - return; - else if (returnValue == 2) - throw new ProviderException ("One or more of the specified user names was not found."); - else if (returnValue == 3) - throw new ProviderException ("One or more of the specified role names was not found."); - else if (returnValue == 4) - throw new ProviderException ("One or more of the specified user names is not associated with one or more of the specified role names."); - else - throw new ProviderException ("Failed to remove users from roles"); - } - } - - public override bool RoleExists (string rolename) - { - if (rolename == null) - throw new ArgumentNullException ("rolename"); - - if (rolename.Length == 0 || rolename.Length > 256 || rolename.IndexOf (",") != -1) - throw new ArgumentException ("rolename is in invalid format"); - - using (DbConnection connection = CreateConnection ()) { - int returnValue = DerbyRolesHelper.Roles_RoleExists (connection, ApplicationName, rolename); - - if (returnValue == 2) - return true; - - return false; - } - } - - public override string ApplicationName - { - get { return applicationName; } - set - { - applicationName = value; - } - } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyRolesHelper.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyRolesHelper.cs deleted file mode 100644 index 04c6ccb0dfe..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyRolesHelper.cs +++ /dev/null @@ -1,428 +0,0 @@ -// -// Mainsoft.Web.Security.DerbyRolesHelper -// -// Authors: -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// (C) 2006 Mainsoft -// -// -// 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. -// - - -using System; -using System.Web.Security; -using System.Data; -using System.Data.OleDb; -using System.Data.Common; -using System.Collections.Generic; -using System.Text; - -namespace Mainsoft.Web.Security -{ - static class DerbyRolesHelper - { - private static OleDbParameter AddParameter (OleDbCommand command, string paramName, object paramValue) - { - OleDbParameter prm = new OleDbParameter (paramName, paramValue); - command.Parameters.Add (prm); - return prm; - } - - public static int Roles_CreateRole (DbConnection connection, string applicationName, string rolename) - { - string appId = (string) DerbyApplicationsHelper.Applications_CreateApplication (connection, applicationName); - if (appId == null) - return 1; - - string querySelect = "SELECT RoleName FROM aspnet_Roles WHERE ApplicationId = ? AND LoweredRoleName = ?"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "ApplicationId", appId); - AddParameter (cmdSelect, "LoweredRoleName", rolename.ToLowerInvariant ()); - - using (OleDbDataReader reader = cmdSelect.ExecuteReader ()) { - if (reader.Read ()) - return 2; // role already exists - } - - string queryInsert = "INSERT INTO aspnet_Roles (ApplicationId, RoleId, RoleName, LoweredRoleName) VALUES (?, ?, ?, ?)"; - OleDbCommand cmdInsert = new OleDbCommand (queryInsert, (OleDbConnection) connection); - AddParameter (cmdInsert, "ApplicationId", appId); - AddParameter (cmdInsert, "RoleId", Guid.NewGuid ().ToString ()); - AddParameter (cmdInsert, "RoleName", rolename); - AddParameter (cmdInsert, "LoweredRoleName", rolename.ToLowerInvariant ()); - cmdInsert.ExecuteNonQuery (); - - return 0; - } - - public static int Roles_DeleteRole (DbConnection connection, string applicationName, string rolename, bool deleteOnlyIfRoleIsEmpty) - { - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return 1; - - string roleId = GetRoleId (connection, appId, rolename); - if (roleId == null) - return 2; - - if (deleteOnlyIfRoleIsEmpty) { - string querySelect = "SELECT RoleId FROM aspnet_UsersInRoles WHERE RoleId = ?"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "RoleId", roleId); - using (OleDbDataReader reader = cmdSelect.ExecuteReader ()) { - if (reader.Read ()) - // role is not empty - return 3; - } - } - - string queryDelUsers = "DELETE FROM aspnet_UsersInRoles WHERE RoleId = ?"; - OleDbCommand cmdDelUsers = new OleDbCommand (queryDelUsers, (OleDbConnection) connection); - AddParameter (cmdDelUsers, "RoleId", roleId); - cmdDelUsers.ExecuteNonQuery (); - - string queryDelRole = "DELETE FROM aspnet_Roles WHERE ApplicationId = ? AND RoleId = ? "; - OleDbCommand cmdDelRole = new OleDbCommand (queryDelRole, (OleDbConnection) connection); - AddParameter (cmdDelRole, "ApplicationId", appId); - AddParameter (cmdDelRole, "RoleId", roleId); - cmdDelRole.ExecuteNonQuery (); - - return 0; - } - - public static int Roles_GetAllRoles (DbConnection connection, string applicationName, out DbDataReader reader) - { - reader = null; - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return 1; - - string querySelect = "SELECT RoleName FROM aspnet_Roles WHERE ApplicationId = ? ORDER BY RoleName"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "ApplicationId", appId); - reader = cmdSelect.ExecuteReader (); - - return 0; - } - - public static int Roles_RoleExists (DbConnection connection, string applicationName, string rolename) - { - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return 1; - - string querySelect = "SELECT RoleName FROM aspnet_Roles WHERE ApplicationId = ? AND LoweredRoleName = ?"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "ApplicationId", appId); - AddParameter (cmdSelect, "LoweredRoleName", rolename.ToLowerInvariant ()); - - using (OleDbDataReader reader = cmdSelect.ExecuteReader ()) { - if (reader.Read ()) - return 2; - } - return 0; - } - - public static int UsersInRoles_AddUsersToRoles (DbConnection connection, string applicationName, string [] userNames, string [] roleNames, DateTime currentTimeUtc) - { - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return 1; - - string [] userIds = new string [userNames.Length]; - string [] loweredUsernames = new string [userNames.Length]; - string [] roleIds = new string [roleNames.Length]; - - string querySelUsers = "SELECT UserId, LoweredUserName FROM aspnet_Users WHERE ApplicationId = ? AND LoweredUserName in " + GetPrms (userNames.Length); - OleDbCommand cmdSelUsers = new OleDbCommand (querySelUsers, (OleDbConnection) connection); - AddParameter (cmdSelUsers, "ApplicationId", appId); - for (int i = 0; i < userNames.Length; i++) - AddParameter (cmdSelUsers, "LoweredUserName", userNames [i].ToLowerInvariant ()); - - int userIndex = 0; - using (OleDbDataReader reader = cmdSelUsers.ExecuteReader ()) { - while (reader.Read ()) { - userIds [userIndex] = reader.GetString (0); - loweredUsernames [userIndex] = reader.GetString (1); - userIndex++; - } - } - - if (userNames.Length != userIndex) { - // find not existing users and create them - for (int j = 0; j < userNames.Length; j++) - if (Array.IndexOf (loweredUsernames, userNames [j].ToLowerInvariant ()) < 0) { - string newUserId = Guid.NewGuid ().ToString (); - string queryAddUser = "INSERT INTO aspnet_Users (ApplicationId, UserId, UserName, " + - "LoweredUserName, IsAnonymous, LastActivityDate) VALUES (?, ?, ?, ?, ?, ?)"; - OleDbCommand cmdAddUser = new OleDbCommand (queryAddUser, (OleDbConnection) connection); - AddParameter (cmdAddUser, "ApplicationId", appId); - AddParameter (cmdAddUser, "UserId", newUserId); - AddParameter (cmdAddUser, "UserName", userNames [j]); - AddParameter (cmdAddUser, "LoweredUserName", userNames [j].ToLowerInvariant ()); - AddParameter (cmdAddUser, "IsAnonymous", 0); - AddParameter (cmdAddUser, "LastActivityDate", DateTime.UtcNow); - cmdAddUser.ExecuteNonQuery (); - - userIds [userIndex++] = newUserId; - } - } - - - string querySelRoles = "SELECT RoleId FROM aspnet_Roles WHERE ApplicationId = ? AND LoweredRoleName in " + GetPrms (roleNames.Length); - OleDbCommand cmdSelRoles = new OleDbCommand (querySelRoles, (OleDbConnection) connection); - AddParameter (cmdSelRoles, "ApplicationId", appId); - for (int i = 0; i < roleNames.Length; i++) - AddParameter (cmdSelRoles, "LoweredRoleName", roleNames [i].ToLowerInvariant ()); - - using (OleDbDataReader reader = cmdSelRoles.ExecuteReader ()) { - int i = 0; - while (reader.Read ()) - roleIds [i++] = reader.GetString (0); - - if (roleNames.Length != i) - return 2; // one or more roles not found - } - - string querySelCount = "SELECT COUNT(*) FROM aspnet_UsersInRoles WHERE UserId in " + GetPrms (userNames.Length) + " AND RoleId in " + GetPrms (roleNames.Length); - OleDbCommand cmdSelCount = new OleDbCommand (querySelCount, (OleDbConnection) connection); - foreach (string userId in userIds) - AddParameter (cmdSelCount, "UserId", userId); - foreach (string roleId in roleIds) - AddParameter (cmdSelCount, "RoleId", roleId); - using (OleDbDataReader reader = cmdSelCount.ExecuteReader ()) { - if (reader.Read ()) - if (reader.GetInt32 (0) > 0) - return 3; - } - - string valuesExp = string.Empty; - int pairs = userNames.Length * roleNames.Length; - for (int i = 0; i < pairs; i++) - valuesExp += "(?, ?),"; - - string queryInsert = "INSERT INTO aspnet_UsersInRoles (UserId, RoleId) VALUES " + valuesExp.Trim (','); - OleDbCommand cmdInsert = new OleDbCommand (queryInsert, (OleDbConnection) connection); - foreach (string roleId in roleIds) - foreach (string userId in userIds) { - AddParameter (cmdInsert, "UserId", userId); - AddParameter (cmdInsert, "RoleId", roleId); - } - - cmdInsert.ExecuteNonQuery (); - return 0; - } - - public static int UsersInRoles_FindUsersInRole (DbConnection connection, string applicationName, string rolename, string userNameToMatch, out DbDataReader reader) - { - reader = null; - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return 1; - - string roleId = GetRoleId (connection, appId, rolename); - if (roleId == null) - return 2; - - string querySelect = "SELECT usr.UserName FROM aspnet_Users usr, aspnet_UsersInRoles uir " + - "WHERE usr.UserId = uir.UserId AND usr.ApplicationId = ? AND uir.RoleId = ? AND LoweredUserName LIKE ? " + - "ORDER BY usr.UserName"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "ApplicationId", appId); - AddParameter (cmdSelect, "RoleId", roleId); - AddParameter (cmdSelect, "LoweredUserName", "%" + userNameToMatch.ToLowerInvariant() + "%"); - reader = cmdSelect.ExecuteReader (); - - return 0; - } - - public static int UsersInRoles_GetRolesForUser (DbConnection connection, string applicationName, string username, out DbDataReader reader) - { - reader = null; - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return 1; - - string userId = GetUserId (connection, appId, username); - if (userId == null) - return 2; - - string querySelect = "SELECT rol.RoleName FROM aspnet_Roles rol, aspnet_UsersInRoles uir " + - "WHERE rol.RoleId = uir.RoleId AND rol.ApplicationId = ? AND uir.UserId = ? ORDER BY rol.RoleName"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "ApplicationId", appId); - AddParameter (cmdSelect, "UserId", userId); - reader = cmdSelect.ExecuteReader (); - - return 0; - } - - public static int UsersInRoles_GetUsersInRoles (DbConnection connection, string applicationName, string rolename, out DbDataReader reader) - { - reader = null; - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return 1; - - string roleId = GetRoleId (connection, appId, rolename); - if (roleId == null) - return 2; - - string querySelect = "SELECT usr.UserName FROM aspnet_Users usr, aspnet_UsersInRoles uir " + - "WHERE usr.UserId = uir.UserId AND usr.ApplicationId = ? AND uir.RoleId = ? ORDER BY usr.UserName"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "ApplicationId", appId); - AddParameter (cmdSelect, "RoleId", roleId); - reader = cmdSelect.ExecuteReader (); - - return 0; - } - - public static int UsersInRoles_IsUserInRole (DbConnection connection, string applicationName, string username, string rolename) - { - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return 1; - - string userId = GetUserId (connection, appId, username); - if (userId == null) - return 2; - - string roleId = GetRoleId (connection, appId, rolename); - if (roleId == null) - return 3; - - string querySelect = "SELECT UserId FROM aspnet_UsersInRoles WHERE UserId = ? AND RoleId = ?"; - OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection); - AddParameter (cmdSelect, "UserId", userId); - AddParameter (cmdSelect, "RoleId", roleId); - using (OleDbDataReader reader = cmdSelect.ExecuteReader ()) { - if (reader.Read ()) - return 4; - } - return 0; - } - - public static int UsersInRoles_RemoveUsersFromRoles (DbConnection connection, string applicationName, string [] userNames, string [] roleNames) - { - string appId = DerbyApplicationsHelper.GetApplicationId (connection, applicationName); - if (appId == null) - return 1; - - string [] userIds = new string [userNames.Length]; - string [] roleIds = new string [roleNames.Length]; - - string querySelUsers = "SELECT UserId FROM aspnet_Users WHERE ApplicationId = ? AND LoweredUserName in " + GetPrms (userNames.Length); - OleDbCommand cmdSelUsers = new OleDbCommand (querySelUsers, (OleDbConnection) connection); - AddParameter (cmdSelUsers, "ApplicationId", appId); - for (int i = 0; i < userNames.Length; i++) - AddParameter (cmdSelUsers, "LoweredUserName", userNames [i].ToLowerInvariant ()); - - using (OleDbDataReader reader = cmdSelUsers.ExecuteReader ()) { - int i = 0; - while (reader.Read ()) - userIds [i++] = reader.GetString (0); - - if (userNames.Length != i) - return 2; // one or more users not found - } - - string querySelRoles = "SELECT RoleId FROM aspnet_Roles WHERE ApplicationId = ? AND LoweredRoleName in " + GetPrms (roleNames.Length); - OleDbCommand cmdSelRoles = new OleDbCommand (querySelRoles, (OleDbConnection) connection); - AddParameter (cmdSelRoles, "ApplicationId", appId); - for (int i = 0; i < roleNames.Length; i++) - AddParameter (cmdSelRoles, "LoweredRoleName", roleNames [i].ToLowerInvariant ()); - - using (OleDbDataReader reader = cmdSelRoles.ExecuteReader ()) { - int i = 0; - while (reader.Read ()) - roleIds [i++] = reader.GetString (0); - - if (roleNames.Length != i) - return 3; // one or more roles not found - } - - string querySelCount = "SELECT COUNT(*) FROM aspnet_UsersInRoles WHERE UserId in " + GetPrms (userNames.Length) + " AND RoleId in " + GetPrms (roleNames.Length); - OleDbCommand cmdSelCount = new OleDbCommand (querySelCount, (OleDbConnection) connection); - foreach (string userId in userIds) - AddParameter (cmdSelCount, "UserId", userId); - foreach (string roleId in roleIds) - AddParameter (cmdSelCount, "RoleId", roleId); - using (OleDbDataReader reader = cmdSelCount.ExecuteReader ()) { - if (reader.Read ()) - if (userNames.Length * roleNames.Length > reader.GetInt32 (0)) - return 4; - } - - string queryDelete = "DELETE FROM aspnet_UsersInRoles WHERE UserId in " + GetPrms (userNames.Length) + " AND RoleId in " + GetPrms (roleNames.Length); - OleDbCommand cmdDelete = new OleDbCommand (queryDelete, (OleDbConnection) connection); - foreach (string userId in userIds) - AddParameter (cmdDelete, "UserId", userId); - foreach (string roleId in roleIds) - AddParameter (cmdDelete, "RoleId", roleId); - cmdDelete.ExecuteNonQuery (); - - return 0; - } - - private static string GetRoleId (DbConnection connection, string applicationId, string rolename) - { - string selectQuery = "SELECT RoleId FROM aspnet_Roles WHERE LoweredRoleName = ? AND ApplicationId = ?"; - - OleDbCommand selectCmd = new OleDbCommand (selectQuery, (OleDbConnection) connection); - AddParameter (selectCmd, "LoweredRoleName", rolename.ToLowerInvariant ()); - AddParameter (selectCmd, "ApplicationId", applicationId); - using (OleDbDataReader reader = selectCmd.ExecuteReader ()) { - if (reader.Read ()) - return reader.GetString (0); - } - - return null; - } - - private static string GetUserId (DbConnection connection, string applicationId, string username) - { - string selectQuery = "SELECT UserId FROM aspnet_Users WHERE LoweredUserName = ? AND ApplicationId = ?"; - - OleDbCommand selectCmd = new OleDbCommand (selectQuery, (OleDbConnection) connection); - AddParameter (selectCmd, "LoweredUserName", username.ToLowerInvariant ()); - AddParameter (selectCmd, "ApplicationId", applicationId); - using (OleDbDataReader reader = selectCmd.ExecuteReader ()) { - if (reader.Read ()) - return reader.GetString (0); - } - - return null; - } - - private static string GetPrms (int n) - { - string exp = string.Empty; - for (int i = 0; i < n; i++) - exp += "?,"; - - exp = "(" + exp.Trim (',') + ")"; - return exp; - } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/J2EEAuthenticationModule.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/J2EEAuthenticationModule.cs deleted file mode 100644 index 0e840e6aabd..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/J2EEAuthenticationModule.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -// Mainsoft.Web.Security.J2EEAuthenticationModule -// -// Authors: -// Eyal Alaluf (eyala@mainsoft.com) -// -// (C) 2006 Mainsoft Co. (http://www.mainsoft.com) -// - -// -// 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. -// - -using System; -using System.Security.Principal; -using System.Text; -using System.Web; -using System.Web.Configuration; -using System.Web.Util; -using javax.servlet; -using javax.servlet.http; - -namespace Mainsoft.Web.Security -{ - public sealed class J2EEAuthenticationModule : IHttpModule - { - public void Dispose () - { - } - - public void Init (HttpApplication app) - { - app.AuthenticateRequest += new EventHandler (OnAuthenticateRequest); - } - - void OnAuthenticateRequest (object sender, EventArgs args) - { - HttpApplication app = (HttpApplication) sender; - HttpServletRequest req = app.Context.Request.ServletWorkerRequest.ServletRequest; - if (req.getRemoteUser() != null) - app.Context.User = new J2EEPrincipal(req); - } - } - - internal class J2EEPrincipal : IPrincipal - { - HttpServletRequest _request; - IIdentity _identity; - - public J2EEPrincipal(HttpServletRequest req) - { - _request = req; - string authType = req.getAuthType(); - if (authType == null) - authType = ""; - _identity = new GenericIdentity(req.getRemoteUser(), authType); - } - - public bool IsInRole(string role) - { - return _request.isUserInRole(role); - } - - public IIdentity Identity { get { return _identity; } } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/ServletAuthenticationModule.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/ServletAuthenticationModule.cs deleted file mode 100644 index 99f7755fcaf..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.Security/ServletAuthenticationModule.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -// System.Web.Security.ServletAuthenticationModule -// - -// -// 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. -// - -using System; -using System.Security.Principal; -using System.Text; -using System.Web; -using System.Web.Configuration; -using System.Web.Util; -using javax.servlet; -using javax.servlet.http; -using Mainsoft.Web.Hosting; - -namespace Mainsoft.Web.Security -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// Sets the identity of the user for an ASP.NET Java EE application. - /// - public sealed class SevletAuthenticationModule : IHttpModule - { - public void Dispose () { - } - - public void Init (HttpApplication app) { - app.AuthenticateRequest += new EventHandler (OnAuthenticateRequest); - } - - void OnAuthenticateRequest (object sender, EventArgs args) { - HttpApplication app = (HttpApplication) sender; - BaseWorkerRequest req = J2EEUtils.GetWorkerRequest (app.Context); - if (req.GetRemoteUser () != null) - app.Context.User = new ServletPrincipal (req); - } - } - - public sealed class ServletPrincipal : IPrincipal - { - readonly BaseWorkerRequest _request; - readonly IIdentity _identity; - - internal ServletPrincipal (BaseWorkerRequest req) { - _request = req; - string authType = req.GetAuthType (); - if (authType == null) - authType = String.Empty; - _identity = new GenericIdentity (req.GetRemoteUser (), authType); - } - - public bool IsInRole (string role) { - return _request.IsUserInRole (role); - } - - public IIdentity Identity { get { return _identity; } } - - public java.security.Principal Principal { get { return _request.GetUserPrincipal (); } } - } -} - diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/.gitattributes b/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/.gitattributes deleted file mode 100644 index 8b7ecf7dba5..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/.gitattributes +++ /dev/null @@ -1,5 +0,0 @@ -/ObjectInputStream.cs -crlf -/ObjectOutputStream.cs -crlf -/ServletSessionIDManager.cs -crlf -/ServletSessionStateItemCollection.cs -crlf -/ServletSessionStateStoreProvider.cs -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ObjectInputStream.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ObjectInputStream.cs deleted file mode 100644 index e6381005269..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ObjectInputStream.cs +++ /dev/null @@ -1,208 +0,0 @@ -// -// (C) 2005 Mainsoft Corporation (http://www.mainsoft.com) -// -// Authors: -// Vladimir Krasnov -// Konstantin Triger -// -// 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. -// - -using System; -using java.io; - -namespace Mainsoft.Web.SessionState -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public sealed partial class ServletSessionStateStoreProvider - { - sealed class ObjectInputStream : System.IO.Stream, ObjectInput - { - readonly ObjectInput _javaObjectInput; - - public ObjectInputStream (ObjectInput stream) { - _javaObjectInput = stream; - } - - public override bool CanRead { - get { - return true; - } - } - - public override bool CanWrite { - get { - return false; - } - } - - public override bool CanSeek { - get { - return true; - } - } - - public override long Length { - get { - throw new NotSupportedException (); - } - } - - public override long Position { - get { - throw new NotSupportedException (); - } - set { - throw new NotSupportedException (); - } - } - - public override void Flush () { - throw new NotSupportedException (); - } - - public override long Seek (long offset, System.IO.SeekOrigin origin) { - if (origin == System.IO.SeekOrigin.Current) - return _javaObjectInput.skip (offset); - - throw new NotSupportedException (); - } - - public override void SetLength (long value) { - throw new NotSupportedException (); - } - - public override int Read (byte [] buffer, int offset, int count) { - int rv = _javaObjectInput.read (vmw.common.TypeUtils.ToSByteArray (buffer), offset, count); - return rv > 0 ? rv : 0; - } - - public override void Write (byte [] buffer, int offset, int count) { - throw new NotSupportedException (); - } - - public override int ReadByte () { - return _javaObjectInput.read (); - } - - public override void Close () { - _javaObjectInput.close (); - } - - #region ObjectInput Members - - public int available () { - return _javaObjectInput.available (); - } - - public void close () { - _javaObjectInput.close (); - } - - public int read (sbyte [] __p1, int __p2, int __p3) { - return _javaObjectInput.read (__p1, __p2, __p3); - } - - public int read (sbyte [] __p1) { - return _javaObjectInput.read (__p1); - } - - public int read () { - return _javaObjectInput.read (); - } - - public object readObject () { - return _javaObjectInput.readObject (); - } - - public long skip (long __p1) { - return _javaObjectInput.skip (__p1); - } - - #endregion - - #region DataInput Members - - public bool readBoolean () { - return _javaObjectInput.readBoolean (); - } - - public sbyte readByte () { - return _javaObjectInput.readByte (); - } - - public char readChar () { - return _javaObjectInput.readChar (); - } - - public double readDouble () { - return _javaObjectInput.readDouble (); - } - - public float readFloat () { - return _javaObjectInput.readFloat (); - } - - public void readFully (sbyte [] __p1, int __p2, int __p3) { - _javaObjectInput.readFully (__p1, __p2, __p3); - } - - public void readFully (sbyte [] __p1) { - _javaObjectInput.readFully (__p1); - } - - public int readInt () { - return _javaObjectInput.readInt (); - } - - public string readLine () { - return _javaObjectInput.readLine (); - } - - public long readLong () { - return _javaObjectInput.readLong (); - } - - public short readShort () { - return _javaObjectInput.readShort (); - } - - public string readUTF () { - return _javaObjectInput.readUTF (); - } - - public int readUnsignedByte () { - return _javaObjectInput.readUnsignedByte (); - } - - public int readUnsignedShort () { - return _javaObjectInput.readUnsignedShort (); - } - - public int skipBytes (int __p1) { - return _javaObjectInput.skipBytes (__p1); - } - - #endregion - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ObjectOutputStream.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ObjectOutputStream.cs deleted file mode 100644 index b0e08ea9548..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ObjectOutputStream.cs +++ /dev/null @@ -1,186 +0,0 @@ -// -// (C) 2005 Mainsoft Corporation (http://www.mainsoft.com) -// -// Authors: -// Vladimir Krasnov -// Konstantin Triger -// -// 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. -// - -using System; -using java.io; - -namespace Mainsoft.Web.SessionState -{ - public sealed partial class ServletSessionStateStoreProvider - { - sealed class ObjectOutputStream : System.IO.Stream, ObjectOutput - { - readonly ObjectOutput _javaObjectOutput; - - public ObjectOutputStream (ObjectOutput stream) { - _javaObjectOutput = stream; - } - - public override bool CanRead { - get { - return false; - } - } - - public override bool CanSeek { - get { - return false; - } - } - - public override bool CanWrite { - get { - return true; - } - } - - public override void Close () { - _javaObjectOutput.close (); - } - - public override void Flush () { - _javaObjectOutput.flush (); - } - - public override long Length { - get { - throw new NotSupportedException (); - } - } - - public override long Position { - get { - throw new NotSupportedException (); - } - set { - throw new NotSupportedException (); - } - } - - public override long Seek (long offset, System.IO.SeekOrigin origin) { - throw new NotSupportedException (); - } - - public override void SetLength (long value) { - throw new NotSupportedException (); - } - - public override int Read (byte [] buffer, int offset, int count) { - throw new NotSupportedException (); - } - - public override void Write (byte [] buffer, int offset, int count) { - _javaObjectOutput.write (vmw.common.TypeUtils.ToSByteArray (buffer), offset, count); - } - - public override void WriteByte (byte value) { - _javaObjectOutput.write (value); - } - - public ObjectOutput NativeStream { - get { return _javaObjectOutput; } - } - - #region ObjectOutput Members - - public void close () { - _javaObjectOutput.close (); - } - - public void flush () { - _javaObjectOutput.flush (); - } - - public void write (sbyte [] __p1, int __p2, int __p3) { - _javaObjectOutput.write (__p1, __p2, __p3); - } - - public void write (sbyte [] __p1) { - _javaObjectOutput.write (__p1); - } - - public void write (int __p1) { - _javaObjectOutput.write (__p1); - } - - public void writeObject (object __p1) { - _javaObjectOutput.writeObject (__p1); - } - - #endregion - - #region DataOutput Members - - - public void writeBoolean (bool __p1) { - _javaObjectOutput.writeBoolean (__p1); - } - - public void writeByte (int __p1) { - _javaObjectOutput.writeByte (__p1); - } - - public void writeBytes (string __p1) { - _javaObjectOutput.writeBytes (__p1); - } - - public void writeChar (int __p1) { - _javaObjectOutput.writeChar (__p1); - } - - public void writeChars (string __p1) { - _javaObjectOutput.writeChars (__p1); - } - - public void writeDouble (double __p1) { - _javaObjectOutput.writeDouble (__p1); - } - - public void writeFloat (float __p1) { - _javaObjectOutput.writeFloat (__p1); - } - - public void writeInt (int __p1) { - _javaObjectOutput.writeInt (__p1); - } - - public void writeLong (long __p1) { - _javaObjectOutput.writeLong (__p1); - } - - public void writeShort (int __p1) { - _javaObjectOutput.writeShort (__p1); - } - - public void writeUTF (string __p1) { - _javaObjectOutput.writeUTF (__p1); - } - - #endregion - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ServletSessionIDManager.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ServletSessionIDManager.cs deleted file mode 100755 index 4aaf38d97d7..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ServletSessionIDManager.cs +++ /dev/null @@ -1,76 +0,0 @@ -// -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// Author: Konstantin Triger -// - -// -// 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. -// - -using System; -using System.Collections.Generic; -using System.Text; -using System.Web; -using System.Web.SessionState; -using javax.servlet.http; -using Mainsoft.Web.Hosting; - -namespace Mainsoft.Web.SessionState -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public sealed class ServletSessionIDManager : ISessionIDManager - { - #region ISessionIDManager Members - - public string CreateSessionID (HttpContext context) { - return ServletSessionStateStoreProvider.GetSession (context, true).getId (); - } - - public string GetSessionID (HttpContext context) { - BaseWorkerRequest request = J2EEUtils.GetWorkerRequest (context); - return request.IsRequestedSessionIdValid () ? request.GetRequestedSessionId () : null; - } - - public void Initialize () { - } - - public bool InitializeRequest (HttpContext context, bool suppressAutoDetectRedirect, out bool supportSessionIDReissue) { - supportSessionIDReissue = true; - return false; - } - - public void RemoveSessionID (HttpContext context) { - ServletSessionStateStoreProvider.GetSession (context, false).invalidate (); - } - - public void SaveSessionID (HttpContext context, string id, out bool redirected, out bool cookieAdded) { - redirected = false; - cookieAdded = false; - } - - public bool Validate (string id) { - return true; - } - - #endregion - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ServletSessionStateItemCollection.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ServletSessionStateItemCollection.cs deleted file mode 100755 index eeb1a716c6c..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ServletSessionStateItemCollection.cs +++ /dev/null @@ -1,191 +0,0 @@ -// -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// Author: Konstantin Triger -// - -// -// 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. -// - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; -using System.Web.SessionState; -using System.Web; -using System.Threading; - -using javax.servlet; -using javax.servlet.http; -using System.Diagnostics; -using Mainsoft.Web.Hosting; - -namespace Mainsoft.Web.SessionState -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public sealed partial class ServletSessionStateStoreProvider - { - sealed class ServletSessionStateItemCollection : ISessionStateItemCollection, java.io.Externalizable - { - SessionStateItemCollection _items; - HttpStaticObjectsCollection _staticObjects; - bool _needSessionPersistence; - - public ServletSessionStateItemCollection () {} // For Java deserialization - - public ServletSessionStateItemCollection (HttpContext context) - : this () { - - _items = new SessionStateItemCollection (); - _staticObjects = new HttpStaticObjectsCollection (); - - if (context != null) { - ServletContext servletContext = J2EEUtils.GetWorkerRequest (context).GetContext (); - string sessionPersistance = servletContext.getInitParameter (J2EEConsts.Enable_Session_Persistency); - if (sessionPersistance != null) { - try { - _needSessionPersistence = Boolean.Parse (sessionPersistance); - } - catch (Exception) { - _needSessionPersistence = false; - Debug.WriteLine ("EnableSessionPersistency init param's value is invalid. the value is " + sessionPersistance); - } - } - } - } - - public HttpStaticObjectsCollection StaticObjects { - get { return _staticObjects; } - } - #region ISessionStateItemCollection Members - - public void Clear () { - _items.Clear (); - } - - public bool Dirty { - get { - return _items.Dirty; - } - set { - _items.Dirty = value; - } - } - - public System.Collections.Specialized.NameObjectCollectionBase.KeysCollection Keys { - get { return _items.Keys; } - } - - public void Remove (string name) { - _items.Remove (name); - } - - public void RemoveAt (int index) { - _items.RemoveAt (index); - } - - public object this [int index] { - get { - return _items [index]; - } - set { - _items [index] = value; - } - } - - public object this [string name] { - get { - return _items [name]; - } - set { - _items [name] = value; - } - } - - #endregion - - #region ICollection Members - - public void CopyTo (Array array, int index) { - ((ICollection) _items).CopyTo (array, index); - } - - public int Count { - get { return ((ICollection) _items).Count; } - } - - public bool IsSynchronized { - get { return ((ICollection) _items).IsSynchronized; } - } - - public object SyncRoot { - get { return ((ICollection) _items).SyncRoot; } - } - - #endregion - - #region IEnumerable Members - - public System.Collections.IEnumerator GetEnumerator () { - return ((IEnumerable) _items).GetEnumerator (); - } - - #endregion - - #region Externalizable Members - - public void readExternal (java.io.ObjectInput input) { - lock (this) { - _needSessionPersistence = input.readBoolean (); - if (!_needSessionPersistence) { //nothing has been written - if (_items == null) - _items = new SessionStateItemCollection (); - if (_staticObjects == null) - _staticObjects = new HttpStaticObjectsCollection (); - return; - } - - ObjectInputStream ms = new ObjectInputStream (input); - System.IO.BinaryReader br = new System.IO.BinaryReader (ms); - _items = SessionStateItemCollection.Deserialize (br); - _staticObjects = HttpStaticObjectsCollection.Deserialize (br); - } - } - - public void writeExternal (java.io.ObjectOutput output) { - lock (this) { - output.writeBoolean (_needSessionPersistence); - if (!_needSessionPersistence) - //indicates that there is nothing to serialize for this object - return; - - ObjectOutputStream ms = new ObjectOutputStream (output); - System.IO.BinaryWriter bw = new System.IO.BinaryWriter (ms); - _items.Serialize (bw); - _staticObjects.Serialize (bw); - } - } - - #endregion - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ServletSessionStateStoreProvider.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ServletSessionStateStoreProvider.cs deleted file mode 100755 index a898317d378..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/ServletSessionStateStoreProvider.cs +++ /dev/null @@ -1,167 +0,0 @@ -// -// (C) 2006 Mainsoft Corporation (http://www.mainsoft.com) -// Author: Konstantin Triger -// - -// -// 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. -// - -using System; -using System.Collections.Generic; -using System.Text; -using System.Web.SessionState; -using System.Web; -using System.Web.Hosting; -using javax.servlet; -using javax.servlet.http; -using Mainsoft.Web.Hosting; - -namespace Mainsoft.Web.SessionState -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// Manages session state information using Java EE session API. - /// - public sealed partial class ServletSessionStateStoreProvider : SessionStateStoreProviderBase - { - const int MAX_MINUTES_TIMEOUT = int.MaxValue / 60; - #region Public Interface - - public override SessionStateStoreData CreateNewStoreData (HttpContext context, int timeout) { - - // we ignore this timeout and use web.xml settings. - //must set now as this can be a last chance for ro item - //GetSession (context, false).setMaxInactiveInterval (timeout * 60); - int javaTimeoutInSeconds = GetSession (context, false).getMaxInactiveInterval (); - timeout = GetIntervalInMinutes (javaTimeoutInSeconds); - ServletSessionStateItemCollection sessionState = new ServletSessionStateItemCollection (context); - return new SessionStateStoreData ( - sessionState, - sessionState.StaticObjects, - timeout); - } - - public override void CreateUninitializedItem (HttpContext context, string id, int timeout) { - } - - public override void Dispose () { - - } - - public override void EndRequest (HttpContext context) { - } - - public override SessionStateStoreData GetItem (HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions) { - locked = false; - lockAge = TimeSpan.Zero; - lockId = null; - actions = SessionStateActions.None; - if (id == null) - return null; - HttpSession session = GetSession (context, false, false); - if (session == null) - return null; - ServletSessionStateItemCollection sessionState = session.getAttribute (J2EEConsts.SESSION_STATE) as ServletSessionStateItemCollection; - if (sessionState == null) //was not set - sessionState = new ServletSessionStateItemCollection (context); - return new SessionStateStoreData ( - sessionState, - sessionState.StaticObjects, - GetIntervalInMinutes(session.getMaxInactiveInterval ())); - } - - public override SessionStateStoreData GetItemExclusive (HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions) { - return GetItem (context, id, out locked, out lockAge, out lockId, out actions); - } - - public override void InitializeRequest (HttpContext context) { - } - - public override void ReleaseItemExclusive (HttpContext context, string id, object lockId) { - } - - public override void RemoveItem (HttpContext context, string id, object lockId, SessionStateStoreData item) { - GetSession (context, false).invalidate (); - } - - public override void ResetItemTimeout (HttpContext context, string id) { - if (context == null) - throw new ArgumentNullException ("context"); - HttpSession session = GetSession (context, false); - int current = session.getMaxInactiveInterval (); - int requested = context.Session.Timeout * 60; - if (current != requested) - session.setMaxInactiveInterval (requested); - } - - public override void SetAndReleaseItemExclusive (HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem) { - if (id == null) - return; - - if (item.Items.Dirty) - GetSession(context, false).setAttribute (J2EEConsts.SESSION_STATE, item.Items); - - ReleaseItemExclusive (context, id, lockId); - } - - public override bool SetItemExpireCallback (SessionStateItemExpireCallback expireCallback) { - return true; //we call session.invalidate so our session listener will call Session_OnEnd - } - - #endregion - - #region helpers - - internal static HttpSessionStateContainer CreateContainer (HttpSession session) { - ServletSessionStateItemCollection sessionState = session.getAttribute (J2EEConsts.SESSION_STATE) as ServletSessionStateItemCollection; - if (sessionState == null) //was not set - sessionState = new ServletSessionStateItemCollection (null); - - return new HttpSessionStateContainer (session.getId (), - sessionState, sessionState.StaticObjects, - GetIntervalInMinutes (session.getMaxInactiveInterval ()), - session.isNew (), - HttpCookieMode.AutoDetect, SessionStateMode.Custom, - true); - } - - internal static HttpSession GetSession (HttpContext context, bool create) { - return GetSession (context, create, true); - } - - internal static HttpSession GetSession (HttpContext context, bool create, bool throwOnError) { - HttpSession session = J2EEUtils.GetWorkerRequest (context).GetSession (create); - if (session == null && throwOnError) - throw new HttpException ("Session is not established"); - - return session; - } - - static int GetIntervalInMinutes (int seconds) - { - if (seconds == -1) - return MAX_MINUTES_TIMEOUT; - return (int) Math.Ceiling ((double) seconds / 60); - } - - #endregion - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/SessionListener.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/SessionListener.cs deleted file mode 100644 index 89a540e3714..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web.SessionState/SessionListener.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -// (C) 2005 Mainsoft Corporation (http://www.mainsoft.com) -// - -// -// 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. -// - -using System; -using System.Web.SessionState; -using System.Reflection; -using javax.servlet.http; -using Mainsoft.Web.Hosting; -using System.Diagnostics; - -namespace Mainsoft.Web.SessionState -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public class SessionListener : javax.servlet.http.HttpSessionListener - { - - public void sessionCreated (HttpSessionEvent se) { - } - - public void sessionDestroyed (HttpSessionEvent se) { - bool setDomain = vmw.@internal.EnvironmentUtils.getAppDomain () == null; - if (setDomain) { - AppDomain servletDomain = (AppDomain) se.getSession ().getServletContext ().getAttribute (J2EEConsts.APP_DOMAIN); - if (servletDomain == null) - return; - vmw.@internal.EnvironmentUtils.setAppDomain (servletDomain); - } - try { - HttpSessionStateContainer container = - ServletSessionStateStoreProvider.CreateContainer (se.getSession ()); - - SessionStateUtility.RaiseSessionEnd (container, this, EventArgs.Empty); - } - catch (Exception e) { - Debug.WriteLine (e.Message); - Debug.WriteLine (e.StackTrace); - } - finally { - if (setDomain) { - vmw.@internal.EnvironmentUtils.clearAppDomain (); - } - } - } - } -} - -namespace System.Web.GH -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public class SessionListener : Mainsoft.Web.SessionState.SessionListener - { - } -} - -namespace System.Web.J2EE -{ - /// - /// This class supports the Framework infrastructure and is not intended to be used directly from your code. - /// - public class SessionListener : Mainsoft.Web.SessionState.SessionListener - { - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web/.gitattributes b/mcs/class/Mainsoft.Web/Mainsoft.Web/.gitattributes deleted file mode 100644 index 6adf0e5a39c..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web/.gitattributes +++ /dev/null @@ -1,4 +0,0 @@ -/BaseHttpContext.cs -crlf -/J2EEConsts.cs -crlf -/J2EEUtils.cs -crlf -/ServletHttpContext.cs -crlf diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web/BaseHttpContext.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web/BaseHttpContext.cs deleted file mode 100644 index 72285bda999..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web/BaseHttpContext.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// (C) 2007 Mainsoft Corporation (http://www.mainsoft.com) -// Author: Konstantin Triger -// - -// -// 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. -// - -using System; -using System.Collections.Generic; - -using System.Text; -using System.Configuration; -using System.Web; -using Mainsoft.Web.Hosting; -using javax.faces.lifecycle; - -namespace Mainsoft.Web -{ - /// - /// BaseHttpContext contains all of the per-request state information related to the processing of a single request, - /// and the rendering of the corresponding response. - /// - public abstract class BaseHttpContext - { - protected readonly HttpContext _context; - static readonly object _contextKey = new object (); - - protected BaseHttpContext (HttpContext context) { - _context = context; - context.Items [_contextKey] = this; - } - - /// - /// Gets the Mainsoft.Web.BaseHttpContext object for the current request. - /// - /// - /// - public static BaseHttpContext GetCurrent(HttpContext context) { - if (context == null) - throw new ArgumentNullException ("context"); - - BaseHttpContext baseContext = (BaseHttpContext) context.Items [_contextKey]; - return baseContext ?? GetWorker (context).CreateContext (context); - } - - /// - /// Returns the javax.faces.lifecycle.Lifecycle instance. - /// - public Lifecycle Lifecycle { - get { return BaseHttpServlet.Lifecycle; } - } - - /// - /// Returns the Mainsoft.Web.Hosting.BaseWorkerRequest object for the current request. - /// - protected BaseWorkerRequest Worker { - get { return GetWorker (_context); } - } - - static BaseWorkerRequest GetWorker (HttpContext context) { - return (BaseWorkerRequest) ((IServiceProvider) context).GetService (typeof (HttpWorkerRequest)); - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web/J2EEConsts.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web/J2EEConsts.cs deleted file mode 100755 index e30122d6907..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web/J2EEConsts.cs +++ /dev/null @@ -1,66 +0,0 @@ -// -// (C) 2005 Mainsoft Corporation (http://www.mainsoft.com) -// - -// -// 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. -// - -using System; - -namespace Mainsoft.Web.Hosting -{ - public static class J2EEConsts - { - public const string SESSION_STATE = "GH_SESSION_STATE"; - - public const string CLASS_LOADER = "GH_ContextClassLoader"; - public const string SERVLET_CONFIG = "GH_ServletConfig"; - public const string RESOURCE_LOADER = "GH_ResourceLoader"; - - public const string APP_DOMAIN = "AppDomain"; - - public const string Enable_Session_Persistency = "EnableSessionPersistency"; - - //Used to save assemblies.xml file per application. - public const string ASSEMBLIES_FILE = "AssembliesXml"; - - //Used to save FileList.xml file per application. - public const string FILE_LIST_FILE = "FileListXml"; - - public const string MAP_PATH_CACHE = "MapPathCache"; - - //Used to save servlet request of current Servlet. - public const string SERVLET_REQUEST = "GH_ServletRequest"; - //Used to save servlet response of current Servlet. - public const string SERVLET_RESPONSE = "GH_ServletResponse"; - //Used to save current Servlet. - public const string CURRENT_SERVLET = "GH_Servlet"; - - public const string DESERIALIZER_CONST = "GH_DeserializeWorkAround"; - //Used to control file system access in web app context - public const string FILESYSTEM_ACCESS = "WebFileSystemAccess"; - public const string ACCESS_FULL = "Full"; - public const string ACCESS_VIRTUAL = "Virtual"; - - public const string ACTION_URL_PREFIX = "ActionURL:"; - public const string RENDER_URL_PREFIX = "RenderURL:"; - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web/J2EEUtils.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web/J2EEUtils.cs deleted file mode 100755 index 7895ea4e7bb..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web/J2EEUtils.cs +++ /dev/null @@ -1,104 +0,0 @@ -// -// (C) 2005 Mainsoft Corporation (http://www.mainsoft.com) -// - -// -// 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. -// - -using System; -using System.Web.Util; -using System.IO; -using vmw.@internal.io; -using vmw.common; - -using javax.servlet; -using System.Web; -using Mainsoft.Web.Hosting; -using System.Diagnostics; - -namespace Mainsoft.Web -{ - internal static class J2EEUtils - { - //public static string GetInitParameterByHierarchy(ServletConfig config, string name) - //{ - // if (config == null) - // throw new ArgumentNullException("config"); - - // string value = config.getInitParameter(name); - // if (value != null) - // return value; - - // return config.getServletContext().getInitParameter(name); - //} - - public static string GetApplicationRealPath (ServletContext context) { - return GetApplicationRealPath (context, "/"); - } - - public static string GetApplicationRealPath (ServletContext context, string appVirtualPath) - { - string realFs = context.getInitParameter (J2EEConsts.FILESYSTEM_ACCESS); - if (realFs == null || realFs == J2EEConsts.ACCESS_FULL) { - try { - string realPath = context.getRealPath (appVirtualPath); - if (!String.IsNullOrEmpty (realPath)) { - if (!String.IsNullOrEmpty (appVirtualPath) && - appVirtualPath [appVirtualPath.Length - 1] == '/') - if (realPath [realPath.Length - 1] != Path.DirectorySeparatorChar) - realPath += Path.DirectorySeparatorChar; - - return realPath; - } - } - catch (Exception e) { - Trace.WriteLine (e.ToString()); - } - } - return IAppDomainConfig.WAR_ROOT_SYMBOL + appVirtualPath; - } - - public static string GetApplicationPhysicalPath (ServletContext context) { - string path = String.Empty; - - string appDir = context.getInitParameter(IAppDomainConfig.APP_DIR_NAME); - if (appDir != null) { - try { - if (Directory.Exists(appDir)) - path = appDir; - } - catch (Exception e) { - Trace.WriteLine (e.Message + appDir + "is invalid or unaccessible." + - " If " + appDir + " really exists, check your security permissions"); - } - } - if (path.Length == 0) - path = GetApplicationRealPath (context); - - return path; - } - - static internal BaseWorkerRequest GetWorkerRequest (HttpContext context) { - IServiceProvider sp = (IServiceProvider) context; - return (BaseWorkerRequest) sp.GetService (typeof (HttpWorkerRequest)); - } - } -} diff --git a/mcs/class/Mainsoft.Web/Mainsoft.Web/ServletHttpContext.cs b/mcs/class/Mainsoft.Web/Mainsoft.Web/ServletHttpContext.cs deleted file mode 100644 index c084e99f73e..00000000000 --- a/mcs/class/Mainsoft.Web/Mainsoft.Web/ServletHttpContext.cs +++ /dev/null @@ -1,106 +0,0 @@ -// -// (C) 2007 Mainsoft Corporation (http://www.mainsoft.com) -// Author: Konstantin Triger -// - -// -// 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. -// - -using System; -using System.Collections.Generic; -using System.Text; -using System.Web; -using Mainsoft.Web.Hosting; -using javax.servlet; -using javax.servlet.http; - -namespace Mainsoft.Web -{ - /// - /// ServletHttpContext contains all of the per-request state information related to the processing of a single request, - /// and the rendering of the corresponding response. - /// - public sealed class ServletHttpContext : BaseHttpContext - { - internal ServletHttpContext (HttpContext context) - : base (context) { - } - - /// - /// Gets the Mainsoft.Web.ServletHttpContext object for the current sevlet request. - /// - /// - /// - public static new ServletHttpContext GetCurrent (HttpContext context) { - return BaseHttpContext.GetCurrent (context) as ServletHttpContext; - } - - private new ServletWorkerRequest Worker { - get { return (ServletWorkerRequest) base.Worker; } - } - - /// - /// Returns the current javax.servlet.http.HttpServlet object. - /// - public HttpServlet Servlet { - get { return Worker.Servlet; } - } - - /// - /// Returns the current javax.servlet.http.HttpServletRequest object. - /// - public HttpServletRequest ServletRequest { - get { return Worker.ServletRequest; } - } - - - /// - /// Returns the current javax.servlet.http.HttpServletResponse object. - /// - public HttpServletResponse ServletResponse { - get { return Worker.ServletResponse; } - } - - /// - /// Returns the javax.servlet.ServletConfig object for the current sevlet. - /// - public ServletConfig ServletConfig { - get { return Servlet.getServletConfig (); } - } - - /// - /// Returns the javax.servlet.ServletContext object for the current application. - /// - public ServletContext ServletContext { - get { return Servlet.getServletContext (); } - } - - - /// - /// Returns the current servlet name. - /// - public string ServletName { - get { - return Servlet.getServletName (); - } - } - } -} diff --git a/mcs/class/Mainsoft.Web/Properties/.gitattributes b/mcs/class/Mainsoft.Web/Properties/.gitattributes deleted file mode 100644 index f7d8287f511..00000000000 --- a/mcs/class/Mainsoft.Web/Properties/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -/AssemblyInfo.cs -crlf diff --git a/mcs/class/Mainsoft.Web/Properties/AssemblyInfo.cs b/mcs/class/Mainsoft.Web/Properties/AssemblyInfo.cs deleted file mode 100644 index 7480e507791..00000000000 --- a/mcs/class/Mainsoft.Web/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle ("DerbyProvider")] -[assembly: AssemblyDescription ("")] -[assembly: AssemblyConfiguration ("")] -[assembly: AssemblyCompany ("")] -[assembly: AssemblyProduct ("DerbyProvider")] -[assembly: AssemblyCopyright ("Copyright © Mainsoft 2006")] -[assembly: AssemblyTrademark ("")] -[assembly: AssemblyCulture ("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible (false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid ("0e5958a7-422c-47c2-b0fd-698a50cf1e1f")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion ("1.0.0.0")] -[assembly: AssemblyFileVersion ("1.0.0.0")] diff --git a/mcs/class/Mainsoft.Web/Tests/Mainsoft.Web.Security/.gitattributes b/mcs/class/Mainsoft.Web/Tests/Mainsoft.Web.Security/.gitattributes deleted file mode 100644 index 10219de4483..00000000000 --- a/mcs/class/Mainsoft.Web/Tests/Mainsoft.Web.Security/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -/MembershipTests.cs -crlf diff --git a/mcs/class/Mainsoft.Web/Tests/Mainsoft.Web.Security/MembershipTests.cs b/mcs/class/Mainsoft.Web/Tests/Mainsoft.Web.Security/MembershipTests.cs deleted file mode 100644 index b86fd8cfdfb..00000000000 --- a/mcs/class/Mainsoft.Web/Tests/Mainsoft.Web.Security/MembershipTests.cs +++ /dev/null @@ -1,230 +0,0 @@ -// -// Mainsoft.Web.Security.Tests.DerbyMembershipProviderTests -// -// Authors: -// Vladimir Krasnov (vladimirk@mainsoft.com) -// -// (C) 2006 Mainsoft -// -// -// 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. -// - - -using System; -using System.IO; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.Configuration; -using System.Web.Security; -using System.Data; -using System.Data.OleDb; -using System.Data.Common; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Text; -using Mainsoft.Web.Security; -using NUnit.Framework; - - -namespace Mainsoft.Web.Security.Tests -{ - [TestFixture] - public class DerbyMembershipProviderTests - { - public void Init () - { - InitDB (); - } - public void InitDB () - { - if (Directory.Exists ("AspDB")) - Directory.Delete ("AspDB", true); - } - public void Finish () - { - ReleaseDB (); - } - - public void ReleaseDB () - { - } - private MembershipProvider CreateMembershipProvider () - { - NameValueCollection nvc = new NameValueCollection (); - nvc.Add ("applicationName", "testapp"); - nvc.Add ("connectionStringName", "derby"); - nvc.Add ("requiresUniqueEmail", "false"); - nvc.Add ("enablePasswordRetrieval", "true"); - nvc.Add ("passwordFormat", "Clear"); - - WebConfigurationManager.ConnectionStrings.Add (new System.Configuration.ConnectionStringSettings ("derby", "JdbcDriverClassName=org.apache.derby.jdbc.EmbeddedDriver;JdbcURL=jdbc:derby:AspDB;create=true", "System.Data.OleDb")); - DerbyMembershipProvider p = new DerbyMembershipProvider (); - p.Initialize ("DerbyMembershipProvider", nvc); - - return p; - } - - [Test] - public void CreateUserTest () - { - MembershipProvider p = CreateMembershipProvider (); - MembershipCreateStatus st; - MembershipUser u = p.CreateUser("username", "123123!", "username@email.com", "q", "a", true, null, out st); - Assert.IsNotNull (u); - Assert.AreEqual ("username", u.UserName); - } - - [Test] - public void ChangePasswordTest () - { - MembershipProvider p = CreateMembershipProvider (); - MembershipCreateStatus st; - MembershipUser u = p.CreateUser("userpwd", "123123!", "username2@email.com", "q", "a", true, null, out st); - bool b = p.ChangePassword ("userpwd", "123123!", "123123!123"); - Assert.IsTrue (b); - - b = p.ChangePassword ("userpwd", "123123!", "123123!123"); - Assert.IsFalse (b); - } - - [Test] - public void ChangePasswordQuestionAndAnswerTest () - { - MembershipProvider p = CreateMembershipProvider (); - MembershipCreateStatus st; - MembershipUser u = p.CreateUser("userpwd2", "123123!", "username3@email.com", "q", "a", true, null, out st); - - bool b = p.ChangePasswordQuestionAndAnswer ("userpwd2", "123123!", "q2", "a2"); - Assert.IsTrue (b); - b = p.ChangePasswordQuestionAndAnswer ("userpwd2", "123123!123", "q2", "a2"); - Assert.IsFalse (b); - } - - [Test] - public void DeleteUserTest () - { - MembershipProvider p = CreateMembershipProvider (); - MembershipCreateStatus st; - p.CreateUser ("user3", "123123!", "username4@email.com", "q", "a", true, null, out st); - - bool b = p.DeleteUser ("user3", true); - Assert.IsTrue (b); - - MembershipUser u = p.GetUser ("user2", false); - Assert.IsNotNull (u); - } - - [Test] - public void GetUserNameByEmailTest () - { - MembershipProvider p = CreateMembershipProvider (); - string u = p.GetUserNameByEmail ("username@email.com"); - Assert.AreEqual ("username", u); - } - - [Test] - public void ValidateUserTest () - { - MembershipProvider p = CreateMembershipProvider (); - bool b = p.ValidateUser ("username", "123"); - Assert.IsFalse (b); - b = p.ValidateUser ("username", "123"); - Assert.IsFalse (b); - b = p.ValidateUser ("username", "123"); - Assert.IsFalse (b); - b = p.ValidateUser ("username", "123"); - Assert.IsFalse (b); - b = p.ValidateUser ("username", "123"); - Assert.IsFalse (b); - b = p.ValidateUser ("username", "123"); - Assert.IsFalse (b); - b = p.ValidateUser ("username", "123"); - Assert.IsFalse (b); - b = p.ValidateUser ("username", "123"); - Assert.IsFalse (b); - b = p.UnlockUser ("username"); - Assert.IsFalse (b); - } - - [Test] - public void UpdateUserTest () - { - MembershipProvider p = CreateMembershipProvider (); - MembershipCreateStatus st; - MembershipUser u = p.CreateUser ("user5", "123123!", "user5@email.com", "q", "a", true, null, out st); - - u.Comment = "comment2"; - u.Email = "email2"; - u.IsApproved = false; - - p.UpdateUser (u); - MembershipUser u2 = p.GetUser (u.ProviderUserKey, false); - - Assert.AreEqual (u.Comment, u2.Comment); - Assert.AreEqual (u.Email, u2.Email); - Assert.AreEqual (u.IsApproved, u2.IsApproved); - } - - [Test] - public void GetPasswordTest () - { - MembershipProvider p = CreateMembershipProvider (); - MembershipCreateStatus st; - p.CreateUser ("user7", "123123!", "user5@email.com", "q", "a", true, null, out st); - string pass = p.GetPassword ("user7", "a"); - Assert.AreEqual ("123123!", pass); - } - - [Test] - public void FindUsersByName () - { - MembershipProvider p = CreateMembershipProvider (); - MembershipCreateStatus st; - p.CreateUser ("user_a", "123123!", "user_a@email.com", "q", "a", true, null, out st); - p.CreateUser ("user_b", "123123!", "user_b@email.com", "q", "a", true, null, out st); - p.CreateUser ("user_c", "123123!", "user_c@email.com", "q", "a", true, null, out st); - p.CreateUser ("user_d", "123123!", "user_d@email.com", "q", "a", true, null, out st); - p.CreateUser ("user_e", "123123!", "user_e@email.com", "q", "a", true, null, out st); - int tr = 0; - MembershipUserCollection u = p.FindUsersByName ("%user_%", 0, 10, out tr); - Assert.AreEqual (5, tr); - Assert.AreEqual (5, u.Count); - } - - [Test] - public void FindUsersByEmail () - { - MembershipProvider p = CreateMembershipProvider (); - MembershipCreateStatus st; - p.CreateUser ("user_7a", "123123!", "user_7a@email.com", "q", "a", true, null, out st); - p.CreateUser ("user_7b", "123123!", "user_7b@email.com", "q", "a", true, null, out st); - p.CreateUser ("user_7c", "123123!", "user_7c@email.com", "q", "a", true, null, out st); - p.CreateUser ("user_7d", "123123!", "user_7d@email.com", "q", "a", true, null, out st); - p.CreateUser ("user_7e", "123123!", "user_7e@email.com", "q", "a", true, null, out st); - int tr = 0; - MembershipUserCollection u = p.FindUsersByEmail ("%user_7%", 0, 10, out tr); - Assert.AreEqual (5, tr); - Assert.AreEqual (5, u.Count); - } - } -} - diff --git a/mcs/class/Mainsoft.Web/Tests/Tests.csproj b/mcs/class/Mainsoft.Web/Tests/Tests.csproj deleted file mode 100644 index 6bed1c9238a..00000000000 --- a/mcs/class/Mainsoft.Web/Tests/Tests.csproj +++ /dev/null @@ -1,112 +0,0 @@ - - - Debug_Java - AnyCPU - 8.0.50727 - 2.0 - {7626DB27-F1CD-4787-8520-95F330A39FDC} - Library - Properties - Tests - 1.5.0_05 - 1 - 2.0 - Tests - iap2 - {F6B19D50-1E2E-4e87-ADFB-10393B439DE0};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - - true - full - false - bin\Debug_Java\ - DEBUG;TRACE;JAVA - prompt - 4 - 285212672 - false - false - 0 - - - - - pdbonly - true - bin\Release_Java\ - TRACE;JAVA - prompt - 4 - 285212672 - false - false - 0 - - - - - true - bin\Debug_Java20\ - TRACE;DEBUG;JAVA;NET_2_0 - 285212672 - full - AnyCPU - prompt - false - false - 1 - false - - - - - 2.0 - 1.5.0_05 - iap2 - 0 - - - - False - ..\bin\Debug_Java20\Mainsoft.Web.dll - True - - - False - ..\..\..\nunit20\nunit-console\bin\Debug_Java20\nunit.framework.dll - True - - - False - - - - False - - - - False - - - - - - - - - - - - - - - - - - diff --git a/mcs/class/Mainsoft.Web/makefile.build b/mcs/class/Mainsoft.Web/makefile.build deleted file mode 100755 index c7db3b3821a..00000000000 --- a/mcs/class/Mainsoft.Web/makefile.build +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/mcs/class/Mono.Debugger.Soft/Test/dtest.cs b/mcs/class/Mono.Debugger.Soft/Test/dtest.cs index c54baffecf9..086c6f5f9aa 100644 --- a/mcs/class/Mono.Debugger.Soft/Test/dtest.cs +++ b/mcs/class/Mono.Debugger.Soft/Test/dtest.cs @@ -3620,12 +3620,15 @@ public class DebuggerTests Assert.AreEqual (ThreadState.WaitSleepJoin, thread.ThreadState, "#6"); frames = thread.GetFrames (); - Assert.AreEqual (4, frames.Length, "#7"); - Assert.AreEqual ("WaitOne_internal", frames [0].Method.Name, "#8"); - Assert.AreEqual ("WaitOne", frames [1].Method.Name, "#8.1"); - Assert.AreEqual ("wait_one", frames [2].Method.Name, "#9"); - Assert.AreEqual ("Main", frames [3].Method.Name, "#10"); - + Assert.AreEqual (8, frames.Length, "#7"); + Assert.AreEqual ("WaitOne_internal", frames [0].Method.Name, "#8.0"); + Assert.AreEqual ("WaitOneNative", frames [1].Method.Name, "#8.1"); + Assert.AreEqual ("InternalWaitOne", frames [2].Method.Name, "#8.2"); + Assert.AreEqual ("WaitOne", frames [3].Method.Name, "#8.3"); + Assert.AreEqual ("WaitOne", frames [4].Method.Name, "#8.4"); + Assert.AreEqual ("WaitOne", frames [5].Method.Name, "#8.5"); + Assert.AreEqual ("wait_one", frames [6].Method.Name, "#8.6"); + Assert.AreEqual ("Main", frames [7].Method.Name, "#8.7"); var frame = frames [0]; Assert.IsTrue (frame.IsNativeTransition, "#11.1"); @@ -3634,12 +3637,12 @@ public class DebuggerTests Assert.Fail ("Known limitation - can't get info from m2n frames"); } catch (AbsentInformationException) {} - frame = frames [1]; + frame = frames [3]; Assert.IsFalse (frame.IsNativeTransition, "#12.1"); var wait_one_this = frame.GetThis (); Assert.IsNotNull (wait_one_this, "#12.2"); - frame = frames [2]; + frame = frames [6]; var locals = frame.GetVisibleVariables (); Assert.AreEqual (1, locals.Count, "#13.1"); diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs b/mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs index d3671c0bf9f..23ccc8316eb 100644 --- a/mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs +++ b/mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs @@ -128,12 +128,25 @@ namespace Mono.Security.X509 { string filename = Path.Combine (_storePath, GetUniqueName (certificate)); if (!File.Exists (filename)) { - using (FileStream fs = File.Create (filename)) { - byte[] data = certificate.RawData; - fs.Write (data, 0, data.Length); - fs.Close (); + filename = Path.Combine (_storePath, GetUniqueNameWithSerial (certificate)); + if (!File.Exists (filename)) { + using (FileStream fs = File.Create (filename)) { + byte[] data = certificate.RawData; + fs.Write (data, 0, data.Length); + fs.Close (); + } + ClearCertificates (); // We have modified the store on disk. So forget the old state. + } + } else { + string newfilename = Path.Combine (_storePath, GetUniqueNameWithSerial (certificate)); + if (GetUniqueNameWithSerial (LoadCertificate (filename)) != GetUniqueNameWithSerial (certificate)) { + using (FileStream fs = File.Create (newfilename)) { + byte[] data = certificate.RawData; + fs.Write (data, 0, data.Length); + fs.Close (); + } + ClearCertificates (); // We have modified the store on disk. So forget the old state. } - ClearCertificates (); // We have modified the store on disk. So forget the old state. } #if !NET_2_1 // Try to save privateKey if available.. @@ -164,10 +177,16 @@ namespace Mono.Security.X509 { public void Remove (X509Certificate certificate) { - string filename = Path.Combine (_storePath, GetUniqueName (certificate)); + string filename = Path.Combine (_storePath, GetUniqueNameWithSerial (certificate)); if (File.Exists (filename)) { File.Delete (filename); ClearCertificates (); // We have modified the store on disk. So forget the old state. + } else { + filename = Path.Combine (_storePath, GetUniqueName (certificate)); + if (File.Exists (filename)) { + File.Delete (filename); + ClearCertificates (); // We have modified the store on disk. So forget the old state. + } } } @@ -182,10 +201,15 @@ namespace Mono.Security.X509 { // private stuff - private string GetUniqueName (X509Certificate certificate) + private string GetUniqueNameWithSerial (X509Certificate certificate) + { + return GetUniqueName (certificate, certificate.SerialNumber); + } + + private string GetUniqueName (X509Certificate certificate, byte[] serial = null) { string method; - byte[] name = GetUniqueName (certificate.Extensions); + byte[] name = GetUniqueName (certificate.Extensions, serial); if (name == null) { method = "tbp"; // thumbprint name = certificate.Hash; @@ -208,7 +232,7 @@ namespace Mono.Security.X509 { return GetUniqueName (method, name, ".crl"); } - private byte[] GetUniqueName (X509ExtensionCollection extensions) + private byte[] GetUniqueName (X509ExtensionCollection extensions, byte[] serial = null) { // We prefer Subject Key Identifier as the unique name // as it will provide faster lookups @@ -217,7 +241,14 @@ namespace Mono.Security.X509 { return null; SubjectKeyIdentifierExtension ski = new SubjectKeyIdentifierExtension (ext); - return ski.Identifier; + if (serial == null) { + return ski.Identifier; + } else { + byte[] uniqueWithSerial = new byte[ski.Identifier.Length + serial.Length]; + System.Buffer.BlockCopy (ski.Identifier, 0, uniqueWithSerial, 0, ski.Identifier.Length ); + System.Buffer.BlockCopy (serial, 0, uniqueWithSerial, ski.Identifier.Length, serial.Length ); + return uniqueWithSerial; + } } private string GetUniqueName (string method, byte[] name, string fileExtension) diff --git a/mcs/class/System.Drawing/System.Drawing.Printing/PrintingServicesUnix.cs b/mcs/class/System.Drawing/System.Drawing.Printing/PrintingServicesUnix.cs index 8e172ad3a4d..e9e90c3e834 100644 --- a/mcs/class/System.Drawing/System.Drawing.Printing/PrintingServicesUnix.cs +++ b/mcs/class/System.Drawing/System.Drawing.Printing/PrintingServicesUnix.cs @@ -299,6 +299,9 @@ namespace System.Drawing.Printing CUPS_OPTIONS cups_options; string option_name, option_value; int cups_size = Marshal.SizeOf(typeof(CUPS_OPTIONS)); + + LoadOptionList (ppd, "PageSize", paper_names, out defsize); + LoadOptionList (ppd, "InputSlot", paper_sources, out defsource); for (int j = 0; j < numOptions; j++) { @@ -306,6 +309,8 @@ namespace System.Drawing.Printing option_name = Marshal.PtrToStringAnsi(cups_options.name); option_value = Marshal.PtrToStringAnsi(cups_options.val); + if (option_name == "PageSize") defsize = option_value; + else if (option_name == "InputSlot") defsource = option_value; #if PrintDebug Console.WriteLine("{0} = {1}", option_name, option_value); #endif @@ -314,9 +319,6 @@ namespace System.Drawing.Printing options = (IntPtr) ((long)options + cups_size); } - - LoadOptionList (ppd, "PageSize", paper_names, out defsize); - LoadOptionList (ppd, "InputSlot", paper_sources, out defsource); } /// diff --git a/mcs/class/System.Drawing/Test/System.Drawing.Printing/PrintingServicesUnixTest.cs b/mcs/class/System.Drawing/Test/System.Drawing.Printing/PrintingServicesUnixTest.cs index 4cc01193e82..e5697165999 100644 --- a/mcs/class/System.Drawing/Test/System.Drawing.Printing/PrintingServicesUnixTest.cs +++ b/mcs/class/System.Drawing/Test/System.Drawing.Printing/PrintingServicesUnixTest.cs @@ -99,7 +99,6 @@ namespace MonoTests.System.Drawing.Printing { optionPtr = (IntPtr)((long)optionPtr + cupsOptionSize); } cupsFreeDests (1, destPtr); - return options; } @@ -115,8 +114,9 @@ namespace MonoTests.System.Drawing.Printing { var settings = new PrinterSettings () { PrinterName = PrinterSettings.InstalledPrinters [0] }; Assert.AreEqual (options ["PageSize"], settings.DefaultPageSettings.PaperSize.PaperName, "Bug #602934 (https://bugzilla.novell.com/show_bug.cgi?id=602934) not fixed (PaperSize)"); - Assert.AreEqual (options ["Resolution"], string.Format ("{0}dpi", settings.DefaultPageSettings.PrinterResolution.X), - "Bug #602934 (https://bugzilla.novell.com/show_bug.cgi?id=602934) not fixed (Resolution)"); + if (options.ContainsKey("Resolution")) + Assert.AreEqual (options ["Resolution"], string.Format ("{0}dpi", settings.DefaultPageSettings.PrinterResolution.X), + "Bug #602934 (https://bugzilla.novell.com/show_bug.cgi?id=602934) not fixed (Resolution)"); } #endregion diff --git a/mcs/class/System.IO.Compression/SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs b/mcs/class/System.IO.Compression/SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs index da5d94f4104..5060897cb9a 100644 --- a/mcs/class/System.IO.Compression/SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs +++ b/mcs/class/System.IO.Compression/SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs @@ -22,7 +22,7 @@ namespace SharpCompress.Writer.Zip byte[] encodedFilename = Encoding.UTF8.GetBytes(FileName); byte[] encodedComment = Encoding.UTF8.GetBytes(Comment); - outputStream.Write(new byte[] {80, 75, 1, 2, 0x3F, 0, 0x0A, 0}, 0, 8); + outputStream.Write(new byte[] {80, 75, 1, 2, 0x14, 0, 0x0A, 0}, 0, 8); HeaderFlags flags = HeaderFlags.UTF8; if (!outputStream.CanSeek) { diff --git a/mcs/class/System.IO.Compression/SharpCompress/Writer/Zip/ZipWriter.cs b/mcs/class/System.IO.Compression/SharpCompress/Writer/Zip/ZipWriter.cs index 70a2eb7d8c4..846d78c8e4f 100644 --- a/mcs/class/System.IO.Compression/SharpCompress/Writer/Zip/ZipWriter.cs +++ b/mcs/class/System.IO.Compression/SharpCompress/Writer/Zip/ZipWriter.cs @@ -142,7 +142,7 @@ namespace SharpCompress.Writer.Zip byte[] encodedFilename = encoding.GetBytes(filename); OutputStream.Write(BitConverter.GetBytes(ZipHeaderFactory.ENTRY_HEADER_BYTES), 0, 4); - OutputStream.Write(new byte[] {63, 0}, 0, 2); //version + OutputStream.Write(new byte[] {20, 0}, 0, 2); //version HeaderFlags flags = encoding == Encoding.UTF8 ? HeaderFlags.UTF8 : (HeaderFlags)0; if (!OutputStream.CanSeek) { diff --git a/mcs/class/System.IO.Compression/Test/System.IO.Compression/ZipTest.cs b/mcs/class/System.IO.Compression/Test/System.IO.Compression/ZipTest.cs index eacf2f6b3dd..36903c675b4 100644 --- a/mcs/class/System.IO.Compression/Test/System.IO.Compression/ZipTest.cs +++ b/mcs/class/System.IO.Compression/Test/System.IO.Compression/ZipTest.cs @@ -114,6 +114,51 @@ namespace MonoTests.System.IO.Compression File.Delete ("test.zip"); } + [Test] + public void ZipOpenAndReopenEntry() + { + try { + File.Copy("archive.zip", "test.zip", overwrite: true); + using (var archive = new ZipArchive(File.Open("test.zip", FileMode.Open), + ZipArchiveMode.Update)) + { + var entry = archive.GetEntry("foo.txt"); + Assert.IsNotNull(entry); + + var stream = entry.Open(); + + try { + stream = entry.Open(); + } catch (global::System.IO.IOException ex) { + return; + } + + Assert.Fail(); + } + } finally { + File.Delete ("test.zip"); + } + } + + + [Test] + public void ZipOpenCloseAndReopenEntry() + { + File.Copy("archive.zip", "test.zip", overwrite: true); + using (var archive = new ZipArchive(File.Open("test.zip", FileMode.Open), + ZipArchiveMode.Update)) + { + var entry = archive.GetEntry("foo.txt"); + Assert.IsNotNull(entry); + + var stream = entry.Open(); + stream.Dispose(); + stream = entry.Open(); + } + + File.Delete ("test.zip"); + } + [Test] public void ZipGetEntryDeleteReadMode() { diff --git a/mcs/class/System.IO.Compression/ZipArchiveEntry.cs b/mcs/class/System.IO.Compression/ZipArchiveEntry.cs index cd783b8eb0c..0bc69786418 100644 --- a/mcs/class/System.IO.Compression/ZipArchiveEntry.cs +++ b/mcs/class/System.IO.Compression/ZipArchiveEntry.cs @@ -29,10 +29,96 @@ using SharpCompress.Archive; namespace System.IO.Compression { + internal class ZipArchiveEntryStream : Stream, IDisposable + { + private readonly ZipArchiveEntry entry; + private readonly Stream stream; + + public override bool CanRead { + get { + return stream.CanRead; + } + } + + public override bool CanSeek { + get { + return stream.CanSeek; + } + } + + public override bool CanWrite { + get { + return stream.CanWrite; + } + } + + public override long Length { + get { + return stream.Length; + } + } + + public override long Position { + get { + return stream.Position; + } + set { + stream.Position = value; + } + } + + public ZipArchiveEntryStream(ZipArchiveEntry entry, Stream stream) + { + this.entry = entry; + this.stream = stream; + } + + public override void Flush () + { + stream.Flush(); + } + + public override long Seek (long offset, SeekOrigin origin) + { + return stream.Seek(offset, origin); + } + + public override void SetLength (long value) + { + stream.SetLength(value); + } + + public override int Read (byte[] buffer, int offset, int count) + { + return stream.Read(buffer, offset, count); + } + + public override void Write (byte[] buffer, int offset, int count) + { + stream.Write(buffer, offset, count); + } + + public new void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + base.Dispose(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + entry.openStream = null; + stream.Dispose(); + } + } + } + public class ZipArchiveEntry { readonly SharpCompress.Archive.Zip.ZipArchiveEntry entry; - private Stream openStream; + internal ZipArchiveEntryStream openStream; private bool wasDeleted; internal ZipArchiveEntry(ZipArchive archive, SharpCompress.Archive.Zip.ZipArchiveEntry entry) @@ -112,7 +198,7 @@ namespace System.IO.Compression if (Archive.Mode == ZipArchiveMode.Create && openStream != null) throw new IOException("The archive for this entry was opened with the Create mode, and this entry has already been written to."); - openStream = entry.OpenEntryStream(); + openStream = new ZipArchiveEntryStream(this, entry.OpenEntryStream()); return openStream; } diff --git a/mcs/class/System.ServiceModel/System.ServiceModel/WSDualHttpBinding.cs b/mcs/class/System.ServiceModel/System.ServiceModel/WSDualHttpBinding.cs index a531b34cf61..789a602e9df 100644 --- a/mcs/class/System.ServiceModel/System.ServiceModel/WSDualHttpBinding.cs +++ b/mcs/class/System.ServiceModel/System.ServiceModel/WSDualHttpBinding.cs @@ -58,7 +58,12 @@ namespace System.ServiceModel { } - protected WSDualHttpBinding (WSDualHttpSecurityMode securityMode) + public WSDualHttpBinding(string configName) + : this (WSDualHttpSecurityMode.Message) + { + } + + public WSDualHttpBinding (WSDualHttpSecurityMode securityMode) { security = new WSDualHttpSecurity (securityMode); } diff --git a/mcs/class/System.Web.ApplicationServices/Makefile b/mcs/class/System.Web.ApplicationServices/Makefile index d7389f43e0d..cfd5e146ec0 100644 --- a/mcs/class/System.Web.ApplicationServices/Makefile +++ b/mcs/class/System.Web.ApplicationServices/Makefile @@ -6,7 +6,9 @@ LIBRARY = System.Web.ApplicationServices.dll LIB_REFS = System System.Configuration LIB_MCS_FLAGS = -d:SYSTEM_WEB_APPLICATIONSERVICES -EXTRA_DISTFILES = $(RESOURCE_FILES) +RESOURCE_STRINGS = ./System.Web.ApplicationServices.txt + +EXTRA_DISTFILES = $(RESOURCE_FILES) $(RESOURCE_STRINGS) VALID_PROFILE := $(filter 4, $(FRAMEWORK_VERSION_MAJOR)) ifndef VALID_PROFILE diff --git a/mcs/class/System.Web.ApplicationServices/System.Web.ApplicationServices.dll.sources b/mcs/class/System.Web.ApplicationServices/System.Web.ApplicationServices.dll.sources index ce75cae57d6..de8e66df804 100644 --- a/mcs/class/System.Web.ApplicationServices/System.Web.ApplicationServices.dll.sources +++ b/mcs/class/System.Web.ApplicationServices/System.Web.ApplicationServices.dll.sources @@ -3,19 +3,21 @@ Assembly/AssemblyInfo.cs ../../build/common/Locale.cs ../../build/common/MonoTODOAttribute.cs -System.Web.Configuration/MembershipPasswordCompatibilityMode.cs +../../../external/referencesource/System.Web.ApplicationServices/Configuration/MembershipPasswordCompatibilityMode.cs +../../../external/referencesource/System.Web.ApplicationServices/Security/IMembershipAdapter.cs System.Web.Security/IMembershipHelper.cs System.Web.UI/KeyedList.cs System.Web.UI/KeyedListEnumerator.cs -System.Web.Security/MembershipCreateStatus.cs -System.Web.Security/MembershipCreateUserException.cs -System.Web.Security/MembershipPasswordException.cs -System.Web.Security/MembershipPasswordFormat.cs -System.Web.Security/MembershipProviderCollection.cs +../../../external/referencesource/System.Web.ApplicationServices/Security/MembershipCreateStatus.cs +../../../external/referencesource/System.Web.ApplicationServices/Security/MembershipCreateUserException.cs +../../../external/referencesource/System.Web.ApplicationServices/Security/MembershipPasswordException.cs +../../../external/referencesource/System.Web.ApplicationServices/Security/MembershipPasswordFormat.cs +../../../external/referencesource/System.Web.ApplicationServices/Security/MembershipProviderCollection.cs System.Web.Security/MembershipProvider.cs -System.Web.Security/MembershipUserCollection.cs +../../../external/referencesource/System.Web.ApplicationServices/Security/MembershipUserCollection.cs System.Web.Security/MembershipUser.cs -System.Web.Security/MembershipValidatePasswordEventHandler.cs +../../../external/referencesource/System.Web.ApplicationServices/Security/MembershipValidatePasswordEventHandler.cs System.Web.Security/RoleProvider.cs -System.Web.Security/ValidatePasswordEventArgs.cs +../../../external/referencesource/System.Web.ApplicationServices/Security/ValidatePasswordEventArgs.cs +System.Web/ApplicationServicesStrings.cs diff --git a/mcs/class/System.Web.ApplicationServices/System.Web.ApplicationServices.txt b/mcs/class/System.Web.ApplicationServices/System.Web.ApplicationServices.txt new file mode 100644 index 00000000000..26d1f17c583 --- /dev/null +++ b/mcs/class/System.Web.ApplicationServices/System.Web.ApplicationServices.txt @@ -0,0 +1,21 @@ +Can_not_use_encrypted_passwords_with_autogen_keys=You must specify a non-autogenerated machine key to store passwords in the encrypted format. Either specify a different passwordFormat, or change the machineKey configuration to use a non-autogenerated decryption key. +CustomLoader_ForbiddenByHost=The host forbids the use of custom loaders. +CustomLoader_MustImplementICustomLoader=The provided type '{0}' must implement the ICustomLoader interface. +CustomLoader_NoAttributeFound=The assembly '{0}' did not contain an assembly-level CustomLoaderAttribute. +CustomLoader_NotInFullTrust=Custom loaders can only be used by fully-trusted applications. +Membership_DuplicateEmail=The E-mail address is already in use. +Membership_DuplicateProviderUserKey=The provider user key is already in use. +Membership_DuplicateUserName=The username is already in use. +Membership_InvalidAnswer=The password-answer supplied is invalid. +Membership_InvalidEmail=The E-mail supplied is invalid. +Membership_InvalidPassword=The password supplied is invalid. Passwords must conform to the password strength requirements configured for the default provider. +Membership_InvalidProviderUserKey=The provider user key supplied is invalid. It must be of type System.Guid. +Membership_InvalidQuestion=The password-question supplied is invalid. Note that the current provider configuration requires a valid password question and answer. As a result, a CreateUser overload that accepts question and answer parameters must also be used. +Membership_InvalidUserName=The username supplied is invalid. +Membership_no_error=No Error. +Membership_provider_name_invalid=The membership provider name specified is invalid. +Membership_UserRejected=The user was rejected. +Parameter_can_not_be_empty=The parameter '{0}' must not be empty. +Platform_not_supported=This member is not supported on this platfom. +Provider_Error=The Provider encountered an unknown error. +Provider_must_implement_type=Provider must implement the class '{0}'. diff --git a/mcs/class/System.Web.ApplicationServices/System.Web.Configuration/MembershipPasswordCompatibilityMode.cs b/mcs/class/System.Web.ApplicationServices/System.Web.Configuration/MembershipPasswordCompatibilityMode.cs deleted file mode 100644 index 367108c0433..00000000000 --- a/mcs/class/System.Web.ApplicationServices/System.Web.Configuration/MembershipPasswordCompatibilityMode.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// System.Web.Security.MembershipPasswordCompatibilityMode -// -// Authors: -// Marek Habersack -// -// Copyright (C) 2010 Novell, Inc (http://novell.com) -// -// 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. -// -using System; - -namespace System.Web.Configuration -{ - public enum MembershipPasswordCompatibilityMode - { - Framework20, - Framework40 - } -} diff --git a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipCreateStatus.cs b/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipCreateStatus.cs deleted file mode 100644 index 71fddb48a04..00000000000 --- a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipCreateStatus.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// System.Web.Security.MembershipCreateStatus -// -// Authors: -// Ben Maurer (bmaurer@users.sourceforge.net) -// -// (C) 2003 Ben Maurer -// Copyright (C) 2005 Novell, Inc (http://www.novell.com) -// -// 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. -// -using System.Runtime.CompilerServices; - -namespace System.Web.Security -{ - [TypeForwardedFrom ("System.Web, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a")] - public enum MembershipCreateStatus - { - Success, - InvalidUserName, - InvalidPassword, - InvalidQuestion, - InvalidAnswer, - InvalidEmail, - DuplicateUserName, - DuplicateEmail, - UserRejected, - InvalidProviderUserKey, - DuplicateProviderUserKey, - ProviderError - } -} - - diff --git a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipCreateUserException.cs b/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipCreateUserException.cs deleted file mode 100644 index a5f9e31a70e..00000000000 --- a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipCreateUserException.cs +++ /dev/null @@ -1,77 +0,0 @@ -// -// System.Web.Security.MembershipCreateUserException -// -// Authors: -// Ben Maurer (bmaurer@users.sourceforge.net) -// -// (C) 2003 Ben Maurer -// - -// -// 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. -// - -using System; -using System.Runtime.Serialization; -using System.Runtime.CompilerServices; - -namespace System.Web.Security -{ - [TypeForwardedFrom ("System.Web, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a")] - [Serializable] - public class MembershipCreateUserException : Exception - { - MembershipCreateStatus statusCode; - - public MembershipCreateUserException () - { - } - - public MembershipCreateUserException (string message): base (message) - { - } - - public MembershipCreateUserException (string message, Exception innerException): base (message, innerException) - { - } - - protected MembershipCreateUserException (SerializationInfo info, StreamingContext context): base (info, context) - { - info.AddValue ("statusCode", statusCode); - } - - public MembershipCreateUserException (MembershipCreateStatus statusCode) : base (statusCode.ToString ()) - { - this.statusCode = statusCode; - } - - public override void GetObjectData (SerializationInfo info, StreamingContext ctx) - { - base.GetObjectData (info, ctx); - statusCode = (MembershipCreateStatus) info.GetValue ("statusCode", typeof(MembershipCreateStatus)); - } - - public MembershipCreateStatus StatusCode { - get { return statusCode; } - } - } -} - - diff --git a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipPasswordException.cs b/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipPasswordException.cs deleted file mode 100644 index 5bf60eb9080..00000000000 --- a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipPasswordException.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// System.Web.Security.MembershipPasswordException -// -// Authors: -// Ben Maurer (bmaurer@users.sourceforge.net) -// -// (C) 2003 Ben Maurer -// - -// -// 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. -// - -using System; -using System.Runtime.Serialization; -using System.Runtime.CompilerServices; - -namespace System.Web.Security -{ - [TypeForwardedFrom ("System.Web, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a")] - [Serializable] - public class MembershipPasswordException : Exception - { - public MembershipPasswordException () : base () {} - public MembershipPasswordException (string message) : base (message) {} - public MembershipPasswordException (string message, Exception innerException) : base (message, innerException) {} - - protected MembershipPasswordException (SerializationInfo info, StreamingContext context): base (info, context) - { - } - } -} - - diff --git a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipPasswordFormat.cs b/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipPasswordFormat.cs deleted file mode 100644 index 294861808d9..00000000000 --- a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipPasswordFormat.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// System.Web.Security.MembershipPasswordFormat -// -// Authors: -// Ben Maurer (bmaurer@users.sourceforge.net) -// -// (C) 2003 Ben Maurer -// - -// -// 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. -// -using System.Runtime.CompilerServices; - -namespace System.Web.Security -{ - [TypeForwardedFrom ("System.Web, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a")] - public enum MembershipPasswordFormat - { - Clear = 0, - Hashed = 1, - Encrypted = 2 - } -} - - diff --git a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipProviderCollection.cs b/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipProviderCollection.cs deleted file mode 100644 index be25a051cc7..00000000000 --- a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipProviderCollection.cs +++ /dev/null @@ -1,62 +0,0 @@ -// -// System.Web.Security.MembershipProviderCollection -// -// Authors: -// Ben Maurer (bmaurer@users.sourceforge.net) -// Sebastien Pouliot -// -// (C) 2003 Ben Maurer -// Copyright (c) 2005 Novell, Inc (http://www.novell.com) -// -// 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. -// -using System.Configuration.Provider; -using System.Runtime.CompilerServices; - -namespace System.Web.Security -{ - [TypeForwardedFrom ("System.Web, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a")] - public sealed class MembershipProviderCollection : ProviderCollection - { - public override void Add (ProviderBase provider) - { - if (provider == null) - throw new ArgumentNullException ("provider"); - - if (provider is MembershipProvider) - base.Add (provider); - else { - throw new ArgumentException ("provider", Locale.GetText ( - "Wrong type, expected {0}.", "MembershipProvider")); - } - } - - public void CopyTo (MembershipProvider[] array, int index) - { - base.CopyTo (array, index); - } - - public new MembershipProvider this [string name] { - get { return (MembershipProvider) base [name]; } - } - } -} - - diff --git a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipUserCollection.cs b/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipUserCollection.cs deleted file mode 100644 index bbb689fa3eb..00000000000 --- a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipUserCollection.cs +++ /dev/null @@ -1,112 +0,0 @@ -// -// System.Web.Security.MembershipUserCollection -// -// Authors: -// Ben Maurer (bmaurer@users.sourceforge.net) -// -// (C) 2003 Ben Maurer -// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com) -// -// 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. -// - -using System.Collections; -using System.Runtime.CompilerServices; -using System.Web.UI; - -namespace System.Web.Security -{ - [TypeForwardedFrom ("System.Web, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a")] - [Serializable] - public sealed class MembershipUserCollection : ICollection - { - public MembershipUserCollection () - { - } - - public void Add (MembershipUser user) - { - if (user == null) - throw new ArgumentNullException ("user"); - - CheckNotReadOnly (); - store.Add (user.UserName, user); - } - - public void Clear () - { - CheckNotReadOnly (); - store.Clear (); - } - - void ICollection.CopyTo (Array array, int index) - { - store.Values.CopyTo (array, index); - } - - public void CopyTo (MembershipUser[] array, int index) - { - store.Values.CopyTo (array, index); - } - - public IEnumerator GetEnumerator () - { - return ((IEnumerable) store).GetEnumerator (); - } - - public void Remove (string name) - { - CheckNotReadOnly (); - store.Remove (name); - } - - public void SetReadOnly () - { - readOnly = true; - } - - public int Count { - get { return store.Count; } - } - - public bool IsSynchronized { - get { return false; } - } - - public MembershipUser this [string name] { - get { return (MembershipUser) store [name]; } - } - - public object SyncRoot { - get { return this; } - } - - void CheckNotReadOnly () - { - if (readOnly) - throw new NotSupportedException (); - } - - KeyedList store = new KeyedList (); - bool readOnly = false; - } -} - - diff --git a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipValidatePasswordEventHandler.cs b/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipValidatePasswordEventHandler.cs deleted file mode 100644 index 1c475112c66..00000000000 --- a/mcs/class/System.Web.ApplicationServices/System.Web.Security/MembershipValidatePasswordEventHandler.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// System.Web.Security.MembershipValidatePasswordEventHandler -// -// Authors: -// Lluis Sanchez Gual (lluis@novell.com) -// -// (C) 2005 Novell, inc. -// - -// -// 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. -// - -using System.Runtime.CompilerServices; - -namespace System.Web.Security -{ - [TypeForwardedFrom ("System.Web, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a")] - public delegate void MembershipValidatePasswordEventHandler (object sender, ValidatePasswordEventArgs e); -} - - diff --git a/mcs/class/System.Web.ApplicationServices/System.Web.Security/ValidatePasswordEventArgs.cs b/mcs/class/System.Web.ApplicationServices/System.Web.Security/ValidatePasswordEventArgs.cs deleted file mode 100644 index ea189038e8e..00000000000 --- a/mcs/class/System.Web.ApplicationServices/System.Web.Security/ValidatePasswordEventArgs.cs +++ /dev/null @@ -1,74 +0,0 @@ -// -// System.Web.Security.ValidatePasswordEventArgs -// -// Authors: -// Lluis Sanchez Gual (lluis@novell.com) -// -// (C) 2005 Novell, inc. -// - -// -// 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. -// -using System; -using System.Runtime.CompilerServices; - -namespace System.Web.Security -{ - [TypeForwardedFrom ("System.Web, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a")] - public sealed class ValidatePasswordEventArgs: EventArgs - { - bool cancel; - Exception exception; - bool isNewUser; - string userName; - string password; - - public ValidatePasswordEventArgs (string userName, string password, bool isNewUser) - { - this.isNewUser = isNewUser; - this.userName = userName; - this.password = password; - } - - public bool Cancel { - get { return cancel; } - set { cancel = value; } - } - - public Exception FailureInformation { - get { return exception; } - set { exception = value; } - } - - public bool IsNewUser { - get { return isNewUser; } - } - - public string UserName { - get { return userName; } - } - - public string Password { - get { return password; } - } - } -} - diff --git a/mcs/class/System.Web.ApplicationServices/System.Web/ApplicationServicesStrings.cs b/mcs/class/System.Web.ApplicationServices/System.Web/ApplicationServicesStrings.cs new file mode 100644 index 00000000000..61fda8a82bc --- /dev/null +++ b/mcs/class/System.Web.ApplicationServices/System.Web/ApplicationServicesStrings.cs @@ -0,0 +1,29 @@ +namespace System.Web +{ + internal class ApplicationServicesStrings + { + internal const string Can_not_use_encrypted_passwords_with_autogen_keys = "You must specify a non-autogenerated machine key to store passwords in the encrypted format. Either specify a different passwordFormat, or change the machineKey configuration to use a non-autogenerated decryption key."; + internal const string CustomLoader_ForbiddenByHost = "The host forbids the use of custom loaders."; + internal const string CustomLoader_MustImplementICustomLoader = "The provided type '{0}' must implement the ICustomLoader interface."; + internal const string CustomLoader_NoAttributeFound = "The assembly '{0}' did not contain an assembly-level CustomLoaderAttribute."; + internal const string CustomLoader_NotInFullTrust = "Custom loaders can only be used by fully-trusted applications ()."; + internal const string Membership_DuplicateEmail = "The E-mail address is already in use."; + internal const string Membership_DuplicateProviderUserKey = "The provider user key is already in use."; + internal const string Membership_DuplicateUserName = "The username is already in use."; + internal const string Membership_InvalidAnswer = "The password-answer supplied is invalid."; + internal const string Membership_InvalidEmail = "The E-mail supplied is invalid."; + internal const string Membership_InvalidPassword = "The password supplied is invalid. Passwords must conform to the password strength requirements configured for the default provider."; + internal const string Membership_InvalidProviderUserKey = "The provider user key supplied is invalid. It must be of type System.Guid."; + internal const string Membership_InvalidQuestion = "The password-question supplied is invalid. Note that the current provider configuration requires a valid password question and answer. As a result, a CreateUser overload that accepts question and answer parameters must also be used."; + internal const string Membership_InvalidUserName = "The username supplied is invalid."; + internal const string Membership_no_error = "No Error."; + internal const string Membership_provider_name_invalid = "The membership provider name specified is invalid."; + internal const string Membership_UserRejected = "The user was rejected."; + internal const string Parameter_can_not_be_empty = "The parameter '{0}' must not be empty."; + internal const string Platform_not_supported = "This member is not supported on the .NET Framework Client Profile."; + internal const string Provider_Error = "The Provider encountered an unknown error."; + internal const string Provider_must_implement_type = "Provider must implement the class '{0}'."; + } +} + + diff --git a/mcs/class/System.Web/System.Web.Profile/DefaultProfile.cs b/mcs/class/System.Web/System.Web.Profile/DefaultProfile.cs deleted file mode 100644 index 4a4250f6197..00000000000 --- a/mcs/class/System.Web/System.Web.Profile/DefaultProfile.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// System.Web.UI.WebControls.DefaultProfile.cs -// -// Authors: -// Chris Toshok (toshok@ximian.com) -// -// (C) 2005 Novell, Inc (http://www.novell.com) -// -// 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. -// - -using System; -using System.Configuration; - -namespace System.Web.Profile -{ - public class DefaultProfile : ProfileBase - { - [MonoTODO("Currently does nothing")] - public DefaultProfile () - { - } - } - -} - diff --git a/mcs/class/System.Web/System.Web.Profile/ProfileAuthenticationOption.cs b/mcs/class/System.Web/System.Web.Profile/ProfileAuthenticationOption.cs deleted file mode 100644 index 78994538f24..00000000000 --- a/mcs/class/System.Web/System.Web.Profile/ProfileAuthenticationOption.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// System.Web.Profile.ProfileAuthenticationOption.cs -// -// Authors: -// Duncan Mak (duncan@ximian.com) -// -// 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. -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// - -namespace System.Web.Profile -{ - public enum ProfileAuthenticationOption - { - Anonymous = 0, - Authenticated = 1, - All = 2 - } -} diff --git a/mcs/class/System.Web/System.Web.Profile/ProfileInfo.cs b/mcs/class/System.Web/System.Web.Profile/ProfileInfo.cs deleted file mode 100644 index b3472815c4e..00000000000 --- a/mcs/class/System.Web/System.Web.Profile/ProfileInfo.cs +++ /dev/null @@ -1,92 +0,0 @@ -// -// System.Web.Profile.ProfileInfo.cs -// -// Authors: -// Chris Toshok (toshok@ximian.com) -// -// (C) 2005 Novell, Inc (http://www.novell.com) -// -// 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. -// - -using System; - -namespace System.Web.Profile -{ - [Serializable] - public class ProfileInfo - { - string user_name; - bool is_anonymous; - DateTime last_activity_date; - DateTime last_updated_date; - int size; - - protected ProfileInfo () - { - } - - public ProfileInfo (string username, - bool isAnonymous, - DateTime lastActivityDate, - DateTime lastUpdatedDate, - int size) - { - user_name = username; - is_anonymous = isAnonymous; - last_activity_date = lastActivityDate; - last_updated_date = lastUpdatedDate; - this.size = size; - } - - public virtual bool IsAnonymous - { - get { - return is_anonymous; - } - } - - public virtual DateTime LastActivityDate - { - get { - return last_activity_date; - } - } - - public virtual DateTime LastUpdatedDate { - get { - return last_updated_date; - } - } - - public virtual int Size { - get { - return size; - } - } - - public virtual string UserName { - get { - return user_name; - } - } - } - -} diff --git a/mcs/class/System.Web/System.Web.Profile/ProfileInfoCollection.cs b/mcs/class/System.Web/System.Web.Profile/ProfileInfoCollection.cs deleted file mode 100644 index 545c2352935..00000000000 --- a/mcs/class/System.Web/System.Web.Profile/ProfileInfoCollection.cs +++ /dev/null @@ -1,127 +0,0 @@ -// -// System.Web.Profile.ProfileInfoCollection.cs -// -// Authors: -// Chris Toshok (toshok@ximian.com) -// -// (C) 2005 Novell, Inc (http://www.novell.com) -// -// 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. -// - -using System; -using System.Collections; - -namespace System.Web.Profile -{ - [Serializable] - public sealed class ProfileInfoCollection : ICollection, IEnumerable - { - public ProfileInfoCollection() - { - list = new ArrayList (); - } - - public void Add (ProfileInfo profileInfo) - { - if (readOnly) - throw new NotSupportedException (); - - list.Add (profileInfo); - } - - public void Clear () - { - if (readOnly) - throw new NotSupportedException (); - - list.Clear (); - } - - public void CopyTo (System.Array array, int index) - { - list.CopyTo (array, index); - } - - public void CopyTo (ProfileInfo[ ] array, int index) - { - list.CopyTo (array, index); - } - - public IEnumerator GetEnumerator () - { - return list.GetEnumerator (); - } - - public void Remove (string name) - { - if (readOnly) - throw new NotSupportedException (); - - for (int i = 0; i < list.Count; i ++) { - ProfileInfo info = (ProfileInfo)list[i]; - if (info.UserName == name) { - list.Remove (i); - break; - } - } - } - - public void SetReadOnly () - { - readOnly = true; - } - - public int Count { - get { - return list.Count; - } - } - - public bool IsSynchronized { - get { - return false; - } - } - - public object SyncRoot { - get { - return this; - } - } - - public ProfileInfo this [string name] { - get { - for (int i = 0; i < list.Count; i ++) { - ProfileInfo info = (ProfileInfo)list[i]; - if (info.UserName == name) { - return info; - } - } - - return null; - } - } - - ArrayList list; - bool readOnly; - } - -} diff --git a/mcs/class/System.Web/System.Web.UI.WebControls/IPostBackContainer.cs b/mcs/class/System.Web/System.Web.UI.WebControls/IPostBackContainer.cs deleted file mode 100644 index c00250c69ff..00000000000 --- a/mcs/class/System.Web/System.Web.UI.WebControls/IPostBackContainer.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// System.Web.UI.WebControls.IPostBackContainer.cs -// -// Authors: -// Sanjay Gupta (gsanjay@novell.com) -// -// (C) 2004-2010 Novell, Inc (http://www.novell.com) -// -// -// 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. -// - -using System; -using System.Web.UI; - -namespace System.Web.UI.WebControls -{ - public interface IPostBackContainer - { - PostBackOptions GetPostBackOptions (IButtonControl control); - } -} - - diff --git a/mcs/class/System.Web/System.Web.UI/ICheckBoxControl.cs b/mcs/class/System.Web/System.Web.UI/ICheckBoxControl.cs deleted file mode 100644 index 006804c67b8..00000000000 --- a/mcs/class/System.Web/System.Web.UI/ICheckBoxControl.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -// System.Web.UI.ICheckBoxControl.cs -// -// Authors: -// Lluis Sanchez Gual (lluis@novell.com) -// -// (C) 2005-2010 Novell, Inc (http://www.novell.com) -// -// -// 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. -// - -using System; - -namespace System.Web.UI -{ - public interface ICheckBoxControl - { - bool Checked { get; set; } - event EventHandler CheckedChanged; - } -} - diff --git a/mcs/class/System.Web/System.Web.UI/IEditableTextControl.cs b/mcs/class/System.Web/System.Web.UI/IEditableTextControl.cs deleted file mode 100644 index 5ce858055ca..00000000000 --- a/mcs/class/System.Web/System.Web.UI/IEditableTextControl.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// System.Web.UI.IEditableTextControl.cs -// -// Authors: -// Lluis Sanchez Gual (lluis@novell.com) -// -// (C) 2005-2010 Novell, Inc (http://www.novell.com) -// -// -// 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. -// - -using System; - -namespace System.Web.UI -{ - public interface IEditableTextControl: ITextControl - { - event EventHandler TextChanged; - } -} - diff --git a/mcs/class/System.Web/System.Web.UI/ITextControl.cs b/mcs/class/System.Web/System.Web.UI/ITextControl.cs deleted file mode 100644 index f30591665df..00000000000 --- a/mcs/class/System.Web/System.Web.UI/ITextControl.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -// System.Web.UI.ITextControl.cs -// -// Authors: -// Lluis Sanchez Gual (lluis@novell.com) -// -// (C) 2005-2010 Novell, Inc (http://www.novell.com) -// -// -// 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. -// - -using System; - -namespace System.Web.UI -{ - public interface ITextControl - { - string Text { get; set; } - } -} diff --git a/mcs/class/System.Web/System.Web.dll.sources b/mcs/class/System.Web/System.Web.dll.sources index 908e44292fe..09fe382000b 100644 --- a/mcs/class/System.Web/System.Web.dll.sources +++ b/mcs/class/System.Web/System.Web.dll.sources @@ -410,16 +410,15 @@ System.Web/ProcessModelInfo.cs System.Web/ProcessShutdownReason.cs System.Web/ProcessStatus.cs System.Web.Profile/CustomProviderDataAttribute.cs -System.Web.Profile/DefaultProfile.cs -System.Web.Profile/ProfileAuthenticationOption.cs +../../../external/referencesource/System.Web/Profile/DefaultHttpProfile.cs +../../../external/referencesource/System.Web/Profile/ProfileAuthenticationOptions.cs System.Web.Profile/ProfileAutoSaveEventArgs.cs System.Web.Profile/ProfileAutoSaveEventHandler.cs System.Web.Profile/ProfileBase.cs ../../../external/referencesource/System.Web/Profile/ProfileEventArgs.cs ../../../external/referencesource/System.Web/Profile/ProfileEventHandler.cs ../../../external/referencesource/System.Web/Profile/HttpProfileGroupBase.cs -System.Web.Profile/ProfileInfoCollection.cs -System.Web.Profile/ProfileInfo.cs +../../../external/referencesource/System.Web/Profile/ProfileInfo.cs System.Web.Profile/ProfileManager.cs System.Web.Profile/ProfileMigrateEventArgs.cs System.Web.Profile/ProfileMigrateEventHandler.cs @@ -620,7 +619,7 @@ System.Web.UI/HtmlTextWriter.cs ../../../external/referencesource/System.Web/UI/IBindableControl.cs ../../../external/referencesource/System.Web/UI/IBindableTemplate.cs ../../../external/referencesource/System.Web/UI/ICallbackEventHandler.cs -System.Web.UI/ICheckBoxControl.cs +../../../external/referencesource/System.Web/UI/WebControls/ICheckBoxControl.cs ../../../external/referencesource/System.Web/UI/IControlBuilderAccessor.cs ../../../external/referencesource/System.Web/UI/IControlDesignerAccessor.cs ../../../external/referencesource/System.Web/UI/IDataBindingsAccessor.cs @@ -628,7 +627,7 @@ System.Web.UI/ICheckBoxControl.cs ../../../external/referencesource/System.Web/UI/IDataSource.cs ../../../external/referencesource/System.Web/UI/IDataSourceViewSchemaAccessor.cs ../../../external/referencesource/System.Web/UI/IDReferencePropertyAttribute.cs -System.Web.UI/IEditableTextControl.cs +../../../external/referencesource/System.Web/UI/WebControls/IEditableTextControl.cs ../../../external/referencesource/System.Web/UI/IExpressionsAccessor.cs ../../../external/referencesource/System.Web/UI/IFilterResolutionService.cs System.Web.UI/IgnoreUnknownContentAttribute.cs @@ -653,7 +652,7 @@ System.Web.UI/IScriptManager.cs ../../../external/referencesource/System.Web/UI/IScriptResourceMapping.cs System.Web.UI/ITagNameToTypeMapper.cs ../../../external/referencesource/System.Web/UI/ITemplate.cs -System.Web.UI/ITextControl.cs +../../../external/referencesource/System.Web/UI/WebControls/ITextControl.cs ../../../external/referencesource/System.Web/UI/IThemeResolutionService.cs ../../../external/referencesource/System.Web/UI/IUrlResolutionService.cs ../../../external/referencesource/System.Web/UI/IUserControlDesignerAccessor.cs @@ -953,7 +952,7 @@ System.Web.UI.WebControls/ImageMap.cs ../../../external/referencesource/System.Web/UI/WebControls/ImageMapEventHandler.cs System.Web.UI.WebControls/IMenuRenderer.cs ../../../external/referencesource/System.Web/UI/WebControls/IPersistedSelector.cs -System.Web.UI.WebControls/IPostBackContainer.cs +../../../external/referencesource/System.Web/UI/WebControls/IPostBackContainer.cs ../../../external/referencesource/System.Web/UI/WebControls/IRepeatInfoUser.cs System.Web.UI.WebControls/LabelControlBuilder.cs System.Web.UI.WebControls/Label.cs @@ -1264,6 +1263,7 @@ System.Web.UI/FileLevelMasterPageControlBuilder.cs ../../../external/referencesource/System.Web/UI/WebControls/IDataBoundItemControl.cs ../../../external/referencesource/System.Web/UI/WebControls/IDataBoundListControl.cs ../../../external/referencesource/System.Web/UI/WebControls/IFieldControl.cs +../../../external/referencesource/System.Web/UI/WebControls/IRenderOuterTableControl.cs System.Web.UI.WebControls/IRenderOuterTable.cs System.Web.UI.WebControls/MenuListRenderer.cs ../../../external/referencesource/System.Web/UI/WebControls/MenuRenderingMode.cs @@ -1420,7 +1420,6 @@ ReferenceSources/SR.cs ../../../external/referencesource/System.Web/Util/GCUtil.cs ../../../external/referencesource/System.Web/Util/SimpleRecyclingCache.cs ../../../external/referencesource/System.Web/Util/VersionUtil.cs - ../../../external/referencesource/System.Web/Util/AppVerifierErrorCode.cs ../../../external/referencesource/System.Web/Util/DateTimeUtil.cs ../../../external/referencesource/System.Web/Util/hresults.cs @@ -1430,4 +1429,23 @@ ReferenceSources/SR.cs ../../../external/referencesource/System.Web/Util/RegexUtil.cs ../../../external/referencesource/System.Web/Util/ObjectSet.cs ../../../external/referencesource/System.Web/Util/ParseHttpDate.cs +../../../external/referencesource/System.Web/IntraPartitionAPIs/xsp/PerfCounterEnum.cs +../../../external/referencesource/System.Web/misc/InvariantComparer.cs + +../../../external/referencesource/System.Web/ModelBinding/DictionaryHelpers.cs +../../../external/referencesource/System.Web/ModelBinding/ValueProviderResult.cs +../../../external/referencesource/System.Web/ModelBinding/ModelState.cs +../../../external/referencesource/System.Web/ModelBinding/ModelStateDictionary.cs +../../../external/referencesource/System.Web/ModelBinding/ModelBindingExecutionContext.cs +../../../external/referencesource/System.Web/ModelBinding/IValueProvider.cs +../../../external/referencesource/System.Web/ModelBinding/IValueProviderSource.cs +../../../external/referencesource/System.Web/ModelBinding/IUnvalidatedValueProviderSource.cs +../../../external/referencesource/System.Web/UI/IUpdatePanel.cs +../../../external/referencesource/System.Web/Configuration/IServerConfig2.cs +../../../external/referencesource/System.Web/UI/WebControls/IBorderPaddingControl.cs +../../../external/referencesource/System.Web/UI/WebControls/IEditableTextControl.cs +../../../external/referencesource/System.Web/UI/WebControls/IWizardSideBarListControl.cs +../../../external/referencesource/System.Web/UI/WebControls/WizardSideBarListControlItemEventArgs.cs +../../../external/referencesource/System.Web/UI/WebControls/WizardSideBarListControlItem.cs +../../../external/referencesource/System.Web/Security/Cryptography/ICryptoService.cs diff --git a/mcs/class/WindowsBase/System.Windows.Threading/Dispatcher.cs b/mcs/class/WindowsBase/System.Windows.Threading/Dispatcher.cs index a28f7a29d0d..1eeb9c9a368 100644 --- a/mcs/class/WindowsBase/System.Windows.Threading/Dispatcher.cs +++ b/mcs/class/WindowsBase/System.Windows.Threading/Dispatcher.cs @@ -1,22 +1,22 @@ // TODO: -// DispatcherObject returned by BeginInvoke must allow: -// * Waiting until delegate is invoked. -// See: BeginInvoke documentation for details +// DispatcherObject returned by BeginInvoke must allow: +// * Waiting until delegate is invoked. +// See: BeginInvoke documentation for details // -// Implement the "Invoke" methods, they are currently not working. +// Implement the "Invoke" methods, they are currently not working. // -// Add support for disabling the dispatcher and resuming it. -// Add support for Waiting for new tasks to be pushed, so that we dont busy loop. -// Add support for aborting an operation (emit the hook.operationaborted too) +// Add support for disabling the dispatcher and resuming it. +// Add support for Waiting for new tasks to be pushed, so that we dont busy loop. +// Add support for aborting an operation (emit the hook.operationaborted too) // // Very confusing information about Shutdown: it states that shutdown is // not over, until all events are unwinded, and also states that all events // are aborted at that point. See 'Dispatcher.InvokeShutdown' docs, // // Testing reveals that -// -> InvokeShutdown() stops processing, even if events are available, -// there is no "unwinding" of events, even of higher priority events, -// they are just ignored. +// -> InvokeShutdown() stops processing, even if events are available, +// there is no "unwinding" of events, even of higher priority events, +// they are just ignored. // // The documentation for the Dispatcher family is poorly written, complete // sections are cut-and-pasted that add no value and the important pieces @@ -43,9 +43,11 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Copyright (c) 2006 Novell, Inc. (http://www.novell.com) +// Copyright (c) 2016 Quamotion (http://quamotion.mobi) // // Authors: // Miguel de Icaza (miguel@novell.com) +// Frederik Carlier (frederik.carlier@quamotion.mobi) // using System; using System.Collections; @@ -181,6 +183,21 @@ namespace System.Windows.Threading { return op; } + public DispatcherOperation InvokeAsync (Action callback) + { + return this.BeginInvoke(callback); + } + + public DispatcherOperation InvokeAsync (Action callback, DispatcherPriority priority) + { + return this.BeginInvoke(callback, priority); + } + + public DispatcherOperation InvokeAsync (Action callback, DispatcherPriority priority, CancellationToken cancellationToken) + { + return this.BeginInvoke(callback, priority); + } + public object Invoke (Delegate method, params object[] args) { throw new NotImplementedException (); @@ -521,32 +538,33 @@ namespace System.Windows.Threading { public void Enqueue (object obj) { - if (size == array.Length) - Grow (); - array[tail] = obj; - tail = (tail+1) % array.Length; - size++; + if (size == array.Length) + Grow (); + array[tail] = obj; + tail = (tail+1) % array.Length; + size++; } public object Dequeue () - { - if (size < 1) - throw new InvalidOperationException (); - object result = array[head]; - array [head] = null; - head = (head + 1) % array.Length; - size--; - return result; - } - - void Grow () { - int newc = array.Length * 2; - object[] new_contents = new object[newc]; - array.CopyTo (new_contents, 0); - array = new_contents; - head = 0; - tail = head + size; - } + { + if (size < 1) + throw new InvalidOperationException (); + object result = array[head]; + array [head] = null; + head = (head + 1) % array.Length; + size--; + return result; + } + + void Grow () + { + int newc = array.Length * 2; + object[] new_contents = new object[newc]; + array.CopyTo (new_contents, 0); + array = new_contents; + head = 0; + tail = head + size; + } public int Count { get { diff --git a/mcs/class/WindowsBase/System.Windows.Threading/DispatcherOperation.cs b/mcs/class/WindowsBase/System.Windows.Threading/DispatcherOperation.cs index 5c06c41ac26..36299db37d2 100644 --- a/mcs/class/WindowsBase/System.Windows.Threading/DispatcherOperation.cs +++ b/mcs/class/WindowsBase/System.Windows.Threading/DispatcherOperation.cs @@ -29,6 +29,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Security; using System.Threading; +using System.Threading.Tasks; namespace System.Windows.Threading { @@ -90,6 +91,12 @@ namespace System.Windows.Threading { throw new NotImplementedException (); } + public Task Task { + get { + throw new NotImplementedException(); + } + } + public DispatcherOperationStatus Status { get { return status; diff --git a/mcs/class/corlib/System.Threading/EventWaitHandle.cs b/mcs/class/corlib/System.Threading/EventWaitHandle.cs index 7d1668ca838..fba21dc3ce5 100644 --- a/mcs/class/corlib/System.Threading/EventWaitHandle.cs +++ b/mcs/class/corlib/System.Threading/EventWaitHandle.cs @@ -195,7 +195,7 @@ namespace System.Threading lock (this) { CheckDisposed (); - return (NativeEventCalls.ResetEvent_internal (Handle)); + return NativeEventCalls.ResetEvent (SafeWaitHandle); } } @@ -204,9 +204,23 @@ namespace System.Threading lock (this) { CheckDisposed (); - return (NativeEventCalls.SetEvent_internal (Handle)); + return NativeEventCalls.SetEvent (SafeWaitHandle); } } + + internal void CheckDisposed () + { + if (disposed) + throw new ObjectDisposedException (GetType ().FullName); + } + + bool disposed; + protected override void Dispose(bool explicitDisposing) + { + base.Dispose (explicitDisposing); + disposed = true; + } + #if !NET_2_1 public void SetAccessControl (EventWaitHandleSecurity eventSecurity) { diff --git a/mcs/class/corlib/System.Threading/NativeEventCalls.cs b/mcs/class/corlib/System.Threading/NativeEventCalls.cs index 3a0c1236126..b0320579bfa 100644 --- a/mcs/class/corlib/System.Threading/NativeEventCalls.cs +++ b/mcs/class/corlib/System.Threading/NativeEventCalls.cs @@ -33,6 +33,7 @@ using System; using System.Runtime.CompilerServices; +using Microsoft.Win32.SafeHandles; #if !MOBILE using System.Security.AccessControl; @@ -46,11 +47,35 @@ namespace System.Threading [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern IntPtr CreateEvent_internal(bool manual,bool initial,string name, out bool created); + public static bool SetEvent (SafeWaitHandle handle) + { + bool release = false; + try { + handle.DangerousAddRef (ref release); + return SetEvent_internal (handle.DangerousGetHandle ()); + } finally { + if (release) + handle.DangerousRelease (); + } + } + [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern bool SetEvent_internal(IntPtr handle); + static extern bool SetEvent_internal(IntPtr handle); + + public static bool ResetEvent (SafeWaitHandle handle) + { + bool release = false; + try { + handle.DangerousAddRef (ref release); + return ResetEvent_internal (handle.DangerousGetHandle ()); + } finally { + if (release) + handle.DangerousRelease (); + } + } [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern bool ResetEvent_internal(IntPtr handle); + static extern bool ResetEvent_internal(IntPtr handle); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void CloseEvent_internal (IntPtr handle); diff --git a/mcs/class/corlib/System.Threading/RegisteredWaitHandle.cs b/mcs/class/corlib/System.Threading/RegisteredWaitHandle.cs index 1c8f4768d31..960ecf6e7b8 100644 --- a/mcs/class/corlib/System.Threading/RegisteredWaitHandle.cs +++ b/mcs/class/corlib/System.Threading/RegisteredWaitHandle.cs @@ -84,7 +84,7 @@ namespace System.Threading lock (this) { _unregistered = true; if (_callsInProcess == 0 && _finalEvent != null) - NativeEventCalls.SetEvent_internal (_finalEvent.Handle); + NativeEventCalls.SetEvent (_finalEvent.SafeWaitHandle); } } catch (ObjectDisposedException) { // Can happen if we called Unregister before we had time to execute Wait @@ -108,7 +108,7 @@ namespace System.Threading { _callsInProcess--; if (_unregistered && _callsInProcess == 0 && _finalEvent != null) - NativeEventCalls.SetEvent_internal (_finalEvent.Handle); + NativeEventCalls.SetEvent (_finalEvent.SafeWaitHandle); } } diff --git a/mcs/class/corlib/System.Threading/Timer.cs b/mcs/class/corlib/System.Threading/Timer.cs index 9efb484e3d8..d1546a8bfca 100644 --- a/mcs/class/corlib/System.Threading/Timer.cs +++ b/mcs/class/corlib/System.Threading/Timer.cs @@ -166,7 +166,7 @@ namespace System.Threading if (notifyObject == null) throw new ArgumentNullException ("notifyObject"); Dispose (); - NativeEventCalls.SetEvent_internal (notifyObject.Handle); + NativeEventCalls.SetEvent (notifyObject.SafeWaitHandle); return true; } diff --git a/mcs/class/corlib/System.Threading/WaitHandle.cs b/mcs/class/corlib/System.Threading/WaitHandle.cs index 5558efad52f..019647bc0bd 100644 --- a/mcs/class/corlib/System.Threading/WaitHandle.cs +++ b/mcs/class/corlib/System.Threading/WaitHandle.cs @@ -39,404 +39,100 @@ using System.Runtime.ConstrainedExecution; namespace System.Threading { - [ComVisible (true)] [StructLayout (LayoutKind.Sequential)] - public abstract class WaitHandle + public abstract partial class WaitHandle : MarshalByRefObject, IDisposable { - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern bool WaitAll_internal(WaitHandle[] handles, int ms, bool exitContext); - - static void CheckArray (WaitHandle [] handles, bool waitAll) - { - if (handles == null) - throw new ArgumentNullException ("waitHandles"); - - int length = handles.Length; - if (length > 64) - throw new NotSupportedException ("Too many handles"); - - if (handles.Length == 0) { - // MS throws different exceptions from the different methods. - if (waitAll) - throw new ArgumentNullException ("waitHandles"); - else - throw new ArgumentException (); - } - -#if false - // - // Although we should thrown an exception if this is an STA thread, - // Mono does not know anything about STA threads, and just makes - // things like Paint.NET not even possible to work. - // - // See bug #78455 for the bug this is supposed to fix. - // - if (waitAll && length > 1 && IsSTAThread) - throw new NotSupportedException ("WaitAll for multiple handles is not allowed on an STA thread."); -#endif - foreach (WaitHandle w in handles) { - if (w == null) - throw new ArgumentNullException ("waitHandles", "null handle"); - - if (w.safe_wait_handle == null) - throw new ArgumentException ("null element found", "waitHandle"); - - } - } -#if false - // usage of property is commented - see above - static bool IsSTAThread { - get { - bool isSTA = Thread.CurrentThread.ApartmentState == - ApartmentState.STA; - - // FIXME: remove this check after Thread.ApartmentState - // has been properly implemented. - if (!isSTA) { - Assembly asm = Assembly.GetEntryAssembly (); - if (asm != null) - isSTA = asm.EntryPoint.GetCustomAttributes (typeof (STAThreadAttribute), false).Length > 0; - } - - return isSTA; - } - } -#endif - public static bool WaitAll(WaitHandle[] waitHandles) - { - CheckArray (waitHandles, true); - return(WaitAll_internal(waitHandles, Timeout.Infinite, false)); - } - - public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) - { - CheckArray (waitHandles, true); - // check negative - except for -1 (which is Timeout.Infinite) - if (millisecondsTimeout < Timeout.Infinite) - throw new ArgumentOutOfRangeException ("millisecondsTimeout"); - - try { - if (exitContext) { -#if MONOTOUCH - throw new NotSupportedException ("exitContext == true is not supported"); -#else - SynchronizationAttribute.ExitContext (); -#endif - } - return(WaitAll_internal(waitHandles, millisecondsTimeout, false)); - } - finally { - if (exitContext) SynchronizationAttribute.EnterContext (); - } - } + protected static readonly IntPtr InvalidHandle = (IntPtr) (-1); - public static bool WaitAll(WaitHandle[] waitHandles, - TimeSpan timeout, - bool exitContext) + static int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll) { - CheckArray (waitHandles, true); - long ms = (long) timeout.TotalMilliseconds; - - if (ms < -1 || ms > Int32.MaxValue) - throw new ArgumentOutOfRangeException ("timeout"); - - try { - if (exitContext) { #if MONOTOUCH - throw new NotSupportedException ("exitContext == true is not supported"); -#else - SynchronizationAttribute.ExitContext (); + if (exitContext) + throw new NotSupportedException ("exitContext == true is not supported"); #endif - } - return (WaitAll_internal (waitHandles, (int) ms, exitContext)); - } - finally { - if (exitContext) SynchronizationAttribute.EnterContext (); - } - } - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern int WaitAny_internal(WaitHandle[] handles, int ms, bool exitContext); - - // LAMESPEC: Doesn't specify how to signal failures - [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)] - public static int WaitAny(WaitHandle[] waitHandles) - { - CheckArray (waitHandles, false); - return(WaitAny_internal(waitHandles, Timeout.Infinite, false)); - } - - [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)] - public static int WaitAny(WaitHandle[] waitHandles, - int millisecondsTimeout, - bool exitContext) - { - CheckArray (waitHandles, false); - // check negative - except for -1 (which is Timeout.Infinite) - if (millisecondsTimeout < Timeout.Infinite) - throw new ArgumentOutOfRangeException ("millisecondsTimeout"); + int release_last = -1; try { - if (exitContext) { -#if MONOTOUCH - throw new NotSupportedException ("exitContext == true is not supported"); -#else + if (exitContext) SynchronizationAttribute.ExitContext (); -#endif - } - return(WaitAny_internal(waitHandles, millisecondsTimeout, exitContext)); - } - finally { - if (exitContext) SynchronizationAttribute.EnterContext (); - } - } - - [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)] - public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout) - { - return WaitAny (waitHandles, timeout, false); - } - - [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)] - public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout) - { - return WaitAny (waitHandles, millisecondsTimeout, false); - } - [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)] - public static int WaitAny(WaitHandle[] waitHandles, - TimeSpan timeout, bool exitContext) - { - CheckArray (waitHandles, false); - long ms = (long) timeout.TotalMilliseconds; - - if (ms < -1 || ms > Int32.MaxValue) - throw new ArgumentOutOfRangeException ("timeout"); - - try { - if (exitContext) { -#if MONOTOUCH - throw new NotSupportedException ("exitContext == true is not supported"); -#else - SynchronizationAttribute.ExitContext (); -#endif + for (int i = 0; i < waitHandles.Length; ++i) { + try { + } finally { + /* we have to put it in a finally block, to avoid having a ThreadAbortException + * between the return from DangerousAddRef and the assignement to release_last */ + bool release = false; + waitHandles [i].SafeWaitHandle.DangerousAddRef (ref release); + release_last = i; + } } - return (WaitAny_internal(waitHandles, (int) ms, exitContext)); - } - finally { - if (exitContext) SynchronizationAttribute.EnterContext (); - } - } - - protected WaitHandle() - { - // FIXME - } - - public virtual void Close () - { - Dispose(true); - } - - public void Dispose () - { - Close (); - } - - public const int WaitTimeout = 258; - // - // In 2.0 we use SafeWaitHandles instead of IntPtrs - // - SafeWaitHandle safe_wait_handle; - - [Obsolete ("In the profiles > 2.x, use SafeHandle instead of Handle")] - public virtual IntPtr Handle { - get { - return safe_wait_handle.DangerousGetHandle (); - } - - [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)] - [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)] - set { - if (value == InvalidHandle) - safe_wait_handle = new SafeWaitHandle (InvalidHandle, false); + if (WaitAll) + return WaitAll_internal (waitHandles, millisecondsTimeout, exitContext); else - safe_wait_handle = new SafeWaitHandle (value, true); - } - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern bool WaitOne_internal(IntPtr handle, int ms, bool exitContext); - - protected virtual void Dispose (bool explicitDisposing) - { - if (!disposed){ - - // - // This is only the case if the handle was never properly initialized - // most likely a bug in the derived class - // - if (safe_wait_handle == null) - return; - - lock (this){ - if (disposed) - return; - - disposed = true; - if (safe_wait_handle != null) - safe_wait_handle.Dispose (); + return WaitAny_internal (waitHandles, millisecondsTimeout, exitContext); + } finally { + for (int i = release_last; i >= 0; --i) { + waitHandles [i].SafeWaitHandle.DangerousRelease (); } - } - } - - public SafeWaitHandle SafeWaitHandle { - [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)] - get { - return safe_wait_handle; - } - [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)] - set { - if (value == null) - safe_wait_handle = new SafeWaitHandle (InvalidHandle, false); - else - safe_wait_handle = value; + if (exitContext) + SynchronizationAttribute.EnterContext (); } } - public static bool SignalAndWait (WaitHandle toSignal, - WaitHandle toWaitOn) - { - return SignalAndWait (toSignal, toWaitOn, -1, false); - } - - public static bool SignalAndWait (WaitHandle toSignal, - WaitHandle toWaitOn, - int millisecondsTimeout, - bool exitContext) - { - if (toSignal == null) - throw new ArgumentNullException ("toSignal"); - if (toWaitOn == null) - throw new ArgumentNullException ("toWaitOn"); - - if (millisecondsTimeout < -1) - throw new ArgumentOutOfRangeException ("millisecondsTimeout"); - - return SignalAndWait_Internal (toSignal.Handle, toWaitOn.Handle, millisecondsTimeout, exitContext); - } - - public static bool SignalAndWait (WaitHandle toSignal, - WaitHandle toWaitOn, - TimeSpan timeout, - bool exitContext) - { - double ms = timeout.TotalMilliseconds; - if (ms > Int32.MaxValue) - throw new ArgumentOutOfRangeException ("timeout"); - - return SignalAndWait (toSignal, toWaitOn, Convert.ToInt32 (ms), false); - } - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern bool SignalAndWait_Internal (IntPtr toSignal, IntPtr toWaitOn, int ms, bool exitContext); + private static extern int WaitAll_internal(WaitHandle[] handles, int ms, bool exitContext); - public virtual bool WaitOne() - { - CheckDisposed (); - bool release = false; - try { - safe_wait_handle.DangerousAddRef (ref release); - return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), Timeout.Infinite, false)); - } finally { - if (release) - safe_wait_handle.DangerousRelease (); - } - } + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private static extern int WaitAny_internal(WaitHandle[] handles, int ms, bool exitContext); - public virtual bool WaitOne(int millisecondsTimeout, bool exitContext) + static int WaitOneNative (SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext) { - CheckDisposed (); - // check negative - except for -1 (which is Timeout.Infinite) - if (millisecondsTimeout < Timeout.Infinite) - throw new ArgumentOutOfRangeException ("millisecondsTimeout"); +#if MONOTOUCH + if (exitContext) + throw new NotSupportedException ("exitContext == true is not supported"); +#endif bool release = false; try { - if (exitContext) { -#if !MONOTOUCH - SynchronizationAttribute.ExitContext (); -#endif - } - safe_wait_handle.DangerousAddRef (ref release); - return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), millisecondsTimeout, exitContext)); - } finally { -#if !MONOTOUCH if (exitContext) - SynchronizationAttribute.EnterContext (); -#endif - if (release) - safe_wait_handle.DangerousRelease (); - } - } + SynchronizationAttribute.ExitContext (); - public virtual bool WaitOne (int millisecondsTimeout) - { - return WaitOne (millisecondsTimeout, false); - } + waitableSafeHandle.DangerousAddRef (ref release); - public virtual bool WaitOne (TimeSpan timeout) - { - return WaitOne (timeout, false); - } - - public virtual bool WaitOne(TimeSpan timeout, bool exitContext) - { - CheckDisposed (); - long ms = (long) timeout.TotalMilliseconds; - if (ms < -1 || ms > Int32.MaxValue) - throw new ArgumentOutOfRangeException ("timeout"); + return WaitOne_internal (waitableSafeHandle.DangerousGetHandle (), (int) millisecondsTimeout, exitContext); + } finally { + if (release) + waitableSafeHandle.DangerousRelease (); - bool release = false; - try { - if (exitContext) { -#if !MONOTOUCH - SynchronizationAttribute.ExitContext (); -#endif - } - safe_wait_handle.DangerousAddRef (ref release); - return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), (int) ms, exitContext)); - } - finally { -#if !MONOTOUCH if (exitContext) SynchronizationAttribute.EnterContext (); -#endif - if (release) - safe_wait_handle.DangerousRelease (); } } - internal void CheckDisposed () - { - if (disposed || safe_wait_handle == null) - throw new ObjectDisposedException (GetType ().FullName); - } + [MethodImplAttribute(MethodImplOptions.InternalCall)] + static extern int WaitOne_internal(IntPtr handle, int ms, bool exitContext); - public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout) + static int SignalAndWaitOne (SafeWaitHandle waitHandleToSignal,SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout, bool hasThreadAffinity, bool exitContext) { - return WaitAll (waitHandles, millisecondsTimeout, false); - } + bool releaseHandleToSignal = false, releaseHandleToWaitOn = false; + try { + waitHandleToSignal.DangerousAddRef (ref releaseHandleToSignal); + waitHandleToWaitOn.DangerousAddRef (ref releaseHandleToWaitOn); - public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout) - { - return WaitAll (waitHandles, timeout, false); + return SignalAndWait_Internal (waitHandleToSignal.DangerousGetHandle (), waitHandleToWaitOn.DangerousGetHandle (), millisecondsTimeout, exitContext); + } finally { + if (releaseHandleToSignal) + waitHandleToSignal.DangerousRelease (); + if (releaseHandleToWaitOn) + waitHandleToWaitOn.DangerousRelease (); + } } - - protected static readonly IntPtr InvalidHandle = (IntPtr) (-1); - bool disposed = false; + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + static extern int SignalAndWait_Internal (IntPtr toSignal, IntPtr toWaitOn, int ms, bool exitContext); } } diff --git a/mcs/class/corlib/System/Environment.cs b/mcs/class/corlib/System/Environment.cs index 126777e1923..70a4dea80df 100644 --- a/mcs/class/corlib/System/Environment.cs +++ b/mcs/class/corlib/System/Environment.cs @@ -57,7 +57,7 @@ namespace System { * of icalls, do not require an increment. */ #pragma warning disable 169 - private const int mono_corlib_version = 142; + private const int mono_corlib_version = 143; #pragma warning restore 169 [ComVisible (true)] diff --git a/mcs/class/corlib/System/TimeZoneInfo.cs b/mcs/class/corlib/System/TimeZoneInfo.cs index 6c58234d892..81675b16232 100644 --- a/mcs/class/corlib/System/TimeZoneInfo.cs +++ b/mcs/class/corlib/System/TimeZoneInfo.cs @@ -736,7 +736,8 @@ namespace System public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset) { - throw new NotImplementedException (); + bool isDST; + return GetUtcOffset (dateTimeOffset.UtcDateTime, out isDST); } private TimeSpan GetUtcOffset (DateTime dateTime, out bool isDST) diff --git a/mcs/class/corlib/Test/System.Threading/AutoResetEventTest.cs b/mcs/class/corlib/Test/System.Threading/AutoResetEventTest.cs index 8a3ad3b76ab..cf35cfbc6a3 100644 --- a/mcs/class/corlib/Test/System.Threading/AutoResetEventTest.cs +++ b/mcs/class/corlib/Test/System.Threading/AutoResetEventTest.cs @@ -90,7 +90,7 @@ namespace MonoTests.System.Threading SafeWaitHandle swh1 = are1.SafeWaitHandle; are1.Handle = (IntPtr) (-1); Assert.IsTrue (swh1 != are1.SafeWaitHandle, "#1"); - Assert.IsFalse (swh1.IsClosed, "#2"); + Assert.IsTrue (swh1.IsClosed, "#2"); // After testing on Windows/.NET, IsClosed returns true Assert.IsFalse (swh1.IsInvalid, "#3"); Assert.IsFalse (are1.SafeWaitHandle.IsClosed, "#4"); Assert.IsTrue (are1.SafeWaitHandle.IsInvalid, "#5"); diff --git a/mcs/class/corlib/Test/System/TimeZoneInfoTest.cs b/mcs/class/corlib/Test/System/TimeZoneInfoTest.cs index e8990a60139..3bb464fe83d 100644 --- a/mcs/class/corlib/Test/System/TimeZoneInfoTest.cs +++ b/mcs/class/corlib/Test/System/TimeZoneInfoTest.cs @@ -1121,7 +1121,33 @@ namespace MonoTests.System Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset (d)); Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset (d.Add (new TimeSpan(0,0,0, 1)))); } - } + + [Test] + public void GetUtcOffset_FromDateTimeOffset () + { + DateTimeOffset offset; + + offset = new DateTimeOffset(dst1Start, baseUtcOffset); + Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, -1))), "dst1Start_with_baseUtcOffset#before"); + Assert.AreEqual(dstUtcOffset, cairo.GetUtcOffset(offset), "dst1Start_with_baseUtcOffset#exact"); + Assert.AreEqual(dstUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, 1))), "dst1Start_with_baseUtcOffset#after"); + + offset = new DateTimeOffset(dst1End, dstOffset + baseUtcOffset); + Assert.AreEqual(dstUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, -1))), "dst1End_with_dstOffset+baseUtcOffset#before"); + Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset(offset), "dst1End_with_dstOffset+baseUtcOffset#exact"); + Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, 1))), "dst1End_with_dstOffset+baseUtcOffset#after"); + + offset = new DateTimeOffset(dst2Start, baseUtcOffset); + Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, -1))), "dst2Start_with_baseUtcOffset#before"); + Assert.AreEqual(dstUtcOffset, cairo.GetUtcOffset(offset), "dst2Start_with_baseUtcOffset#exact"); + Assert.AreEqual(dstUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, 1))), "dst2Start_with_baseUtcOffset#after"); + + offset = new DateTimeOffset(dst2End, baseUtcOffset + dstOffset); + Assert.AreEqual(dstUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, -1))), "dst2End_with_dstOffset+baseUtcOffset#before"); + Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset(offset), "dst2End_with_dstOffset+baseUtcOffset#exact"); + Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, 1))), "dst2End_with_dstOffset+baseUtcOffset#after"); + } + } [TestFixture] public class GetDaylightChanges diff --git a/mcs/class/corlib/corlib.dll.sources b/mcs/class/corlib/corlib.dll.sources index 036771deee1..00cccc2c023 100644 --- a/mcs/class/corlib/corlib.dll.sources +++ b/mcs/class/corlib/corlib.dll.sources @@ -1571,6 +1571,7 @@ ReferenceSources/SecurityContext.cs ../../../external/referencesource/mscorlib/system/threading/timeout.cs ../../../external/referencesource/mscorlib/system/threading/waithandlecannotbeopenedexception.cs ../../../external/referencesource/mscorlib/system/threading/threadpool.cs +../../../external/referencesource/mscorlib/system/threading/waithandle.cs ../../../external/referencesource/mscorlib/system/threading/Tasks/AsyncCausalityTracer.cs ../../../external/referencesource/mscorlib/system/threading/Tasks/BeginEndAwaitableAdapter.cs diff --git a/mcs/class/test-helpers/SocketResponder.cs b/mcs/class/test-helpers/SocketResponder.cs index ba3d0b8ef71..118d89410e2 100644 --- a/mcs/class/test-helpers/SocketResponder.cs +++ b/mcs/class/test-helpers/SocketResponder.cs @@ -64,7 +64,7 @@ namespace MonoTests.Helpers tcpListener = new TcpListener (ep); tcpListener.Start (); - listenTask = Task.Run (Listen); + listenTask = Task.Run ((Action) Listen); } public void Dispose () diff --git a/mcs/mcs/settings.cs b/mcs/mcs/settings.cs index 7b092135a2b..16a67f4cbd9 100644 --- a/mcs/mcs/settings.cs +++ b/mcs/mcs/settings.cs @@ -1216,6 +1216,8 @@ namespace Mono.CSharp { case "/highentropyva": case "/highentropyva+": case "/highentropyva-": + case "/win32manifest": + case "/nowin32manifest": return ParseResult.Success; default: diff --git a/mcs/tools/mkbundle/mkbundle.cs b/mcs/tools/mkbundle/mkbundle.cs index 7a3936fd34b..46c63cd9dfe 100755 --- a/mcs/tools/mkbundle/mkbundle.cs +++ b/mcs/tools/mkbundle/mkbundle.cs @@ -353,10 +353,12 @@ void mono_register_config_for_assembly (const char* assembly_name, cons // The non-parallel part byte [] buffer = new byte [8192]; + // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols. + var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]"); foreach (var url in files) { string fname = LocateFile (new Uri (url).LocalPath); string aname = Path.GetFileName (fname); - string encoded = aname.Replace ("-", "_").Replace (".", "_"); + string encoded = symbolEscapeRE.Replace (aname, "_"); if (prog == null) prog = aname; @@ -549,14 +551,15 @@ void mono_register_config_for_assembly (const char* assembly_name, cons compilerArgs.Add(String.Format ("/I {0}", quote (include))); if (!nomain || custom_main != null) { - compilerArgs.Add(temp_c); - compilerArgs.Add(temp_o); + compilerArgs.Add(quote(temp_c)); + compilerArgs.Add(quote(temp_o)); if (custom_main != null) compilerArgs.Add(quote(custom_main)); - compilerArgs.Add(monoLib); + compilerArgs.Add(quote(monoLib)); compilerArgs.Add("/link"); compilerArgs.Add("/NODEFAULTLIB"); - compilerArgs.Add("/SUBSYSTEM:CONSOLE"); + compilerArgs.Add("/SUBSYSTEM:windows"); + compilerArgs.Add("/ENTRY:mainCRTStartup"); compilerArgs.AddRange(linkLibraries); compilerArgs.Add("/out:"+ output); @@ -599,7 +602,7 @@ void mono_register_config_for_assembly (const char* assembly_name, cons smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a "; else smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic "; - cmd = String.Format("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " + + cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " + "`pkg-config --libs-only-L mono-2` " + smonolib + "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}", temp_c, temp_o, output, zlib, cc); @@ -607,7 +610,7 @@ void mono_register_config_for_assembly (const char* assembly_name, cons else { - cmd = String.Format("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}", + cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}", temp_c, temp_o, output, zlib, cc); } Execute (cmd); diff --git a/mono/dis/dump.c b/mono/dis/dump.c index a593d26cacb..9242e8639fe 100755 --- a/mono/dis/dump.c +++ b/mono/dis/dump.c @@ -598,6 +598,12 @@ dump_table_method (MonoImage *m) sigblob = mono_metadata_blob_heap (m, cols [MONO_METHOD_SIGNATURE]); mono_metadata_decode_blob_size (sigblob, &sigblob); method = mono_metadata_parse_method_signature_full (m, method_container ? method_container : type_container, i, sigblob, &sigblob, &error); + if (!mono_error_ok (&error)) { + fprintf (output,"%d: failed to parse due to %s\n", i, mono_error_get_message (&error)); + mono_error_cleanup (&error); + continue; + } + g_assert (mono_error_ok (&error)); /*FIXME don't swallow the error message*/ sig = dis_stringify_method_signature (m, method, i, method_container ? method_container : type_container, FALSE); impl_flags = get_method_impl_flags (cols [MONO_METHOD_IMPLFLAGS]); diff --git a/mono/dis/get.c b/mono/dis/get.c index a5d3faae04c..24df084d6e3 100755 --- a/mono/dis/get.c +++ b/mono/dis/get.c @@ -1283,12 +1283,14 @@ get_type (MonoImage *m, const char *ptr, char **result, gboolean is_def, MonoGen case MONO_TYPE_VALUETYPE: case MONO_TYPE_CLASS: { guint32 token = mono_metadata_parse_typedef_or_ref (m, ptr, &ptr); - MonoClass *klass = mono_class_get (m, token); + MonoClass *klass = mono_class_get_checked (m, token, &error); char *temp; - if (klass) + if (klass) { temp = dis_stringify_object_with_class (m, klass, TRUE, FALSE); - else - temp = g_strdup_printf ("", token); + } else { + temp = g_strdup_printf ("", token, mono_error_get_message (&error)); + mono_error_cleanup (&error); + } if (show_tokens) { *result = g_strdup_printf ("%s/*%08x*/", temp, token); @@ -3180,7 +3182,7 @@ cant_print_generic_param_name (MonoGenericParam *gparam) container = mono_generic_param_owner (gparam); check_ambiguous_genparams (container); return (!container || (mono_generic_params_with_ambiguous_names && - g_hash_table_lookup (mono_generic_params_with_ambiguous_names, gparam))); + g_hash_table_lookup (mono_generic_params_with_ambiguous_names, gparam)) || !mono_generic_param_info (gparam)); } diff --git a/mono/io-layer/processes.c b/mono/io-layer/processes.c index 385945f4301..d54f84bd324 100644 --- a/mono/io-layer/processes.c +++ b/mono/io-layer/processes.c @@ -2757,6 +2757,11 @@ process_wait (gpointer handle, guint32 timeout, gboolean alertable) if (!mp) { pid_t res; + if (pid == mono_process_current_pid ()) { + MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on current process", __func__, handle, timeout); + return WAIT_TIMEOUT; + } + /* This path is used when calling Process.HasExited, so * it is only used to poll the state of the process, not * to actually wait on it to exit */ diff --git a/mono/metadata/appdomain.c b/mono/metadata/appdomain.c index 961ff534165..226e0071784 100644 --- a/mono/metadata/appdomain.c +++ b/mono/metadata/appdomain.c @@ -80,7 +80,7 @@ * Changes which are already detected at runtime, like the addition * of icalls, do not require an increment. */ -#define MONO_CORLIB_VERSION 142 +#define MONO_CORLIB_VERSION 143 typedef struct { @@ -118,6 +118,9 @@ get_shadow_assembly_location_base (MonoDomain *domain, MonoError *error); static MonoLoadFunc load_function = NULL; +/* Lazy class loading functions */ +static GENERATE_GET_CLASS_WITH_CACHE (assembly, System.Reflection, Assembly) + void mono_install_runtime_load (MonoLoadFunc func) { @@ -256,11 +259,11 @@ mono_runtime_init_checked (MonoDomain *domain, MonoThreadStartCB start_cb, MonoT mono_thread_init (start_cb, attach_cb); - klass = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup"); + klass = mono_class_load_from_name (mono_defaults.corlib, "System", "AppDomainSetup"); setup = (MonoAppDomainSetup *) mono_object_new_pinned (domain, klass, error); return_if_nok (error); - klass = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain"); + klass = mono_class_load_from_name (mono_defaults.corlib, "System", "AppDomain"); ad = (MonoAppDomain *) mono_object_new_pinned (domain, klass, error); return_if_nok (error); @@ -306,7 +309,7 @@ mono_get_corlib_version (void) MonoClassField *field; MonoObject *value; - klass = mono_class_from_name (mono_defaults.corlib, "System", "Environment"); + klass = mono_class_load_from_name (mono_defaults.corlib, "System", "Environment"); mono_class_init (klass); field = mono_class_get_field_from_name (klass, "mono_corlib_version"); if (!field) @@ -357,8 +360,7 @@ mono_context_init_checked (MonoDomain *domain, MonoError *error) mono_error_init (error); - klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting.Contexts", "Context"); - + klass = mono_class_load_from_name (mono_defaults.corlib, "System.Runtime.Remoting.Contexts", "Context"); context = (MonoAppContext *) mono_object_new_pinned (domain, klass, error); return_if_nok (error); @@ -427,7 +429,7 @@ mono_domain_create_appdomain (char *friendly_name, char *configuration_file) MonoAppDomainSetup *setup; MonoClass *klass; - klass = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup"); + klass = mono_class_load_from_name (mono_defaults.corlib, "System", "AppDomainSetup"); setup = (MonoAppDomainSetup *) mono_object_new_checked (mono_domain_get (), klass, &error); mono_error_raise_exception (&error); /* FIXME don't raise here */ setup->configuration_file = configuration_file != NULL ? mono_string_new (mono_domain_get (), configuration_file) : NULL; @@ -467,7 +469,7 @@ copy_app_domain_setup (MonoDomain *domain, MonoAppDomainSetup *setup, MonoError mono_error_init (error); caller_domain = mono_domain_get (); - ads_class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup"); + ads_class = mono_class_load_from_name (mono_defaults.corlib, "System", "AppDomainSetup"); copy = (MonoAppDomainSetup*)mono_object_new_checked (domain, ads_class, error); return_val_if_nok (error, NULL); @@ -510,7 +512,7 @@ mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup * mono_error_init (error); - adclass = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain"); + adclass = mono_class_load_from_name (mono_defaults.corlib, "System", "AppDomain"); /* FIXME: pin all those objects */ data = mono_domain_create(); @@ -957,17 +959,12 @@ ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly MonoError error; MonoDomain *domain = ad->data; MonoAssembly* ass; - static MonoClass *System_Reflection_Assembly; MonoArray *res; GSList *tmp; int i; GPtrArray *assemblies; mono_error_init (&error); - - if (!System_Reflection_Assembly) - System_Reflection_Assembly = mono_class_from_name ( - mono_defaults.corlib, "System.Reflection", "Assembly"); /* * Make a copy of the list of assemblies because we can't hold the assemblies @@ -986,7 +983,7 @@ ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly } mono_domain_assemblies_unlock (domain); - res = mono_array_new (domain, System_Reflection_Assembly, assemblies->len); + res = mono_array_new (domain, mono_class_get_assembly_class (), assemblies->len); for (i = 0; i < assemblies->len; ++i) { ass = (MonoAssembly *)g_ptr_array_index (assemblies, i); MonoReflectionAssembly *ass_obj = mono_assembly_get_object_checked (domain, ass, &error); diff --git a/mono/metadata/assembly.c b/mono/metadata/assembly.c index fde74b06b7a..20373d0afcf 100644 --- a/mono/metadata/assembly.c +++ b/mono/metadata/assembly.c @@ -193,6 +193,9 @@ static mono_mutex_t assembly_binding_mutex; /* Loaded assembly binding info */ static GSList *loaded_assembly_bindings = NULL; +/* Class lazy loading functions */ +static GENERATE_TRY_GET_CLASS_WITH_CACHE (internals_visible, System.Runtime.CompilerServices, InternalsVisibleToAttribute) + static MonoAssembly* mono_assembly_invoke_search_hook_internal (MonoAssemblyName *aname, MonoAssembly *requesting, gboolean refonly, gboolean postload); static MonoAssembly* @@ -1684,7 +1687,7 @@ free_item (gpointer val, gpointer user_data) * names in custom attributes. * * This is an internal method, we need this because when we load mscorlib - * we do not have the mono_defaults.internals_visible_class loaded yet, + * we do not have the internals visible cattr loaded yet, * so we need to load these after we initialize the runtime. * * LOCKING: Acquires the assemblies lock plus the loader lock. @@ -1724,7 +1727,7 @@ mono_assembly_load_friends (MonoAssembly* ass) MonoAssemblyName *aname; const gchar *data; /* Do some sanity checking */ - if (!attr->ctor || attr->ctor->klass != mono_defaults.internals_visible_class) + if (!attr->ctor || attr->ctor->klass != mono_class_try_get_internals_visible_class ()) continue; if (attr->data_size < 4) continue; diff --git a/mono/metadata/class-internals.h b/mono/metadata/class-internals.h index 28a25a1f8f7..ffd9749f383 100644 --- a/mono/metadata/class-internals.h +++ b/mono/metadata/class-internals.h @@ -1147,16 +1147,12 @@ typedef struct { MonoClass *typed_reference_class; MonoClass *argumenthandle_class; MonoClass *monitor_class; - MonoClass *runtimesecurityframe_class; - MonoClass *executioncontext_class; - MonoClass *internals_visible_class; MonoClass *generic_ilist_class; MonoClass *generic_nullable_class; - MonoClass *safehandle_class; MonoClass *handleref_class; MonoClass *attribute_class; MonoClass *customattribute_data_class; - MonoClass *critical_finalizer_object; + MonoClass *critical_finalizer_object; /* MAYBE NULL */ MonoClass *generic_ireadonlylist_class; MonoClass *threadpool_wait_callback_class; MonoMethod *threadpool_perform_wait_callback_method; @@ -1182,6 +1178,9 @@ mono_install_remoting_trampoline (MonoRemotingTrampoline func); #define GENERATE_GET_CLASS_WITH_CACHE_DECL(shortname) \ MonoClass* mono_class_get_##shortname##_class (void); +#define GENERATE_TRY_GET_CLASS_WITH_CACHE_DECL(shortname) \ +MonoClass* mono_class_try_get_##shortname##_class (void); + #define GENERATE_GET_CLASS_WITH_CACHE(shortname,namespace,name) \ MonoClass* \ mono_class_get_##shortname##_class (void) \ @@ -1189,17 +1188,31 @@ mono_class_get_##shortname##_class (void) \ static MonoClass *tmp_class; \ MonoClass *klass = tmp_class; \ if (!klass) { \ - klass = mono_class_from_name (mono_defaults.corlib, #namespace, #name); \ - g_assert (klass); \ + klass = mono_class_load_from_name (mono_defaults.corlib, #namespace, #name); \ mono_memory_barrier (); \ tmp_class = klass; \ } \ return klass; \ } -#define GENERATE_STATIC_GET_CLASS_WITH_CACHE(shortname,namespace,name) \ -static GENERATE_GET_CLASS_WITH_CACHE (shortname,namespace,name) +#define GENERATE_TRY_GET_CLASS_WITH_CACHE(shortname,namespace,name) \ +MonoClass* \ +mono_class_try_get_##shortname##_class (void) \ +{ \ + static volatile MonoClass *tmp_class; \ + static volatile gboolean inited; \ + MonoClass *klass = (MonoClass *)tmp_class; \ + mono_memory_barrier (); \ + if (!inited) { \ + klass = mono_class_try_load_from_name (mono_defaults.corlib, #namespace, #name); \ + tmp_class = klass; \ + mono_memory_barrier (); \ + inited = TRUE; \ + } \ + return klass; \ +} +GENERATE_TRY_GET_CLASS_WITH_CACHE_DECL (safehandle) #ifndef DISABLE_COM @@ -1477,4 +1490,10 @@ get_image_for_generic_param (MonoGenericParam *param); char * make_generic_name_string (MonoImage *image, int num); +MonoClass * +mono_class_load_from_name (MonoImage *image, const char* name_space, const char *name); + +MonoClass* +mono_class_try_load_from_name (MonoImage *image, const char* name_space, const char *name); + #endif /* __MONO_METADATA_CLASS_INTERNALS_H__ */ diff --git a/mono/metadata/class.c b/mono/metadata/class.c index 983f1ca4149..8648223d8a9 100644 --- a/mono/metadata/class.c +++ b/mono/metadata/class.c @@ -3102,15 +3102,15 @@ get_implicit_generic_array_interfaces (MonoClass *klass, int *num, int *is_enume all_interfaces = eclass->rank && eclass->element_class->rank? FALSE: TRUE; if (!generic_icollection_class) { - generic_icollection_class = mono_class_from_name (mono_defaults.corlib, + generic_icollection_class = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ICollection`1"); - generic_ienumerable_class = mono_class_from_name (mono_defaults.corlib, + generic_ienumerable_class = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "IEnumerable`1"); - generic_ienumerator_class = mono_class_from_name (mono_defaults.corlib, + generic_ienumerator_class = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "IEnumerator`1"); - generic_ireadonlylist_class = mono_class_from_name (mono_defaults.corlib, + generic_ireadonlylist_class = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "IReadOnlyList`1"); - generic_ireadonlycollection_class = mono_class_from_name (mono_defaults.corlib, + generic_ireadonlycollection_class = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "IReadOnlyCollection`1"); } @@ -6217,7 +6217,7 @@ make_generic_param_class (MonoGenericParam *param, MonoGenericParamInfo *pinfo) CHECKED_METADATA_WRITE_PTR ( klass->parent , pinfo->constraints [0] ); pos++; } else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) { - CHECKED_METADATA_WRITE_PTR ( klass->parent , mono_class_from_name (mono_defaults.corlib, "System", "ValueType") ); + CHECKED_METADATA_WRITE_PTR ( klass->parent , mono_class_load_from_name (mono_defaults.corlib, "System", "ValueType") ); } else { CHECKED_METADATA_WRITE_PTR ( klass->parent , mono_defaults.object_class ); } @@ -6743,7 +6743,7 @@ mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded) /* for the building corlib use System.Array from it */ if (image->assembly && assembly_is_dynamic (image->assembly) && image->assembly_name && strcmp (image->assembly_name, "mscorlib") == 0) { - parent = mono_class_from_name (image, "System", "Array"); + parent = mono_class_load_from_name (image, "System", "Array"); corlib_type = TRUE; } else { parent = mono_defaults.array_class; @@ -7836,13 +7836,15 @@ return_nested_in (MonoClass *klass, char *nested) } static MonoClass* -search_modules (MonoImage *image, const char *name_space, const char *name) +search_modules (MonoImage *image, const char *name_space, const char *name, MonoError *error) { MonoTableInfo *file_table = &image->tables [MONO_TABLE_FILE]; MonoImage *file_image; MonoClass *klass; int i; + mono_error_init (error); + /* * The EXPORTEDTYPES table only contains public types, so have to search the * modules as well. @@ -7857,8 +7859,8 @@ search_modules (MonoImage *image, const char *name_space, const char *name) file_image = mono_image_load_file_for_image (image, i + 1); if (file_image) { - klass = mono_class_from_name (file_image, name_space, name); - if (klass) + klass = mono_class_from_name_checked (file_image, name_space, name, error); + if (klass || !is_ok (error)) return klass; } } @@ -7867,7 +7869,7 @@ search_modules (MonoImage *image, const char *name_space, const char *name) } static MonoClass * -mono_class_from_name_checked_aux (MonoImage *image, const char* name_space, const char *name, MonoError *error, GHashTable* visited_images) +mono_class_from_name_checked_aux (MonoImage *image, const char* name_space, const char *name, GHashTable* visited_images, MonoError *error) { GHashTable *nspace_table; MonoImage *loaded_image; @@ -7900,8 +7902,11 @@ mono_class_from_name_checked_aux (MonoImage *image, const char* name_space, cons if (get_class_from_name && image->tables [MONO_TABLE_EXPORTEDTYPE].rows == 0) { gboolean res = get_class_from_name (image, name_space, name, &klass); if (res) { - if (!klass) - klass = search_modules (image, name_space, name); + if (!klass) { + klass = search_modules (image, name_space, name, error); + if (!is_ok (error)) + return NULL; + } if (nested) return klass ? return_nested_in (klass, nested) : NULL; else @@ -7924,15 +7929,15 @@ mono_class_from_name_checked_aux (MonoImage *image, const char* name_space, cons for (i = 0; i < image->module_count; ++i) { MonoImage *module = image->modules [i]; - klass = mono_class_from_name (module, name_space, name); - if (klass) + klass = mono_class_from_name_checked (module, name_space, name, error); + if (klass || !is_ok (error)) return klass; } } if (!token) { - klass = search_modules (image, name_space, name); - if (klass) + klass = search_modules (image, name_space, name, error); + if (klass || !is_ok (error)) return klass; } @@ -7953,7 +7958,7 @@ mono_class_from_name_checked_aux (MonoImage *image, const char* name_space, cons loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS); if (!loaded_image) return NULL; - klass = mono_class_from_name_checked_aux (loaded_image, name_space, name, error, visited_images); + klass = mono_class_from_name_checked_aux (loaded_image, name_space, name, visited_images, error); if (nested) return klass ? return_nested_in (klass, nested) : NULL; return klass; @@ -7966,9 +7971,9 @@ mono_class_from_name_checked_aux (MonoImage *image, const char* name_space, cons g_assert (image->references [assembly_idx - 1]); if (image->references [assembly_idx - 1] == (gpointer)-1) return NULL; - klass = mono_class_from_name_checked_aux (image->references [assembly_idx - 1]->image, name_space, name, error, visited_images); + klass = mono_class_from_name_checked_aux (image->references [assembly_idx - 1]->image, name_space, name, visited_images, error); if (nested) - return return_nested_in (klass, nested); + return klass ? return_nested_in (klass, nested) : NULL; return klass; } else { g_assert_not_reached (); @@ -7983,6 +7988,18 @@ mono_class_from_name_checked_aux (MonoImage *image, const char* name_space, cons return klass; } +/** + * mono_class_from_name_checked: + * @image: The MonoImage where the type is looked up in + * @name_space: the type namespace + * @name: the type short name. + * + * Obtains a MonoClass with a given namespace and a given name which + * is located in the given MonoImage. + * + * Works like mono_class_from_name, but error handling is tricky. It can return NULL and have no error + * set if the class was not found or it will return NULL and set the error if there was a loading error. + */ MonoClass * mono_class_from_name_checked (MonoImage *image, const char* name_space, const char *name, MonoError *error) { @@ -7991,7 +8008,7 @@ mono_class_from_name_checked (MonoImage *image, const char* name_space, const ch visited_images = g_hash_table_new (g_direct_hash, g_direct_equal); - klass = mono_class_from_name_checked_aux (image, name_space, name, error, visited_images); + klass = mono_class_from_name_checked_aux (image, name_space, name, visited_images, error); g_hash_table_destroy (visited_images); @@ -8025,6 +8042,56 @@ mono_class_from_name (MonoImage *image, const char* name_space, const char *name return klass; } +/** + * mono_class_load_from_name: + * @image: The MonoImage where the type is looked up in + * @name_space: the type namespace + * @name: the type short name. + * + * This function works exactly like mono_class_from_name but it will abort if the class is not found. + * This function should be used by the runtime for critical types to which there's no way to recover but crash + * If they are missing. Thing of System.Object or System.String. + */ +MonoClass * +mono_class_load_from_name (MonoImage *image, const char* name_space, const char *name) +{ + MonoError error; + MonoClass *klass; + + klass = mono_class_from_name_checked (image, name_space, name, &error); + if (!klass) + g_error ("Runtime critical type %s.%s not found", name_space, name); + if (!mono_error_ok (&error)) + g_error ("Could not load runtime critical type %s.%s due to %s", name_space, name, mono_error_get_message (&error)); + return klass; +} + +/** + * mono_class_try_load_from_name: + * @image: The MonoImage where the type is looked up in + * @name_space: the type namespace + * @name: the type short name. + * + * This function tries to load a type, returning the class was found or NULL otherwise. + * This function should be used by the runtime when probing for optional types, those that could have being linked out. + * + * Big design consideration. This function aborts if there was an error loading the type. This prevents us from missing + * a type that we would otherwise assume to be available but was not due some error. + * + */ +MonoClass* +mono_class_try_load_from_name (MonoImage *image, const char* name_space, const char *name) +{ + MonoError error; + MonoClass *klass; + + klass = mono_class_from_name_checked (image, name_space, name, &error); + if (!mono_error_ok (&error)) + g_error ("Could not load runtime critical type %s.%s due to %s", name_space, name, mono_error_get_message (&error)); + return klass; +} + + /** * mono_class_is_subclass_of: * @klass: class to probe if it is a subclass of another one @@ -10813,3 +10880,5 @@ mono_class_full_name (MonoClass *klass) return mono_type_full_name (&klass->byval_arg); } +/* Declare all shared lazy type lookup functions */ +GENERATE_TRY_GET_CLASS_WITH_CACHE (safehandle, System.Runtime.InteropServices, SafeHandle) diff --git a/mono/metadata/class.h b/mono/metadata/class.h index d9f315139b1..3b5ca560b79 100644 --- a/mono/metadata/class.h +++ b/mono/metadata/class.h @@ -26,10 +26,10 @@ mono_class_init (MonoClass *klass); MONO_API MonoVTable * mono_class_vtable (MonoDomain *domain, MonoClass *klass); -MONO_API MonoClass * +MONO_RT_EXTERNAL_ONLY MONO_API MonoClass * mono_class_from_name (MonoImage *image, const char* name_space, const char *name); -MONO_API MonoClass * +MONO_RT_EXTERNAL_ONLY MONO_API MonoClass * mono_class_from_name_case (MonoImage *image, const char* name_space, const char *name); MONO_API MonoMethod * diff --git a/mono/metadata/cominterop.c b/mono/metadata/cominterop.c index 94a12036088..8d3f714f7a9 100644 --- a/mono/metadata/cominterop.c +++ b/mono/metadata/cominterop.c @@ -95,6 +95,10 @@ GENERATE_GET_CLASS_WITH_CACHE (iunknown, Mono.Interop, IUnknown) GENERATE_GET_CLASS_WITH_CACHE (com_object, System, __ComObject) GENERATE_GET_CLASS_WITH_CACHE (variant, System, Variant) +static GENERATE_GET_CLASS_WITH_CACHE (interface_type_attribute, System.Runtime.InteropServices, InterfaceTypeAttribute) +static GENERATE_GET_CLASS_WITH_CACHE (guid_attribute, System.Runtime.InteropServices, GuidAttribute) +static GENERATE_GET_CLASS_WITH_CACHE (com_visible_attribute, System.Runtime.InteropServices, ComVisibleAttribute) + /* Upon creation of a CCW, only allocate a weak handle and set the * reference count to 0. If the unmanaged client code decides to addref and * hold onto the CCW, I then allocate a strong handle. Once the reference count @@ -177,7 +181,7 @@ mono_class_try_get_com_object_class (void) static gboolean inited; MonoClass *klass; if (!inited) { - klass = mono_class_from_name (mono_defaults.corlib, "System", "__ComObject"); + klass = mono_class_load_from_name (mono_defaults.corlib, "System", "__ComObject"); mono_memory_barrier (); tmp_class = klass; mono_memory_barrier (); @@ -296,16 +300,13 @@ cominterop_object_is_rcw (MonoObject *obj) static int cominterop_get_com_slot_begin (MonoClass* klass) { - static MonoClass *interface_type_attribute = NULL; MonoCustomAttrInfo *cinfo = NULL; MonoInterfaceTypeAttribute* itf_attr = NULL; - if (!interface_type_attribute) - interface_type_attribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "InterfaceTypeAttribute"); cinfo = mono_custom_attrs_from_class (klass); if (cinfo) { MonoError error; - itf_attr = (MonoInterfaceTypeAttribute*)mono_custom_attrs_get_attr_checked (cinfo, interface_type_attribute, &error); + itf_attr = (MonoInterfaceTypeAttribute*)mono_custom_attrs_get_attr_checked (cinfo, mono_class_get_interface_type_attribute_class (), &error); g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/ if (!cinfo->cached) mono_custom_attrs_free (cinfo); @@ -404,17 +405,12 @@ cominterop_mono_string_to_guid (MonoString* string, guint8 *guid); static gboolean cominterop_class_guid (MonoClass* klass, guint8* guid) { - static MonoClass *GuidAttribute = NULL; MonoCustomAttrInfo *cinfo; - /* Handle the GuidAttribute */ - if (!GuidAttribute) - GuidAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "GuidAttribute"); - cinfo = mono_custom_attrs_from_class (klass); if (cinfo) { MonoError error; - MonoReflectionGuidAttribute *attr = (MonoReflectionGuidAttribute*)mono_custom_attrs_get_attr_checked (cinfo, GuidAttribute, &error); + MonoReflectionGuidAttribute *attr = (MonoReflectionGuidAttribute*)mono_custom_attrs_get_attr_checked (cinfo, mono_class_get_guid_attribute_class (), &error); g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/ if (!attr) @@ -431,20 +427,15 @@ cominterop_class_guid (MonoClass* klass, guint8* guid) static gboolean cominterop_com_visible (MonoClass* klass) { - static MonoClass *ComVisibleAttribute = NULL; MonoError error; MonoCustomAttrInfo *cinfo; GPtrArray *ifaces; MonoBoolean visible = 1; - /* Handle the ComVisibleAttribute */ - if (!ComVisibleAttribute) - ComVisibleAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "ComVisibleAttribute"); - cinfo = mono_custom_attrs_from_class (klass); if (cinfo) { MonoError error; - MonoReflectionComVisibleAttribute *attr = (MonoReflectionComVisibleAttribute*)mono_custom_attrs_get_attr_checked (cinfo, ComVisibleAttribute, &error); + MonoReflectionComVisibleAttribute *attr = (MonoReflectionComVisibleAttribute*)mono_custom_attrs_get_attr_checked (cinfo, mono_class_get_guid_attribute_class (), &error); g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/ if (attr) @@ -618,7 +609,6 @@ mono_cominterop_emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, case MONO_MARSHAL_CONV_OBJECT_INTERFACE: case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN: case MONO_MARSHAL_CONV_OBJECT_IDISPATCH: { - static MonoClass* com_interop_proxy_class = NULL; static MonoMethod* com_interop_proxy_get_proxy = NULL; static MonoMethod* get_transparent_proxy = NULL; guint32 pos_null = 0, pos_ccw = 0, pos_end = 0; @@ -643,16 +633,14 @@ mono_cominterop_emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, mono_mb_emit_icall (mb, cominterop_get_ccw_object); pos_ccw = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S); - if (!com_interop_proxy_class) - com_interop_proxy_class = mono_class_from_name (mono_defaults.corlib, "Mono.Interop", "ComInteropProxy"); if (!com_interop_proxy_get_proxy) - com_interop_proxy_get_proxy = mono_class_get_method_from_name_flags (com_interop_proxy_class, "GetProxy", 2, METHOD_ATTRIBUTE_PRIVATE); + com_interop_proxy_get_proxy = mono_class_get_method_from_name_flags (mono_class_get_interop_proxy_class (), "GetProxy", 2, METHOD_ATTRIBUTE_PRIVATE); #ifndef DISABLE_REMOTING if (!get_transparent_proxy) get_transparent_proxy = mono_class_get_method_from_name (mono_defaults.real_proxy_class, "GetTransparentProxy", 0); #endif - mono_mb_add_local (mb, &com_interop_proxy_class->byval_arg); + mono_mb_add_local (mb, &mono_class_get_interop_proxy_class ()->byval_arg); mono_mb_emit_ldloc (mb, 0); mono_mb_emit_byte (mb, CEE_LDIND_I); @@ -1054,13 +1042,10 @@ mono_cominterop_get_invoke (MonoMethod *method) } if (!strcmp(method->name, ".ctor")) { - static MonoClass *com_interop_proxy_class = NULL; static MonoMethod *cache_proxy = NULL; - if (!com_interop_proxy_class) - com_interop_proxy_class = mono_class_from_name (mono_defaults.corlib, "Mono.Interop", "ComInteropProxy"); if (!cache_proxy) - cache_proxy = mono_class_get_method_from_name (com_interop_proxy_class, "CacheProxy", 0); + cache_proxy = mono_class_get_method_from_name (mono_class_get_interop_proxy_class (), "CacheProxy", 0); mono_mb_emit_ldarg (mb, 0); mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoTransparentProxy, rp)); @@ -1925,7 +1910,7 @@ cominterop_get_ccw (MonoObject* object, MonoClass* itf) if (cinfo) { static MonoClass* coclass_attribute = NULL; if (!coclass_attribute) - coclass_attribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "CoClassAttribute"); + coclass_attribute = mono_class_load_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "CoClassAttribute"); if (mono_custom_attrs_has_attr (cinfo, coclass_attribute)) { g_assert(itf->interface_count && itf->interfaces[0]); itf = itf->interfaces[0]; @@ -2469,7 +2454,7 @@ cominterop_ccw_get_ids_of_names (MonoCCWInterface* ccwe, gpointer riid, /* Handle DispIdAttribute */ if (!ComDispIdAttribute) - ComDispIdAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "DispIdAttribute"); + ComDispIdAttribute = mono_class_load_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "DispIdAttribute"); g_assert (object); klass = mono_object_class (object); diff --git a/mono/metadata/console-unix.c b/mono/metadata/console-unix.c index 5a4d518c230..f2105335356 100644 --- a/mono/metadata/console-unix.c +++ b/mono/metadata/console-unix.c @@ -231,7 +231,7 @@ do_console_cancel_event (void) if (!domain->domain) return; - klass = mono_class_from_name (mono_defaults.corlib, "System", "Console"); + klass = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Console"); if (klass == NULL) return; diff --git a/mono/metadata/debug-helpers.c b/mono/metadata/debug-helpers.c index 86c3965365f..df32fb052af 100644 --- a/mono/metadata/debug-helpers.c +++ b/mono/metadata/debug-helpers.c @@ -538,7 +538,7 @@ mono_method_desc_search_in_image (MonoMethodDesc *desc, MonoImage *image) } if (desc->name_space && desc->klass) { - klass = mono_class_from_name (image, desc->name_space, desc->klass); + klass = mono_class_try_load_from_name (image, desc->name_space, desc->klass); if (!klass) return NULL; return mono_method_desc_search_in_class (desc, klass); diff --git a/mono/metadata/domain.c b/mono/metadata/domain.c index e8f5dfc13bc..9f2d9fbd814 100644 --- a/mono/metadata/domain.c +++ b/mono/metadata/domain.c @@ -624,258 +624,184 @@ mono_init_internal (const char *filename, const char *exe_filename, const char * } mono_defaults.corlib = mono_assembly_get_image (ass); - mono_defaults.object_class = mono_class_from_name ( + mono_defaults.object_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Object"); - g_assert (mono_defaults.object_class != 0); - mono_defaults.void_class = mono_class_from_name ( + mono_defaults.void_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Void"); - g_assert (mono_defaults.void_class != 0); - mono_defaults.boolean_class = mono_class_from_name ( + mono_defaults.boolean_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Boolean"); - g_assert (mono_defaults.boolean_class != 0); - mono_defaults.byte_class = mono_class_from_name ( + mono_defaults.byte_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Byte"); - g_assert (mono_defaults.byte_class != 0); - mono_defaults.sbyte_class = mono_class_from_name ( + mono_defaults.sbyte_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "SByte"); - g_assert (mono_defaults.sbyte_class != 0); - mono_defaults.int16_class = mono_class_from_name ( + mono_defaults.int16_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Int16"); - g_assert (mono_defaults.int16_class != 0); - mono_defaults.uint16_class = mono_class_from_name ( + mono_defaults.uint16_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "UInt16"); - g_assert (mono_defaults.uint16_class != 0); - mono_defaults.int32_class = mono_class_from_name ( + mono_defaults.int32_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Int32"); - g_assert (mono_defaults.int32_class != 0); - mono_defaults.uint32_class = mono_class_from_name ( + mono_defaults.uint32_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "UInt32"); - g_assert (mono_defaults.uint32_class != 0); - mono_defaults.uint_class = mono_class_from_name ( + mono_defaults.uint_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "UIntPtr"); - g_assert (mono_defaults.uint_class != 0); - mono_defaults.int_class = mono_class_from_name ( + mono_defaults.int_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "IntPtr"); - g_assert (mono_defaults.int_class != 0); - mono_defaults.int64_class = mono_class_from_name ( + mono_defaults.int64_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Int64"); - g_assert (mono_defaults.int64_class != 0); - mono_defaults.uint64_class = mono_class_from_name ( + mono_defaults.uint64_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "UInt64"); - g_assert (mono_defaults.uint64_class != 0); - mono_defaults.single_class = mono_class_from_name ( + mono_defaults.single_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Single"); - g_assert (mono_defaults.single_class != 0); - mono_defaults.double_class = mono_class_from_name ( + mono_defaults.double_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Double"); - g_assert (mono_defaults.double_class != 0); - mono_defaults.char_class = mono_class_from_name ( + mono_defaults.char_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Char"); - g_assert (mono_defaults.char_class != 0); - mono_defaults.string_class = mono_class_from_name ( + mono_defaults.string_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "String"); - g_assert (mono_defaults.string_class != 0); - mono_defaults.enum_class = mono_class_from_name ( + mono_defaults.enum_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Enum"); - g_assert (mono_defaults.enum_class != 0); - mono_defaults.array_class = mono_class_from_name ( + mono_defaults.array_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Array"); - g_assert (mono_defaults.array_class != 0); - mono_defaults.delegate_class = mono_class_from_name ( + mono_defaults.delegate_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Delegate"); - g_assert (mono_defaults.delegate_class != 0 ); - mono_defaults.multicastdelegate_class = mono_class_from_name ( + mono_defaults.multicastdelegate_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "MulticastDelegate"); - g_assert (mono_defaults.multicastdelegate_class != 0 ); - mono_defaults.asyncresult_class = mono_class_from_name ( + mono_defaults.asyncresult_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Runtime.Remoting.Messaging", "AsyncResult"); - g_assert (mono_defaults.asyncresult_class != 0 ); - mono_defaults.manualresetevent_class = mono_class_from_name ( + mono_defaults.manualresetevent_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Threading", "ManualResetEvent"); - g_assert (mono_defaults.manualresetevent_class != 0 ); - mono_defaults.typehandle_class = mono_class_from_name ( + mono_defaults.typehandle_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "RuntimeTypeHandle"); - g_assert (mono_defaults.typehandle_class != 0); - mono_defaults.methodhandle_class = mono_class_from_name ( + mono_defaults.methodhandle_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "RuntimeMethodHandle"); - g_assert (mono_defaults.methodhandle_class != 0); - mono_defaults.fieldhandle_class = mono_class_from_name ( + mono_defaults.fieldhandle_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "RuntimeFieldHandle"); - g_assert (mono_defaults.fieldhandle_class != 0); - mono_defaults.systemtype_class = mono_class_from_name ( + mono_defaults.systemtype_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Type"); - g_assert (mono_defaults.systemtype_class != 0); - mono_defaults.monotype_class = mono_class_from_name ( + mono_defaults.monotype_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "MonoType"); - g_assert (mono_defaults.monotype_class != 0); - mono_defaults.runtimetype_class = mono_class_from_name ( + mono_defaults.runtimetype_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "RuntimeType"); - g_assert (mono_defaults.runtimetype_class != 0); - mono_defaults.exception_class = mono_class_from_name ( + mono_defaults.exception_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Exception"); - g_assert (mono_defaults.exception_class != 0); - mono_defaults.threadabortexception_class = mono_class_from_name ( + mono_defaults.threadabortexception_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Threading", "ThreadAbortException"); - g_assert (mono_defaults.threadabortexception_class != 0); - mono_defaults.thread_class = mono_class_from_name ( + mono_defaults.thread_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Threading", "Thread"); - g_assert (mono_defaults.thread_class != 0); - mono_defaults.internal_thread_class = mono_class_from_name ( + mono_defaults.internal_thread_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Threading", "InternalThread"); - if (!mono_defaults.internal_thread_class) { - /* This can happen with an old mscorlib */ - fprintf (stderr, "Corlib too old for this runtime.\n"); - fprintf (stderr, "Loaded from: %s\n", - mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown"); - exit (1); - } - mono_defaults.appdomain_class = mono_class_from_name ( + mono_defaults.appdomain_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "AppDomain"); - g_assert (mono_defaults.appdomain_class != 0); #ifndef DISABLE_REMOTING - mono_defaults.transparent_proxy_class = mono_class_from_name ( + mono_defaults.transparent_proxy_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "TransparentProxy"); - g_assert (mono_defaults.transparent_proxy_class != 0); - mono_defaults.real_proxy_class = mono_class_from_name ( + mono_defaults.real_proxy_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "RealProxy"); - g_assert (mono_defaults.real_proxy_class != 0); - mono_defaults.marshalbyrefobject_class = mono_class_from_name ( + mono_defaults.marshalbyrefobject_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "MarshalByRefObject"); - g_assert (mono_defaults.marshalbyrefobject_class != 0); - mono_defaults.iremotingtypeinfo_class = mono_class_from_name ( + mono_defaults.iremotingtypeinfo_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Runtime.Remoting", "IRemotingTypeInfo"); - g_assert (mono_defaults.iremotingtypeinfo_class != 0); + #endif - mono_defaults.mono_method_message_class = mono_class_from_name ( + mono_defaults.mono_method_message_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Runtime.Remoting.Messaging", "MonoMethodMessage"); - g_assert (mono_defaults.mono_method_message_class != 0); - mono_defaults.field_info_class = mono_class_from_name ( + mono_defaults.field_info_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Reflection", "FieldInfo"); - g_assert (mono_defaults.field_info_class != 0); - mono_defaults.method_info_class = mono_class_from_name ( + mono_defaults.method_info_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Reflection", "MethodInfo"); - g_assert (mono_defaults.method_info_class != 0); - mono_defaults.stringbuilder_class = mono_class_from_name ( + mono_defaults.stringbuilder_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Text", "StringBuilder"); - g_assert (mono_defaults.stringbuilder_class != 0); - mono_defaults.math_class = mono_class_from_name ( + mono_defaults.math_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Math"); - g_assert (mono_defaults.math_class != 0); - mono_defaults.stack_frame_class = mono_class_from_name ( + mono_defaults.stack_frame_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Diagnostics", "StackFrame"); - g_assert (mono_defaults.stack_frame_class != 0); - mono_defaults.stack_trace_class = mono_class_from_name ( + mono_defaults.stack_trace_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Diagnostics", "StackTrace"); - g_assert (mono_defaults.stack_trace_class != 0); - mono_defaults.marshal_class = mono_class_from_name ( + mono_defaults.marshal_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Runtime.InteropServices", "Marshal"); - g_assert (mono_defaults.marshal_class != 0); - mono_defaults.typed_reference_class = mono_class_from_name ( + mono_defaults.typed_reference_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "TypedReference"); - g_assert (mono_defaults.typed_reference_class != 0); - mono_defaults.argumenthandle_class = mono_class_from_name ( + mono_defaults.argumenthandle_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "RuntimeArgumentHandle"); - g_assert (mono_defaults.argumenthandle_class != 0); - mono_defaults.monitor_class = mono_class_from_name ( + mono_defaults.monitor_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Threading", "Monitor"); - g_assert (mono_defaults.monitor_class != 0); - - mono_defaults.runtimesecurityframe_class = mono_class_from_name ( - mono_defaults.corlib, "System.Security", "RuntimeSecurityFrame"); - - mono_defaults.executioncontext_class = mono_class_from_name ( - mono_defaults.corlib, "System.Threading", "ExecutionContext"); - - mono_defaults.internals_visible_class = mono_class_from_name ( - mono_defaults.corlib, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute"); - - mono_defaults.critical_finalizer_object = mono_class_from_name ( - mono_defaults.corlib, "System.Runtime.ConstrainedExecution", "CriticalFinalizerObject"); - /* - * mscorlib needs a little help, only now it can load its friends list (after we have - * loaded the InternalsVisibleToAttribute), load it now - */ + Not using GENERATE_TRY_GET_CLASS_WITH_CACHE_DECL as this type is heavily checked by sgen when computing finalization. + */ + mono_defaults.critical_finalizer_object = mono_class_try_load_from_name (mono_defaults.corlib, + "System.Runtime.ConstrainedExecution", "CriticalFinalizerObject"); + mono_assembly_load_friends (ass); - - mono_defaults.safehandle_class = mono_class_from_name ( - mono_defaults.corlib, "System.Runtime.InteropServices", "SafeHandle"); - mono_defaults.handleref_class = mono_class_from_name ( + mono_defaults.handleref_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Runtime.InteropServices", "HandleRef"); - mono_defaults.attribute_class = mono_class_from_name ( + mono_defaults.attribute_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Attribute"); - mono_defaults.customattribute_data_class = mono_class_from_name ( + mono_defaults.customattribute_data_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Reflection", "CustomAttributeData"); mono_class_init (mono_defaults.array_class); - mono_defaults.generic_nullable_class = mono_class_from_name ( + mono_defaults.generic_nullable_class = mono_class_load_from_name ( mono_defaults.corlib, "System", "Nullable`1"); - mono_defaults.generic_ilist_class = mono_class_from_name ( + mono_defaults.generic_ilist_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Collections.Generic", "IList`1"); - mono_defaults.generic_ireadonlylist_class = mono_class_from_name ( + mono_defaults.generic_ireadonlylist_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Collections.Generic", "IReadOnlyList`1"); - mono_defaults.threadpool_wait_callback_class = mono_class_from_name ( + mono_defaults.threadpool_wait_callback_class = mono_class_load_from_name ( mono_defaults.corlib, "System.Threading", "_ThreadPoolWaitCallback"); - if (!mono_defaults.threadpool_wait_callback_class) { - /* This can happen with an old mscorlib */ - fprintf (stderr, "Corlib too old for this runtime.\n"); - fprintf (stderr, "Loaded from: %s\n", - mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown"); - exit (1); - } + mono_defaults.threadpool_perform_wait_callback_method = mono_class_get_method_from_name ( mono_defaults.threadpool_wait_callback_class, "PerformWaitCallback", 0); diff --git a/mono/metadata/exception.c b/mono/metadata/exception.c index d97fa428655..a66c9d723d1 100644 --- a/mono/metadata/exception.c +++ b/mono/metadata/exception.c @@ -64,7 +64,7 @@ mono_exception_from_name_domain (MonoDomain *domain, MonoImage *image, MonoObject *o; MonoDomain *caller_domain = mono_domain_get (); - klass = mono_class_from_name (image, name_space, name); + klass = mono_class_load_from_name (image, name_space, name); o = mono_object_new_checked (domain, klass, &error); g_assert (o != NULL && mono_error_ok (&error)); /* FIXME don't swallow the error */ @@ -168,7 +168,7 @@ MonoException * mono_exception_from_name_two_strings (MonoImage *image, const char *name_space, const char *name, MonoString *a1, MonoString *a2) { - MonoClass *klass = mono_class_from_name (image, name_space, name); + MonoClass *klass = mono_class_load_from_name (image, name_space, name); return create_exception_two_strings (klass, a1, a2); } @@ -583,8 +583,7 @@ mono_get_exception_type_initialization (const gchar *type_name, MonoException *i MonoMethod *method; gpointer iter; - klass = mono_class_from_name (mono_get_corlib (), "System", "TypeInitializationException"); - g_assert (klass); + klass = mono_class_load_from_name (mono_get_corlib (), "System", "TypeInitializationException"); mono_class_init (klass); @@ -759,8 +758,8 @@ mono_get_exception_reflection_type_load (MonoArray *types, MonoArray *exceptions MonoMethod *method; gpointer iter; - klass = mono_class_from_name (mono_get_corlib (), "System.Reflection", "ReflectionTypeLoadException"); - g_assert (klass); + klass = mono_class_load_from_name (mono_get_corlib (), "System.Reflection", "ReflectionTypeLoadException"); + mono_class_init (klass); /* Find the Type[], Exception[] ctor */ @@ -798,8 +797,7 @@ mono_get_exception_runtime_wrapped (MonoObject *wrapped_exception) MonoDomain *domain = mono_domain_get (); gpointer params [16]; - klass = mono_class_from_name (mono_get_corlib (), "System.Runtime.CompilerServices", "RuntimeWrappedException"); - g_assert (klass); + klass = mono_class_load_from_name (mono_get_corlib (), "System.Runtime.CompilerServices", "RuntimeWrappedException"); o = mono_object_new_checked (domain, klass, &error); g_assert (o != NULL && mono_error_ok (&error)); /* FIXME don't swallow the error */ diff --git a/mono/metadata/image.c b/mono/metadata/image.c index fbbf58f6b3e..c99de7aa04f 100644 --- a/mono/metadata/image.c +++ b/mono/metadata/image.c @@ -1046,7 +1046,8 @@ do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status, } } if (!image->loader) { - *status = MONO_IMAGE_IMAGE_INVALID; + if (status) + *status = MONO_IMAGE_IMAGE_INVALID; goto invalid_image; } diff --git a/mono/metadata/marshal.c b/mono/metadata/marshal.c index cb762d82e95..82e0b9b69fb 100644 --- a/mono/metadata/marshal.c +++ b/mono/metadata/marshal.c @@ -146,6 +146,8 @@ ves_icall_marshal_alloc (gulong size); /* Lazy class loading functions */ static GENERATE_GET_CLASS_WITH_CACHE (string_builder, System.Text, StringBuilder) static GENERATE_GET_CLASS_WITH_CACHE (date_time, System, DateTime) +static GENERATE_TRY_GET_CLASS_WITH_CACHE (unmanaged_function_pointer_attribute, System.Runtime.InteropServices, UnmanagedFunctionPointerAttribute) +static GENERATE_TRY_GET_CLASS_WITH_CACHE (icustom_marshaler, System.Runtime.InteropServices, ICustomMarshaler) /* MonoMethod pointers to SafeHandle::DangerousAddRef and ::DangerousRelease */ static MonoMethod *sh_dangerous_add_ref; @@ -156,9 +158,9 @@ static void init_safe_handle () { sh_dangerous_add_ref = mono_class_get_method_from_name ( - mono_defaults.safehandle_class, "DangerousAddRef", 1); + mono_class_try_get_safehandle_class (), "DangerousAddRef", 1); sh_dangerous_release = mono_class_get_method_from_name ( - mono_defaults.safehandle_class, "DangerousRelease", 0); + mono_class_try_get_safehandle_class (), "DangerousRelease", 0); } static void @@ -394,15 +396,11 @@ mono_marshal_use_aot_wrappers (gboolean use) static void parse_unmanaged_function_pointer_attr (MonoClass *klass, MonoMethodPInvoke *piinfo) { - static MonoClass *UnmanagedFunctionPointerAttribute; MonoCustomAttrInfo *cinfo; MonoReflectionUnmanagedFunctionPointerAttribute *attr; - if (!UnmanagedFunctionPointerAttribute) - UnmanagedFunctionPointerAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute"); - /* The attribute is only available in Net 2.0 */ - if (UnmanagedFunctionPointerAttribute) { + if (mono_class_try_get_unmanaged_function_pointer_attribute_class ()) { /* * The pinvoke attributes are stored in a real custom attribute so we have to * construct it. @@ -410,7 +408,7 @@ parse_unmanaged_function_pointer_attr (MonoClass *klass, MonoMethodPInvoke *piin cinfo = mono_custom_attrs_from_class (klass); if (cinfo && !mono_runtime_get_no_exec ()) { MonoError error; - attr = (MonoReflectionUnmanagedFunctionPointerAttribute*)mono_custom_attrs_get_attr_checked (cinfo, UnmanagedFunctionPointerAttribute, &error); + attr = (MonoReflectionUnmanagedFunctionPointerAttribute*)mono_custom_attrs_get_attr_checked (cinfo, mono_class_try_get_unmanaged_function_pointer_attribute_class (), &error); if (attr) { piinfo->piflags = (attr->call_conv << 8) | (attr->charset ? (attr->charset - 1) * 2 : 1) | attr->set_last_error; } else { @@ -1807,7 +1805,7 @@ emit_struct_conv_full (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_obje return; } - if (klass != mono_defaults.safehandle_class) { + if (klass != mono_class_try_get_safehandle_class ()) { if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT) { char *msg = g_strdup_printf ("Type %s which is passed to unmanaged code must have a StructLayout attribute.", mono_type_full_name (&klass->byval_arg)); @@ -1837,7 +1835,7 @@ emit_struct_conv_full (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_obje usize = info->fields [i + 1].offset - info->fields [i].offset; } - if (klass != mono_defaults.safehandle_class){ + if (klass != mono_class_try_get_safehandle_class ()){ /* * FIXME: Should really check for usize==0 and msize>0, but we apply * the layout to the managed structure as well. @@ -4336,7 +4334,7 @@ emit_marshal_custom (EmitMarshalContext *m, int argnum, MonoType *t, int pos2; if (!ICustomMarshaler) { - MonoClass *klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "ICustomMarshaler"); + MonoClass *klass = mono_class_try_get_icustom_marshaler_class (); if (!klass) { exception_msg = g_strdup ("Current profile doesn't support ICustomMarshaler"); goto handle_exception; @@ -7070,8 +7068,8 @@ emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t, return mono_cominterop_emit_marshal_safearray (m, argnum, t, spec, conv_arg, conv_arg_type, action); #endif - if (mono_defaults.safehandle_class != NULL && t->data.klass && - mono_class_is_subclass_of (t->data.klass, mono_defaults.safehandle_class, FALSE)) + if (mono_class_try_get_safehandle_class () != NULL && t->data.klass && + mono_class_is_subclass_of (t->data.klass, mono_class_try_get_safehandle_class (), FALSE)) return emit_marshal_safehandle (m, argnum, t, spec, conv_arg, conv_arg_type, action); return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action); @@ -7756,9 +7754,10 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i } #else MonoMethodSignature *sig, *csig; + MonoExceptionClause *clause; int i, *tmp_locals; + int leave_pos; gboolean closed = FALSE; - int coop_gc_var, coop_gc_dummy_local; sig = m->sig; csig = m->csig; @@ -7785,30 +7784,46 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i mono_mb_add_local (mb, sig->ret); } + /* + * try { + * mono_jit_attach (); + * + * + * + * ret = method (...); + * } finally { + * mono_jit_detach (); + * } + * + * return ret; + */ + if (mono_threads_is_coop_enabled ()) { - /* local 4, the local to be used when calling the reset_blocking funcs */ - /* tons of code hardcode 3 to be the return var */ - coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg); - /* local 5, the local used to get a stack address for suspend funcs */ - coop_gc_dummy_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg); + clause = g_new0 (MonoExceptionClause, 1); + clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY; } mono_mb_emit_icon (mb, 0); mono_mb_emit_stloc (mb, 2); + if (mono_threads_is_coop_enabled ()) { + /* try { */ + clause->try_offset = mono_mb_get_label (mb); + } + /* * Might need to attach the thread to the JIT or change the * domain for the callback. + * + * Also does the (STARTING|BLOCKING|RUNNING) -> RUNNING thread state transtion + * + * mono_jit_attach (); */ mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX); mono_mb_emit_byte (mb, CEE_MONO_JIT_ATTACH); - if (mono_threads_is_coop_enabled ()) { - /* XXX can we merge reset_blocking_start with JIT_ATTACH above and save one call? */ - mono_mb_emit_ldloc_addr (mb, coop_gc_dummy_local); - mono_mb_emit_icall (mb, mono_threads_reset_blocking_start); - mono_mb_emit_stloc (mb, coop_gc_var); - } + /* */ + emit_thread_interrupt_checkpoint (mb); /* we first do all conversions */ tmp_locals = (int *)alloca (sizeof (int) * sig->param_count); @@ -7832,8 +7847,6 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i } } - emit_thread_interrupt_checkpoint (mb); - if (sig->hasthis) { if (target_handle) { mono_mb_emit_icon (mb, (gint32)target_handle); @@ -7860,6 +7873,7 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i mono_mb_emit_ldarg (mb, i); } + /* ret = method (...) */ mono_mb_emit_managed_call (mb, method, NULL); if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) { @@ -7939,15 +7953,31 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i } if (mono_threads_is_coop_enabled ()) { - /* XXX merge reset_blocking_end with detach */ - mono_mb_emit_ldloc (mb, coop_gc_var); - mono_mb_emit_ldloc_addr (mb, coop_gc_dummy_local); - mono_mb_emit_icall (mb, mono_threads_reset_blocking_end); + leave_pos = mono_mb_emit_branch (mb, CEE_LEAVE); + + /* } finally { */ + clause->try_len = mono_mb_get_label (mb) - clause->try_offset; + clause->handler_offset = mono_mb_get_label (mb); } + /* + * Also does the RUNNING -> (BLOCKING|RUNNING) thread state transition + * + * mono_jit_detach (); + */ mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX); mono_mb_emit_byte (mb, CEE_MONO_JIT_DETACH); + if (mono_threads_is_coop_enabled ()) { + mono_mb_emit_byte (mb, CEE_ENDFINALLY); + + /* } [endfinally] */ + clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset; + + mono_mb_patch_branch (mb, leave_pos); + } + + /* return ret; */ if (m->retobj_var) { mono_mb_emit_ldloc (mb, m->retobj_var); mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX); @@ -7959,6 +7989,10 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i mono_mb_emit_byte (mb, CEE_RET); } + if (mono_threads_is_coop_enabled ()) { + mono_mb_set_clauses (mb, 1, clause); + } + if (closed) g_free (sig); #endif @@ -8008,7 +8042,6 @@ mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature * MonoMethod * mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle) { - static MonoClass *UnmanagedFunctionPointerAttribute; MonoMethodSignature *sig, *csig, *invoke_sig; MonoMethodBuilder *mb; MonoMethod *res, *invoke; @@ -8063,12 +8096,8 @@ mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, mono_marshal_set_callconv_from_modopt (invoke, csig); - /* Handle the UnmanagedFunctionPointerAttribute */ - if (!UnmanagedFunctionPointerAttribute) - UnmanagedFunctionPointerAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute"); - /* The attribute is only available in Net 2.0 */ - if (UnmanagedFunctionPointerAttribute) { + if (mono_class_try_get_unmanaged_function_pointer_attribute_class ()) { MonoCustomAttrInfo *cinfo; MonoCustomAttrEntry *attr; @@ -8082,7 +8111,7 @@ mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, if (cinfo) { for (i = 0; i < cinfo->num_attrs; ++i) { MonoClass *ctor_class = cinfo->attrs [i].ctor->klass; - if (mono_class_has_parent (ctor_class, UnmanagedFunctionPointerAttribute)) { + if (mono_class_has_parent (ctor_class, mono_class_try_get_unmanaged_function_pointer_attribute_class ())) { attr = &cinfo->attrs [i]; break; } diff --git a/mono/metadata/metadata.c b/mono/metadata/metadata.c index 9c082de29c6..7ff64f517ac 100644 --- a/mono/metadata/metadata.c +++ b/mono/metadata/metadata.c @@ -5894,7 +5894,7 @@ handle_enum: *conv = MONO_MARSHAL_CONV_DEL_FTN; return MONO_NATIVE_FUNC; } - if (mono_defaults.safehandle_class && type->data.klass == mono_defaults.safehandle_class){ + if (mono_class_try_get_safehandle_class () && type->data.klass == mono_class_try_get_safehandle_class ()){ *conv = MONO_MARSHAL_CONV_SAFEHANDLE; return MONO_NATIVE_INT; } diff --git a/mono/metadata/method-builder.c b/mono/metadata/method-builder.c index 23f8d599095..5bbedbbb816 100644 --- a/mono/metadata/method-builder.c +++ b/mono/metadata/method-builder.c @@ -550,7 +550,7 @@ mono_mb_emit_exception_full (MonoMethodBuilder *mb, const char *exc_nspace, cons { MonoMethod *ctor = NULL; - MonoClass *mme = mono_class_from_name (mono_defaults.corlib, exc_nspace, exc_name); + MonoClass *mme = mono_class_load_from_name (mono_defaults.corlib, exc_nspace, exc_name); mono_class_init (mme); ctor = mono_class_get_method_from_name (mme, ".ctor", 0); g_assert (ctor); diff --git a/mono/metadata/mono-mlist.c b/mono/metadata/mono-mlist.c index d82ca0c831f..7e90b652dd5 100644 --- a/mono/metadata/mono-mlist.c +++ b/mono/metadata/mono-mlist.c @@ -41,7 +41,7 @@ mono_mlist_alloc (MonoObject *data) MonoError error; MonoMList* res; if (!monolist_item_vtable) { - MonoClass *klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoListItem"); + MonoClass *klass = mono_class_load_from_name (mono_defaults.corlib, "System", "MonoListItem"); monolist_item_vtable = mono_class_vtable (mono_get_root_domain (), klass); g_assert (monolist_item_vtable); } diff --git a/mono/metadata/mono-security.c b/mono/metadata/mono-security.c index 03cc519767a..a27f82ecd29 100644 --- a/mono/metadata/mono-security.c +++ b/mono/metadata/mono-security.c @@ -956,7 +956,7 @@ void invoke_protected_memory_method (MonoArray *data, MonoObject *scope, gboolea } } - klass = mono_class_from_name (system_security_assembly, + klass = mono_class_load_from_name (system_security_assembly, "System.Security.Cryptography", "ProtectedMemory"); method = mono_class_get_method_from_name (klass, encrypt ? "Protect" : "Unprotect", 2); params [0] = data; diff --git a/mono/metadata/object-internals.h b/mono/metadata/object-internals.h index 45f93f157fa..352dae4ff9c 100644 --- a/mono/metadata/object-internals.h +++ b/mono/metadata/object-internals.h @@ -101,16 +101,6 @@ #ifdef __GNUC__ -/* namespace and name should be a constant */ -/* image must be mscorlib since other assemblies can be unloaded */ -#define mono_class_from_name_cached(image,namespace,name) ({ \ - static MonoClass *tmp_klass; \ - if (!tmp_klass) { \ - g_assert (image == mono_defaults.corlib); \ - tmp_klass = mono_class_from_name ((image), (namespace), (name)); \ - g_assert (tmp_klass); \ - }; \ - tmp_klass; }) /* name should be a compile-time constant */ #define mono_class_get_field_from_name_cached(klass,name) ({ \ static MonoClassField *tmp_field; \ @@ -137,7 +127,6 @@ #else -#define mono_class_from_name_cached(image,namespace,name) mono_class_from_name ((image), (namespace), (name)) #define mono_class_get_field_from_name_cached(klass,name) mono_class_get_field_from_name ((klass), (name)) #define mono_array_class_get_cached(eclass,rank) mono_array_class_get ((eclass), (rank)) #define mono_array_new_cached(domain, eclass, size) mono_array_new_specific (mono_class_vtable ((domain), mono_array_class_get_cached ((eclass), 1)), (size)) @@ -297,7 +286,6 @@ typedef struct { typedef struct { MonoMarshalByRefObject object; gpointer handle; - MonoBoolean disposed; } MonoWaitHandle; /* This is a copy of System.Runtime.Remoting.Messaging.CallType */ diff --git a/mono/metadata/object.c b/mono/metadata/object.c index 533abdf3529..8d0abf7f987 100644 --- a/mono/metadata/object.c +++ b/mono/metadata/object.c @@ -6604,23 +6604,16 @@ mono_wait_handle_get_handle (MonoWaitHandle *handle) { MONO_REQ_GC_UNSAFE_MODE; - static MonoClassField *f_os_handle; - static MonoClassField *f_safe_handle; + static MonoClassField *f_safe_handle = NULL; + MonoSafeHandle *sh; - if (!f_os_handle && !f_safe_handle) { - f_os_handle = mono_class_get_field_from_name (mono_defaults.manualresetevent_class, "os_handle"); - f_safe_handle = mono_class_get_field_from_name (mono_defaults.manualresetevent_class, "safe_wait_handle"); + if (!f_safe_handle) { + f_safe_handle = mono_class_get_field_from_name (mono_defaults.manualresetevent_class, "safeWaitHandle"); + g_assert (f_safe_handle); } - if (f_os_handle) { - HANDLE retval; - mono_field_get_value ((MonoObject*)handle, f_os_handle, &retval); - return retval; - } else { - MonoSafeHandle *sh; - mono_field_get_value ((MonoObject*)handle, f_safe_handle, &sh); - return sh->handle; - } + mono_field_get_value ((MonoObject*)handle, f_safe_handle, &sh); + return sh->handle; } diff --git a/mono/metadata/process.c b/mono/metadata/process.c index 1d2cd363c10..dca9ccfc305 100644 --- a/mono/metadata/process.c +++ b/mono/metadata/process.c @@ -58,6 +58,34 @@ HANDLE ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid) static MonoImage *system_assembly=NULL; +//Hand coded version that loads from system +static MonoClass* +mono_class_get_file_version_info_class (void) +{ + static MonoClass *tmp_class; + MonoClass *klass = tmp_class; + if (!klass) { + klass = mono_class_load_from_name (system_assembly, "System.Diagnostics", "FileVersionInfo"); + mono_memory_barrier (); + tmp_class = klass; + } + return klass; +} + +static MonoClass* +mono_class_get_process_module_class (void) +{ + static MonoClass *tmp_class; + MonoClass *klass = tmp_class; + if (!klass) { + klass = mono_class_load_from_name (system_assembly, "System.Diagnostics", "ProcessModule"); + mono_memory_barrier (); + tmp_class = klass; + } + return klass; +} + + static guint32 unicode_chars (const gunichar2 *str) { guint32 len=0; @@ -360,7 +388,6 @@ static void process_get_assembly_fileversion (MonoObject *filever, MonoAssembly static MonoObject* get_process_module (MonoAssembly *assembly, MonoClass *proc_class) { MonoError error; - static MonoClass *filever_class = NULL; MonoObject *item, *filever; MonoDomain *domain = mono_domain_get (); char *filename; @@ -372,13 +399,7 @@ static MonoObject* get_process_module (MonoAssembly *assembly, MonoClass *proc_c */ item = mono_object_new_checked (domain, proc_class, &error); mono_error_raise_exception (&error); /* FIXME don't raise here */ - - if (!filever_class) - filever_class = mono_class_from_name (system_assembly, - "System.Diagnostics", - "FileVersionInfo"); - - filever = mono_object_new_checked (domain, filever_class, &error); + filever = mono_object_new_checked (domain, mono_class_get_file_version_info_class (), &error); if (!mono_error_ok (&error)) goto leave; process_get_assembly_fileversion (filever, assembly); @@ -400,7 +421,6 @@ leave: static MonoObject* process_add_module (HANDLE process, HMODULE mod, gunichar2 *filename, gunichar2 *modulename, MonoClass *proc_class) { MonoError error; - static MonoClass *filever_class = NULL; MonoObject *item, *filever; MonoDomain *domain=mono_domain_get (); MODULEINFO modinfo; @@ -410,13 +430,7 @@ static MonoObject* process_add_module (HANDLE process, HMODULE mod, gunichar2 *f */ item=mono_object_new_checked (domain, proc_class, &error); mono_error_raise_exception (&error); /* FIXME don't raise here */ - - if (!filever_class) - filever_class=mono_class_from_name (system_assembly, - "System.Diagnostics", - "FileVersionInfo"); - - filever=mono_object_new_checked (domain, filever_class, &error); + filever = mono_object_new_checked (domain, mono_class_get_file_version_info_class (), &error); mono_error_raise_exception (&error); /* FIXME don't raise here */ process_get_fileversion (filever, filename); @@ -475,7 +489,6 @@ MonoArray *ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject DWORD needed; guint32 count = 0, module_count = 0, assembly_count = 0; guint32 i, num_added = 0; - static MonoClass *proc_class = NULL; GPtrArray *assemblies = NULL; static HANDLE current_process = 0; @@ -496,16 +509,13 @@ MonoArray *ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject } count = module_count + assembly_count; - if (!proc_class) - proc_class = mono_class_from_name (system_assembly, "System.Diagnostics", "ProcessModule"); - - temp_arr = mono_array_new (mono_domain_get (), proc_class, count); + temp_arr = mono_array_new (mono_domain_get (), mono_class_get_process_module_class (), count); for (i = 0; i < module_count; i++) { if (GetModuleBaseName (process, mods[i], modname, MAX_PATH) && GetModuleFileNameEx (process, mods[i], filename, MAX_PATH)) { MonoObject *module = process_add_module (process, mods[i], - filename, modname, proc_class); + filename, modname, mono_class_get_process_module_class ()); mono_array_setref (temp_arr, num_added++, module); } } @@ -513,7 +523,7 @@ MonoArray *ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject if (assemblies) { for (i = 0; i < assembly_count; i++) { MonoAssembly *ass = (MonoAssembly *)g_ptr_array_index (assemblies, i); - MonoObject *module = get_process_module (ass, proc_class); + MonoObject *module = get_process_module (ass, mono_class_get_process_module_class ()); mono_array_setref (temp_arr, num_added++, module); } g_ptr_array_free (assemblies, TRUE); @@ -523,7 +533,7 @@ MonoArray *ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject arr = temp_arr; } else { /* shorter version of the array */ - arr = mono_array_new (mono_domain_get (), proc_class, num_added); + arr = mono_array_new (mono_domain_get (), mono_class_get_process_module_class (), num_added); for (i = 0; i < num_added; i++) mono_array_setref (arr, i, mono_array_get (temp_arr, MonoObject*, i)); diff --git a/mono/metadata/security-manager.c b/mono/metadata/security-manager.c index 2de7972026a..e3c3cbc82d5 100644 --- a/mono/metadata/security-manager.c +++ b/mono/metadata/security-manager.c @@ -11,6 +11,7 @@ /* Class lazy loading functions */ static GENERATE_GET_CLASS_WITH_CACHE (security_manager, System.Security, SecurityManager) +static GENERATE_TRY_GET_CLASS_WITH_CACHE (execution_context, System.Threading, ExecutionContext) static MonoSecurityMode mono_security_mode = MONO_SECURITY_MODE_NONE; @@ -96,9 +97,10 @@ mono_get_context_capture_method (void) return NULL; /* older corlib revisions won't have the class (nor the method) */ - if (mono_defaults.executioncontext_class && !method) { - mono_class_init (mono_defaults.executioncontext_class); - method = mono_class_get_method_from_name (mono_defaults.executioncontext_class, "Capture", 0); + MonoClass *execution_context = mono_class_try_get_execution_context_class (); + if (execution_context && !method) { + mono_class_init (execution_context); + method = mono_class_get_method_from_name (execution_context, "Capture", 0); } return method; diff --git a/mono/metadata/sgen-mono.c b/mono/metadata/sgen-mono.c index 8f86228dce1..e070fed4ad4 100644 --- a/mono/metadata/sgen-mono.c +++ b/mono/metadata/sgen-mono.c @@ -1198,14 +1198,12 @@ create_allocator (int atype, gboolean slowpath) /* catch */ clause->flags = MONO_EXCEPTION_CLAUSE_NONE; clause->try_len = mono_mb_get_pos (mb) - clause->try_offset; - clause->data.catch_class = mono_class_from_name (mono_defaults.corlib, + clause->data.catch_class = mono_class_load_from_name (mono_defaults.corlib, "System", "OverflowException"); - g_assert (clause->data.catch_class); clause->handler_offset = mono_mb_get_label (mb); - oom_exc_class = mono_class_from_name (mono_defaults.corlib, + oom_exc_class = mono_class_load_from_name (mono_defaults.corlib, "System", "OutOfMemoryException"); - g_assert (oom_exc_class); ctor = mono_class_get_method_from_name (oom_exc_class, ".ctor", 0); g_assert (ctor); diff --git a/mono/metadata/socket-io.c b/mono/metadata/socket-io.c index 7ddf9d3e468..333c4197500 100644 --- a/mono/metadata/socket-io.c +++ b/mono/metadata/socket-io.c @@ -602,8 +602,7 @@ get_family_hint (void) socket_assembly = get_socket_assembly (); g_assert (socket_assembly); - socket_class = mono_class_from_name (socket_assembly, "System.Net.Sockets", "Socket"); - g_assert (socket_class); + socket_class = mono_class_load_from_name (socket_assembly, "System.Net.Sockets", "Socket"); ipv4_field = mono_class_get_field_from_name (socket_class, "ipv4_supported"); g_assert (ipv4_field); @@ -832,8 +831,7 @@ create_object_from_sockaddr(struct sockaddr *saddr, int sa_size, gint32 *error) /* Build a System.Net.SocketAddress object instance */ if (!domain->sockaddr_class) { - domain->sockaddr_class=mono_class_from_name (get_socket_assembly (), "System.Net", "SocketAddress"); - g_assert (domain->sockaddr_class); + domain->sockaddr_class = mono_class_load_from_name (get_socket_assembly (), "System.Net", "SocketAddress"); } sockaddr_obj=mono_object_new_checked(domain, domain->sockaddr_class, &merror); mono_error_raise_exception (&merror); /* FIXME don't raise here */ @@ -1978,7 +1976,7 @@ ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal (SOCKET sock, g switch(name) { case SocketOptionName_Linger: /* build a System.Net.Sockets.LingerOption */ - obj_class=mono_class_from_name(get_socket_assembly (), + obj_class = mono_class_load_from_name (get_socket_assembly (), "System.Net.Sockets", "LingerOption"); obj=mono_object_new_checked(domain, obj_class, &merror); @@ -2027,7 +2025,7 @@ ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal (SOCKET sock, g } } - obj_class = mono_class_from_name(mono_posix_image, + obj_class = mono_class_load_from_name (mono_posix_image, "Mono.Posix", "PeerCredData"); obj = mono_object_new_checked(domain, obj_class, &merror); diff --git a/mono/metadata/threadpool-ms.c b/mono/metadata/threadpool-ms.c index 82f9d75c83a..ba70e75ca01 100644 --- a/mono/metadata/threadpool-ms.c +++ b/mono/metadata/threadpool-ms.c @@ -357,8 +357,7 @@ mono_threadpool_ms_enqueue_work_item (MonoDomain *domain, MonoObject *work_item) g_assert (work_item); if (!threadpool_class) - threadpool_class = mono_class_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool"); - g_assert (threadpool_class); + threadpool_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool"); if (!unsafe_queue_custom_work_item_method) unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2); @@ -1326,8 +1325,7 @@ mono_threadpool_ms_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMet MonoObject *state = NULL; if (!async_call_klass) - async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall"); - g_assert (async_call_klass); + async_call_klass = mono_class_load_from_name (mono_defaults.corlib, "System", "MonoAsyncCall"); mono_lazy_initialize (&status, initialize); diff --git a/mono/metadata/threads-types.h b/mono/metadata/threads-types.h index 86a01a481f3..b097a377fe6 100644 --- a/mono/metadata/threads-types.h +++ b/mono/metadata/threads-types.h @@ -95,10 +95,10 @@ gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle); void ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle); HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name, gint32 rights, gint32 *error); -gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext); +gint32 ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext); gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext); -gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this_obj, HANDLE handle, gint32 ms, gboolean exitContext); -gboolean ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext); +gint32 ves_icall_System_Threading_WaitHandle_WaitOne_internal(HANDLE handle, gint32 ms, gboolean exitContext); +gint32 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext); MonoArray* ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr); MonoArray* ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr); diff --git a/mono/metadata/threads.c b/mono/metadata/threads.c index 3c04b893353..1cb5e238b4d 100644 --- a/mono/metadata/threads.c +++ b/mono/metadata/threads.c @@ -1583,7 +1583,7 @@ mono_wait_uninterrupted (MonoInternalThread *thread, gboolean multiple, guint32 } /* FIXME: exitContext isnt documented */ -gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext) +gint32 ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext) { HANDLE *handles; guint32 numhandles; @@ -1616,15 +1616,7 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_ g_free(handles); - if(ret==WAIT_FAILED) { - THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, mono_native_thread_id_get ())); - return(FALSE); - } else if(ret==WAIT_TIMEOUT) { - THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, mono_native_thread_id_get ())); - return(FALSE); - } - - return(TRUE); + return ret; } /* FIXME: exitContext isnt documented */ @@ -1676,7 +1668,7 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_ha } /* FIXME: exitContext isnt documented */ -gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this_obj, HANDLE handle, gint32 ms, gboolean exitContext) +gint32 ves_icall_System_Threading_WaitHandle_WaitOne_internal(HANDLE handle, gint32 ms, gboolean exitContext) { guint32 ret; MonoInternalThread *thread = mono_thread_internal_current (); @@ -1695,18 +1687,10 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this mono_thread_clr_state (thread, ThreadState_WaitSleepJoin); - if(ret==WAIT_FAILED) { - THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, mono_native_thread_id_get ())); - return(FALSE); - } else if(ret==WAIT_TIMEOUT) { - THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, mono_native_thread_id_get ())); - return(FALSE); - } - - return(TRUE); + return ret; } -gboolean +gint32 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext) { guint32 ret; @@ -1725,7 +1709,7 @@ ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, H mono_thread_clr_state (thread, ThreadState_WaitSleepJoin); - return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED)); + return ret; } HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created) diff --git a/mono/mini/aot-compiler.c b/mono/mini/aot-compiler.c index 4dca2e2e092..5d0cd89cfeb 100644 --- a/mono/mini/aot-compiler.c +++ b/mono/mini/aot-compiler.c @@ -3609,7 +3609,7 @@ add_wrappers (MonoAotCompile *acfg) /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */ csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2); csig->hasthis = 1; - csig->ret = &(mono_class_from_name ( + csig->ret = &(mono_class_load_from_name ( mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg; csig->params [0] = &mono_defaults.string_class->byval_arg; csig->params [1] = &mono_defaults.boolean_class->byval_arg; @@ -4279,14 +4279,13 @@ add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, memset (&ctx, 0, sizeof (ctx)); - icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1"); - g_assert (icomparable); + icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1"); + args [0] = &tclass->byval_arg; ctx.class_inst = mono_metadata_get_generic_inst (1, args); if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) { - gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1"); - g_assert (gcomparer); + gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1"); add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer"); } } @@ -4300,14 +4299,13 @@ add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, memset (&ctx, 0, sizeof (ctx)); - iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1"); + iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1"); g_assert (iface); args [0] = &tclass->byval_arg; ctx.class_inst = mono_metadata_get_generic_inst (1, args); if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) { - gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1"); - g_assert (gcomparer); + gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1"); add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer"); } } @@ -4324,8 +4322,7 @@ add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, args [0] = &tclass->byval_arg; ctx.class_inst = mono_metadata_get_generic_inst (1, args); - enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1"); - g_assert (enum_comparer); + enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1"); add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer"); } } @@ -4342,8 +4339,7 @@ add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, args [0] = &tclass->byval_arg; ctx.class_inst = mono_metadata_get_generic_inst (1, args); - comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1"); - g_assert (comparer); + comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1"); add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer"); } } @@ -4561,10 +4557,10 @@ add_generic_instances (MonoAotCompile *acfg) insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg; /* Add GenericComparer instances for primitive types for Enum.ToString () */ - klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1"); + klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1"); if (klass) add_instances_of (acfg, klass, insts, ninsts, TRUE); - klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1"); + klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1"); if (klass) add_instances_of (acfg, klass, insts, ninsts, TRUE); @@ -4579,24 +4575,20 @@ add_generic_instances (MonoAotCompile *acfg) insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg; insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg; insts [ninsts ++] = &mono_defaults.byte_class->byval_arg; - enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1"); - g_assert (enum_comparer); + enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1"); add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE); ninsts = 0; insts [ninsts ++] = &mono_defaults.int16_class->byval_arg; - enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1"); - g_assert (enum_comparer); + enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1"); add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE); ninsts = 0; insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg; - enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1"); - g_assert (enum_comparer); + enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1"); add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE); - enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1"); - g_assert (enum_comparer); + enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1"); ninsts = 0; insts [ninsts ++] = &mono_defaults.int64_class->byval_arg; insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg; @@ -4605,13 +4597,15 @@ add_generic_instances (MonoAotCompile *acfg) /* Add instances of the array generic interfaces for primitive types */ /* This will add instances of the InternalArray_ helper methods in Array too */ - klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1"); + klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1"); if (klass) add_instances_of (acfg, klass, insts, ninsts, TRUE); - klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1"); + + klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1"); if (klass) add_instances_of (acfg, klass, insts, ninsts, TRUE); - klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1"); + + klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1"); if (klass) add_instances_of (acfg, klass, insts, ninsts, TRUE); @@ -4642,7 +4636,7 @@ add_generic_instances (MonoAotCompile *acfg) MonoGenericContext ctx; MonoType *args [16]; MonoMethod *m; - MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked"); + MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked"); gpointer iter = NULL; while ((m = mono_class_get_methods (interlocked_klass, &iter))) { @@ -4662,7 +4656,7 @@ add_generic_instances (MonoAotCompile *acfg) MonoGenericContext ctx; MonoType *args [16]; MonoMethod *m; - MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile"); + MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile"); gpointer iter = NULL; if (volatile_klass) { @@ -5383,9 +5377,8 @@ encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint MonoClass *ex_class; ex_class = - mono_class_from_name (mono_defaults.exception_class->image, + mono_class_load_from_name (mono_defaults.exception_class->image, "System", (const char *)patch_info->data.target); - g_assert (ex_class); encode_klass_ref (acfg, ex_class, p, &p); break; } @@ -7105,6 +7098,7 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method) gboolean skip; int index, depth; MonoMethod *wrapped; + GTimer *jit_timer; JitFlags flags; if (acfg->aot_opts.metadata_only) @@ -7159,7 +7153,11 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method) flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS); if (acfg->aot_opts.no_direct_calls) flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS); + + jit_timer = mono_time_track_start (); cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index); + mono_time_track_end (&mono_jit_stats.jit_time, jit_timer); + mono_loader_clear_error (); if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) { @@ -7458,6 +7456,8 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method) g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg); + mono_update_jit_stats (cfg); + /* if (cfg->orig_method->wrapper_type) g_ptr_array_add (acfg->extra_methods, cfg->orig_method); @@ -7920,7 +7920,6 @@ emit_llvm_file (MonoAotCompile *acfg) * then removing tailcallelim + the global opts. * strip-dead-prototypes deletes unused intrinsics definitions. */ - //opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -domtree -verify"); /* The dse pass is disabled because of #13734 and #17616 */ /* * The dse bug is in DeadStoreElimination.cpp:isOverwrite (): @@ -7936,7 +7935,11 @@ emit_llvm_file (MonoAotCompile *acfg) // FIXME: This doesn't work yet opts = g_strdup (""); else +#if LLVM_API_VERSION > 100 + opts = g_strdup ("-O2"); +#else opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -inline-cost -inline -sroa -domtree -early-cse -lazy-value-info -correlated-propagation -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -indvars -loop-idiom -loop-deletion -loop-unroll -memdep -gvn -memdep -memcpyopt -sccp -instcombine -lazy-value-info -correlated-propagation -domtree -memdep -adce -simplifycfg -instcombine -strip-dead-prototypes -domtree -verify"); +#endif command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc); aot_printf (acfg, "Executing opt: %s\n", command); if (execute_system (command) != 0) @@ -7971,6 +7974,10 @@ emit_llvm_file (MonoAotCompile *acfg) g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol); +#if LLVM_API_VERSION > 100 + g_string_append_printf (acfg->llc_args, " -disable-tail-calls"); +#endif + #if defined(TARGET_MACH) && defined(TARGET_ARM) /* ios requires PIC code now */ g_string_append_printf (acfg->llc_args, " -relocation-model=pic"); diff --git a/mono/mini/branch-opts.c b/mono/mini/branch-opts.c index aeb11a0ff0e..1a4ea53fe1f 100644 --- a/mono/mini/branch-opts.c +++ b/mono/mini/branch-opts.c @@ -44,7 +44,7 @@ mono_branch_optimize_exception_target (MonoCompile *cfg, MonoBasicBlock *bb, con if (bb->region == -1 || !MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY)) return NULL; - exclass = mono_class_from_name (mono_get_corlib (), "System", exname); + exclass = mono_class_load_from_name (mono_get_corlib (), "System", exname); /* search for the handler */ for (i = 0; i < header->num_clauses; ++i) { clause = &header->clauses [i]; diff --git a/mono/mini/debugger-agent.c b/mono/mini/debugger-agent.c index f3de9130ce6..6b72d9571d8 100644 --- a/mono/mini/debugger-agent.c +++ b/mono/mini/debugger-agent.c @@ -3328,18 +3328,14 @@ init_jit_info_dbg_attrs (MonoJitInfo *ji) if (ji->dbg_attrs_inited) return; - if (!hidden_klass) { - hidden_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute"); - g_assert (hidden_klass); - } - if (!step_through_klass) { - step_through_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute"); - g_assert (step_through_klass); - } - if (!non_user_klass) { - non_user_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute"); - g_assert (non_user_klass); - } + if (!hidden_klass) + hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute"); + + if (!step_through_klass) + step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute"); + + if (!non_user_klass) + non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute"); ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji)); if (ainfo) { @@ -6957,7 +6953,7 @@ vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf) wait_for_suspend (); #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT - env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment"); + env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment"); if (env_class) exit_method = mono_class_get_method_from_name (env_class, "Exit", 1); #endif @@ -9634,12 +9630,13 @@ debugger_thread (void *arg) ErrorCode err; gboolean no_reply; gboolean attach_failed = FALSE; + gpointer attach_cookie, attach_dummy; DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ()); debugger_thread_id = mono_native_thread_id_get (); - mono_jit_thread_attach (mono_get_root_domain ()); + attach_cookie = mono_jit_thread_attach (mono_get_root_domain (), &attach_dummy); mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE; @@ -9792,7 +9789,9 @@ debugger_thread (void *arg) DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n"); start_debugger_thread (); } - + + mono_jit_thread_detach (attach_cookie, &attach_dummy); + return 0; } diff --git a/mono/mini/decompose.c b/mono/mini/decompose.c index a96c6bfd4ac..10c8c75e134 100644 --- a/mono/mini/decompose.c +++ b/mono/mini/decompose.c @@ -471,6 +471,68 @@ mono_decompose_opcode (MonoCompile *cfg, MonoInst *ins) } break; +#if SIZEOF_VOID_P == 8 + case OP_LDIV: + case OP_LREM: + case OP_LDIV_UN: + case OP_LREM_UN: + if (cfg->backend->emulate_div && mono_arch_opcode_needs_emulation (cfg, ins->opcode)) + emulate = TRUE; + if (!emulate) { + if (cfg->backend->need_div_check) { + int reg1 = alloc_ireg (cfg); + int reg2 = alloc_ireg (cfg); + int reg3 = alloc_ireg (cfg); + /* b == 0 */ + MONO_EMIT_NEW_LCOMPARE_IMM (cfg, ins->sreg2, 0); + MONO_EMIT_NEW_COND_EXC (cfg, IEQ, "DivideByZeroException"); + if (ins->opcode == OP_LDIV || ins->opcode == OP_LREM) { + /* b == -1 && a == 0x80000000 */ + MONO_EMIT_NEW_I8CONST (cfg, reg3, -1); + MONO_EMIT_NEW_BIALU (cfg, OP_LCOMPARE, -1, ins->sreg2, reg3); + MONO_EMIT_NEW_UNALU (cfg, OP_LCEQ, reg1, -1); + MONO_EMIT_NEW_I8CONST (cfg, reg3, 0x8000000000000000L); + MONO_EMIT_NEW_BIALU (cfg, OP_LCOMPARE, -1, ins->sreg1, reg3); + MONO_EMIT_NEW_UNALU (cfg, OP_LCEQ, reg2, -1); + MONO_EMIT_NEW_BIALU (cfg, OP_IAND, reg1, reg1, reg2); + MONO_EMIT_NEW_ICOMPARE_IMM (cfg, reg1, 1); + MONO_EMIT_NEW_COND_EXC (cfg, IEQ, "OverflowException"); + } + } + MONO_EMIT_NEW_BIALU (cfg, ins->opcode, ins->dreg, ins->sreg1, ins->sreg2); + NULLIFY_INS (ins); + } + break; +#endif + + case OP_DIV_IMM: + case OP_REM_IMM: + case OP_IDIV_IMM: + case OP_IREM_IMM: + case OP_IDIV_UN_IMM: + case OP_IREM_UN_IMM: + if (cfg->backend->need_div_check) { + int reg1 = alloc_ireg (cfg); + /* b == 0 */ + if (ins->inst_imm == 0) { + // FIXME: Optimize this + MONO_EMIT_NEW_ICONST (cfg, reg1, 0); + MONO_EMIT_NEW_ICOMPARE_IMM (cfg, reg1, 0); + MONO_EMIT_NEW_COND_EXC (cfg, IEQ, "DivideByZeroException"); + } + if ((ins->opcode == OP_DIV_IMM || ins->opcode == OP_IDIV_IMM || ins->opcode == OP_REM_IMM || ins->opcode == OP_IREM_IMM) && + (ins->inst_imm == -1)) { + /* b == -1 && a == 0x80000000 */ + MONO_EMIT_NEW_ICOMPARE_IMM (cfg, ins->sreg1, 0x80000000); + MONO_EMIT_NEW_COND_EXC (cfg, IEQ, "OverflowException"); + } + MONO_EMIT_NEW_BIALU_IMM (cfg, ins->opcode, ins->dreg, ins->sreg1, ins->inst_imm); + NULLIFY_INS (ins); + } else { + emulate = TRUE; + } + break; + default: emulate = TRUE; break; diff --git a/mono/mini/driver.c b/mono/mini/driver.c index dada64022d8..0f6aed5e673 100644 --- a/mono/mini/driver.c +++ b/mono/mini/driver.c @@ -1928,6 +1928,11 @@ mono_main (int argc, char* argv[]) } #endif +#ifdef DISABLE_HW_TRAPS + // Signal handlers not available + opt->explicit_null_checks = TRUE; +#endif + if (!argv [i]) { mini_usage (); return 1; diff --git a/mono/mini/llvm-jit.cpp b/mono/mini/llvm-jit.cpp index dc39414e557..d4ba5599049 100644 --- a/mono/mini/llvm-jit.cpp +++ b/mono/mini/llvm-jit.cpp @@ -12,6 +12,13 @@ #include "config.h" +#include +#include + +#include "mini-llvm-cpp.h" + +#if !defined(MONO_CROSS_COMPILE) && LLVM_API_VERSION < 100 + #include #include @@ -36,13 +43,6 @@ #include #include -#include -#include - -#include "mini-llvm-cpp.h" - -#ifndef MONO_CROSS_COMPILE - using namespace llvm; static void (*unhandled_exception)() = default_mono_llvm_unhandled_exception; diff --git a/mono/mini/local-propagation.c b/mono/mini/local-propagation.c index 5b11f776cf6..2120fa08728 100644 --- a/mono/mini/local-propagation.c +++ b/mono/mini/local-propagation.c @@ -205,8 +205,8 @@ mono_local_cprop (MonoCompile *cfg) int initial_max_vregs = cfg->next_vreg; max = cfg->next_vreg; - defs = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * cfg->next_vreg + 1); - def_index = (gint32 *)mono_mempool_alloc (cfg->mempool, sizeof (guint32) * cfg->next_vreg + 1); + defs = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * cfg->next_vreg); + def_index = (gint32 *)mono_mempool_alloc (cfg->mempool, sizeof (guint32) * cfg->next_vreg); cfg->cbb = bb_opt = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)); for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { @@ -219,22 +219,28 @@ mono_local_cprop (MonoCompile *cfg) int sregs [MONO_MAX_SRC_REGS]; int num_sregs, i; - if ((ins->dreg != -1) && (ins->dreg < max)) { - defs [ins->dreg] = NULL; + if (ins->dreg != -1) { #if SIZEOF_REGISTER == 4 - defs [ins->dreg + 1] = NULL; + const char *spec = INS_INFO (ins->opcode); + if (spec [MONO_INST_DEST] == 'l') { + defs [ins->dreg + 1] = NULL; + defs [ins->dreg + 2] = NULL; + } #endif + defs [ins->dreg] = NULL; } num_sregs = mono_inst_get_src_registers (ins, sregs); for (i = 0; i < num_sregs; ++i) { int sreg = sregs [i]; - if (sreg < max) { - defs [sreg] = NULL; #if SIZEOF_REGISTER == 4 + const char *spec = INS_INFO (ins->opcode); + if (spec [MONO_INST_SRC1 + i] == 'l') { defs [sreg + 1] = NULL; -#endif + defs [sreg + 2] = NULL; } +#endif + defs [sreg] = NULL; } } diff --git a/mono/mini/method-to-ir.c b/mono/mini/method-to-ir.c index b0d03803d43..d76f2085b96 100644 --- a/mono/mini/method-to-ir.c +++ b/mono/mini/method-to-ir.c @@ -160,6 +160,7 @@ static MonoMethodSignature *helper_sig_llvmonly_imt_thunk; /* type loading helpers */ static GENERATE_GET_CLASS_WITH_CACHE (runtime_helpers, System.Runtime.CompilerServices, RuntimeHelpers) +static GENERATE_TRY_GET_CLASS_WITH_CACHE (debuggable_attribute, System.Diagnostics, DebuggableAttribute) /* * Instruction metadata @@ -7895,7 +7896,7 @@ is_jit_optimizer_disabled (MonoMethod *m) { MonoAssembly *ass = m->klass->image->assembly; MonoCustomAttrInfo* attrs; - static MonoClass *klass; + MonoClass *klass; int i; gboolean val = FALSE; @@ -7903,8 +7904,8 @@ is_jit_optimizer_disabled (MonoMethod *m) if (ass->jit_optimizer_disabled_inited) return ass->jit_optimizer_disabled; - if (!klass) - klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggableAttribute"); + klass = mono_class_try_get_debuggable_attribute_class (); + if (!klass) { /* Linked away */ ass->jit_optimizer_disabled = FALSE; @@ -12750,47 +12751,54 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b MonoInst *ad_ins, *jit_tls_ins; MonoBasicBlock *next_bb = NULL, *call_bb = NULL; - cfg->orig_domain_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL); + cfg->attach_cookie = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL); + cfg->attach_dummy = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL); - EMIT_NEW_PCONST (cfg, ins, NULL); - MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg); + if (mono_threads_is_coop_enabled ()) { + /* AOT code is only used in the root domain */ + EMIT_NEW_PCONST (cfg, args [0], cfg->compile_aot ? NULL : cfg->domain); + EMIT_NEW_VARLOADA (cfg, args [1], cfg->attach_dummy, cfg->attach_dummy->inst_vtype); + ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args); + MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->attach_cookie->dreg, ins->dreg); + } else { + EMIT_NEW_PCONST (cfg, ins, NULL); + MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->attach_cookie->dreg, ins->dreg); - ad_ins = mono_get_domain_intrinsic (cfg); - jit_tls_ins = mono_get_jit_tls_intrinsic (cfg); + ad_ins = mono_get_domain_intrinsic (cfg); + jit_tls_ins = mono_get_jit_tls_intrinsic (cfg); - if (cfg->backend->have_tls_get && ad_ins && jit_tls_ins) { - NEW_BBLOCK (cfg, next_bb); - NEW_BBLOCK (cfg, call_bb); + if (cfg->backend->have_tls_get && ad_ins && jit_tls_ins) { + NEW_BBLOCK (cfg, next_bb); + NEW_BBLOCK (cfg, call_bb); - if (cfg->compile_aot) { - /* AOT code is only used in the root domain */ - EMIT_NEW_PCONST (cfg, domain_ins, NULL); - } else { - EMIT_NEW_PCONST (cfg, domain_ins, cfg->domain); - } - MONO_ADD_INS (cfg->cbb, ad_ins); - MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, ad_ins->dreg, domain_ins->dreg); - MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, call_bb); + if (cfg->compile_aot) { + /* AOT code is only used in the root domain */ + EMIT_NEW_PCONST (cfg, domain_ins, NULL); + } else { + EMIT_NEW_PCONST (cfg, domain_ins, cfg->domain); + } + MONO_ADD_INS (cfg->cbb, ad_ins); + MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, ad_ins->dreg, domain_ins->dreg); + MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, call_bb); - MONO_ADD_INS (cfg->cbb, jit_tls_ins); - MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, jit_tls_ins->dreg, 0); - MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, call_bb); + MONO_ADD_INS (cfg->cbb, jit_tls_ins); + MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, jit_tls_ins->dreg, 0); + MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, call_bb); - MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, next_bb); - MONO_START_BB (cfg, call_bb); - } + MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, next_bb); + MONO_START_BB (cfg, call_bb); + } - if (cfg->compile_aot) { /* AOT code is only used in the root domain */ - EMIT_NEW_PCONST (cfg, args [0], NULL); - } else { - EMIT_NEW_PCONST (cfg, args [0], cfg->domain); + EMIT_NEW_PCONST (cfg, args [0], cfg->compile_aot ? NULL : cfg->domain); + EMIT_NEW_PCONST (cfg, args [1], NULL); + ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args); + MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->attach_cookie->dreg, ins->dreg); + + if (next_bb) + MONO_START_BB (cfg, next_bb); } - ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args); - MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg); - if (next_bb) - MONO_START_BB (cfg, next_bb); ip += 2; break; } @@ -12799,8 +12807,9 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b /* Restore the original domain */ dreg = alloc_ireg (cfg); - EMIT_NEW_UNALU (cfg, args [0], OP_MOVE, dreg, cfg->orig_domain_var->dreg); - mono_emit_jit_icall (cfg, mono_jit_set_domain, args); + EMIT_NEW_UNALU (cfg, args [0], OP_MOVE, dreg, cfg->attach_cookie->dreg); + EMIT_NEW_VARLOADA (cfg, args [1], cfg->attach_dummy, cfg->attach_dummy->inst_vtype); + mono_emit_jit_icall (cfg, mono_jit_thread_detach, args); ip += 2; break; } diff --git a/mono/mini/mini-amd64.c b/mono/mini/mini-amd64.c index 66d6d5c6481..56ca3d7aaeb 100644 --- a/mono/mini/mini-amd64.c +++ b/mono/mini/mini-amd64.c @@ -7597,8 +7597,7 @@ mono_arch_emit_exceptions (MonoCompile *cfg) amd64_patch (patch_info->ip.i + cfg->native_code, code); - exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name); - g_assert (exc_class); + exc_class = mono_class_load_from_name (mono_defaults.corlib, "System", patch_info->data.name); throw_ip = patch_info->ip.i; //x86_breakpoint (code); diff --git a/mono/mini/mini-arm.c b/mono/mini/mini-arm.c index b1ddb65fc8f..c9b74ee958f 100644 --- a/mono/mini/mini-arm.c +++ b/mono/mini/mini-arm.c @@ -6802,8 +6802,7 @@ mono_arch_emit_exceptions (MonoCompile *cfg) } arm_patch (ip, code); - exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name); - g_assert (exc_class); + exc_class = mono_class_load_from_name (mono_defaults.corlib, "System", patch_info->data.name); ARM_MOV_REG_REG (code, ARMREG_R1, ARMREG_LR); #ifdef USE_JUMP_TABLES diff --git a/mono/mini/mini-generic-sharing.c b/mono/mini/mini-generic-sharing.c index 6667530f927..43d192707de 100644 --- a/mono/mini/mini-generic-sharing.c +++ b/mono/mini/mini-generic-sharing.c @@ -2630,19 +2630,19 @@ mini_method_is_open (MonoMethod *method) return FALSE; } +/* Lazy class loading functions */ +static GENERATE_TRY_GET_CLASS_WITH_CACHE (iasync_state_machine, System.Runtime.CompilerServices, IAsyncStateMachine) +static GENERATE_TRY_GET_CLASS_WITH_CACHE (async_state_machine_attribute, System.Runtime.CompilerServices, AsyncStateMachineAttribute) + + static G_GNUC_UNUSED gboolean is_async_state_machine_class (MonoClass *klass) { - static MonoClass *iclass; - static gboolean iclass_set; + MonoClass *iclass; return FALSE; - if (!iclass_set) { - iclass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.CompilerServices", "IAsyncStateMachine"); - mono_memory_barrier (); - iclass_set = TRUE; - } + iclass = mono_class_try_get_iasync_state_machine_class (); if (iclass && klass->valuetype && mono_class_is_assignable_from (iclass, klass)) return TRUE; @@ -2655,16 +2655,11 @@ is_async_method (MonoMethod *method) MonoCustomAttrInfo *cattr; MonoMethodSignature *sig; gboolean res = FALSE; - static MonoClass *attr_class; - static gboolean attr_class_set; + MonoClass *attr_class; return FALSE; - if (!attr_class_set) { - attr_class = mono_class_from_name (mono_defaults.corlib, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute"); - mono_memory_barrier (); - attr_class_set = TRUE; - } + attr_class = mono_class_try_get_iasync_state_machine_class (); /* Do less expensive checks first */ sig = mono_method_signature (method); diff --git a/mono/mini/mini-ia64.c b/mono/mini/mini-ia64.c index 54222c26698..aee49d44b21 100644 --- a/mono/mini/mini-ia64.c +++ b/mono/mini/mini-ia64.c @@ -4188,8 +4188,7 @@ mono_arch_emit_exceptions (MonoCompile *cfg) guint8* buf; guint64 exc_token_index; - exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name); - g_assert (exc_class); + exc_class = mono_class_load_from_name (mono_defaults.corlib, "System", patch_info->data.name); exc_token_index = mono_metadata_token_index (exc_class->type_token); throw_ip = cfg->native_code + patch_info->ip.i; diff --git a/mono/mini/mini-llvm.c b/mono/mini/mini-llvm.c index f6c95a0cb36..1a65475f212 100644 --- a/mono/mini/mini-llvm.c +++ b/mono/mini/mini-llvm.c @@ -265,7 +265,7 @@ static void init_jit_module (MonoDomain *domain); static void emit_dbg_loc (EmitContext *ctx, LLVMBuilderRef builder, const unsigned char *cil_code); static LLVMValueRef emit_dbg_subprogram (EmitContext *ctx, MonoCompile *cfg, LLVMValueRef method, const char *name); static void emit_dbg_info (MonoLLVMModule *module, const char *filename, const char *cu_name); - +static void emit_cond_system_exception (EmitContext *ctx, MonoBasicBlock *bb, const char *exc_type, LLVMValueRef cmp); static inline void set_failure (EmitContext *ctx, const char *message) @@ -1866,8 +1866,19 @@ emit_load_general (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder const char *intrins_name; LLVMValueRef args [16], res; LLVMTypeRef addr_type; + gboolean use_intrinsics = TRUE; +#if LLVM_API_VERSION > 100 if (is_faulting && bb->region != -1 && !ctx->cfg->llvm_only) { + /* The llvm.mono.load/store intrinsics are not supported by this llvm version, emit an explicit null check instead */ + LLVMValueRef cmp = LLVMBuildICmp (*builder_ref, LLVMIntEQ, addr, LLVMConstNull (LLVMTypeOf (addr)), ""); + emit_cond_system_exception (ctx, bb, "NullReferenceException", cmp); + *builder_ref = ctx->builder; + use_intrinsics = FALSE; + } +#endif + + if (is_faulting && bb->region != -1 && !ctx->cfg->llvm_only && use_intrinsics) { LLVMAtomicOrdering ordering; switch (barrier) { @@ -1955,8 +1966,19 @@ emit_store_general (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builde { const char *intrins_name; LLVMValueRef args [16]; + gboolean use_intrinsics = TRUE; +#if LLVM_API_VERSION > 100 if (is_faulting && bb->region != -1 && !ctx->cfg->llvm_only) { + /* The llvm.mono.load/store intrinsics are not supported by this llvm version, emit an explicit null check instead */ + LLVMValueRef cmp = LLVMBuildICmp (*builder_ref, LLVMIntEQ, addr, LLVMConstNull (LLVMTypeOf (addr)), ""); + emit_cond_system_exception (ctx, bb, "NullReferenceException", cmp); + *builder_ref = ctx->builder; + use_intrinsics = FALSE; + } +#endif + + if (is_faulting && bb->region != -1 && !ctx->cfg->llvm_only && use_intrinsics) { LLVMAtomicOrdering ordering; switch (barrier) { @@ -2035,8 +2057,7 @@ emit_cond_system_exception (EmitContext *ctx, MonoBasicBlock *bb, const char *ex LLVMBuildCondBr (ctx->builder, cmp, ex_bb, noex_bb); - exc_class = mono_class_from_name (mono_get_corlib (), "System", exc_type); - g_assert (exc_class); + exc_class = mono_class_load_from_name (mono_get_corlib (), "System", exc_type); /* Emit exception throwing code */ ctx->builder = builder = create_builder (ctx); @@ -4852,7 +4873,7 @@ process_bb (EmitContext *ctx, MonoBasicBlock *bb) break; case OP_FCONV_TO_U1: case OP_RCONV_TO_U1: - values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), ""); + values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildTrunc (builder, LLVMBuildFPToUI (builder, lhs, IntPtrType (), dname), LLVMInt8Type (), ""), LLVMInt32Type (), ""); break; case OP_FCONV_TO_I2: case OP_RCONV_TO_I2: @@ -5014,7 +5035,9 @@ process_bb (EmitContext *ctx, MonoBasicBlock *bb) * they can't fail, allowing them to be hoisted out of loops. */ set_invariant_load_flag (values [ins->dreg]); +#if LLVM_API_VERSION < 100 set_metadata_flag (values [ins->dreg], "mono.nofail.load"); +#endif } if (sext) diff --git a/mono/mini/mini-mips.c b/mono/mini/mini-mips.c index 0b1265e9e78..a5453a88e05 100644 --- a/mono/mini/mini-mips.c +++ b/mono/mini/mini-mips.c @@ -221,8 +221,7 @@ mips_emit_exc_by_name(guint8 *code, const char *name) gpointer addr; MonoClass *exc_class; - exc_class = mono_class_from_name (mono_defaults.corlib, "System", name); - g_assert (exc_class); + exc_class = mono_class_load_from_name (mono_defaults.corlib, "System", name); mips_load_const (code, mips_a0, exc_class->type_token); addr = mono_get_throw_corlib_exception (); diff --git a/mono/mini/mini-ppc.c b/mono/mini/mini-ppc.c index 9e715e2dd71..c9116ff46e1 100644 --- a/mono/mini/mini-ppc.c +++ b/mono/mini/mini-ppc.c @@ -5621,8 +5621,7 @@ mono_arch_emit_exceptions (MonoCompile *cfg) exc_throw_pos [i] = code; } - exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name); - g_assert (exc_class); + exc_class = mono_class_load_from_name (mono_defaults.corlib, "System", patch_info->data.name); ppc_patch (ip, code); /*mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_EXC_NAME, patch_info->data.target);*/ diff --git a/mono/mini/mini-runtime.c b/mono/mini/mini-runtime.c index 89633ace28f..a3fe3305d5c 100644 --- a/mono/mini/mini-runtime.c +++ b/mono/mini/mini-runtime.c @@ -825,7 +825,8 @@ mono_get_lmf_addr (void) * mono_get_lmf_addr, and mono_get_lmf_addr requires the thread to be attached. */ - mono_jit_thread_attach (NULL); + mono_thread_attach (mono_get_root_domain ()); + mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background); if ((jit_tls = mono_native_tls_get_value (mono_jit_tls_id))) return &jit_tls->lmf; @@ -884,48 +885,119 @@ mono_set_lmf_addr (gpointer lmf_addr) } /* - * mono_jit_thread_attach: + * mono_jit_thread_attach: called by native->managed wrappers * - * Called by native->managed wrappers. Returns the original domain which needs to be - * restored, or NULL. + * In non-coop mode: + * - @dummy: is NULL + * - @return: the original domain which needs to be restored, or NULL. + * + * In coop mode: + * - @dummy: contains the original domain + * - @return: a cookie containing current MonoThreadInfo* if it was in BLOCKING mode, NULL otherwise */ -MonoDomain* -mono_jit_thread_attach (MonoDomain *domain) +gpointer +mono_jit_thread_attach (MonoDomain *domain, gpointer *dummy) { MonoDomain *orig; - if (!domain) - /* - * Happens when called from AOTed code which is only used in the root - * domain. - */ + if (!domain) { + /* Happens when called from AOTed code which is only used in the root domain. */ domain = mono_get_root_domain (); + } + + g_assert (domain); + + if (!mono_threads_is_coop_enabled ()) { + gboolean attached; #ifdef MONO_HAVE_FAST_TLS - if (!MONO_FAST_TLS_GET (mono_lmf_addr)) { - mono_thread_attach (domain); - // #678164 - mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background); - } + attached = MONO_FAST_TLS_GET (mono_lmf_addr) != NULL; #else - if (!mono_native_tls_get_value (mono_jit_tls_id)) { - mono_thread_attach (domain); - mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background); - } + attached = mono_native_tls_get_value (mono_jit_tls_id) != NULL; #endif - orig = mono_domain_get (); - if (orig != domain) - mono_domain_set (domain, TRUE); - return orig != domain ? orig : NULL; + if (!attached) { + mono_thread_attach (domain); + + // #678164 + mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background); + } + + orig = mono_domain_get (); + if (orig != domain) + mono_domain_set (domain, TRUE); + + return orig != domain ? orig : NULL; + } else { + MonoThreadInfo *info; + + info = mono_thread_info_current_unchecked (); + if (!info || !mono_thread_info_is_live (info)) { + /* thread state STARTING -> RUNNING */ + mono_thread_attach (domain); + + // #678164 + mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background); + + *dummy = NULL; + + /* mono_threads_reset_blocking_start returns the current MonoThreadInfo + * if we were in BLOCKING mode */ + return mono_thread_info_current (); + } else { + orig = mono_domain_get (); + + /* orig might be null if we did an attach -> detach -> attach sequence */ + + if (orig != domain) + mono_domain_set (domain, TRUE); + + *dummy = orig; + + /* thread state (BLOCKING|RUNNING) -> RUNNING */ + return mono_threads_reset_blocking_start (dummy); + } + } } -/* Called by native->managed wrappers */ +/* + * mono_jit_thread_detach: called by native->managed wrappers + * + * In non-coop mode: + * - @cookie: the original domain which needs to be restored, or NULL. + * - @dummy: is NULL + * + * In coop mode: + * - @cookie: contains current MonoThreadInfo* if it was in BLOCKING mode, NULL otherwise + * - @dummy: contains the original domain + */ void -mono_jit_set_domain (MonoDomain *domain) +mono_jit_thread_detach (gpointer cookie, gpointer *dummy) { - if (domain) - mono_domain_set (domain, TRUE); + MonoDomain *domain, *orig; + + if (!mono_threads_is_coop_enabled ()) { + orig = (MonoDomain*) cookie; + + if (orig) + mono_domain_set (orig, TRUE); + } else { + orig = (MonoDomain*) *dummy; + + domain = mono_domain_get (); + g_assert (domain); + + /* it won't do anything if cookie is NULL + * thread state RUNNING -> (RUNNING|BLOCKING) */ + mono_threads_reset_blocking_end (cookie, dummy); + + if (orig != domain) { + if (!orig) + mono_domain_unset (); + else + mono_domain_set (orig, TRUE); + } + } } /** @@ -3309,6 +3381,43 @@ register_jit_stats (void) mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_aot); mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm); mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm); + mono_counters_register ("JIT/method-to-IR (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_method_to_ir); + mono_counters_register ("JIT/liveness_handle_exception_clauses (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_liveness_handle_exception_clauses); + mono_counters_register ("JIT/handle_out_of_line_bblock (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_handle_out_of_line_bblock); + mono_counters_register ("JIT/decompose_long_opts (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_decompose_long_opts); + mono_counters_register ("JIT/local_cprop (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_cprop); + mono_counters_register ("JIT/local_emulate_ops (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_emulate_ops); + mono_counters_register ("JIT/optimize_branches (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_optimize_branches); + mono_counters_register ("JIT/handle_global_vregs (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_handle_global_vregs); + mono_counters_register ("JIT/local_deadce (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_deadce); + mono_counters_register ("JIT/local_alias_analysis (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_alias_analysis); + mono_counters_register ("JIT/if_conversion (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_if_conversion); + mono_counters_register ("JIT/bb_ordering (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_bb_ordering); + mono_counters_register ("JIT/compile_dominator_info (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_compile_dominator_info); + mono_counters_register ("JIT/compute_natural_loops (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_compute_natural_loops); + mono_counters_register ("JIT/insert_safepoints (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_insert_safepoints); + mono_counters_register ("JIT/ssa_compute (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_ssa_compute); + mono_counters_register ("JIT/ssa_cprop (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_ssa_cprop); + mono_counters_register ("JIT/ssa_deadce(sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_ssa_deadce); + mono_counters_register ("JIT/perform_abc_removal (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_perform_abc_removal); + mono_counters_register ("JIT/ssa_remove (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_ssa_remove); + mono_counters_register ("JIT/local_cprop2 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_cprop2); + mono_counters_register ("JIT/handle_global_vregs2 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_handle_global_vregs2); + mono_counters_register ("JIT/local_deadce2 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_deadce2); + mono_counters_register ("JIT/optimize_branches2 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_optimize_branches2); + mono_counters_register ("JIT/decompose_vtype_opts (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_decompose_vtype_opts); + mono_counters_register ("JIT/decompose_array_access_opts (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_decompose_array_access_opts); + mono_counters_register ("JIT/liveness_handle_exception_clauses2 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_liveness_handle_exception_clauses2); + mono_counters_register ("JIT/analyze_liveness (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_analyze_liveness); + mono_counters_register ("JIT/linear_scan (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_linear_scan); + mono_counters_register ("JIT/arch_allocate_vars (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_arch_allocate_vars); + mono_counters_register ("JIT/spill_global_vars (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_spill_global_vars); + mono_counters_register ("JIT/jit_local_cprop3 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_cprop3); + mono_counters_register ("JIT/jit_local_deadce3 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_deadce3); + mono_counters_register ("JIT/codegen (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_codegen); + mono_counters_register ("JIT/create_jit_info (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_create_jit_info); + mono_counters_register ("JIT/gc_create_gc_map (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_gc_create_gc_map); + mono_counters_register ("JIT/save_seq_point_info (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_save_seq_point_info); mono_counters_register ("Total time spent JITting (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_time); mono_counters_register ("Basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.basic_blocks); mono_counters_register ("Max basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.max_basic_blocks); @@ -3740,8 +3849,8 @@ register_icalls (void) register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE); register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE); register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE); - register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "ptr ptr", TRUE); - register_icall (mono_jit_set_domain, "mono_jit_set_domain", "void ptr", TRUE); + register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "ptr ptr ptr", TRUE); + register_icall (mono_jit_thread_detach, "mono_jit_thread_detach", "void ptr ptr", TRUE); register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE); register_icall (mono_llvm_throw_exception, "mono_llvm_throw_exception", "void object", TRUE); diff --git a/mono/mini/mini-s390x.c b/mono/mini/mini-s390x.c index a4a7776094c..4cf7b4df7ad 100644 --- a/mono/mini/mini-s390x.c +++ b/mono/mini/mini-s390x.c @@ -6077,10 +6077,9 @@ mono_arch_emit_exceptions (MonoCompile *cfg) /*-----------------------------------------------------*/ s390_patch_rel (ip + 2, (guint64) S390_RELATIVE(code,ip)); - exc_class = mono_class_from_name (mono_defaults.corlib, + exc_class = mono_class_load_from_name (mono_defaults.corlib, "System", patch_info->data.name); - g_assert (exc_class); throw_ip = patch_info->ip.i; for (iExc = 0; iExc < nThrows; ++iExc) diff --git a/mono/mini/mini-sparc.c b/mono/mini/mini-sparc.c index 7f99809d51f..f791290851c 100644 --- a/mono/mini/mini-sparc.c +++ b/mono/mini/mini-sparc.c @@ -4208,8 +4208,7 @@ mono_arch_emit_exceptions (MonoCompile *cfg) sparc_patch ((guint32*)(cfg->native_code + patch_info->ip.i), code); - exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name); - g_assert (exc_class); + exc_class = mono_class_load_from_name (mono_defaults.corlib, "System", patch_info->data.name); type_idx = exc_class->type_token - MONO_TOKEN_TYPE_DEF; throw_ip = patch_info->ip.i; diff --git a/mono/mini/mini-x86.c b/mono/mini/mini-x86.c index 0407c7cc57e..c772cf21305 100644 --- a/mono/mini/mini-x86.c +++ b/mono/mini/mini-x86.c @@ -5664,8 +5664,7 @@ mono_arch_emit_exceptions (MonoCompile *cfg) x86_patch (patch_info->ip.i + cfg->native_code, code); - exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name); - g_assert (exc_class); + exc_class = mono_class_load_from_name (mono_defaults.corlib, "System", patch_info->data.name); throw_ip = patch_info->ip.i; /* Find a throw sequence for the same exception class */ diff --git a/mono/mini/mini.c b/mono/mini/mini.c index a93659383f1..09b31feaaf2 100644 --- a/mono/mini/mini.c +++ b/mono/mini/mini.c @@ -2713,6 +2713,42 @@ compute_reachable (MonoBasicBlock *bb) } } +static void mono_bb_ordering (MonoCompile *cfg) +{ + int dfn = 0; + /* Depth-first ordering on basic blocks */ + cfg->bblocks = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1)); + + cfg->max_block_num = cfg->num_bblocks; + + df_visit (cfg->bb_entry, &dfn, cfg->bblocks); + if (cfg->num_bblocks != dfn + 1) { + MonoBasicBlock *bb; + + cfg->num_bblocks = dfn + 1; + + /* remove unreachable code, because the code in them may be + * inconsistent (access to dead variables for example) */ + for (bb = cfg->bb_entry; bb; bb = bb->next_bb) + bb->flags &= ~BB_VISITED; + compute_reachable (cfg->bb_entry); + for (bb = cfg->bb_entry; bb; bb = bb->next_bb) + if (bb->flags & BB_EXCEPTION_HANDLER) + compute_reachable (bb); + for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { + if (!(bb->flags & BB_VISITED)) { + if (cfg->verbose_level > 1) + g_print ("found unreachable code in BB%d\n", bb->block_num); + bb->code = bb->last_ins = NULL; + while (bb->out_count) + mono_unlink_bblock (cfg, bb, bb->out_bb [0]); + } + } + for (bb = cfg->bb_entry; bb; bb = bb->next_bb) + bb->flags &= ~BB_VISITED; + } +} + static void mono_handle_out_of_line_bblock (MonoCompile *cfg) { @@ -3220,6 +3256,52 @@ mono_insert_safepoints (MonoCompile *cfg) } + +static void +mono_insert_branches_between_bblocks (MonoCompile *cfg) +{ + MonoBasicBlock *bb; + + /* Add branches between non-consecutive bblocks */ + for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { + if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) && + bb->last_ins->inst_false_bb && bb->next_bb != bb->last_ins->inst_false_bb) { + /* we are careful when inverting, since bugs like #59580 + * could show up when dealing with NaNs. + */ + if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) { + MonoBasicBlock *tmp = bb->last_ins->inst_true_bb; + bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb; + bb->last_ins->inst_false_bb = tmp; + + bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode); + } else { + MonoInst *inst = (MonoInst *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst)); + inst->opcode = OP_BR; + inst->inst_target_bb = bb->last_ins->inst_false_bb; + mono_bblock_add_inst (bb, inst); + } + } + } + + if (cfg->verbose_level >= 4) { + for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { + MonoInst *tree = bb->code; + g_print ("DUMP BLOCK %d:\n", bb->block_num); + if (!tree) + continue; + for (; tree; tree = tree->next) { + mono_print_ins_index (-1, tree); + } + } + } + + /* FIXME: */ + for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { + bb->max_vreg = cfg->next_vreg; + } +} + static void init_backend (MonoBackend *backend) { @@ -3303,7 +3385,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl MonoMethodSignature *sig; MonoError err; MonoCompile *cfg; - int dfn, i, code_size_ratio; + int i, code_size_ratio; gboolean try_generic_shared, try_llvm = FALSE; MonoMethod *method_to_compile, *method_to_register; gboolean method_is_gshared = FALSE; @@ -3649,7 +3731,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl */ mono_compile_create_vars (cfg); - i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, NULL, NULL, 0, FALSE); + MONO_TIME_TRACK (mono_jit_stats.jit_method_to_ir, i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, NULL, NULL, 0, FALSE)); if (i < 0) { if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) { @@ -3710,71 +3792,43 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl * This also allows SSA to be run on methods containing exception clauses, since * SSA will ignore variables marked VOLATILE. */ - mono_liveness_handle_exception_clauses (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_liveness_handle_exception_clauses, mono_liveness_handle_exception_clauses (cfg)); - mono_handle_out_of_line_bblock (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_handle_out_of_line_bblock, mono_handle_out_of_line_bblock (cfg)); /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/ - if (!COMPILE_LLVM (cfg)) - mono_decompose_long_opts (cfg); + if (!COMPILE_LLVM (cfg)) { + MONO_TIME_TRACK (mono_jit_stats.jit_decompose_long_opts, mono_decompose_long_opts (cfg)); + } /* Should be done before branch opts */ if (cfg->opt & (MONO_OPT_CONSPROP | MONO_OPT_COPYPROP)) - mono_local_cprop (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_local_cprop, mono_local_cprop (cfg)); + /* * Should be done after cprop which can do strength reduction on * some of these ops, after propagating immediates. */ if (cfg->has_emulated_ops) - mono_local_emulate_ops (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_local_emulate_ops, mono_local_emulate_ops (cfg)); + if (cfg->opt & MONO_OPT_BRANCH) - mono_optimize_branches (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_optimize_branches, mono_optimize_branches (cfg)); /* This must be done _before_ global reg alloc and _after_ decompose */ - mono_handle_global_vregs (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_handle_global_vregs, mono_handle_global_vregs (cfg)); if (cfg->opt & MONO_OPT_DEADCE) - mono_local_deadce (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_local_deadce, mono_local_deadce (cfg)); if (cfg->opt & MONO_OPT_ALIAS_ANALYSIS) - mono_local_alias_analysis (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_local_alias_analysis, mono_local_alias_analysis (cfg)); /* Disable this for LLVM to make the IR easier to handle */ if (!COMPILE_LLVM (cfg)) - mono_if_conversion (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_if_conversion, mono_if_conversion (cfg)); mono_threads_safepoint (); - /* Depth-first ordering on basic blocks */ - cfg->bblocks = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1)); - - cfg->max_block_num = cfg->num_bblocks; - - dfn = 0; - df_visit (cfg->bb_entry, &dfn, cfg->bblocks); - if (cfg->num_bblocks != dfn + 1) { - MonoBasicBlock *bb; - - cfg->num_bblocks = dfn + 1; - - /* remove unreachable code, because the code in them may be - * inconsistent (access to dead variables for example) */ - for (bb = cfg->bb_entry; bb; bb = bb->next_bb) - bb->flags &= ~BB_VISITED; - compute_reachable (cfg->bb_entry); - for (bb = cfg->bb_entry; bb; bb = bb->next_bb) - if (bb->flags & BB_EXCEPTION_HANDLER) - compute_reachable (bb); - for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { - if (!(bb->flags & BB_VISITED)) { - if (cfg->verbose_level > 1) - g_print ("found unreachable code in BB%d\n", bb->block_num); - bb->code = bb->last_ins = NULL; - while (bb->out_count) - mono_unlink_bblock (cfg, bb, bb->out_bb [0]); - } - } - for (bb = cfg->bb_entry; bb; bb = bb->next_bb) - bb->flags &= ~BB_VISITED; - } + MONO_TIME_TRACK (mono_jit_stats.jit_bb_ordering, mono_bb_ordering (cfg)); if (((cfg->num_varinfo > 2000) || (cfg->num_bblocks > 1000)) && !cfg->compile_aot) { /* @@ -3787,11 +3841,11 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl } if (cfg->opt & MONO_OPT_LOOP) { - mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM); - mono_compute_natural_loops (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_compile_dominator_info, mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM)); + MONO_TIME_TRACK (mono_jit_stats.jit_compute_natural_loops, mono_compute_natural_loops (cfg)); } - mono_insert_safepoints (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_insert_safepoints, mono_insert_safepoints (cfg)); /* after method_to_ir */ if (parts == 1) { @@ -3820,7 +3874,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl if (cfg->opt & MONO_OPT_SSA) { if (!(cfg->comp_done & MONO_COMP_SSA) && !cfg->disable_ssa) { #ifndef DISABLE_SSA - mono_ssa_compute (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_ssa_compute, mono_ssa_compute (cfg)); #endif if (cfg->verbose_level >= 2) { @@ -3840,7 +3894,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) { if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) { #ifndef DISABLE_SSA - mono_ssa_cprop (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_ssa_cprop, mono_ssa_cprop (cfg)); #endif } } @@ -3850,19 +3904,19 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl //mono_ssa_strength_reduction (cfg); if (cfg->opt & MONO_OPT_DEADCE) - mono_ssa_deadce (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_ssa_deadce, mono_ssa_deadce (cfg)); if ((cfg->flags & (MONO_CFG_HAS_LDELEMA|MONO_CFG_HAS_CHECK_THIS)) && (cfg->opt & MONO_OPT_ABCREM)) - mono_perform_abc_removal (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_perform_abc_removal, mono_perform_abc_removal (cfg)); - mono_ssa_remove (cfg); - mono_local_cprop (cfg); - mono_handle_global_vregs (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_ssa_remove, mono_ssa_remove (cfg)); + MONO_TIME_TRACK (mono_jit_stats.jit_local_cprop2, mono_local_cprop (cfg)); + MONO_TIME_TRACK (mono_jit_stats.jit_handle_global_vregs2, mono_handle_global_vregs (cfg)); if (cfg->opt & MONO_OPT_DEADCE) - mono_local_deadce (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_local_deadce2, mono_local_deadce (cfg)); if (cfg->opt & MONO_OPT_BRANCH) - mono_optimize_branches (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_optimize_branches2, mono_optimize_branches (cfg)); } #endif @@ -3887,9 +3941,9 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl if (COMPILE_SOFT_FLOAT (cfg)) mono_decompose_soft_float (cfg); #endif - mono_decompose_vtype_opts (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_decompose_vtype_opts, mono_decompose_vtype_opts (cfg)); if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS) - mono_decompose_array_access_opts (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_decompose_array_access_opts, mono_decompose_array_access_opts (cfg)); if (cfg->got_var) { #ifndef MONO_ARCH_GOT_REG @@ -3922,7 +3976,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl /* * Have to call this again to process variables added since the first call. */ - mono_liveness_handle_exception_clauses (cfg); + MONO_TIME_TRACK(mono_jit_stats.jit_liveness_handle_exception_clauses2, mono_liveness_handle_exception_clauses (cfg)); if (cfg->opt & MONO_OPT_LINEARS) { GList *vars, *regs, *l; @@ -3930,7 +3984,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl /* fixme: maybe we can avoid to compute livenesss here if already computed ? */ cfg->comp_done &= ~MONO_COMP_LIVENESS; if (!(cfg->comp_done & MONO_COMP_LIVENESS)) - mono_analyze_liveness (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_analyze_liveness, mono_analyze_liveness (cfg)); if ((vars = mono_arch_get_allocatable_int_vars (cfg))) { regs = mono_arch_get_global_int_regs (cfg); @@ -3943,7 +3997,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl } } } - mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs); + MONO_TIME_TRACK (mono_jit_stats.jit_linear_scan, mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs)); } } @@ -3953,69 +4007,28 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl /* variables are allocated after decompose, since decompose could create temps */ if (!COMPILE_LLVM (cfg)) { - mono_arch_allocate_vars (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_arch_allocate_vars, mono_arch_allocate_vars (cfg)); if (cfg->exception_type) return cfg; } - { - MonoBasicBlock *bb; - gboolean need_local_opts; - - if (cfg->gsharedvt) - mono_allocate_gsharedvt_vars (cfg); - - if (!COMPILE_LLVM (cfg)) { - mono_spill_global_vars (cfg, &need_local_opts); - - if (need_local_opts || cfg->compile_aot) { - /* To optimize code created by spill_global_vars */ - mono_local_cprop (cfg); - if (cfg->opt & MONO_OPT_DEADCE) - mono_local_deadce (cfg); - } - } - - /* Add branches between non-consecutive bblocks */ - for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { - if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) && - bb->last_ins->inst_false_bb && bb->next_bb != bb->last_ins->inst_false_bb) { - /* we are careful when inverting, since bugs like #59580 - * could show up when dealing with NaNs. - */ - if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) { - MonoBasicBlock *tmp = bb->last_ins->inst_true_bb; - bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb; - bb->last_ins->inst_false_bb = tmp; - - bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode); - } else { - MonoInst *inst = (MonoInst *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst)); - inst->opcode = OP_BR; - inst->inst_target_bb = bb->last_ins->inst_false_bb; - mono_bblock_add_inst (bb, inst); - } - } - } + if (cfg->gsharedvt) + mono_allocate_gsharedvt_vars (cfg); - if (cfg->verbose_level >= 4) { - for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { - MonoInst *tree = bb->code; - g_print ("DUMP BLOCK %d:\n", bb->block_num); - if (!tree) - continue; - for (; tree; tree = tree->next) { - mono_print_ins_index (-1, tree); - } - } - } + if (!COMPILE_LLVM (cfg)) { + gboolean need_local_opts; + MONO_TIME_TRACK (mono_jit_stats.jit_spill_global_vars, mono_spill_global_vars (cfg, &need_local_opts)); - /* FIXME: */ - for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { - bb->max_vreg = cfg->next_vreg; + if (need_local_opts || cfg->compile_aot) { + /* To optimize code created by spill_global_vars */ + MONO_TIME_TRACK (mono_jit_stats.jit_local_cprop3, mono_local_cprop (cfg)); + if (cfg->opt & MONO_OPT_DEADCE) + MONO_TIME_TRACK (mono_jit_stats.jit_local_deadce3, mono_local_deadce (cfg)); } } + mono_insert_branches_between_bblocks (cfg); + if (COMPILE_LLVM (cfg)) { #ifdef ENABLE_LLVM char *nm; @@ -4055,7 +4068,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl } #endif } else { - mono_codegen (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_codegen, mono_codegen (cfg)); } if (COMPILE_LLVM (cfg)) @@ -4063,7 +4076,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl else InterlockedIncrement (&mono_jit_stats.methods_without_llvm); - cfg->jit_info = create_jit_info (cfg, method_to_compile); + MONO_TIME_TRACK (mono_jit_stats.jit_create_jit_info, cfg->jit_info = create_jit_info (cfg, method_to_compile)); #ifdef MONO_ARCH_HAVE_LIVERANGE_OPS if (cfg->extend_live_ranges) { @@ -4076,9 +4089,9 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFl if (!cfg->compile_aot) mono_save_xdebug_info (cfg); - mini_gc_create_gc_map (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_gc_create_gc_map, mini_gc_create_gc_map (cfg)); - mono_save_seq_point_info (cfg); + MONO_TIME_TRACK (mono_jit_stats.jit_save_seq_point_info, mono_save_seq_point_info (cfg)); if (cfg->verbose_level >= 2) { char *id = mono_method_full_name (cfg->method, FALSE); @@ -4186,6 +4199,31 @@ create_jit_info_for_trampoline (MonoMethod *wrapper, MonoTrampInfo *info) return jinfo; } +GTimer *mono_time_track_start () +{ + return g_timer_new (); +} + +void mono_time_track_end (double *time, GTimer *timer) +{ + g_timer_stop (timer); + *time += g_timer_elapsed (timer, NULL); + g_timer_destroy (timer); +} + +void mono_update_jit_stats (MonoCompile *cfg) +{ + mono_jit_stats.allocate_var += cfg->stat_allocate_var; + mono_jit_stats.locals_stack_size += cfg->stat_locals_stack_size; + mono_jit_stats.basic_blocks += cfg->stat_basic_blocks; + mono_jit_stats.max_basic_blocks = MAX (cfg->stat_basic_blocks, mono_jit_stats.max_basic_blocks); + mono_jit_stats.cil_code_size += cfg->stat_cil_code_size; + mono_jit_stats.regvars += cfg->stat_n_regvars; + mono_jit_stats.inlineable_methods += cfg->stat_inlineable_methods; + mono_jit_stats.inlined_methods += cfg->stat_inlined_methods; + mono_jit_stats.code_reallocs += cfg->stat_code_reallocs; +} + /* * mono_jit_compile_method_inner: * @@ -4319,14 +4357,11 @@ mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, in return NULL; } - jit_timer = g_timer_new (); - + jit_timer = mono_time_track_start (); cfg = mini_method_compile (method, opt, target_domain, JIT_FLAG_RUN_CCTORS, 0, -1); - prof_method = cfg->method; + mono_time_track_end (&mono_jit_stats.jit_time, jit_timer); - g_timer_stop (jit_timer); - mono_jit_stats.jit_time += g_timer_elapsed (jit_timer, NULL); - g_timer_destroy (jit_timer); + prof_method = cfg->method; switch (cfg->exception_type) { case MONO_EXCEPTION_NONE: @@ -4414,15 +4449,7 @@ mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, in * Update global stats while holding a lock, instead of doing many * InterlockedIncrement operations during JITting. */ - mono_jit_stats.allocate_var += cfg->stat_allocate_var; - mono_jit_stats.locals_stack_size += cfg->stat_locals_stack_size; - mono_jit_stats.basic_blocks += cfg->stat_basic_blocks; - mono_jit_stats.max_basic_blocks = MAX (cfg->stat_basic_blocks, mono_jit_stats.max_basic_blocks); - mono_jit_stats.cil_code_size += cfg->stat_cil_code_size; - mono_jit_stats.regvars += cfg->stat_n_regvars; - mono_jit_stats.inlineable_methods += cfg->stat_inlineable_methods; - mono_jit_stats.inlined_methods += cfg->stat_inlined_methods; - mono_jit_stats.code_reallocs += cfg->stat_code_reallocs; + mono_update_jit_stats (cfg); mono_destroy_compile (cfg); diff --git a/mono/mini/mini.h b/mono/mini/mini.h index 6954a7639ac..5ebe8e3b142 100644 --- a/mono/mini/mini.h +++ b/mono/mini/mini.h @@ -1605,8 +1605,9 @@ typedef struct { /* Points to a MonoGSharedVtMethodRuntimeInfo at runtime */ MonoInst *gsharedvt_info_var; - /* For native-to-managed wrappers, the saved old domain */ - MonoInst *orig_domain_var; + /* For native-to-managed wrappers, CEE_MONO_JIT_(AT|DE)TACH opcodes */ + MonoInst *attach_cookie; + MonoInst *attach_dummy; MonoInst *lmf_var; MonoInst *lmf_addr_var; @@ -1893,6 +1894,43 @@ typedef struct { int methods_without_llvm; char *max_ratio_method; char *biggest_method; + double jit_method_to_ir; + double jit_liveness_handle_exception_clauses; + double jit_handle_out_of_line_bblock; + double jit_decompose_long_opts; + double jit_local_cprop; + double jit_local_emulate_ops; + double jit_optimize_branches; + double jit_handle_global_vregs; + double jit_local_deadce; + double jit_local_alias_analysis; + double jit_if_conversion; + double jit_bb_ordering; + double jit_compile_dominator_info; + double jit_compute_natural_loops; + double jit_insert_safepoints; + double jit_ssa_compute; + double jit_ssa_cprop; + double jit_ssa_deadce; + double jit_perform_abc_removal; + double jit_ssa_remove; + double jit_local_cprop2; + double jit_handle_global_vregs2; + double jit_local_deadce2; + double jit_optimize_branches2; + double jit_decompose_vtype_opts; + double jit_decompose_array_access_opts; + double jit_liveness_handle_exception_clauses2; + double jit_analyze_liveness; + double jit_linear_scan; + double jit_arch_allocate_vars; + double jit_spill_global_vars; + double jit_local_cprop3; + double jit_local_deadce3; + double jit_codegen; + double jit_create_jit_info; + double jit_gc_create_gc_map; + double jit_save_seq_point_info; double jit_time; gboolean enabled; } MonoJitStats; @@ -2332,8 +2370,8 @@ MonoLMF * mono_get_lmf (void); MonoLMF** mono_get_lmf_addr (void); void mono_set_lmf (MonoLMF *lmf); MonoJitTlsData* mono_get_jit_tls (void); -MONO_API MonoDomain *mono_jit_thread_attach (MonoDomain *domain); -MONO_API void mono_jit_set_domain (MonoDomain *domain); +MONO_API gpointer mono_jit_thread_attach (MonoDomain *domain, gpointer *dummy); +MONO_API void mono_jit_thread_detach (gpointer cookie, gpointer *dummy); gint32 mono_get_jit_tls_offset (void); gint32 mono_get_lmf_tls_offset (void); gint32 mono_get_lmf_addr_tls_offset (void); @@ -3008,6 +3046,18 @@ void mono_cfg_add_try_hole (MonoCompile *cfg, MonoExceptionClause *clause, guint void mono_cfg_set_exception (MonoCompile *cfg, int type); void mono_cfg_set_exception_invalid_program (MonoCompile *cfg, char *msg); +#define MONO_TIME_TRACK(a, phase) \ + { \ + GTimer *timer = mono_time_track_start (); \ + (phase) ; \ + mono_time_track_end (&(a), timer); \ + } + +GTimer *mono_time_track_start (void); +void mono_time_track_end (double *time, GTimer *timer); + +void mono_update_jit_stats (MonoCompile *cfg); + gboolean mini_type_is_reference (MonoType *type); gboolean mini_type_is_vtype (MonoType *t) MONO_LLVM_INTERNAL; gboolean mini_type_var_is_vt (MonoType *type) MONO_LLVM_INTERNAL; @@ -3115,6 +3165,11 @@ void mono_cross_helpers_run (void); * Signal handling */ +#ifdef DISABLE_HW_TRAPS + // Signal handlers not available +#define MONO_ARCH_NEED_DIV_CHECK 1 +#endif + void MONO_SIG_HANDLER_SIGNATURE (mono_sigfpe_signal_handler) ; void MONO_SIG_HANDLER_SIGNATURE (mono_sigill_signal_handler) ; void MONO_SIG_HANDLER_SIGNATURE (mono_sigsegv_signal_handler); diff --git a/mono/profiler/mono-profiler-iomap.c b/mono/profiler/mono-profiler-iomap.c index 0dff9e98088..7030a4b3e5f 100644 --- a/mono/profiler/mono-profiler-iomap.c +++ b/mono/profiler/mono-profiler-iomap.c @@ -195,7 +195,7 @@ static inline void print_report (const gchar *format, ...) vfprintf (stdout, format, ap); fprintf (stdout, "\n"); va_end (ap); - klass = mono_class_from_name (mono_get_corlib (), "System", "Environment"); + klass = mono_class_load_from_name (mono_get_corlib (), "System", "Environment"); mono_class_init (klass); prop = mono_class_get_property_from_name (klass, "StackTrace"); str = (MonoString*)mono_property_get_value (prop, NULL, NULL, NULL); diff --git a/mono/tests/load-exceptions.cs b/mono/tests/load-exceptions.cs index 97279d2fb6d..5bfa3a89da5 100644 --- a/mono/tests/load-exceptions.cs +++ b/mono/tests/load-exceptions.cs @@ -350,7 +350,7 @@ public class Tests : LoadMissing { return 2; } - public static int Main () { - return TestDriver.RunTests (typeof (Tests)); + public static int Main (string[] args) { + return TestDriver.RunTests (typeof (Tests), args); } } diff --git a/mono/utils/mono-error.c b/mono/utils/mono-error.c index 768b169079f..c37fc3d16cb 100644 --- a/mono/utils/mono-error.c +++ b/mono/utils/mono-error.c @@ -599,7 +599,7 @@ mono_error_prepare_exception (MonoError *oerror, MonoError *error_out) break; case MONO_ERROR_TYPE_LOAD: - if (error->type_name || error->assembly_name) { + if (error->type_name && error->assembly_name) { type_name = get_type_name_as_mono_string (error, domain, error_out); if (!mono_error_ok (error_out)) break; diff --git a/msvc/mono.def b/msvc/mono.def index e92d3720656..d11059161c5 100644 --- a/msvc/mono.def +++ b/msvc/mono.def @@ -486,7 +486,6 @@ mono_jit_init_version mono_jit_parse_options mono_jit_set_aot_mode mono_jit_set_aot_only -mono_jit_set_domain mono_jit_set_trace_options mono_jit_thread_attach mono_ldstr diff --git a/msvc/monosgen.def b/msvc/monosgen.def index dc32801d088..aaa6969cfff 100644 --- a/msvc/monosgen.def +++ b/msvc/monosgen.def @@ -488,7 +488,6 @@ mono_jit_init_version mono_jit_parse_options mono_jit_set_aot_mode mono_jit_set_aot_only -mono_jit_set_domain mono_jit_set_trace_options mono_jit_thread_attach mono_ldstr diff --git a/scripts/dmcs.in b/scripts/dmcs.in index e86cdf9df09..223dac2e7f6 100755 --- a/scripts/dmcs.in +++ b/scripts/dmcs.in @@ -1,2 +1,3 @@ #!/bin/sh +echo "Note: dmcs is deprecated, please use mcs instead!" exec @bindir@/mono $MONO_OPTIONS @mono_instdir@/4.5/mcs.exe -sdk:4.0 "$@"