From c48b1e214cf448a355a710c742dc376c4eb1bb5b Mon Sep 17 00:00:00 2001 From: Ernst Peter Tamminga Date: Sun, 12 Jul 2015 17:15:23 +0200 Subject: [PATCH] Initial load from CodePlex --- .gitignore | 328 +++--- .hgignore | 8 + App_LocalResources/ExportCSV.ascx.resx | 168 +++ App_LocalResources/FieldEditor.ascx.resx | 261 +++++ App_LocalResources/ImportCSV.ascx.resx | 168 +++ App_LocalResources/configuration.ascx.resx | 629 ++++++++++ App_LocalResources/default.ascx.resx | 138 +++ App_LocalResources/form.ascx.resx | 150 +++ App_LocalResources/helppopup.aspx.resx | 654 +++++++++++ App_LocalResources/list.ascx.resx | 211 ++++ App_LocalResources/settings.ascx.resx | 169 +++ App_LocalResources/sharedresources.resx | 768 ++++++++++++ App_LocalResources/template.ascx.resx | 150 +++ App_LocalResources/templatelist.ascx.resx | 165 +++ App_LocalResources/token2xsl.ascx.resx | 314 +++++ AssemblyInfo.cs | 36 + BuildScripts/MSBuild.Community.Tasks.Targets | 105 ++ BuildScripts/ModulePackage.targets | 149 +++ BusinessController.cs | 423 +++++++ CSV/CSVWriter.cs | 50 + CaptionValueEditor.js | 136 +++ Cleanup_06.00.00.txt | 60 + Components/BaseController.cs | 108 ++ Components/DataProvider.cs | 100 ++ Components/DataTableExtensions.cs | 57 + Components/DnnExtensionMethods.cs | 26 + Components/DownloadPropertyAccess.cs | 102 ++ Components/EditControls.cs | 68 ++ Components/FieldController.cs | 203 ++++ Components/FieldSettingsController.cs | 41 + ...lteredNameValueCollectionPropertyAccess.cs | 47 + Components/FormColumnInfo.cs | 63 + Components/GlobalConstants.cs | 168 +++ Components/GravatarPropertyAccess.cs | 62 + Components/ModuleSecurity.cs | 204 ++++ Components/Settings.cs | 215 ++++ Components/TokenReplace.cs | 35 + Components/TrackingController.cs | 158 +++ Components/UserDefinedTableController.cs | 639 ++++++++++ Components/Utilities.cs | 204 ++++ Components/XSLTemplatingUtilities.cs | 216 ++++ Configuration.ascx.cs | 613 ++++++++++ Configuration.ascx.designer.cs | 717 ++++++++++++ Controls/Field.ascx | 149 +++ Controls/Field.ascx.cs | 430 +++++++ Controls/Field.ascx.designer.cs | 429 +++++++ Controls/FieldSettings.ascx | 15 + Controls/FieldSettings.ascx.cs | 84 ++ Controls/FieldSettings.ascx.designer.cs | 24 + Controls/Fields.ascx | 112 ++ Controls/Fields.ascx.cs | 172 +++ Controls/Fields.ascx.designer.cs | 42 + DataTypes/Abstract/DataType.cs | 380 ++++++ DataTypes/Abstract/EditControl.cs | 306 +++++ DataTypes/Boolean.cs | 160 +++ DataTypes/ChangedAt.cs | 76 ++ DataTypes/ChangedBy.cs | 38 + DataTypes/CreatedAt.cs | 111 ++ DataTypes/CreatedBy.cs | 223 ++++ DataTypes/Currency.cs | 132 +++ DataTypes/Date.cs | 258 ++++ DataTypes/DateTime.cs | 233 ++++ DataTypes/Decimal.cs | 136 +++ DataTypes/Download.cs | 252 ++++ DataTypes/EMail.cs | 192 +++ DataTypes/Expression.cs | 224 ++++ DataTypes/FieldSettingType.cs | 18 + DataTypes/Image.cs | 279 +++++ DataTypes/Int32.cs | 132 +++ DataTypes/LookUp.cs | 202 ++++ DataTypes/Separator.cs | 46 + DataTypes/String.cs | 170 +++ DataTypes/TextHtml.cs | 160 +++ DataTypes/Time.cs | 185 +++ DataTypes/URL.cs | 492 ++++++++ DataTypes/UserLink.cs | 365 ++++++ Default.ascx.cs | 136 +++ Default.ascx.designer.cs | 24 + ExportCSV.ascx | 30 + ExportCSV.ascx.cs | 219 ++++ ExportCSV.ascx.designer.cs | 87 ++ FieldEditor.ascx | 3 + FieldEditor.ascx.cs | 38 + FieldEditor.ascx.designer.cs | 24 + Form.ascx.cs | 574 +++++++++ Form.ascx.designer.cs | 78 ++ FormAndList.csproj | 411 +++++++ FormAndList.dnn | 297 +++++ HelpPopup.aspx.cs | 34 + HelpPopup.aspx.designer.cs | 33 + ImportCSV.ascx | 32 + ImportCSV.ascx.cs | 242 ++++ ImportCSV.ascx.designer.cs | 87 ++ Interfaces/IEmailAdressSource.cs | 9 + Interfaces/IFormEvents.cs | 10 + Interfaces/IPortable2.cs | 11 + Interfaces/IUserSource.cs | 10 + License.htm | 20 + List.ascx.cs | 1034 +++++++++++++++++ List.ascx.designer.cs | 118 ++ MakeThumbnail.ashx.cs | 168 +++ .../sqldataprovider/03.01.00.sqldataprovider | 370 ++++++ .../sqldataprovider/03.01.01.sqldataprovider | 33 + .../sqldataprovider/03.02.00.sqldataprovider | 333 ++++++ .../sqldataprovider/03.03.00.sqldataprovider | 329 ++++++ .../sqldataprovider/03.03.04.sqldataprovider | 119 ++ .../sqldataprovider/03.03.05.sqldataprovider | 86 ++ .../sqldataprovider/03.03.06.sqldataprovider | 39 + .../sqldataprovider/03.03.07.sqldataprovider | 297 +++++ .../sqldataprovider/03.04.00.sqldataprovider | 237 ++++ .../sqldataprovider/03.05.00.sqldataprovider | 68 ++ .../sqldataprovider/04.05.00.sqldataprovider | 193 +++ .../sqldataprovider/05.00.00.sqldataprovider | 77 ++ .../sqldataprovider/05.00.02.sqldataprovider | 58 + .../sqldataprovider/05.01.00.sqldataprovider | 23 + .../sqldataprovider/05.01.01.sqldataprovider | 197 ++++ .../sqldataprovider/05.02.00.sqldataprovider | 216 ++++ .../sqldataprovider/06.00.00.sqldataprovider | 343 ++++++ .../sqldataprovider/06.00.03.sqldataprovider | 22 + .../sqldataprovider/06.00.04.sqldataprovider | 70 ++ .../sqldataprovider/06.00.06.sqldataprovider | 25 + .../sqldataprovider/sqldataprovider.cs | 286 +++++ .../sqldataprovider/uninstall.sqldataprovider | 128 ++ .../ModuleSerializationController.cs | 624 ++++++++++ Settings.ascx.cs | 46 + Settings.ascx.designer.cs | 87 ++ ShowXml.ashx.cs | 77 ++ Template.ascx.cs | 67 ++ Template.ascx.designer.cs | 132 +++ TemplateList.ascx.cs | 192 +++ TemplateList.ascx.designer.cs | 96 ++ Templates/TemplateController.cs | 145 +++ Templates/TemplateInfo.cs | 64 + Templates/TemplateValueInfo.cs | 70 ++ Token2Xsl.ascx.cs | 907 +++++++++++++++ Token2Xsl.ascx.designer.cs | 600 ++++++++++ UserDefinedTable.sln | 26 + UserDefinedTable.vs2013.sln | 22 + configuration.ascx | 256 ++++ datatypes.config | 32 + default.ascx | 2 + form.ascx | 44 + helppopup.aspx | 18 + icon_fnl_32px.gif | Bin 0 -> 2422 bytes list.ascx | 39 + makethumbnail.ashx | 1 + module.css | 71 ++ releasenotes.htm | 74 ++ settings.ascx | 35 + showxml.ashx | 1 + template.ascx | 42 + templatelist.ascx | 42 + token2xsl.ascx | 294 +++++ xslstylesheets/tracking/auto.xsl | 103 ++ xslstylesheets/xslscripts.xml | 345 ++++++ 155 files changed, 27192 insertions(+), 153 deletions(-) create mode 100644 .hgignore create mode 100644 App_LocalResources/ExportCSV.ascx.resx create mode 100644 App_LocalResources/FieldEditor.ascx.resx create mode 100644 App_LocalResources/ImportCSV.ascx.resx create mode 100644 App_LocalResources/configuration.ascx.resx create mode 100644 App_LocalResources/default.ascx.resx create mode 100644 App_LocalResources/form.ascx.resx create mode 100644 App_LocalResources/helppopup.aspx.resx create mode 100644 App_LocalResources/list.ascx.resx create mode 100644 App_LocalResources/settings.ascx.resx create mode 100644 App_LocalResources/sharedresources.resx create mode 100644 App_LocalResources/template.ascx.resx create mode 100644 App_LocalResources/templatelist.ascx.resx create mode 100644 App_LocalResources/token2xsl.ascx.resx create mode 100644 AssemblyInfo.cs create mode 100644 BuildScripts/MSBuild.Community.Tasks.Targets create mode 100644 BuildScripts/ModulePackage.targets create mode 100644 BusinessController.cs create mode 100644 CSV/CSVWriter.cs create mode 100644 CaptionValueEditor.js create mode 100644 Cleanup_06.00.00.txt create mode 100644 Components/BaseController.cs create mode 100644 Components/DataProvider.cs create mode 100644 Components/DataTableExtensions.cs create mode 100644 Components/DnnExtensionMethods.cs create mode 100644 Components/DownloadPropertyAccess.cs create mode 100644 Components/EditControls.cs create mode 100644 Components/FieldController.cs create mode 100644 Components/FieldSettingsController.cs create mode 100644 Components/FilteredNameValueCollectionPropertyAccess.cs create mode 100644 Components/FormColumnInfo.cs create mode 100644 Components/GlobalConstants.cs create mode 100644 Components/GravatarPropertyAccess.cs create mode 100644 Components/ModuleSecurity.cs create mode 100644 Components/Settings.cs create mode 100644 Components/TokenReplace.cs create mode 100644 Components/TrackingController.cs create mode 100644 Components/UserDefinedTableController.cs create mode 100644 Components/Utilities.cs create mode 100644 Components/XSLTemplatingUtilities.cs create mode 100644 Configuration.ascx.cs create mode 100644 Configuration.ascx.designer.cs create mode 100644 Controls/Field.ascx create mode 100644 Controls/Field.ascx.cs create mode 100644 Controls/Field.ascx.designer.cs create mode 100644 Controls/FieldSettings.ascx create mode 100644 Controls/FieldSettings.ascx.cs create mode 100644 Controls/FieldSettings.ascx.designer.cs create mode 100644 Controls/Fields.ascx create mode 100644 Controls/Fields.ascx.cs create mode 100644 Controls/Fields.ascx.designer.cs create mode 100644 DataTypes/Abstract/DataType.cs create mode 100644 DataTypes/Abstract/EditControl.cs create mode 100644 DataTypes/Boolean.cs create mode 100644 DataTypes/ChangedAt.cs create mode 100644 DataTypes/ChangedBy.cs create mode 100644 DataTypes/CreatedAt.cs create mode 100644 DataTypes/CreatedBy.cs create mode 100644 DataTypes/Currency.cs create mode 100644 DataTypes/Date.cs create mode 100644 DataTypes/DateTime.cs create mode 100644 DataTypes/Decimal.cs create mode 100644 DataTypes/Download.cs create mode 100644 DataTypes/EMail.cs create mode 100644 DataTypes/Expression.cs create mode 100644 DataTypes/FieldSettingType.cs create mode 100644 DataTypes/Image.cs create mode 100644 DataTypes/Int32.cs create mode 100644 DataTypes/LookUp.cs create mode 100644 DataTypes/Separator.cs create mode 100644 DataTypes/String.cs create mode 100644 DataTypes/TextHtml.cs create mode 100644 DataTypes/Time.cs create mode 100644 DataTypes/URL.cs create mode 100644 DataTypes/UserLink.cs create mode 100644 Default.ascx.cs create mode 100644 Default.ascx.designer.cs create mode 100644 ExportCSV.ascx create mode 100644 ExportCSV.ascx.cs create mode 100644 ExportCSV.ascx.designer.cs create mode 100644 FieldEditor.ascx create mode 100644 FieldEditor.ascx.cs create mode 100644 FieldEditor.ascx.designer.cs create mode 100644 Form.ascx.cs create mode 100644 Form.ascx.designer.cs create mode 100644 FormAndList.csproj create mode 100644 FormAndList.dnn create mode 100644 HelpPopup.aspx.cs create mode 100644 HelpPopup.aspx.designer.cs create mode 100644 ImportCSV.ascx create mode 100644 ImportCSV.ascx.cs create mode 100644 ImportCSV.ascx.designer.cs create mode 100644 Interfaces/IEmailAdressSource.cs create mode 100644 Interfaces/IFormEvents.cs create mode 100644 Interfaces/IPortable2.cs create mode 100644 Interfaces/IUserSource.cs create mode 100644 License.htm create mode 100644 List.ascx.cs create mode 100644 List.ascx.designer.cs create mode 100644 MakeThumbnail.ashx.cs create mode 100644 Providers/DataProviders/sqldataprovider/03.01.00.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/03.01.01.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/03.02.00.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/03.03.00.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/03.03.04.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/03.03.05.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/03.03.06.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/03.03.07.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/03.04.00.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/03.05.00.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/04.05.00.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/05.00.00.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/05.00.02.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/05.01.00.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/05.01.01.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/05.02.00.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/06.00.00.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/06.00.03.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/06.00.04.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/06.00.06.sqldataprovider create mode 100644 Providers/DataProviders/sqldataprovider/sqldataprovider.cs create mode 100644 Providers/DataProviders/sqldataprovider/uninstall.sqldataprovider create mode 100644 Serialization/ModuleSerializationController.cs create mode 100644 Settings.ascx.cs create mode 100644 Settings.ascx.designer.cs create mode 100644 ShowXml.ashx.cs create mode 100644 Template.ascx.cs create mode 100644 Template.ascx.designer.cs create mode 100644 TemplateList.ascx.cs create mode 100644 TemplateList.ascx.designer.cs create mode 100644 Templates/TemplateController.cs create mode 100644 Templates/TemplateInfo.cs create mode 100644 Templates/TemplateValueInfo.cs create mode 100644 Token2Xsl.ascx.cs create mode 100644 Token2Xsl.ascx.designer.cs create mode 100644 UserDefinedTable.sln create mode 100644 UserDefinedTable.vs2013.sln create mode 100644 configuration.ascx create mode 100644 datatypes.config create mode 100644 default.ascx create mode 100644 form.ascx create mode 100644 helppopup.aspx create mode 100644 icon_fnl_32px.gif create mode 100644 list.ascx create mode 100644 makethumbnail.ashx create mode 100644 module.css create mode 100644 releasenotes.htm create mode 100644 settings.ascx create mode 100644 showxml.ashx create mode 100644 template.ascx create mode 100644 templatelist.ascx create mode 100644 token2xsl.ascx create mode 100644 xslstylesheets/tracking/auto.xsl create mode 100644 xslstylesheets/xslscripts.xml diff --git a/.gitignore b/.gitignore index 57a1574..d75c90d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,51 +1,32 @@ +################# +## Visual Studio +################# + ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. # User-specific files *.suo *.user -*.userosscache *.sln.docstates +*.local.sln +*.sln.GhostDoc.xml -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -build/ -bld/ -[Bb]in/ -[Oo]bj/ - -# Visual Studo 2015 cache/options directory +## Ignore VS2015/Roslyn artifacts +*.sln.ide/ .vs/ -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c +## Ignore Webstorm artifacts +*.idea/ +# Build results +[Rr]elease *_i.c *_p.c -*_i.h *.ilk *.meta *.obj *.pch -*.pdb *.pgc *.pgd *.rsp @@ -54,143 +35,184 @@ dlldata.c *.tli *.tlh *.tmp -*.tmp_proj -*.log +*.eml *.vspscc -*.vssscc .builds -*.pidb -*.svclog -*.scc +*.dotCover +*.ldf -# Chutzpah Test files -_Chutzpah* +# git merge artifacts +*.orig +*.gitmodules -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opensdf -*.sdf -*.cachefile +## TODO: If you have NuGet Package Restore enabled, uncomment this +[Pp]ackages/ # Visual Studio profiler *.psess *.vsp -*.vspx - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState # ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding addin-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# NCrunch -_NCrunch_* -.*crunch*.local.xml - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# TODO: Comment the next line if you want to checkin your web deploy settings -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/packages/* -# except build/, which is used as an MSBuild target. -!**/packages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config - -# Windows Azure Build Output -csx/ -*.build.csdef - -# Windows Store app package directory -AppPackages/ +_ReSharper* # Others -*.[Cc]ache -ClientBin/ -[Ss]tyle[Cc]op.* + +[Oo]bj +TestResults +*.Cache +ClientBin +stylecop.* ~$* -*~ *.dbmdl -*.dbproj.schemaview -*.pfx -*.publishsettings -node_modules/ -bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) +Generated_Code #added for RIA/Silverlight projects + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML -UpgradeLog*.htm - -# SQL Server files -*.mdf -*.ldf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings - -# Microsoft Fakes -FakesAssemblies/ - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat - -# Visual Studio 6 build log -*.plg -# Visual Studio 6 workspace options file -*.opt +############ +## DNN +############ + +# Ignore artifacts from deployed/installed site + +DNN_*.zip + +!DNN [Pp]latform/[Cc]omponents +!DNN [Pp]latform/[Cc]ontrols +DNN [Pp]latform/[Cc]omponents/[Cc]lient[Dd]ependency/[Ss]ource/[Bb]in +DNN [Pp]latform/[Cc]ontrols/[Cc]ountry[Ll]ist[Bb]ox/[Bb]in/* + +DNN [Pp]latform/*/[Bb]in +DNN [Pp]latform/Tests/*/[Bb]in/* +DNN [Pp]latform/Modules/*/[Bb]in/* +DNN [Pp]latform/Admin Modules/*/[Bb]in/* +DNN [Pp]latform/MVC Modules/*/[Bb]in/* +DNN [Pp]latform/[Pp]roviders/*/*/[Bb]in/* +DNN [Pp]latform/[Pp]roviders/*/*/*/[Bb]in/* +DNN [Pp]latform/Syndication/[Bb]in/* + + +[Ww]ebsite/*/[Dd]efault.aspx + +[Ww]ebsite/[Aa]dmin/[Pp]ersonabar + +[Ww]ebsite/[Aa]pp_[Cc]ode + +[Ww]ebsite/[Aa]pp_[Dd]ata + +[Ww]ebsite/[Bb]in + +[Ww]ebsite/[Cc]onfig + +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]dmin/[Ff]ifty[Oo]ne[Cc]lient[Cc]apability[Pp]rovider +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]dmin/[Rr]ad[Ee]ditor[Pp]rovider +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]dmin/[Tt]axonomy +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]dmin/[Uu]rl[Mm]anagement +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]dmin/[Hh]tml[Ee]ditor[Mm]anager +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]dmin/[Rr]ecycle[Bb]in +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]dmin/[Nn]ewsletters + +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]uthentication[Ss]ervices/[Ff]acebook +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]uthentication[Ss]ervices/[Gg]oogle +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]uthentication[Ss]ervices/[Ll]ive +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]uthentication[Ss]ervices/[Tt]witter +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]uthentication[Ss]ervices/DNN[Pp]ro_[Aa]ctive[Dd]irectory + +[Ww]ebsite/[Dd]esktop[Mm]odules/[Cc]ore[Mm]essaging +[Ww]ebsite/[Dd]esktop[Mm]odules/DDRMenu +[Ww]ebsite/[Dd]esktop[Mm]odules/[Dd]evice[Pp]review[Mm]anagement +[Ww]ebsite/[Dd]esktop[Mm]odules/[Dd]igital[Aa]ssets +[Ww]ebsite/[Dd]esktop[Mm]odules/DNNCorp +[Ww]ebsite/[Dd]esktop[Mm]odules/[Dd][Nn][Nn] +[Ww]ebsite/[Dd]esktop[Mm]odules/HTML +[Ww]ebsite/[Dd]esktop[Mm]odules/MVC +[Ww]ebsite/[Dd]esktop[Mm]odules/[Jj]ournal +[Ww]ebsite/[Dd]esktop[Mm]odules/[Mm]ember[Dd]irectory +[Ww]ebsite/[Dd]esktop[Mm]odules/[Mm]obile[Mm]anagement +[Ww]ebsite/[Dd]esktop[Mm]odules/[Rr]azor[Mm]odules +[Ww]ebsite/[Dd]esktop[Mm]odules/[Ss]ocial[Gg]roups +[Ww]ebsite/[Dd]esktop[Mm]odules/[Ss]ubscriptions[Mm]gmt +[Ww]ebsite/[Dd]esktop[Mm]odules/[Ii]dentity[Ss]witcher +[Ww]ebsite/[Dd]esktop[Mm]odules/[Bb]log +[Ww]ebsite/[Dd]esktop[Mm]odules/[Ii][Ff]rame +[Ww]ebsite/[Dd]esktop[Mm]odules/[Aa]nnouncements +[Ww]ebsite/[Dd]esktop[Mm]odules/[Ee]vents +[Ww]ebsite/[Dd]esktop[Mm]odules/[Ff]eedback +[Ww]ebsite/[Dd]esktop[Mm]odules/[Ff][Aa][Qq]s +[Ww]ebsite/[Dd]esktop[Mm]odules/[Mm]edia +[Ww]ebsite/[Dd]esktop[Mm]odules/[Uu]ser[Dd]efined[Tt]able +[Ww]ebsite/[Dd]esktop[Mm]odules/dnnGlimpse +[Ww]ebsite/[Dd]esktop[Mm]odules/[Tt]est* + +[Ww]ebsite/[Ii]nstall/*/*.zip +[Ww]ebsite/[Ii]nstall/*/*.resources +[Ww]ebsite/[Ii]nstall/[Cc]leanup +[Ww]ebsite/[Ii]nstall/[Cc]onfig +[Ww]ebsite/[Ii]nstall/[Dd]ot[Nn]et[Nn]uke.install.config +[Ww]ebsite/[Ii]nstall/installstat.log.resources.txt +[Ww]ebsite/[Ii]nstall/upgradestat.log.resources.txt + +[Ww]ebsite/[Ll]icenses/*.txt + +[Ww]ebsite/[Mm]odules + +[Ww]ebsite/[Pp]ortals/_default/[Ll]ogs +[Ww]ebsite/[Pp]ortals/_default/[Mm]erged[Tt]emplate +[Ww]ebsite/[Pp]ortals/_default/[Bb]lank [Ww]ebsite*.* +[Ww]ebsite/[Pp]ortals/_default/[Dd]efault [Ww]ebsite*.* +[Ww]ebsite/[Pp]ortals/_default/[Mm]obile [Ww]ebsite*.* +[Ww]ebsite/[Pp]ortals/_default/[Cc]ontainers/*/thumbnail*.jpg +[Ww]ebsite/[Pp]ortals/_default/[Cc]ontainers/[Cc]avalier/*.* +[Ww]ebsite/[Pp]ortals/_default/[Ss]kins/*/thumbnail*.jpg +[Ww]ebsite/[Pp]ortals/_default/[Ss]kins/[Cc]avalier +[Ww]ebsite/[Pp]ortals/_default/[Ss]kins/[Cc]avalier/*/*.* + +[Ww]ebsite/[Pp]ortals/_default/[Uu]ser* +[Ww]ebsite/[Pp]ortals/[0-9]*/ + +[Ww]ebsite/[Pp]roviders/[Dd]ata[Pp]roviders/*/*.resources +[Ww]ebsite/[Pp]roviders/*/*/license.txt +[Ww]ebsite/[Pp]roviders/*/*/release[Nn]otes.txt +[Ww]ebsite/[Pp]roviders/[Ff]older[Pp]roviders + +[Ww]ebsite/[Rr]esources/[Ll]ibraries + +[Ww]ebsite/[Ss]ignatures + +[Ww]ebsite/51[Dd]egrees.mobi.config +[Ww]ebsite/[Dd]ot[Nn]et[Nn]uke.log4net.config +[Ww]ebsite/[Dd]ot[Nn]et[Nn]uke.config +[Ww]ebsite/[Ss]ite[Aa]nalytics.config +[Ww]ebsite/[Ss]ite[Uu]rls.config +[Ww]ebsite/web.config +[Ww]ebsite/app_offline.htm + +# ignore all other language resx files +*.de-DE.resx +*.es-ES.resx +*.fr-FR.resx +*.it-IT.resx +*.nl-NL.resx + +# but do track translations in the Install folder +![Ww]ebsite/[Ii]nstall/[Aa]pp_[Ll]ocal[Rr]esources/*.de-DE.resx +![Ww]ebsite/[Ii]nstall/[Aa]pp_[Ll]ocal[Rr]esources/*.es-ES.resx +![Ww]ebsite/[Ii]nstall/[Aa]pp_[Ll]ocal[Rr]esources/*.fr-FR.resx +![Ww]ebsite/[Ii]nstall/[Aa]pp_[Ll]ocal[Rr]esources/*.it-IT.resx +![Ww]ebsite/[Ii]nstall/[Aa]pp_[Ll]ocal[Rr]esources/*.nl-NL.resx + +*.zip.manifest + +############ +## Windows +############ + +# Windows image file caches +Thumbs.db + +# Folder config file +Desktop.ini +Website/Install/Temp/ diff --git a/.hgignore b/.hgignore new file mode 100644 index 0000000..7f8a129 --- /dev/null +++ b/.hgignore @@ -0,0 +1,8 @@ +syntax: glob +Backup/* +_ReSharper.*/* +obj/* +_UpgradeReport_Files/* +*suo +*csproj.user +DotNetNuke.Modules.UserDefinedTable.xml diff --git a/App_LocalResources/ExportCSV.ascx.resx b/App_LocalResources/ExportCSV.ascx.resx new file mode 100644 index 0000000..7142bc9 --- /dev/null +++ b/App_LocalResources/ExportCSV.ascx.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Folder + + + Select the export folder + + + File + + + Enter the export filename + + + Export + + + Export to CSV File + + + <h1>Export to CSV File</h1><p>Administrators can export content into a CSV file.</p> + + + The module specified does not have any content + + + The module specified does not support the exporting of content + + + An error occurred during the export + + + You must specify a folder and file for export + + + Root + + + Fields are separated with delimiter characters, and each row is saved in a new line. Commas and semicolons are widely used. The default delimiter usually depends on your country setting. + + + Delimiter + + + Comma "," + + + Semicolon ";" + + \ No newline at end of file diff --git a/App_LocalResources/FieldEditor.ascx.resx b/App_LocalResources/FieldEditor.ascx.resx new file mode 100644 index 0000000..2c38f8f --- /dev/null +++ b/App_LocalResources/FieldEditor.ascx.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + This is the Help Text displayed to the user to explain this field. + + + Help Text + + + This setting enforces an input for this field. + + + Required + + + The field is only shown in the form if the user fullfils the corresponding permission. + + + Restricted Form Field + + + Indicates whether this field should be included in the module Search. This setting has no influence whether the field gets indexed for the side wide search. + + + Searchable + + + The type of the field controls controls the form elements and the content displayed in the list. + + + Type + + + Title + + + Title of the field + + + Title is required! + + + Field Editor + + + This setting decides whether this field gets hidden by default in a normal grid view. By default it gets still shown to Administrators (which can be overridden in Module Settings). <br>This setting acts just as a marker within XSLT scripts - it is up to the script editor to control the desired behavior. + + + Display on List + + + Cancel + + + Caption + + + Edit + + + Edit + + + Remove + + + Add + + + Save + + + Value + + + Save + + + Field title has to be unique + + + You have changed the Field type for <b>{2}</b> from "{0}" to "{1}". Note that this might cause an error, this is an unsupported cast! + + + Column title MUST NOT contain any of these characters: *:,? + + + This message will be displayed if the user entered value violates the Validation Rule. + + + Validation Message + + + This Regular Expression is used to validate the value entered by the user. Failure to match this Regular Expression will prevent the record from being updated. + + + Validation Rule + + + Style which is applied on text box or list control in form, for example to change width set "width:300px;min-width:300px;" + + + CSS Style + + + (Placeholder, please translate in sharedResources.resx per datatype!) + + + (Placeholder, please translate in sharedResources.resx per datatype!) + + + (Placeholder, please translate in sharedResources.resx per datatype!) + + + (Placeholder, please translate in sharedResources.resx per datatype!) + + + (Placeholder, please translate in sharedResources.resx per datatype!) + + + (Placeholder, please translate in sharedResources.resx per datatype!) + + + Dropdown-List + + + Radio buttons (vert.) + + + Radio buttons (hor.) + + + Hidden Columns Help + + + Available Tokens Help + + + Form Settings + + + List Settings + + \ No newline at end of file diff --git a/App_LocalResources/ImportCSV.ascx.resx b/App_LocalResources/ImportCSV.ascx.resx new file mode 100644 index 0000000..76c0870 --- /dev/null +++ b/App_LocalResources/ImportCSV.ascx.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Folder + + + Select the folder + + + File + + + Select the file to import. + + + Import + + + Import CSV File + + + <h1>Import CSV</h1><p>Administrators can import content out of a CSV file into a Form and List Module. The process will delete any existing data inside the module.</p> + + + The module specified does not have any content + + + An error occurred during the export + + + You must specify a folder and file for Import + + + Root + + + Error occured during Import operation. Please make sure that you have fully valid CSV file and the delimiter is correct for this file. {0} + + + Fields are separated with delimiter characters, and each row is saved in a new line. Commas and semicolons are widely used. The default delimiter usually depends on your country setting. + + + Delimiter + + + Comma "," + + + Semicolon ";" + + \ No newline at end of file diff --git a/App_LocalResources/configuration.ascx.resx b/App_LocalResources/configuration.ascx.resx new file mode 100644 index 0000000..c728f10 --- /dev/null +++ b/App_LocalResources/configuration.ascx.resx @@ -0,0 +1,629 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Ascending + + + Add New Column + + + Apply + + + Show XSL source code + + + Save Configuration and Return + + + Show Table Data as XML + + + Generate New + + + Edit + + + This is the Help Text displayed to the user to explain this field. + + + Help Text + + + Form and List Configuration + + + Default Grid Table + + + Are you sure you wish to delete this column? + + + Descending + + + <h1>Form and List Configuration</h1> +<p>The <strong>Form and List </strong> module stores its data inside a table. The table and its columns are defined by the user, which is the origin of the former name for this module: "User Defined Table". The following data types are available for defining columns:</p> +<ul> + <li>Text</li> + <li>Rich Text (HTML)</li> + <li>Integer </li> + <li>Decimal </li> + <li>Date and Time </li> + <li>Date </li> + <li>Time </li> + <li>True/false </li> + <li>Email </li> + <li>Currency </li> + <li>URL Link</li> + <li>Image </li> + <li>User </li> + <li>Download </li> + <li>LookUp </li> + <li>Calculated Column</li> +</ul> +<p>Individual columns can be configured&#160;visible only&#160;for site Administrator accounts&#160;or&#160;visible by specific&#160;Roles&#160;granted&#160;permission to see all columns. You can specify a column default value and designate if a value is required or optional.</p> +<p>For the default Grid Table Display Setting, column headings are also links that when clicked, reorder the column&#160;data alphanumerically from&#160;A-Z or Z-A. You can predefine a sorting column,&#160;and by specifying a page size, you may activate the built-in multi-paging controls. For&#160;type URL column, you can specify static link text, and for images, you may preset&#160;the maximum display size so all&#160;images get scaled proportionally to fit.</p> +<h1>Quick Start: Setup Form and List</h1> +<ol> + <li>Add a new instance of Form and List to an existing page;</li> + <li>Select <strong>Form and List Configuration </strong>from the module's Action Menu;</li> + <li>Click <strong>Add New Column</strong>;</li> + <li>Enter a <strong>Title</strong> for the column that will be displayed as column header. Note&#160;that some special characters are not allowed in Title names;</li> + <li>Choose the desired data<strong> Type</strong> for this column;</li> + <li>(Optional) Enable <strong>Required</strong> if every record should&#160;contain&#160;data for this column;</li> + <li>(Optional) Enable <strong>Visible</strong> if this column should be visible in List View&#160;for all users.&#160;If disabled,&#160;only Administrators and&#160;Roles granted module Permission Grid rights to&#160;<strong>Display All Columns</strong> will see this column in List View. Note that this setting only affects&#160;List View.</li> + <li>(Optional) Enable <strong>Searchable</strong> if you wish the Module&#160;Search function to search this column.</li> + <li>(Optional) <strong>Advanced Column Options</strong> allow you to specifically tailor each column with powerful added functionality. Click the Help tooltip (?) for more information on Advanced Column Options;</li> + <li>Click <strong>Save Settings and Return</strong>.</li> +</ol> +<h1>More Features</h1> +<ul> + <li>Use the&#160;<strong>Move Column Up </strong>and <strong>Move&#160;Column Down</strong> arrows to determine the order of&#160;columns</li> + <li>Specify <strong>Columns Settings</strong> to manage popup browser windows and to control image sizing</li> + <li>Access&#160;<strong>Display Settings</strong> to choose options for advanced&#160;<strong>Rendering Method </strong>options including build-in XSL Transformation templates, or even use your own self made XSLT stylesheets&#160;</li> + <li>Select the <strong>Sort&#160;Column</strong> and specific the <strong>Sort Direction</strong> (ascending/descending)</li> + <li>Activate multi-paging functionality by choosing a <strong>Paging</strong> value from the dropdown list</li> + <li>Select&#160;which <strong>CSS Classes</strong> should be applied to the Default Grid Display</li> + <li>Using SQL, you may choose to&#160;<strong>Filter</strong> which records&#160;will appear in this module instance</li> + <li>You may&#160;enable the <strong>Search</strong> function. Enable <strong>Show Search Box</strong>, then choose options to <strong>Show no records until Search</strong> and enable&#160;<strong>Simple Search</strong> to display only&#160;a Search Box (and help). Disable Simple Search for more detailed search&#160;conditional&#160;options</li> +</ul> +<p>You can display Form and List data in any layout&#160;or format&#160;you choose using XML&#160;and XSL style sheets. The module includes a set of built in XSL Transformation (XSLT) files that you may use as a starting point to creating more advanced and customized XSLT of your own. XSL Transformations offer you maximum&#160;flexibility for presenting &#160;your data.</p> +<p>Two very powerful options are available for helping you work with XSL transformations. These features are especially useful for debugging and learning more about XSL transformations syntax.</p> +<ol> + <li>Choose <strong>Display Settings</strong> &gt; Rendering Method: <strong>XSLT using built-in stylesheets</strong>, then select a <strong>XSL File </strong>from the dropdown list</li> + <li>Click <strong>Show XSL source code </strong>to view the XSL</li> +</ol> +<p align="center">-or-</p> +<ol> + <li>Choose <strong>Display Settings</strong> &gt; Rendering Method: <strong>XSLT using self made stylesheets</strong></li> + <li>Click <strong>Generate New</strong></li> +</ol> + + + <no paging> + + + Specify which CSS classes will be assigned to the Default Grid Table. + + + CSS Classes + + + Enter a <a href="http://msdn.microsoft.com/library/system.data.datacolumn.expression.aspx" target=”_blank">filter expression</a> which a record must match to be displayed,. If your column name has spaces or special characters, surround the column name with [brackets]. Example: [fieldname] ='value'. + + + Filter statement + + + Specify the default sort order direction, either Ascending (low to high) or Descending (high to low). + + + Sort Direction + + + To enable paging, specify the number of items to display per page. + + + Paging + + + Choose to display data using a Default Grid Table or by applying a self made or built-in XSL script. + + + Rendering Method + + + Show Search Box + + + Display a text box above the data grid to allow users to search for data in the columns specified as Searchable. + + + Specify a default sort column. This sort order is overridden when the user clicks the heading of another column. + + + Sort Column + + + Show full path, when displaying a link to an external URL, file with folders and tabs with path? Otherwise file name / page name is displayed only. + + + Show full path? + + + Specify the location of an XSL file or create a new one. + + + XSL script + + + Form Settings + + + Appearance: + + + List or Form mode, this setting applies to the current page only. + + + Displayed text after form post: + + + Enter text to display to the user after the Form "Submit" is clicked. + + + List + + + Form + + + Required + + + Save + + + Show on Edit Form? + + + If enabled, value will be displayed to all users when editing. + + + Column title contains special characters like "*", ":", "," or "?" + + + Title + + + True/False + + + Type + + + Column title contains "_UDT_" + + + Column title has to be unique + + + Display<br/>on List + + + XSLT + + + Generate XSL Stylesheet using a Token language + + + Searchable + + + Show no records until Search + + + Enable to display no records until a search is performed. Click the Search link with no criteria to display all records. + + + Simple Search + + + Enable a simple, single field search. + + + Available Tokens Help + + + Hidden Columns Help + + + Edit Tracking Message + + + Edit + + + Generate new Tracking Message + + + Generate New + + + Enter one or more email addresses, separated by semicolon ";" or enclosed in [brackets]. You may enter the column Title name for column types Email, Created By, Changed By, User Link, e.g. admin@domain.com;[Created By];[Secondary Email] + + + To + + + Enter the body of the notification email message. + + + Email Message + + + Enter a Subject for the notification email. You can also use [field:<em>columnname</em>] or commen [tokens] within the Subject field. + + + Subject + + + Your submission was successful. + + + Drop Down List + + + Radio Button List (vertical) + + + Auto + + + XSL Script + + + The body of the email can be created automatically using the message and text fields above or created by a self made customizable XSL script. + + + Email Body Creation + + + Choose which actions will trigger a notification email. + + + Trigger + + + Specify the location of a XSL file or create a new one. + + + Email XSL script + + + On Delete + + + On New + + + On Update + + + Delete All Records + + + Are you sure you wish to delete all records stored in this table? + + + Reset to default Configuration + + + Are you sure you wish to reset all page related settings for this module? + + + Save Configuration as default + + + Enable this setting to include URL paths in search. + + + Search URL Paths + + + If you want to limit the number of records returned, enter a number between 1 and 1000 and only the first records will be displayed (according to Sorting Options). + + + Records Returned + + + Please enter a valid integer number between 1 and 1000! + + + Search and Filter Options: + + + Sorting Options: + + + Please apply also "Create Record/Submit Form" permissions in Module Settings! + + + Optional message to display in the body of the notification email, on Delete. + + + On Delete Text + + + Optional message to display in the body of the notification email, on New. + + + On New Text + + + Optional message to display in the body of the notification email, on Update. + + + On Update Text + + + RBL (horizontal) + + + Tracking/Notification issue: Field {0} is either not a valid source for email adresses or it was not found inside fields definitions. + + + Data Table Setup + + + Specify the "User Defined Table" columns you wish to include in your Form or List. + + + Page or URL you want to redirect the user after submission + + + Redirect upon submit + + + Show Form and Text + + + Redirect to another page + + + Show Text only + + + Action upon submit + + + Action upon submit: + + + Tracking/Notification issue: {0} is not a valid email address. If you want to add a field, please surround your input with square brackets. + + + Restricted<br/>Form Field + + + Form above List + + + Form below List + + + By default, List is shown if "Form above List" or "Form below List" is selected. If this setting is enabled, it is controlled by "List View" permission. In "Form" mode, the permission will control also the module action "Show Records". + + + Is List view restricted by Permission? + + + Enter one or more email addresses, separated by semicolon ";" or enclosed in [brackets]. You may enter the column Title name for column types Email, Created By, Changed By, User Link, e.g. admin@domain.com;[Created By];[Secondary Email] + + + BCC + + + Enter one or more email addresses, separated by semicolon ";" or enclosed in [brackets]. You may enter the column Title name for column types Email, Created By, Changed By, User Link, e.g. admin@domain.com;[Created By];[Secondary Email] + + + CC + + + Schema Definition + + + Page Related Settings + + + Cancel + + + Email Settings + + + List Settings + + + Enable this setting to keep the data of this modul confidential, When enabled, data will be excluded from the website search index. + + + Exclude module content from search: + + + DataType "{0}" is not installed. Please either check DataTypes.Config or change the type of the matching fields. + + + Style which is applied on text box or list control in form, e.g. "width:300px" + + + CSS Style + + + Sender email address for the notification message. Only set a value if you know exactly what you are doing! Customizing this setting, you risk the chance that notification emails will be treated as unsolicited SPAM. ReplyTo is the safest option to customize for most situations. If you are unsure, leave this setting blank and the email address of the portal administrator will be used. + + + From (overrides default) + + + Email address used to reply to the notification message. If you are unsure, leave this setting blank and the email address of the portal administrator will be used. + + + ReplyTo (overrides default) + + + Add + + + Cancel + + + Caption + + + Edit + + + Edit + + + Remove + + + Save + + + Value + + + Actions as Buttons instead of ActionMenu commands + + + Actions as Buttons + + + Current View Options + + + No settings for this configuration + + \ No newline at end of file diff --git a/App_LocalResources/default.ascx.resx b/App_LocalResources/default.ascx.resx new file mode 100644 index 0000000..46baa5d --- /dev/null +++ b/App_LocalResources/default.ascx.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <h1>About the Form and List Module</h1> +<p>The Form and List Module allows you to manage an individual table of data, where each column of data is a specific data type and each row represents a single record.&#160;Column headings, when clicked, reorder data alphanumerically&#160;A-Z or Z-A. If the feature is enabled, you may <strong>Search</strong> through records that contain only select data.</p> +<p>If granted permission by the site Administrator,&#160;you can <strong>Add&#160;New Record</strong> and&#160;optionally&#160;<strong>Edit</strong>&#160;and <strong>Delete</strong> any records or only those records you have added yourself. If you have the ability to&#160;add or edit records without being logged in this site, you may need to enter a CAPTCHA confirmation code.</p> +<p>Page Administrators can edit <strong>Module Settings</strong> and select <strong>Form and List Configuration</strong> from the module Action Menu to define columns and column properties.</p> + + + Save as Template + + + Form and List Configuration + + + Export to CSV file + + + Import from CSV file + + \ No newline at end of file diff --git a/App_LocalResources/form.ascx.resx b/App_LocalResources/form.ascx.resx new file mode 100644 index 0000000..c7bf4e2 --- /dev/null +++ b/App_LocalResources/form.ascx.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Edit Record + + + <h1>About Form and List Module - Edit Records</h1> +<p>The Form and List module allows you to define an individual table of data. On this page you can add or edit&#160;records&#160;that contain columns that have been previously defined by a site or page&#160;Administrator in <strong>Form and List Configuration</strong>.&#160;</p> +<p>Depending on the&#160;column type definition, you can enter a value&#160;in a field or&#160;select a value from a dropdown list. Some&#160;columns&#160;have special&#160;entry functions, for example, with <strong>Date</strong> columns,&#160;you can select a date from a&#160;popup calendar. To enter a&#160;<strong>Link </strong>you can choose between an external URL, a link to a page or&#160;a link to a file stored on this site. When you choose <strong>File</strong>&#160;to&#160;link to a local file, you may choose to upload a file to the site.</p> +<p>Click <strong>Update</strong> to save your changes, or click&#160;<strong>Cancel</strong> to undo the changes you have made. If the site Administrator has granted permissions, you may&#160;<strong>D</strong><strong>elete</strong>&#160;the current record. If you are adding or editing&#160;records and&#160;you are not&#160;logged into the site, you might need to verify your changes by entering a CAPTCHA&#160;security code.</p> + + + Form and List Configuration + + + Show Records + + + Security Code + + + Submit + + + Security Code entered is not the same as displayed or empty. + + + CAPTCHA - Completely Automated Public Turing + + + Cancel + + \ No newline at end of file diff --git a/App_LocalResources/helppopup.aspx.resx b/App_LocalResources/helppopup.aspx.resx new file mode 100644 index 0000000..519ae7e --- /dev/null +++ b/App_LocalResources/helppopup.aspx.resx @@ -0,0 +1,654 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Available Tokens Reference + + + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" > +<head> + <title></title> +</head> +<body> +<div> +<table cellspacing="3" cellpadding="2" width="100%" summary="" border="0"> +<colgroup> +<col class="UDT_Help_RowHead" /> +<col class="UDT_Help_Row" /> +</colgroup> +<thead> +<tr> +<td class="UDT_Help_ColHead">Token</td> +<td class="UDT_Help_ColHead">Description</td> +</tr> +</thead> +<tbody> +<tr> +<td>[Portal:Currency]</td> +<td>Currency String</td> +</tr> +<tr> +<td>[Portal:Description]</td> +<td>Portal Description</td> +</tr> +<tr> +<td>[Portal:Email]</td> +<td>Portal Admin Email</td> +</tr> +<tr> +<td>[Portal:FooterText]</td> +<td>Portal Copyright Text</td> +</tr> +<tr> +<td>[Portal:HomeDirectory]</td> +<td>Portal Path (relative) of Home Directory</td> +</tr> +<tr> +<td>[Portal:LogoFile]</td> +<td>Portal Path to Logo File</td> +</tr> +<tr> +<td>[Portal:PortalName]</td> +<td>Portal Name</td> +</tr> +<tr> +<td>[Portal:PortalAlias]</td> +<td>Portal URL</td> +</tr> +<tr> +<td>[Portal:TimeZoneOffset]</td> +<td>Difference in Minutes between Portal Default Time and UTC</td> +</tr> +<tr> +<td>&nbsp;</td> +<td>&nbsp;</td> +</tr> +<tr> +<td>[User:DisplayName]</td> +<td>User&rsquo;s Display Name</td> +</tr> +<tr> +<td>[User:Email]</td> +<td>User&rsquo;s Email Address</td> +</tr> +<tr> +<td>[User:FirstName]</td> +<td>User&rsquo;s First Name</td> +</tr> +<tr> +<td>[User:FullName]</td> +<td>[deprecated]</td> +</tr> +<tr> +<td>[User:LastName]</td> +<td>User&rsquo;s Last Name</td> +</tr> +<tr> +<td>[User:Username]</td> +<td>User&rsquo;s Login User Name</td> +</tr> +<tr> +<td>&nbsp;</td> +<td>&nbsp;</td> +</tr> +<tr> +<td>[Membership:Approved]</td> +<td>Is User Approved?</td> +</tr> +<tr> +<td>[Membership:CreatedDate] </td> +<td>User Signup Date</td> +</tr> +<tr> +<td>[Membership:IsOnline]</td> +<td>Is User Currently Online?</td> +</tr> +<tr> +<td>&nbsp;</td> +<td>&nbsp;</td> +</tr> +<tr> +<td>[Profile:&lt;Property&gt;]</td> +<td>Use any default or custom Profile Property as listed in Profile Property Definition section of Manage User Accounts. Use non-localized Property Name only.</td> +</tr> +<tr> +<td>&nbsp;</td> +<td>&nbsp;</td> +</tr> +<tr> +<td>[Tab:Description]</td> +<td>Page Description Text for Search Engine</td> +</tr> +<tr> +<td>[Tab:EndDate]</td> +<td>Page Display Until Date</td> +</tr> +<tr> +<td>[Tab:FullUrl]</td> +<td>Page Full URL</td> +</tr> +<tr> +<td>[Tab:IconFile]</td> +<td>Page Relative Path to Icon File</td> +</tr> +<tr> +<td>[Tab:KeyWords]</td> +<td>Page Keywords for Search Engine</td> +</tr> +<tr> +<td>[Tab:PageHeadText]</td> +<td>Page Header Text</td> +</tr> +<tr> +<td>[Tab:StartDate]</td> +<td>Page Display from Date</td> +</tr> +<tr> +<td>[Tab:TabName]</td> +<td>Page Name</td> +</tr> +<tr> +<td>[Tab:TabPath]</td> +<td>Page Relative Path</td> +</tr> +<tr> +<td>[Tab:Title]</td> +<td>Page Title (Window Title)</td> +</tr> +<tr> +<td>[Tab:URL]</td> +<td>Page URL</td> +</tr> +<tr> +<td>&nbsp;</td> +<td>&nbsp;</td> +</tr> +<tr> +<td>[Module:Description]</td> +<td>Module Definition Description</td> +</tr> +<tr> +<td>[Module:EndDate]</td> +<td>Module Display Until Date</td> +</tr> +<tr> +<td>[Module:Footer]</td> +<td>Module Footer Text</td> +</tr> +<tr> +<td>[Module:FriendlyName]</td> +<td>Module Definition Name</td> +</tr> +<tr> +<td>[Module:Header]</td> +<td>Module Header Text</td> +</tr> +<tr> +<td>[Module:HelpURL]</td> +<td>Module Help URL</td> +</tr> +<tr> +<td>[Module:IconFile]</td> +<td>Module Path to Icon File</td> +</tr> +<tr> +<td>[Module:ModuleTitle]</td> +<td>Module Title</td> +</tr> +<tr> +<td>[Module:PaneName]</td> +<td>Module Name of Pane (where the module resides)</td> +</tr> +<tr> +<td>[Module:StartDate]</td> +<td>Module Display from Date</td> +</tr> +<tr> +<td>&nbsp;</td> +<td>&nbsp;</td> +</tr> +<tr> +<td>[DateTime:Now]</td> +<td>Current Date and Time (User Time)</td> +</tr> +<tr> +<td>[DateTime:UTC]</td> +<td>Current Date and Time (UTC)</td> +</tr> +<tr> +<td>[DateTime:System]</td> +<td>Current Date and Time (Server Time)</td> +</tr> +<tr> +<td>[Ticks:Now]</td> +<td>CPU Tick Count for Current Second (Server Time)</td> +</tr> +<tr> +<td>[Ticks:Today]</td> +<td>CPU Tick Count since Midnight (Server Time)</td> +</tr> +<tr> +<td>[Ticks:TicksPerDay] </td> +<td>CPU Ticks per Day (for calculations)</td> +</tr> +<tr> +<td>&nbsp;</td> +<td>&nbsp;</td> +</tr> +<tr> +<td>[Server:<i>Name</i>]</td> +<td>Server <i>Name</i></td> +</tr> +<tr> +<td>[Querystring:<i>Name</i>]</td> +<td>Value of Querystring <i>Name</i> </td> +</tr> +<tr> +<td>[Form:<i>Name</i>]</td> +<td>Form Posted Value of <i>Name</i></td> +</tr> +<tr> +<td>&nbsp;</td> +<td>&nbsp;</td> +</tr> +<tr> +<td colspan="2">Data Type &quot;Look-Up&quot; to Source Column Type &quot;Download&quot; or &quot;URL&quot; + also supports:</td> +</tr> +<tr> +<td>[File:Name]</td> +<td>Name of File</td> +</tr> +<tr> +<td>[File:Folder]</td> +<td>Folder of File</td> +</tr> +<tr> +<td>[File:Path]</td> +<td>Complete Path to File</td> +</tr> +<tr> +<td>[File:Size]</td> +<td>File Size in Bytes</td> +</tr> +<tr> +<td>[File:SizeMB]</td> +<td>File Size in Megabytes</td> +</tr> +<tr> +<td>[File:Clicks]</td> +<td>Number of Downloads</td> +</tr> +<tr> +<td>[File:Extension]</td> +<td>File Extension</td> +</tr> +<tr> +<td>&nbsp;</td> +<td>&nbsp;</td> +</tr> +<tr> +<td colspan="2">Data Type &quot;Look-Up&quot; to Type &quot;Email&quot;, &quot;Created by&quot;, &quot;Changed by&quot; or &quot;Link to User&rsquo;s Profile&quot; + also supports:</td> +</tr> +<tr> +<td>[Gravatar:MD5Hash]</td> +<td>MD5 Hash of the Email Address (if available)</td> +</tr> +<tr> +<td>[Gravatar:URL]</td> +<td>URL to the Gravatar Image</td> +</tr> +<tr> +<td>[Gravatar:Image]</td> +<td>Gravatar Image</td> +</tr> + +</tbody> +</table> +</div> +<div class="UDT_Help_Text"><br /> +For Date/Time and numeric values, you can also append a &lt;format&gt; string defined by the .NET framework, for example: [DateTime:Now|&lt;format&gt;] current Date/Time formatted according to &lt;format&gt;, e.g. [DateTime:Now|f] displays current date in short format (does not apply to Calculated Column expressions)<br /> + <br /> + You can also add alternative text that gets returned if the requested value is + null or empty: [Token:Property|Format|Alternative]</div> + +</body> +</html> + + + Hidden Columns Reference + + + <table cellspacing="3" cellpadding="2" width="100%" summary="" border="0"> +<colgroup> +<col class="UDT_Help_RowHead" /> +<col class="UDT_Help_Row" /> +<col class="UDT_Help_Row" /> +<col class="UDT_Help_Row" /> +<col class="UDT_Help_Row" /> +<col class="UDT_Help_Row" /> +<col class="UDT_Help_Row" /> +</colgroup> +<thead> +<tr> +<td class="UDT_Help_ColHead">&nbsp;</td> +<td class="UDT_Help_ColHead">ColumnName</td> +<td class="UDT_Help_ColHead">+_UDT_Original </td> +<td class="UDT_Help_ColHead">+_UDT_Caption</td> +<td class="UDT_Help_ColHead">+_UDT_Value</td> +<td class="UDT_Help_ColHead">+_UDT_Ticks</td> +<td class="UDT_Help_ColHead">+_UDT_Url</td> +</tr> +</thead> +<tbody> +<tr> +<td>Changed at</td> +<td>Date</td> +<td align="center">-</td> +<td align="center">-</td> +<td>Localized Date</td> +<td>DateTime in Ticks</td> +<td align="center">-</td> +</tr> +<tr> +<td>Changed by</td> +<td>Display Name/ Link to Profile</td> +<td>User Name</td> +<td>Display Name</td> +<td align="center">-</td> +<td align="center">-</td> +<td>Profile URL</td> +</tr> +<tr> +<td>Created at</td> +<td>Date</td> +<td align="center">-</td> +<td align="center">-</td> +<td>Localized Date</td> +<td>DateTime in Ticks</td> +<td align="center">-</td> +</tr> +<tr> +<td>Created by</td> +<td>Display Name/ Link to Profile</td> +<td>User Name</td> +<td>Display Name</td> +<td align="center">-</td> +<td align="center">-</td> +<td>Profile URL</td> +</tr> +<tr> +<td>Calculated Column</td> +<td>Result of Expression</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +</tr> +<tr> +<td>Currency</td> +<td>Value</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +</tr> +<tr> +<td>Date</td> +<td>Date</td> +<td align="center">-</td> +<td align="center">-</td> +<td>Localized Date</td> +<td>DateTime in Ticks</td> +<td align="center">-</td> +</tr> +<tr> +<td>Date and Time</td> +<td>DateTime</td> +<td align="center">-</td> +<td align="center">-</td> +<td>Localized Date</td> +<td>DateTime in Ticks</td> +<td align="center">-</td> +</tr> +<tr> +<td>Decimal</td> +<td>Value</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +</tr> +<tr> +<td>Download</td> +<td>HTML Link</td> +<td>FileID=</td> +<td>Filename</td> +<td align="center">-</td> +<td align="center">-</td> +<td>File URL</td> +</tr> +<tr> +<td>Email</td> +<td>HTML Link</td> +<td>Value</td> +<td>Caption</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +</tr> +<tr> +<td>Image</td> +<td>HTML Image</td> +<td>FileID=</td> +<td>Caption (Alt)</td> +<td align="center">-</td> +<td align="center">-</td> +<td>Image URL</td> +</tr> +<tr> +<td>Integer</td> +<td>Value</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +</tr> +<tr> +<td>Link to User&rsquo;s Profile</td> +<td>Link to Profile</td> +<td>Value</td> +<td>Display Name</td> +<td align="center">-</td> +<td align="center">-</td> +<td>Profile URL</td> +</tr> +<tr> +<td>Look-Up</td> +<td>Result of Look Up</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +</tr> +<tr> +<td>Rich Text/HTML</td> +<td>Value</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +</tr> +<tr> +<td>Separator</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +</tr> +<tr> +<td>Text</td> +<td>Value</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +</tr> +<tr> +<td>Time</td> +<td>Value</td> +<td align="center">-</td> +<td align="center">-</td> +<td align="center">-</td> +<td>DateTime in Ticks</td> +<td align="center">-</td> +</tr> +<tr> +<td>True/False</td> +<td>Image (un)checked.gif</td> +<td align="center">[true|false]</td> +<td align="center">[true|false]</td> +<td align="center">[1|0]</td> +<td align="center">-</td> +<td align="center">-</td> +</tr> +<tr> +<td>URL</td> +<td>HTML Link</td> +<td>Value</td> +<td>Caption</td> +<td align="center">-</td> +<td align="center">-</td> +<td>URL</td> +</tr> +</tbody> +</table> + + \ No newline at end of file diff --git a/App_LocalResources/list.ascx.resx b/App_LocalResources/list.ascx.resx new file mode 100644 index 0000000..b9c16dc --- /dev/null +++ b/App_LocalResources/list.ascx.resx @@ -0,0 +1,211 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + are equal to + + + Search + + + Add New Record + + + start with + + + No records found. + + + end with + + + Delete All Records + + + Unsupported Filter Statement + + + Show All Data as XML + + + There are no columns defined. Setup the module inside the <a href="{0}">Form and List Configuration</a>. + + + contain + + + XSL Tranformation failed. Switched back to Default Grid Table. + + + Are you sure you wish to delete all records stored in this table? + + + <h1>About the Form and List Module</h1> +<p>The Form and List Module allows you to manage an individual table of data, where each column of data is a specific data type and each row represents a single record.&#160;Column headings, when clicked, reorder data alphanumerically&#160;A-Z or Z-A. If the feature is enabled, you may <strong>Search</strong> through records that contain only select data.</p> +<p>If granted permission by the site Administrator,&#160;you can <strong>Add&#160;New Record</strong> and&#160;optionally&#160;<strong>Edit</strong>&#160;and <strong>Delete</strong> any records or only those records you have added yourself. If you have the ability to&#160;add or edit records without being logged in this site, you may need to enter a CAPTCHA confirmation code.</p> +<p>Page Administrators can edit <strong>Module Settings</strong> and select <strong>Form and List Configuration</strong> from the module Action Menu to define columns and column properties.</p> + + + Reset Search + + + Enter Search Value:<br/> +- without any prefix or suffix to find all records where a column contains the value you enter, e.g. Net<br /> +- with | prefix to find all records where a&#160;column starts with the value you enter, e.g. |Network<br /> +- with |&#160;suffix to find all records where a&#160;column ends with the value you enter, e.g. Network|<br /> +- with | prefix and suffix&#160;to find all records containing the value you enter exactly,&#160;e.g. |Network| + + + all searchable columns + + + Browse records in {1} that {2} {3} + + + Edit Current XSL Script + + + Reset Search + + + Save as Template + + + Description + + + Name + + + Apply + + + + + + Show Records + + + Back to Form + + + Data Binding Failed. This issue might be caused by an unsupported cast of a data type. + + \ No newline at end of file diff --git a/App_LocalResources/settings.ascx.resx b/App_LocalResources/settings.ascx.resx new file mode 100644 index 0000000..0efd342 --- /dev/null +++ b/App_LocalResources/settings.ascx.resx @@ -0,0 +1,169 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <h1>Specific Settings for Form and List Module</h1> + <p>The Form and List Module allows you to define an individual table of data. </p> +<p>On the Module Settings page, you can grant extended <strong>permissions</strong> for security roles, defined in your portal:</p> + <ul> + <li>Use <strong>View Module</strong>, to allow members of a role to&#160;view&#160;all existing records. (The check boxes are only active, if "Inherit view permissions from page" is unchecked).</li> + <li>Select <strong>Edit Module</strong>,&#160;to grant permission to all members of the role&#160;to define&#160;columns and view options using <em>Manage Table.</em></li> + <li>Enable <strong>Edit Row, </strong>to allow all members of a role to edit&#160;records.</li> + <li>Use <strong>Create New Row</strong>,&#160;to allow&#160;role members to add rows.</li> + <li>Enable <strong>Delete Row,&#160; </strong>if role members are allowed to delete rows.</li> + <li>If there are Roles that should not&#160;view data of specific columns, define these columns as hidden and enable <strong>Display All Columns</strong> for all&#160;other roles with view permission. Note:&#160;Administrators always see all defined columns, except in preview mode.</li> + </ul> +<p>On the <strong>Form and List Settings&#160;</strong>section, there&#160;are these options:</p> + <ul> + <li>By default all users are able to edit and delete all records. However, if users edit permissions are limited to rows, enable <strong>Users are&#160;only allowed to manipulate their&#160;own items</strong>. Note: Administrators are always allowed to edit all records.</li> + <li>Enable <strong>Force CAPTCHA&#160;Control</strong>, to allow users to add, edit or delete records even when they are not logged in. This ensures that data entries are not added by bots automatically.</li> + <li>Enable <strong>Filter entry for markup code or script input,</strong> to avoid harmful code from being input in the Form and List.</li> + <li>Enable <strong>Negate permission/feature "Display All Columns" for Administrators,</strong> to hide columns that would otherwise be displayed to Administrators.</li> + <li>Enable <strong>Negate permission/feature "Edit Also Restricted Columns" for Administrators,</strong> to hide Private Columns that would otherwise be displayed to Administrators.</li> + <li>Enter <strong>Max. Records per User</strong> to set a limit on the number of records any one user can create/edit; leave blank for no limit.</li> +</ul> + + + Form and List Settings + + + Users are only allowed to manipulate their own items. + + + Force CAPTCHA control during edit for Anonymous users. + + + Filter entry for markup code or script input. Note: filtering is always enabled for Anonymous users. + + + Negate permission/feature "Display All Columns" for Administators. + + + Negate permission/feature "Edit Also Restricted Columns" for Administators. + + + Leave blank for no limit, or enter the maximum number of records each user can create. + + + Max. Records per User + + + Hide System Fields even if "Display All Column" permission is set. + + \ No newline at end of file diff --git a/App_LocalResources/sharedresources.resx b/App_LocalResources/sharedresources.resx new file mode 100644 index 0000000..8e25273 --- /dev/null +++ b/App_LocalResources/sharedresources.resx @@ -0,0 +1,768 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Create Record/ Submit Form + + + Delete Record + + + Edit Record + + + * + + + * required + + + This field is required. + + + Display All Columns + + + Edit Also Restricted Columns + + + True/False + + + Changed at + + + Changed by + + + Created by + + + Created at + + + Currency + + + Date + + + Date and Time + + + Decimal + + + Download + + + Email + + + Calculated Column + + + Image + + + Integer + + + Separator + + + Text + + + Rich Text (Html) + + + Time + + + URL + + + Look-Up + + + Link to User's Profile + + + Please enter a valid True/False value. + + + Please enter a valid Currency value. + + + Please enter a valid Date value. + + + Please enter a valid Date and Time value. + + + Please enter a valid Decimal value. + + + Please enter a valid Email address. + + + Please enter a valid Integer value. + + + Page not found + + + Please enter a valid Time value. + + + Please enter a valid URL. + + + Value entered is too long. Please shorten your input. + + + Display options for image columns: + + + Default Value: + + + New records will use this value as the default value, for example, "True" or "False". + + + Output Format: + + + Enter a date format, for example, "DD-MM-YYYY". + + + Output Format: + + + Enter a date format, for example, "dd.MM.yyyy". + + + List of Values: + + + Enter a list of numbers separated with ";", for example, 1;12,23;99,87. + + + Currency Symbol: + + + Enter the name or symbol of the currency. + + + Default Value: + + + New records will use this amount as the default value. + + + Enter a list of dates separated with ";", for example, 2000-01-01;2000-12-31;2001-7-24. + + + Output Format: + + + New records will use this date as the default value, for example, "MM/dd/yyyy". + + + Default Value: + + + New records will use this value as the default value. You can enter a format, for example, MM/DD/YYYY. + + + List of Values: + + + Convert TimeZone? + + + Activate to store values with respect to the users timezone. + + + Output Format: + + + Enter a date format, for example, "dd.MM.yyyy". + + + Default Value: + + + New records will use this value as the default value, for example, 2000-01-01T12:00:00. If no TimeZone information is added , the value will be treated as UTC. Example for same in CET Summer Time: 2000-01-01T12:00:00+2.00 + + + List of Values: + + + Enter a list of numbers separated with ";", for example, 1;12.23;99.87. + + + Default Value: + + + New records will use this value as the default value, for example, 12.23. + + + Output Format: + + + Enter a number format, for example, "0.00". + + + List of Values: + + + Enter a list of image links separated with ";". + + + Link Caption: + + + Enter static text that is displayed instead of a file name. + + + Default Value: + + + New records will use this value as the default value. Enter a valid URL. + + + List of Values: + + + Enter a list of email addresses separated by ";". + + + Link Caption: + + + Enter the static text that is displayed instead of an email address (with mailto: link). + + + Default Value: + + + New records will use this default value. Enter a valid email address. + + + Disable Hyperlink? + + + Enable to display email address as text. + + + Data Type: + + + Select result Type. Default is "Text", but you may want to alter it for sorting/formatting purposes. + + + Output Format: + + + Enter an output format string suitable for this data type, for example, "###.###" + + + Expression: + + + Enter an expression formula (appropriate for the data type) which will be evaluated at runtime. + + + Source Column: + + + Name of the column containing a ref to a User or local File. + + + Token Text: + + + Token Text to query the User or File object. + + + List of Values: + + + Enter a list of image links separated with ";". + + + ALT Tag: + + + Enter text to be used as "ALT tag" for all records. + + + Default Value: + + + New records will use this default value. Enter a valid image link. + + + Hyperlink: + + + Enable to display thumbnail image as a link to open full sized image in new window. + + + List of Values: + + + Enter a list of integers separated with ";", for example, 5;10;50;100 + + + Output Format: + + + Enter a format string, for example, "###.###" + + + Default Value: + + + New records will use this number as the default value. + + + List of Values: + + + Enter either a list of values (1;2;3 or A;B;C) or name|value pairs (One|1;Two|2;Three|3), with elements separated by a ";" (semicolon). + + + Default Value: + + + New records will auto-fill using this default value. + + + Default Value: + + + Enable to display a Plain Text Box instead of a Rich Text (HTML) editor. + + + Plain Text Box? + + + New records will use this HTML text as the default value. + + + List of Values: + + + Enter a list of usernames separated with ";". + + + Caption options: + + + Output of Caption can be controlled with Tokens. It defaults to [User:Displayname] + + + Default Value: + + + New records will use this username. + + + Show user's username instead of his displayname: + + + Show user's username instead of his displayname + + + List of Values: + + + Enter a list of times separated with ";", for example, 10:00:00;11:30:00;13:00:00. + + + Output Format: + + + You can specify an appropriate output format, for example, "hh:mm". + + + Default Value: + + + New records will use this default time value. + + + Convert TimeZone? + + + Enable to store time based on the user's timezone. + + + List of Values: + + + Enter a list of URLs separated with ";". + + + Link Caption: + + + Enter a static (HTML) value to be used as a link caption. + + + Default Value: + + + New records will use this value as the default value. Enter a valid URL. + + + Abbreviated URL: + + + Enable to display file or page name only. + + + Search + + + Page + + + of + + + First + + + Previous + + + Next + + + Last + + + Collapsible Area + + + Collapsible Area + + + Attachment + + + In&#160;form&#160;mode permit&#160;list&#160;as&#160;well + + + Text of the label to the RIGHT of checkbox + + + Right label text: + + + By default the date time is returned in the server's time zone. If this setting is enabled, the value will be converted to the timezone of the user. + + + Convert to user's timezone + + + By default, the caption of the file inludes path and filename. You can shorten the caption to only return the filename. + + + Abbreviate caption + + + Enable to enforce a download + + + Enforce Download + + + Enable "Open in new window" inside form. + + + Enable "Open in new window" + + + If enabled, the email address is returned as plain text + + + No Link + + + Show on Edit Form? + + + Show on Edit Form? + + + The expression gets executed based on the current data. Doesn't work with all expressions. + + + Render in form + + + "Alt" caption of the image. [Tokens] are supported here. + + + Alt caption + + + Link the thumbnail to the original image. + + + Thumbnail As Link + + + Heigth of thumbnail. Set width and height blank to use original size. + + + Thumbnail Heigtht + + + Width of thumbnail. Set width and height blank to use original size. + + + Thumbnail Width + + + By default, the caption of the link inludes path and filename. You can shorten the caption to only return the filename. + + + Abbreviate caption + + + Enable to enforce a download + + + Enforce Download + + + Enable "Open in new window" inside form. + + + Enable "Open in new window" + + + Decide whther the link should use linkclick.aspx instead a direct link. + + + Track Number of Downloads + + + Link opens a new window/tab + + + Open in new Window + + + If enabled, the username will be shown, otherwise the displayname. + + + Show Username + + + Expression based on [Tokens]. If empty, the displayname or username of the user will be returned. + + + Expression + + + This setting will replace radio buttons with checkboxes. Selected values are stored as string separated by semicolons (";") + + + Multiple Values + + + By default the date time is returned in the server's time zone. If this setting is enabled, the value will be converted to the timezone of the user. + + + Convert to user's timezone + + + If enabled, value will be displayed to all users when editing. + + + Show on Edit Form? + + + As Link to User Profile + + + As Link: + + + If enabled, value will be displayed to all users when editing. + + + Show on Edit Form? + + + Open in new window + + + New window: + + + Prefer Displayname over user name + + + Prefer Displayname + + + By default the date time is returned in the server's time zone. If this setting is enabled, the value will be converted to the timezone of the user. + + + Convert to user's timezone + + + If enabled, value will be displayed to all users when editing. + + + Show on Edit Form? + + + As Link to User Profile + + + As Link: + + + If enabled, value will be displayed to all users when editing. + + + Show on Edit Form? + + + Open in new window + + + New window: + + + Prefer Displayname over user name + + + Prefer Displayname + + \ No newline at end of file diff --git a/App_LocalResources/template.ascx.resx b/App_LocalResources/template.ascx.resx new file mode 100644 index 0000000..ac92fb4 --- /dev/null +++ b/App_LocalResources/template.ascx.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Save as Form and List - Module Template + + + Form and List - Module Template + + + Create Module Template + + + A template with this name already exists.<br/>Do you wish to overwrite? + + + Description + + + Description + + + Name of Form and List - Module Template + + + Name + + + Max Number of records that are included in the template, usually 0 or 1 + + + Max Records + + \ No newline at end of file diff --git a/App_LocalResources/templatelist.ascx.resx b/App_LocalResources/templatelist.ascx.resx new file mode 100644 index 0000000..a3fa780 --- /dev/null +++ b/App_LocalResources/templatelist.ascx.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Form and List Configuration + + + Unsupported Filter Statement + + + <h1>About the Form and List Module</h1> +<p>The Form and List Module allows you to manage an individual table of data, where each column of data is a specific data type and each row represents a single record.&#160;Column headings, when clicked, reorder data alphanumerically&#160;A-Z or Z-A. If the feature is enabled, you may <strong>Search</strong> through records that contain only select data.</p> +<p>If granted permission by the site Administrator,&#160;you can <strong>Add&#160;New Record</strong> and&#160;optionally&#160;<strong>Edit</strong>&#160;and <strong>Delete</strong> any records or only those records you have added yourself. If you have the ability to&#160;add or edit records without being logged in this site, you may need to enter a CAPTCHA confirmation code.</p> +<p>Page Administrators can edit <strong>Module Settings</strong> and select <strong>Form and List Configuration</strong> from the module Action Menu to define columns and column properties.</p> + + + Save as Template + + + Create a new Form or List based on a template from the list above, or design your own in <a class="dnnPrimaryAction" href="{0}">Form and List Configuration</a>. + + + Name + + + Apply + + + Show Records + + + Description + + + Scan for new Module Templates + + + <p>You selected the Module Template <b>{0}</b> which requires an initial configuration:</p> + + + Configuration + + + Start with a new + + + or choose a template: + + \ No newline at end of file diff --git a/App_LocalResources/token2xsl.ascx.resx b/App_LocalResources/token2xsl.ascx.resx new file mode 100644 index 0000000..74f2c0b --- /dev/null +++ b/App_LocalResources/token2xsl.ascx.resx @@ -0,0 +1,314 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + List Type + + + Determines which HTML elements are used to render columns. + + + Token Based XSLT Generator and Editor + + + Available Fields and Context + + + Choose Data and Context columns to be rendered by the XSL script. + + + Insert + + + Table + + + Generate from HTML Template + + + Save File and Return + + + Rebuild + + + Insert Column + + + All changes will get lost. Are you sure you want to rebuild? + + + 1. Edit HTML Template + + + 2. Edit XSLT Script + + + This file already exists. Do you want to overwrite? + + + File Name + + + File extension *.xsl will be appended automatically,<br/>if it is not entered by the user.<br/>The script will be saved to "...\[PortalHomeDirectory]\XslStyleSheets\". + + + 3. Save File + + + The Template is not well-formed:<br/> + + + Division + + + Paragraph + + + Delimiter + + + Enter one or more characters or HTML tag used as a column delimiter. + + + Folder Name + + + Folder where XSL scripts are stored (cannot be changed). + + + Hidden Columns Help + + + Line Break + + + Unordered List + + + Ordered List + + + Application Path + + + Current Culture + + + Display Name + + + Home Path + + + Is Administrator Role + + + ModuleId + + + Order By + + + Order Direction + + + Parameter + + + Portal ID + + + Tab ID + + + User Name + + + User Roles + + + Add Sorting Support + + + Add Paging Support + + + <h1>Token based HTML Editor and XSL Converter</h1> +<p>Use these features to help you&#160;create your own custom XSL files.</p> +<p>Choose between different layout constructs: Table, Paragraphs and Lists with custom separators.</p> +<p>We recommend that you&#160;start with a default view and modify the HTML template to fit your needs. Add additional fields using the column selector.</p> +<p>After you create your HTML template, convert it to an XSL template, then add additional&#160;code before you save it as a file.</p> +<p>Click <strong>Back</strong> to return to&#160;<strong>Form and List Configuration</strong>.</p> + + + Add Sorting Support to the Style Sheet + + + Enable this setting to sort displayed records<br>according to the Sort Column and Sort Direction<br>specified in Form and List Configuration. + + + Add Paging Support to the Style Sheet + + + Enable this setting to add a pager for the displayed list.<br>Paging is specified in Form and List Configuration. + + + Add Search Box to the Style Sheet + + + Enable this setting to add a search box above<br>the displayed list where users can enter text to search<br>in columns specified as Searchable. + + + Add Detail View + + + Enable this setting to add a link to an additional Detail View,<br>showing the columns of the currently selected record only. + + + Options + + + List View + + + Detail View + + + List type cannot be changed, but the template still seems to be valid. + + + Nothing + + + XSL-Search is obsolete, please use the build in Search instead. + + + Shows textbox for header definition + + + Enable header definition + + + Choose columns to use as Headers.<br>If sorting is enabled, Headers can be clicked<br>to alter the sort sequence. + + + Available Headers + + \ No newline at end of file diff --git a/AssemblyInfo.cs b/AssemblyInfo.cs new file mode 100644 index 0000000..7c53685 --- /dev/null +++ b/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +// Allgemeine Informationen über eine Assembly werden über die folgenden +// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, +// die mit einer Assembly verknüpft sind. + +// Die Werte der Assemblyattribute überprüfen + +[assembly: AssemblyTitle("DotNetNuke.Modules.UserDefinedTable")] +[assembly: AssemblyDescription("ASP.NET Open Source Portal Application,Form and List Module")] +[assembly: AssemblyCompany("DotNetNuke Inc")] +[assembly: AssemblyProduct("http://www.dotnetnuke.com")] +[assembly: + AssemblyCopyright("Portal engine source code is copyright © 2002-YYYY by DotNetNuke. All Rights Reserved")] +[assembly: AssemblyTrademark("DotNetNuke")] +[assembly: ComVisible(false)] + +//Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird + +[assembly: Guid("334e9cee-0d47-4d70-924b-b5098a3432cb")] + +// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: +// +// Hauptversion +// Nebenversion +// Buildnummer +// Revision +// +// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern +// übernehmen, indem Sie "*" eingeben: +// + +[assembly: AssemblyVersion("06.01.00.*")] +[assembly: CLSCompliant(true)] \ No newline at end of file diff --git a/BuildScripts/MSBuild.Community.Tasks.Targets b/BuildScripts/MSBuild.Community.Tasks.Targets new file mode 100644 index 0000000..f458c48 --- /dev/null +++ b/BuildScripts/MSBuild.Community.Tasks.Targets @@ -0,0 +1,105 @@ + + + + + + $(MSBuildProjectDirectory)\BuildScripts + $(MSBuildProjectDirectory)\..\..\bin + $(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BuildScripts/ModulePackage.targets b/BuildScripts/ModulePackage.targets new file mode 100644 index 0000000..1427b45 --- /dev/null +++ b/BuildScripts/ModulePackage.targets @@ -0,0 +1,149 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BusinessController.cs b/BusinessController.cs new file mode 100644 index 0000000..3800ccf --- /dev/null +++ b/BusinessController.cs @@ -0,0 +1,423 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Globalization; +using System.IO; +using System.Web; +using System.Xml; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Modules.UserDefinedTable.Interfaces; +using DotNetNuke.Services.Exceptions; +using DotNetNuke.Services.FileSystem; +using DotNetNuke.Services.Search; +using Microsoft.VisualBasic; +using Globals = DotNetNuke.Common.Globals; + +namespace DotNetNuke.Modules.UserDefinedTable +{ + public class BusinessController : ISearchable, IPortable, IPortable2 + { + public enum SettingsType + { + ModuleSettings, + TabModuleSettings + } + + static DataTable GetSettingsTable(int id, SettingsType type) + { + var modules = new ModuleController(); + Hashtable settings = null; + DataTable returnValue = null; + + switch (type) + { + case SettingsType.ModuleSettings: + settings = modules.GetModuleSettings(id); + returnValue = new DataTable(DataSetTableName.Settings); + break; + case SettingsType.TabModuleSettings: + settings = modules.GetTabModuleSettings(id); + returnValue = new DataTable(DataSetTableName.TabSettings); + break; + } + + var sortedSettings = new SortedList(); + if (settings != null) + foreach (DictionaryEntry item in settings) + { + sortedSettings.Add(item.Key.ToString(), item.Value.ToString()); + } + + + var dc = new DataColumn(SettingsTableColumn.Setting, typeof (string)) + {ColumnMapping = MappingType.Attribute}; + if (returnValue != null) returnValue.Columns.Add(dc); + + dc = new DataColumn(SettingsTableColumn.Value, typeof (string)) {ColumnMapping = MappingType.Attribute}; + if (returnValue != null) + { + returnValue.Columns.Add(dc); + + foreach (var key in sortedSettings.Keys) + { + var row = returnValue.NewRow(); + row[SettingsTableColumn.Setting] = key; + row[SettingsTableColumn.Value] = sortedSettings[key]; + returnValue.Rows.Add(row); + } + return returnValue; + } + return null; + } + + DataTable GetStylesheetTable(Components.Settings settings, int portalId) + { + var returnValue = new DataTable(DataSetTableName.Stylesheets); + + returnValue.Columns.Add(new DataColumn(StylesheetTableColumn.NameOfSetting, typeof (string))); + returnValue.Columns.Add(new DataColumn(StylesheetTableColumn.LocalFilePath, typeof (string))); + returnValue.Columns.Add(new DataColumn(StylesheetTableColumn.Stylesheet, typeof (string))); + + var renderMethod = string.Format("UDT_{0}", settings.RenderingMethod ); + var listScript = renderMethod == SettingName.XslUserDefinedStyleSheet + ? settings.ScriptByRenderingMethod( renderMethod ) + : string.Empty; + if (listScript.Length > 0) + { + var row = returnValue.NewRow(); + row[StylesheetTableColumn.NameOfSetting] = SettingName.XslUserDefinedStyleSheet; + row[StylesheetTableColumn.LocalFilePath] = listScript; + row[StylesheetTableColumn.Stylesheet] = Utilities.ReadStringFromFile(listScript, portalId); + returnValue.Rows.Add(row); + } + + var trackingSkript = settings.TrackingScript; + + if (trackingSkript.Length > 0 && trackingSkript != "[AUTO]") + { + var row = returnValue.NewRow(); + row[StylesheetTableColumn.NameOfSetting] = SettingName.TrackingScript; + row[StylesheetTableColumn.LocalFilePath] = trackingSkript; + row[StylesheetTableColumn.Stylesheet] = Utilities.ReadStringFromFile(trackingSkript, portalId); + returnValue.Rows.Add(row); + } + + return returnValue; + } + + /// ----------------------------------------------------------------------------- + /// + /// Implements the search interface for DotNetNuke + /// + /// ----------------------------------------------------------------------------- + public SearchItemInfoCollection GetSearchItems(ModuleInfo modInfo) + { + var searchItemCollection = new SearchItemInfoCollection(); + var udtController = new UserDefinedTableController(modInfo); + + try + { + var dsUserDefinedRows = udtController.GetDataSet(withPreRenderedValues: false); + + //Get names of ChangedBy and ChangedAt columns + var colnameChangedBy = udtController.ColumnNameByDataType(dsUserDefinedRows, + DataTypeNames.UDT_DataType_ChangedBy); + var colnameChangedAt = udtController.ColumnNameByDataType(dsUserDefinedRows, + DataTypeNames.UDT_DataType_ChangedAt); + + var moduleController = new ModuleController(); + var settings = moduleController.GetModuleSettings(modInfo.ModuleID); + var includeInSearch = !(settings[SettingName.ExcludeFromSearch].AsBoolean()); + + if (includeInSearch) + { + foreach (DataRow row in dsUserDefinedRows.Tables[DataSetTableName.Data].Rows) + { + var changedDate = DateTime.Today; + var changedByUserId = 0; + + if (colnameChangedAt != string.Empty && ! Information.IsDBNull(row[colnameChangedAt])) + { + changedDate = Convert.ToDateTime(row[colnameChangedAt]); + } + if (colnameChangedBy != string.Empty && ! Information.IsDBNull(row[colnameChangedBy])) + { + changedByUserId = ModuleSecurity.UserId(row[colnameChangedBy].ToString(), modInfo.PortalID); + } + + var desc = string.Empty; + foreach (DataRow col in dsUserDefinedRows.Tables[DataSetTableName.Fields].Rows) + { + var fieldType = col[FieldsTableColumn.Type].ToString(); + var fieldTitle = col[FieldsTableColumn.Title].ToString(); + var visible = Convert.ToBoolean(col[FieldsTableColumn.Visible]); + if (visible && + (fieldType.StartsWith("Text") || fieldType == DataTypeNames.UDT_DataType_String)) + { + desc += string.Format("{0} • ", Convert.ToString(row[fieldTitle])); + } + } + if (desc.EndsWith("
")) + { + desc = desc.Substring(0, Convert.ToInt32(desc.Length - 5)); + } + var searchItem = new SearchItemInfo(modInfo.ModuleTitle, desc, changedByUserId, changedDate, + modInfo.ModuleID, row[DataTableColumn.RowId].ToString(), + desc); + searchItemCollection.Add(searchItem); + } + } + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + + return searchItemCollection; + } + + + /// ----------------------------------------------------------------------------- + /// + /// Implements the export interface for DotNetNuke + /// + /// ----------------------------------------------------------------------------- + public string ExportModule(int moduleId) + { + return ExportModule(moduleId, Null.NullInteger); + } + + + /// + /// Implements the enhanced export interface for DotNetNuke + /// + public string ExportModule(int moduleId, int tabId) + { + return ExportModule(moduleId, tabId, Null.NullInteger); + } + + + public string ExportModule(int moduleId, int tabId, int maxNumberOfItems) + { + var ds = ExportModuleDataSet(moduleId, tabId); + if (maxNumberOfItems > Null.NullInteger) + { + //clear all but first row + for (var i = ds.Tables[DataSetTableName.Data].Rows.Count - 1; i >= maxNumberOfItems; i--) + { + ds.Tables[DataSetTableName.Data].Rows.RemoveAt(i); + } + } + //dataset to xml + return ds.GetXml(); + } + + public DataSet ExportModuleDataSet(int moduleId, int tabId) + { + DataSet ds; + + if (tabId == Null.NullInteger) + { + var udtController = new UserDefinedTableController(moduleId); + ds = udtController.GetDataSet(false); + ds.Tables.Add(GetSettingsTable(moduleId, SettingsType.ModuleSettings)); + } + else + { + var moduleInfo = new ModuleController().GetModule(moduleId, tabId); + var udtController = new UserDefinedTableController(moduleInfo); + ds = udtController.GetDataSet(false); + ds.Tables.Add(GetSettingsTable(moduleId, SettingsType.ModuleSettings)); + ds.Tables.Add(GetSettingsTable(moduleInfo.TabModuleID, SettingsType.TabModuleSettings)); + ds.Tables.Add(GetStylesheetTable(udtController.Settings, moduleInfo.PortalID)); + } + return (ds); + } + + + /// ----------------------------------------------------------------------------- + /// + /// Implements the import interface for DotNetNuke + /// + /// ----------------------------------------------------------------------------- + public void ImportModule(int moduleId, string content, string version, int userId) + { + ImportModule(moduleId, Null.NullInteger, content, version, userId, false); + } + + /// + /// Implements the enhanced Import Interface for DotNetNuke + /// + public void ImportModule(int moduleId, int tabId, string content, string version, int userId, bool isInstance) + { + // save script timeout + var scriptTimeOut = HttpContext.Current.Server.ScriptTimeout; + + try + { + // temporarily set script timeout to large value ( this value is only applicable when application is not running in Debug mode ) + HttpContext.Current.Server.ScriptTimeout = int.MaxValue; + + var udtController = new UserDefinedTableController(moduleId); + using (var ds = new DataSet()) + { + var xmlNode = Globals.GetContent(content, string.Empty); + ds.ReadXml(new XmlNodeReader(xmlNode)); + var modules = new ModuleController(); + var tabModuleId = Null.NullInteger; + if (tabId != Null.NullInteger) + { + var moduleInfo = modules.GetModule(moduleId, tabId); + tabModuleId = moduleInfo.TabModuleID; + } + if (tabModuleId != Null.NullInteger && ds.Tables[DataSetTableName.TabSettings] != null) + { + AddTabModuleSettings(modules, tabModuleId, ds); + } + if (! isInstance) + { + AddModuleSettings(moduleId, modules, ds); + //Fields - first delete old Fields + udtController.ResetModule(); + AddFields(moduleId, ds); + AddData(udtController, ds); + } + if (ds.Tables.Contains(DataSetTableName.Stylesheets)) + { + ImportStyleSheet(moduleId, isInstance, tabModuleId, modules, ds); + } + } + } + finally + { + // reset script timeout + HttpContext.Current.Server.ScriptTimeout = scriptTimeOut; + } + } + + static void AddTabModuleSettings(ModuleController modules, int tabModuleId, DataSet ds) + { + foreach (DataRow row in ds.Tables[DataSetTableName.TabSettings].Rows) + { + modules.UpdateTabModuleSetting(tabModuleId, row[SettingsTableColumn.Setting].ToString(), + row[SettingsTableColumn.Value].ToString()); + } + } + + static void AddModuleSettings(int moduleId, ModuleController modules, DataSet ds) + { + if (ds.Tables[DataSetTableName.Settings] != null) + { + foreach (DataRow row in ds.Tables[DataSetTableName.Settings].Rows) + { + modules.UpdateModuleSetting(moduleId, row[SettingsTableColumn.Setting].ToString(), + row[SettingsTableColumn.Value].ToString()); + } + } + } + + static void ImportStyleSheet(int moduleId, bool isInstance, int tabModuleId, ModuleController modules, + DataSet ds) + { + var portalSettings = Globals.GetPortalSettings(); + foreach (DataRow row in ds.Tables[DataSetTableName.Stylesheets].Rows) + { + var settingName = row[StylesheetTableColumn.NameOfSetting].ToString(); + var localFilePath = row[StylesheetTableColumn.LocalFilePath].ToString(); + var stylesheet = row[StylesheetTableColumn.Stylesheet].ToString(); + //Check whether file exists + if (File.Exists(((portalSettings.HomeDirectoryMapPath + localFilePath).Replace("/", "\\")))) + { + //nothing to do, settings points to existing stylesheet + } + else + { + var fileName = + localFilePath.Substring( + Convert.ToInt32( + localFilePath.LastIndexOf("/", StringComparison.InvariantCultureIgnoreCase) + 1)); + var folder = Utilities.GetFolder(portalSettings, Definition.XSLFolderName); + Utilities.SaveScript(stylesheet, fileName, folder, false); + if (tabModuleId != Null.NullInteger) + { + modules.UpdateTabModuleSetting(tabModuleId, settingName, + string.Format("{0}/{1}", Definition.XSLFolderName, fileName)); + } + else + { + if (! isInstance) + { + modules.UpdateModuleSetting(moduleId, settingName, + string.Format("{0}/{1}", Definition.XSLFolderName, fileName)); + } + } + } + } + } + + static void AddData(UserDefinedTableController udtController, DataSet ds) + { + if (ds.Tables[DataSetTableName.Data] != null) + { + for (var rowNr = 0; rowNr <= ds.Tables[DataSetTableName.Data].Rows.Count - 1; rowNr++) + { + udtController.UpdateRow(ds, rowNr, isDataToImport: true); + } + } + } + + static void AddFields(int moduleId, DataSet ds) + { + var fieldIndex = ds.Tables[DataSetTableName.Fields].Rows.Count; + var fieldSettings = ds.Tables[DataSetTableName.FieldSettings]; + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + var oldFieldId = row[FieldsTableColumn.Id].AsInt( ); + var newFieldId= + FieldController.AddField(moduleId, row[FieldsTableColumn.Title].ToString(), + row.AsString(FieldsTableColumn.Order).AsInt(fieldIndex ), + row.AsString((FieldsTableColumn.HelpText)), + row.AsString(FieldsTableColumn.Required).AsBoolean(), + row.AsString((FieldsTableColumn.Type)), + row.AsString((FieldsTableColumn.Default)), + row.AsString(FieldsTableColumn.Visible).AsBoolean(), + row.AsString(FieldsTableColumn.ShowOnEdit).AsBoolean(true), + row.AsString(FieldsTableColumn.Searchable).AsBoolean(), + row.AsString(FieldsTableColumn.IsPrivate).AsBoolean(), + row.AsString(FieldsTableColumn.MultipleValues).AsBoolean(), + row.AsString((FieldsTableColumn.InputSettings)), + row.AsString((FieldsTableColumn.OutputSettings)), + row.AsString(FieldsTableColumn.NormalizeFlag).AsBoolean(), + row.AsString((FieldsTableColumn.ValidationRule)), + row.AsString((FieldsTableColumn.ValidationMessage)), + row.AsString((FieldsTableColumn.EditStyle))); + + if (fieldSettings != null) + { + foreach (DataRowView setting in fieldSettings.WithFieldId(oldFieldId)) + { + FieldSettingsController.UpdateFieldSetting( + (string) setting["SettingName"], + (string) setting["SettingValue"], + newFieldId); + } + } + row[FieldsTableColumn.Id] = newFieldId; + fieldIndex--; + } + } + + public bool ManagesModuleSettings + { + get { return true; } + } + + public bool ManagesTabModuleSettings + { + get { return true; } + } + } +} \ No newline at end of file diff --git a/CSV/CSVWriter.cs b/CSV/CSVWriter.cs new file mode 100644 index 0000000..a434de2 --- /dev/null +++ b/CSV/CSVWriter.cs @@ -0,0 +1,50 @@ +using System.IO; + +namespace DotNetNuke.Modules.UserDefinedTable.CSV +{ + public class CSVWriter + { + public static void WriteCSV(string[] data, TextWriter sw, string delimiter) + { + for (var i = 0; i <= data.Length - 1; i++) + { + sw.Write(EncodeString(data[i], delimiter)); + //Not last, need a comma after + if (i != data.Length - 1) + { + sw.Write(delimiter); + } + } + sw.WriteLine(""); + sw.Flush(); + } + + static string EncodeString(string str, string delimiter) + { + string escaped; + var commaPos = str.IndexOf(delimiter); + var returnPos = str.IndexOf('\r'); + var quotePos = str.IndexOf('\u0022'); + + + //there are both commas and quotes in string, need to escape + if (quotePos >= 0) + { + //firstly, escape quotes + escaped = str.Replace("\u0022", "\u0022\u0022"); + } + else + { + escaped = str; + } + + //there is comma or quote in string, need to escape + if (commaPos >= 0 || quotePos >= 0 || returnPos >= 0) + { + escaped = ('\u0022' + escaped + '\u0022'); + } + + return escaped; + } + } +} \ No newline at end of file diff --git a/CaptionValueEditor.js b/CaptionValueEditor.js new file mode 100644 index 0000000..6f19114 --- /dev/null +++ b/CaptionValueEditor.js @@ -0,0 +1,136 @@ +(function ($) { + $.fn.CaptionValueEditor = function (options) { + + var settings = { + editLinkText: 'edit', + editImageUrl: '~/images/edit.png', + captionHeaderText: 'Caption', + valueHeaderText: 'Value', + addButtonText: 'add', + addImageUrl: '~/images/add.gif', + removeButtonText: 'remove', + removeImageUrl: '~/images/delete.gif', + saveButtonText: 'save', + cancelButtonText: 'cancel', + title: 'Edit', + dialogClass: 'dnnFormPopup dnnClear', + modal: true, + resizable: true, + width: 420, + height: 360 + }; + + if (options) { + $.extend(settings, options); + } + + var input = this; + var dialog; + + input.parent().append('' + settings.editLinkText + ''); + input.parent().append('
'); + + // in tabelle wandeln + $("#editCaptions").click(function () { + dialog = $("#cveditor").dialog(settings); + $("#popupCaptions").text(""); + $("#popupCaptions").append('
' + + '
' + + ''); + + $("#inputTbl > thead").append('' + settings.captionHeaderText + '' + settings.valueHeaderText + ''); + $("#inputTbl > tbody").remove(); + $("#inputTbl").append(""); + + if (input.val().indexOf(';') != -1 || $.trim(input.val()).length > 0) { + var splits = input.val().split(";"); + + for (var i = 0; i < splits.length; i++) { + var newLine = ""; + if (splits[i].indexOf('|') != -1) { + var kvp = splits[i].split('|'); + newLine = getRow(kvp[0], kvp[1], false); + } + else { + if ($.trim(splits[i]).length > 0) { + newLine = getRow("", splits[i], false); + } + } + + $("#inputTbl > tbody:last").append(newLine); + } + } + $("#inputTbl > tbody:last").append(getRow("", "", true)); +// $("#inputTbl tr:odd").addClass("dnnGridAltItem"); +// $("#inputTbl tr:even").addClass("dnnGridItem"); + $("#popupCaptions").show(); + }); + + // tabelle auslesen + $("#parse").live('click', function () { + var array = new Array(); + + $("#inputTbl > tbody tr").each(function () { + var value = $(this).find(':text'); + + var first = $.trim(value.first().val()); + var last = $.trim(value.last().val()); + + if (first.length > 0 && last.length > 0) { + if (first == last) { + array.push(first); + } else { + array.push(first + "|" + last); + } + } else if (last.length > 0) { + array.push(last); + } + }); + input.val(array.join(';')); + $("#popupCaptions").hide(); + dialog.dialog("close"); + }); + + $("#cancelEdit").live('click', function () { + $("#popupCaptions").hide(); + dialog.dialog("close"); + }); + + // zeile entfernen + $('a.rem').live('click', function () { + $(this).parent().parent().remove(); + }); + + // neue zeile + $('a.add').live('click', function () { + var values = $(this).parent().siblings().find(':text'); + var first = $.trim(values.first().val()); + var last = $.trim(values.last().val()); + + if (first.length > 0 || last.length > 0) { + $(this).hide(); + $(this).siblings(".rem").show(); + $("#inputTbl > tbody:last").append(getRow("", "", true)); + } + }); + + function getRow(key, value, isAdd) { + var row = ""; + + if (isAdd) { + row += "" + + "" + settings.addButtonText + ""; + } else { + row += "" + settings.removeButtonText + ""; + } + + row += '' + + ''; + + return row; + } + }; +})(jQuery); + + diff --git a/Cleanup_06.00.00.txt b/Cleanup_06.00.00.txt new file mode 100644 index 0000000..8134b4f --- /dev/null +++ b/Cleanup_06.00.00.txt @@ -0,0 +1,60 @@ +desktopModules\UserDefinedTable\resources.zip +bin\dotnetnuke.modules.userdefinedtable.sqldataprovider.dll +install\module\UserDefinedTable_03.03.06_Install.resources +install\module\UserDefinedTable_03.04.00_Install.resources +install\module\UserDefinedTable_03.05.00_Install.resources +install\module\UserDefinedTable_03.05.01_Install.resources +install\module\FormAndList_05.00.00_Install.resources +install\module\FormAndList_05.00.02_Install.resources +install\module\FormAndList_05.01.03_Install.resources +desktopModules\UserDefinedTable\UserDefinedTable.ascx +desktopModules\UserDefinedTable\UserDefinedTable.ascx.resx +desktopModules\UserDefinedTable\UserDefinedTable.ascx.vb +desktopModules\UserDefinedTable\MakeThumbnail.aspx +desktopModules\UserDefinedTable\MakeThumbnail.ashx +desktopModules\UserDefinedTable\MakeThumbnail.aspx.resx +desktopModules\UserDefinedTable\MakeThumbnail.aspx.vb +desktopModules\UserDefinedTable\ManageUserDefinedTable.ascx +desktopModules\UserDefinedTable\ManageUserDefinedTable.ascx.resx +desktopModules\UserDefinedTable\ManageUserDefinedTable.ascx.vb +desktopModules\UserDefinedTable\EditUserDefinedTable.ascx +desktopModules\UserDefinedTable\EditUserDefinedTable.ascx.resx +desktopModules\UserDefinedTable\EditUserDefinedTable.ascx.vb +desktopModules\UserDefinedTable\ShowXml.aspx +desktopModules\UserDefinedTable\ShowXml.ashx +desktopModules\UserDefinedTable\ShowXml.aspx.resx +desktopModules\UserDefinedTable\ShowXml.aspx.vb +desktopModules\UserDefinedTable\ImportCsv.vb +desktopModules\UserDefinedTable\DNN_UserDefinedTable.dnn.config +desktopModules\UserDefinedTable\03.01.00.SqlDataProvider +desktopModules\UserDefinedTable\03.02.00.SqlDataProvider +desktopModules\UserDefinedTable\03.03.00.SqlDataProvider +desktopModules\UserDefinedTable\03.03.04.SqlDataProvider +desktopModules\UserDefinedTable\03.03.05.SqlDataProvider +desktopModules\UserDefinedTable\03.03.06.SqlDataProvider +desktopModules\UserDefinedTable\03.03.07.SqlDataProvider +desktopModules\UserDefinedTable\03.04.00.SqlDataProvider +desktopModules\UserDefinedTable\03.05.00.SqlDataProvider +desktopModules\UserDefinedTable\03.05.01.SqlDataProvider +desktopModules\UserDefinedTable\03.05.02.SqlDataProvider +desktopModules\UserDefinedTable\Uninstall.SqlDataProvider +desktopModules\UserDefinedTable\resources.zip.manifest +desktopModules\UserDefinedTable\App_LocalResources\EditUserDefinedTable.ascx.resx +desktopModules\UserDefinedTable\App_LocalResources\ManageUserDefinedTable.ascx.resx +desktopModules\UserDefinedTable\App_LocalResources\UserDefinedTable.ascx.resx +desktopModules\UserDefinedTable\Components\DataTypeController.vb +desktopModules\UserDefinedTable\Components\PagingControl.vb +desktopModules\UserDefinedTable\Components\DataTypeController.vb +desktopModules\UserDefinedTable\Datatypes\Abstract_DataType.vb +desktopModules\UserDefinedTable\Datatypes\Abstract_EditControl.vb +desktopModules\UserDefinedTable\Providers\DataProviders\sqldataprovider\AssemblyInfo.vb +desktopModules\UserDefinedTable\core\iportable2.vb +desktopModules\UserDefinedTable\core\modulecontroller.vb +desktopModules\xslstylesheets\advancedtable.xsl +desktopModules\xslstylesheets\basictable.xsl +desktopModules\xslstylesheets\cardview.xsl +desktopModules\xslstylesheets\onlyownitems.xsl +desktopModules\xslstylesheets\transpose.xsl +desktopModules\img\dt-arrow-dn.png +desktopModules\img\dt-arrow-up.png +desktopModules\img\sprite.png \ No newline at end of file diff --git a/Components/BaseController.cs b/Components/BaseController.cs new file mode 100644 index 0000000..5dc3e51 --- /dev/null +++ b/Components/BaseController.cs @@ -0,0 +1,108 @@ +using System.Collections; +using System.Globalization; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Entities.Users; +using DotNetNuke.UI.Modules; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public abstract class BaseController + { + protected BaseController() + { + TabId = Null.NullInteger; + TabModuleId = Null.NullInteger; + } + + Hashtable _moduleSettings; + + ModuleInfo _configuration; + PortalInfo _portalInfo; + Components.Settings _settings; + + public Components.Settings Settings + { + get + { + if (_settings == null) + { + if (_moduleSettings == null) + { + var mc = new ModuleController(); + _moduleSettings = new Hashtable(mc.GetModuleSettings(ModuleId)); + if (TabModuleId != Null.NullInteger) + { + var tabModuleSettings = mc.GetTabModuleSettings(TabModuleId); + foreach (string strKey in tabModuleSettings.Keys) + { + _moduleSettings[strKey] = tabModuleSettings[strKey]; + } + } + } + _settings = new Settings(_moduleSettings); + } + return _settings; + } + } + + public ModuleInfo Configuration + { + get { return _configuration; } + set + { + _configuration = value; + ModuleId = value.ModuleID; + TabModuleId = value.TabModuleID; + TabId = value.TabID; + PortalId = value.PortalID; + } + } + + public int TabModuleId { get; set; } + + public UserInfo User { get; set; } + + public int TabId { get; set; } + + public PortalInfo PortalInfo + { + get { return _portalInfo ?? (_portalInfo = new PortalController().GetPortal(PortalId)); } + } + + public int ModuleId { get; set; } + + + protected int PortalId { get; set; } + + + public string EditUrlPattern { get; set; } + + public void Initialise(ModuleInstanceContext context) + { + _moduleSettings = context.Settings; + Configuration = context.Configuration; + User = context.PortalSettings.UserInfo; + + EditUrlPattern = context.EditUrl( DataTableColumn.RowId.ToString(CultureInfo.InvariantCulture), "{0}","edit"); + } + + public void Initialise(int moduleId, int tabId, UserInfo user) + { + ModuleId = moduleId; + TabId = tabId; + User = user; + } + + public void Initialise(int moduleId) + { + ModuleId = moduleId; + } + + public void Initialise(ModuleInfo moduleInfo) + { + Configuration = moduleInfo; + } + } +} \ No newline at end of file diff --git a/Components/DataProvider.cs b/Components/DataProvider.cs new file mode 100644 index 0000000..670c8cb --- /dev/null +++ b/Components/DataProvider.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.Data; +using DotNetNuke.Framework; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + /// ----------------------------------------------------------------------------- + /// + /// The DataProvider Class Is an abstract class that provides the DataLayer + /// for the UserDefinedTable Module. + /// + /// ----------------------------------------------------------------------------- + public abstract class DataProvider + { + #region Shared/Static Methods + + // singleton reference to the instantiated object + static DataProvider _provider; + + // constructor + static DataProvider() + { + CreateProvider(); + } + + // dynamically create provider + static void CreateProvider() + { + _provider = (DataProvider) (Reflection.CreateObject("data", "DotNetNuke.Modules.UserDefinedTable", "")); + } + + // return the provider + public static DataProvider Instance() + { + return _provider; + } + + #endregion + + #region Abstract methods + + public abstract void AddData(int UserDefinedRowID, int UserDefinedFieldID, string FieldValue); + + public abstract int AddField(int ModuleID, string FieldTitle, int before, string HelpText, bool Required, + string FieldType, string Default, bool Visible, bool ShowOnEdit, bool Searchable, + bool isPrivateColumn, bool MultipleValues, string inputSettings, + string outputSettings, bool NormalizeFlag, string validationRule, + string validationMessage, string EditStyle); + + public abstract int AddRow(int ModuleId); + + public abstract void FillDefaultData(int ModuleId, int FieldId, string DefaultValue); + + public abstract void DeleteData(int UserDefinedRowID, int UserDefinedFieldID); + + public abstract void DeleteField(int UserDefinedFieldID); + + public abstract void DeleteRow(int UserDefinedRowID, int ModuleId); + + public abstract void DeleteRows(int ModuleId); + + public abstract void Reset(int ModuleId); + + public abstract IDataReader GetData(int UserDefinedRowID, int UserDefinedFieldID); + + public abstract IDataReader GetField(int UserDefinedFieldId); + + public abstract IDataReader GetFields(int ModuleId); + + public abstract IDataReader GetRow(int UserDefinedRowId, int ModuleId); + + public abstract IDataReader GetRows(int ModuleId); + public abstract IDataReader GetFieldSettings(int moduleId); + public abstract void UpdateFieldSetting(int fieldid, string key, string value); + + + public abstract void UpdateData(int UserDefinedRowID, int UserDefinedFieldID, string FieldValue); + public abstract void UpdateData(int rowId, IDictionary values ); + + + public abstract void UpdateField(int UserDefinedFieldID, string FieldTitle, string HelpText, bool Required, + string FieldType, string Default, bool Visible, bool ShowOnEdit, + bool Searchable, bool isPrivateColumn, bool MultipleValues, + string inputSettings, string outputSettings, bool NormalizeFlag, + string validationRule, string validationMessage, string EditStyle); + + public abstract void SwapFieldOrder(int FirstUserDefinedFieldId, int SecondUserDefinedFieldId); + + public abstract int GetMaxFieldSize(); + + public abstract int GetFieldDataCount(int UserDefinedFieldID); + public abstract void SetFieldOrder(int UserDefinedFieldID, int FieldOrder); + + + #endregion + + + } +} \ No newline at end of file diff --git a/Components/DataTableExtensions.cs b/Components/DataTableExtensions.cs new file mode 100644 index 0000000..4b73bb1 --- /dev/null +++ b/Components/DataTableExtensions.cs @@ -0,0 +1,57 @@ +using System.Data; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public static class DataTableExtensions + { + static public DataTable Top(this DataTable dataTable, int topCount) + { + var topFilter = topCount; + if (topFilter > 0) + { + for (var index = dataTable.Rows.Count - 1; index >= topFilter; index--) + { + dataTable.Rows.RemoveAt(index); + } + } + return dataTable; + } + + static public DataTable FilterAndSort(this DataTable dataTable, string filter, string sortField, string sortOrder) + { + var sort = string.Empty; + if (sortField != string.Empty && sortOrder != string.Empty) + { + sort = string.Format("{0} {1}", sortField, sortOrder); + } + var dv = new DataView(dataTable) {RowFilter = filter, Sort = sort}; + + var filteredtable = dv.ToTable(); + dataTable.Clear(); + dataTable.Merge(filteredtable); + return dataTable; + } + + static public DataTable Page(this DataTable dataTable, int pageIndex, int pageSize) + { + if (pageSize > 0) + { + var indexOfFirstItem = pageIndex * pageSize; + var rows = dataTable.Rows; + if (indexOfFirstItem < rows.Count) + { + for (var index = indexOfFirstItem - 1; index >= 0; index--) + { + rows.RemoveAt(index); + } + } + + for (var index = rows.Count - 1; index >= pageSize; index--) + { + rows.RemoveAt(index); + } + } + return dataTable; + } + } +} \ No newline at end of file diff --git a/Components/DnnExtensionMethods.cs b/Components/DnnExtensionMethods.cs new file mode 100644 index 0000000..747ab1f --- /dev/null +++ b/Components/DnnExtensionMethods.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using DotNetNuke.Entities.Users; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public static class DnnExtensionMethods + { + public static string GetSafeUsername(this UserInfo userInfo) + { + if (userInfo.Username == null) + return Definition.NameOfAnonymousUser; + else + return userInfo.Username; + } + public static string GetSafeDisplayname(this UserInfo userInfo) + { + if (userInfo.Username == null) + return Definition.NameOfAnonymousUser; + else + return userInfo.DisplayName; + } + } +} \ No newline at end of file diff --git a/Components/DownloadPropertyAccess.cs b/Components/DownloadPropertyAccess.cs new file mode 100644 index 0000000..82eafdd --- /dev/null +++ b/Components/DownloadPropertyAccess.cs @@ -0,0 +1,102 @@ +using System.Globalization; +using System.IO; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Tabs; +using DotNetNuke.Entities.Users; +using DotNetNuke.Services.FileSystem; +using DotNetNuke.Services.Tokens; +using Microsoft.VisualBasic; +using Microsoft.VisualBasic.CompilerServices; +using Globals = DotNetNuke.Common.Globals; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public class DownloadPropertyAccess : IPropertyAccess + { + readonly string _fileIdentifier; + IFileInfo _currentFile; + readonly int _moduleId; + readonly int _portalId; + + public DownloadPropertyAccess(string id, int portalId, int moduleId) + { + _fileIdentifier = id; + _portalId = portalId; + _moduleId = moduleId; + } + + IFileInfo File + { + get + { + if (_currentFile == null) + { + if (LikeOperator.LikeString(_fileIdentifier, "FileID=*", CompareMethod.Binary)) + { + _currentFile = FileManager.Instance.GetFile(int.Parse(UrlUtils.GetParameterValue(_fileIdentifier))); + } + else + { + if (Globals.GetURLType(_fileIdentifier) == TabType.File) + { + var fileName = Path.GetFileName(_fileIdentifier); + var folderInfo = FolderManager.Instance.GetFolder(_portalId, + _fileIdentifier.Replace(fileName, "")); + if (folderInfo != null) + { + _currentFile = FileManager.Instance.GetFile(folderInfo,fileName); + } + } + } + } + return _currentFile; + } + } + + + public CacheLevel Cacheability + { + get { return CacheLevel.fullyCacheable; } + } + + public string GetProperty(string strPropertyName, string strFormat, CultureInfo formatProvider, + UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) + { + string outputFormat = strFormat == string.Empty ? "g" : strFormat; + + strPropertyName = strPropertyName.ToLowerInvariant(); + + if (File != null) + { + switch (strPropertyName) + { + case "name": + return PropertyAccess.FormatString(File.FileName, strFormat); + case "folder": + return + PropertyAccess.FormatString( + FolderManager.Instance.GetFolder( File.FolderId).FolderName , + strFormat); + case "path": + return + PropertyAccess.FormatString( + FolderManager.Instance.GetFolder(File.FolderId).FolderPath, + strFormat); + case "size": + return File.Size.ToString(outputFormat, formatProvider); + case "sizemb": + return (File.Size/1024 ^ 2).ToString(outputFormat, formatProvider); + case "extension": + return PropertyAccess.FormatString(File.Extension, strFormat); + } + } + if (strPropertyName == "clicks") + { + var tracking = new UrlController().GetUrlTracking(_portalId, _fileIdentifier, _moduleId); + return tracking != null ? tracking.Clicks.ToString(outputFormat, formatProvider) : ""; + } + propertyNotFound = true; + return string.Empty; + } + } +} \ No newline at end of file diff --git a/Components/EditControls.cs b/Components/EditControls.cs new file mode 100644 index 0000000..0bcc2d4 --- /dev/null +++ b/Components/EditControls.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Data; +using DotNetNuke.Modules.UserDefinedTable.Interfaces; +using DotNetNuke.UI.Modules; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + /// ----------------------------------------------------------------------------- + /// + /// EditControls acts as a Factory and Collection for concrete "EditControl"s + /// + /// ----------------------------------------------------------------------------- + public class EditControls : Dictionary + { + readonly ModuleInstanceContext _moduleContext; + readonly bool _inputFilterScript; + readonly bool _inputFilterTags; + + public EditControls(ModuleInstanceContext moduleContext) + { + _moduleContext = moduleContext; + var isAdmin = ModuleSecurity.IsAdministrator(); + var isAnonymous = Convert.ToBoolean(moduleContext.PortalSettings.UserId == - 1); + _inputFilterScript = + Convert.ToBoolean( + !(isAdmin && ! moduleContext.Settings[SettingName.ForceInputFiltering].AsBoolean())); + _inputFilterTags = + Convert.ToBoolean(! isAdmin && + (isAnonymous || + moduleContext.Settings[SettingName.ForceInputFiltering].AsBoolean())); + } + + public EditControl Add(string fieldTitle, string fieldType, int fieldId, string controlHelpText, + string defaultValue, bool required, string validationRule, string validationMsg, + string editStyle, string inputSettings, string outputSettings, bool normalizeFlag, + bool multipleValuesFlag, DataTable fieldSettingsTable, IFormEvents formEvents) + { + var editor = DataType.ByName(fieldType).EditControl; + + var tr = new TokenReplace {ModuleInfo = _moduleContext.Configuration}; + var strDefaultValue = tr.ReplaceEnvironmentTokens(defaultValue); + + var listInputType = EditControl.InputType.DropdownList; + if (inputSettings.EndsWith(Definition.verticalRadioButtonEnabledToken)) + { + inputSettings = + inputSettings.Remove(inputSettings.Length - Definition.verticalRadioButtonEnabledToken.Length); + listInputType = EditControl.InputType.verticalRadioButtons; + } + else if (inputSettings.EndsWith(Definition.horizontalRadioButtonEnabledToken)) + { + inputSettings = + inputSettings.Remove(inputSettings.Length - Definition.horizontalRadioButtonEnabledToken.Length); + listInputType = EditControl.InputType.horizontalRadioButtons; + } + + editor.Initialise(fieldTitle, fieldType, fieldId, _moduleContext.ModuleId, controlHelpText, strDefaultValue, + required, validationRule, validationMsg, editStyle, inputSettings, outputSettings, + normalizeFlag, multipleValuesFlag, _inputFilterTags, _inputFilterScript, listInputType, + _moduleContext,fieldSettingsTable , formEvents ); + + editor.ID = string.Format("Edit{0}", fieldId); + Add(fieldTitle, editor); + return editor; + } + } +} \ No newline at end of file diff --git a/Components/FieldController.cs b/Components/FieldController.cs new file mode 100644 index 0000000..cc2b4f9 --- /dev/null +++ b/Components/FieldController.cs @@ -0,0 +1,203 @@ +using System.Collections.Generic; +using System.Data; +using System.Globalization; +using DotNetNuke.Common; +using DotNetNuke.Common.Utilities; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public class FieldController + { + public static void ChangeFieldOrder(IEnumerable fieldIds) + { + var i = 0; + foreach (var fieldId in fieldIds) + { + DataProvider.Instance().SetFieldOrder(fieldId, i++); + } + } + + public static int GetMaxFieldSize() + { + return DataProvider.Instance().GetMaxFieldSize(); + } + + public static void DeleteField(int userDefinedFieldId) + { + DataProvider.Instance().DeleteField(userDefinedFieldId); + } + + /// ----------------------------------------------------------------------------- + /// + /// persists a new column setting in the database + /// + /// ID of the column + /// ID of the column + /// + /// + /// is an entry in this column required, when adding a row? + /// type name of data field + /// default value, entered when a new row is added + /// is this column visible in list view? + /// + /// + /// is this column available for search in list view? + /// + /// additional settings stored in single string + /// additional settings stored in single string + /// display flag, usage dependant on data type + /// optional expresion that needs to be true, to successfully enter a record + /// displayed, if validation rules is eveluated to "false" + /// + /// The ID of the created Field + /// ----------------------------------------------------------------------------- + public static int AddField(int moduleId, string fieldTitle, int before, string helpText, bool required, + string fieldType, string Default, + bool visible, bool showOnEdit, bool searchable, bool isPrivateColumn, + bool multipleValues, + string inputSettings, string outputSettings, bool normalizeFlag, + string validationRule, + string validationMessage, string editStyle) + { + return DataProvider.Instance().AddField(moduleId, fieldTitle, before, helpText, required, fieldType, Default, + visible, showOnEdit, searchable, isPrivateColumn, multipleValues, + inputSettings, outputSettings, normalizeFlag, validationRule, + validationMessage, editStyle); + } + + public static int AddField(int moduleId, string fieldTitle) + { + return AddField(moduleId, fieldTitle, Null.NullInteger, string.Empty, false, + DataTypeNames.UDT_DataType_String, + string.Empty, true, true, true, false, false, string.Empty, string.Empty, false, + string.Empty, string.Empty, string.Empty); + } + + /// ----------------------------------------------------------------------------- + /// + /// persists an altered column setting in the database + /// + /// ID of the column field + /// ID of the column + /// + /// is an entry in this column required, when adding a row? + /// type name of data field + /// default value, entered when a new row is added + /// is this column visible in list view? + /// + /// is this column available for search in list view? + /// + /// additional settings stored in single string + /// additional settings stored in single string + /// display flag, usage dependant on data type + /// optional expresion that needs to be true, to successfully enter a record + /// displayed, if validation rules is eveluated to "false" + /// + /// + /// ----------------------------------------------------------------------------- + public static void UpdateField(int userDefinedFieldId, string fieldTitle, string helpText, bool required, + string fieldType, string Default, bool visible, bool showOnEdit, bool searchable, + bool isPrivateColumn, bool multipleValues, string inputSettings, string outputSettings, + bool normalizeFlag, string validationRule, string validationMessage, string editStyle) + { + DataProvider.Instance().UpdateField(userDefinedFieldId, fieldTitle, helpText, required, fieldType, Default, + visible, showOnEdit, searchable, isPrivateColumn, multipleValues, + inputSettings, outputSettings, normalizeFlag, validationRule, + validationMessage, editStyle); + } + + + /// ----------------------------------------------------------------------------- + /// + /// Gets all field definitions for one UDT table (module) from the database + /// + /// All field settings as DataTable + /// ----------------------------------------------------------------------------- + public static DataTable GetFieldsTable(int moduleId) + { + return GetFieldsTable(moduleId, false); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets all field definitions for one UDT table (module) from the database + /// + /// + /// specifies, whether a new column shall be added + /// All field settings as DataTable + /// ----------------------------------------------------------------------------- + public static DataTable GetFieldsTable(int moduleId, bool addNewColumn) + { + return GetFieldsTable( moduleId, addNewColumn, true); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets all field definitions for one UDT table (module) from the database + /// + /// + /// specifies, whether a new column shall be added + /// specifies, whether colums for creation and update (user and timestamp) shall be added + /// All field settings as DataTable + /// ----------------------------------------------------------------------------- + public static DataTable GetFieldsTable(int moduleId, bool addNewColumn, bool addAuditColumns) + { + DataTable fieldsTable; + using (var dr = DataProvider.Instance().GetFields(moduleId)) + { + fieldsTable = Globals.ConvertDataReaderToDataTable(dr); + } + + + //Insert CreatedBy & Co Fields + if (addAuditColumns && fieldsTable.Rows.Count == 0) + { + const int order = 0; + foreach (var localizedFieldType in DataType.SystemDataTypes().Keys) + { + AddField(moduleId , localizedFieldType, order, string.Empty, true, + DataType.SystemDataTypes()[localizedFieldType], + string.Empty, false, false, false, false, false, string.Empty, string.Empty, false, + string.Empty, string.Empty, string.Empty); + } + return GetFieldsTable(moduleId, addNewColumn); + //Reload fields again + } + + if (addNewColumn) + { + //find position (insert before first trailing "insert/updated by/at" field): + var pos = fieldsTable.Rows.Count; + var intOrder = 0; + while (pos >= 1) + { + var fieldType = fieldsTable.Rows[pos - 1]["FieldType"].ToString(); + if (DataType.ByName(fieldType).IsUserDefinedField) + { + break; + } + pos--; + intOrder = int.Parse((fieldsTable.Rows[pos]["FieldOrder"].ToString())); + } + var row = fieldsTable.NewRow(); + row[FieldsTableColumn.Id] = Null.NullInteger.ToString(CultureInfo.InvariantCulture); + row[FieldsTableColumn.Title] = string.Empty; + row[FieldsTableColumn.Required] = false; + row[FieldsTableColumn.Type] = "String"; + row[FieldsTableColumn.Default] = string.Empty; + row[FieldsTableColumn.Visible] = true; + row[FieldsTableColumn.Searchable] = false; + row[FieldsTableColumn.IsPrivate] = false; + row[FieldsTableColumn.NormalizeFlag] = false; + row[FieldsTableColumn.Order] = intOrder; + row[FieldsTableColumn.ShowOnEdit] = true; + fieldsTable.Rows.InsertAt(row, pos); + } + return fieldsTable; + } + + + + + } +} \ No newline at end of file diff --git a/Components/FieldSettingsController.cs b/Components/FieldSettingsController.cs new file mode 100644 index 0000000..074d577 --- /dev/null +++ b/Components/FieldSettingsController.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using DotNetNuke.Common; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public static class FieldSettingsController + { + public static DataTable GetFieldSettingsTable(int moduleId) + { + DataTable fieldSettingsTable; + using (var dr = DataProvider.Instance().GetFieldSettings(moduleId)) + { + fieldSettingsTable = Globals.ConvertDataReaderToDataTable(dr); + } + fieldSettingsTable.TableName = DataSetTableName.FieldSettings; + return fieldSettingsTable; + } + + public static string GetFieldSetting(this DataTable table, string key, int fieldId) + { + var r = table.Select(String.Format("FieldId={0} and SettingName='{1}'", fieldId, key)).FirstOrDefault(); + return (string)(r == null ? null : r["SettingValue"]); + } + + public static void UpdateFieldSetting( string key, string value, int fieldId) + { + DataProvider.Instance().UpdateFieldSetting(fieldId, key, value); + } + + public static DataView WithFieldId(this DataTable table, int fieldId) + { + var filter = (String.Format("FieldId={0}", fieldId)); + return new DataView(table, filter, string.Empty, DataViewRowState.CurrentRows); + } + + + } +} \ No newline at end of file diff --git a/Components/FilteredNameValueCollectionPropertyAccess.cs b/Components/FilteredNameValueCollectionPropertyAccess.cs new file mode 100644 index 0000000..164e5ce --- /dev/null +++ b/Components/FilteredNameValueCollectionPropertyAccess.cs @@ -0,0 +1,47 @@ +using System.Collections.Specialized; +using System.Globalization; +using DotNetNuke.Entities.Users; +using DotNetNuke.Security; +using DotNetNuke.Services.Tokens; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public class FilteredNameValueCollectionPropertyAccess : IPropertyAccess + { + readonly NameValueCollection NameValueCollection; + + public FilteredNameValueCollectionPropertyAccess(NameValueCollection list) + { + NameValueCollection = list; + } + + + public CacheLevel Cacheability + { + get { return CacheLevel.notCacheable; } + } + + public string GetProperty(string strPropertyName, string strFormat, CultureInfo formatProvider, + UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) + { + if (NameValueCollection == null) + { + return string.Empty; + } + var value = NameValueCollection[strPropertyName]; + + if (value != null) + { + var security = new PortalSecurity(); + value = security.InputFilter(value, PortalSecurity.FilterFlag.NoScripting); + return security.InputFilter(PropertyAccess.FormatString(value, strFormat), + PortalSecurity.FilterFlag.NoScripting); + } + else + { + PropertyNotFound = true; + return string.Empty; + } + } + } +} \ No newline at end of file diff --git a/Components/FormColumnInfo.cs b/Components/FormColumnInfo.cs new file mode 100644 index 0000000..35f8dae --- /dev/null +++ b/Components/FormColumnInfo.cs @@ -0,0 +1,63 @@ +using System.Web.UI; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public class FormColumnInfo + { + bool _isUserDefinedField = true; + + + public string Title { get; set; } + public string Help { get; set; } + public Control EditControl { get; set; } + public bool Visible { get; set; } + public bool Required { get; set; } + public bool IsCollapsible { get; set; } + public bool IsSeparator { get; set; } + + public bool IsUserDefinedField + { + get { return _isUserDefinedField; } + set { _isUserDefinedField = value; } + } + + public Control ValueControl + { + get + { + if ((EditControl) is EditControl) + { + return ((EditControl) EditControl).ValueControl; + } + else + { + return (null); + } + } + } + + + public string FieldType + { + get + { + if ((EditControl) is EditControl) + { + return ((EditControl) EditControl).FieldType; + } + else if (IsSeparator) + { + return "Separator"; + } + else if (IsCollapsible) + { + return "FieldSet"; + } + else + { + return "Captcha"; + } + } + } + } +} \ No newline at end of file diff --git a/Components/GlobalConstants.cs b/Components/GlobalConstants.cs new file mode 100644 index 0000000..23ec0d7 --- /dev/null +++ b/Components/GlobalConstants.cs @@ -0,0 +1,168 @@ +using DotNetNuke.Services.Localization; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public class RenderingMethod + { + public const string GridRendering = "DataGrid"; + public const string UserdefinedXSL = "XslUserDefinedStyleSheet"; + public const string PredefinedXSL = "XslPreDefinedStyleSheet"; + } + + + public class Definition + { + public const string NameOfAnonymousUser = "Anonymous"; + public const string PathOfCustomConfig = "/Portals/_Default/UserDefinedTable/"; + public const string PathOfModule = "/DesktopModules/UserDefinedTable/"; + public const string ModuleDefinitionFriendlyName = "Form and List"; + public const string ModuleName = "DNN_UserDefinedTable"; + public const string QueryStringParameter = "udt_{0}_param"; + public const string XSLFolderName = "XslStyleSheets"; + public const string TemplateFolderName = "templates"; + public const string horizontalRadioButtonEnabledToken = "-[[hRBL]]"; + public const string verticalRadioButtonEnabledToken = "-[[vRBL]]"; + + public static readonly string SharedRessources = string.Format("~{0}{1}/SharedRescources.resx", PathOfModule, + Localization.LocalResourceDirectory); + } + + public class PermissionName + { + public const string HasEditRowPermission = "ROWEDIT"; + public const string HasDeleteRowPermission = "ROWDELETE"; + public const string HasAddRowPermission = "ROWADD"; + public const string ShowAllUserDefinedColumnsPermission = "COLUMNVISIBLE"; + public const string EditRestricedFieldsPermission = "PRIVATECOLUMNS"; + public const string ShowListPermission = "SHOWLIST"; + public const string Code = "UDTEDIT"; + } + + public class DataSetTableName + { + public const string Fields = "Fields"; + public const string FieldSettings = "FieldSettings"; + public const string Data = "Data"; + public const string Settings = "Settings"; + public const string TabSettings = "TabSettings"; + public const string Stylesheets = "XSL"; + } + + public class FieldsTableColumn + { + public const string Id = "UserDefinedFieldId"; + public const string Title = "FieldTitle"; + public const string Required = "Required"; + public const string Type = "FieldType"; + public const string HelpText = "HelpText"; + public const string Default = "Default"; + public const string Visible = "Visible"; + public const string ShowOnEdit = "ShowOnEdit"; + public const string ValueColumn = "ValueColumn"; + public const string SortColumn = "SortColumn"; + public const string Order = "FieldOrder"; + public const string Searchable = "Searchable"; + public const string IsPrivate = "PrivateField"; + public const string MultipleValues = "MultipleValues"; + public const string InputSettings = "InputSettings"; + public const string OutputSettings = "OutputSettings"; + public const string NormalizeFlag = "NormalizeFlag"; + public const string ValidationMessage = "ValidationMessage"; + public const string ValidationRule = "ValidationRule"; + public const string EditStyle = "EditStyle"; + } + + public class DataTypeNames + { + public const string UDT_DataType_CreatedBy = "CreatedBy"; + public const string UDT_DataType_CreatedAt = "CreatedAt"; + public const string UDT_DataType_ChangedBy = "ChangedBy"; + public const string UDT_DataType_ChangedAt = "ChangedAt"; + public const string UDT_DataType_String = "String"; + } + + public class DataTableColumn + { + public const string EditLink = "EditLink"; + public const string Value = "FieldValue"; + public const string RowId = "UserDefinedRowId"; + public const string Appendix_Prefix = "_UDT_"; + public const string Appendix_Url = Appendix_Prefix + "Url"; + public const string Appendix_Ticks = Appendix_Prefix + "Ticks"; + public const string Appendix_Original = Appendix_Prefix + "Original"; + public const string Appendix_LocalizedValue = Appendix_Prefix + "Value"; + public const string Appendix_Caption = Appendix_Prefix + "Caption"; + } + + public class SettingsTableColumn + { + public const string Value = "Value"; + public const string Setting = "Setting"; + } + + public class StylesheetTableColumn + { + public const string NameOfSetting = "Type"; + public const string LocalFilePath = "LocalFilePath"; + public const string Stylesheet = "Stylesheet"; + } + + public class SettingName + { + // public const string UsedCssClasses = "UDT_UsedCssClasses"; + public const string ImageWidth = "UDT_ImageWidth"; + public const string ImageHeight = "UDT_ImageHeight"; + public const string Paging = "UDT_Paging"; + public const string RenderingMethod = "UDT_RenderingMethod"; + public const string SortField = "UDT_SortField"; + public const string SortOrder = "UDT_SortOrder"; + public const string CalculatedColumnsRenderExpressionInForm = "CalculatedColumnsRenderExpressionInForm"; + public const string URLNewWindow = "UDT_URLNewWindow"; + public const string URLDownloadTracking = "UDT_ URLDownloadTracking"; + public const string UserLinkNewWindow = "UDT_UserLinkNewWindow"; + public const string UserLinkCaption = "UDT_UserLinkUserName"; + public const string CnCLink = "UDT_CnCLink"; + public const string XslPreDefinedStyleSheet = "UDT_XslPreDefinedStyleSheet"; + public const string XslUserDefinedStyleSheet = "UDT_XslUserDefinedStyleSheet"; + public const string ShowSearchTextBox = "UDT_ShowSearchTextBox"; + public const string ShowNoRecordsUntilSearch = "UDT_ShowNoRecordsUntilSearch"; + public const string SimpleSearch = "UDT_SimpleSearch"; + public const string URLSearch = "UDT_URLSearch"; + // public const string UseButtons = "UDT_UseButtons"; + public const string ForceCaptchaForAnonymous = "UDT_ForceCaptchaForAnonymous"; + public const string ForceInputFiltering = "UDT_ForceFiltering"; + public const string EditOnlyOwnItems = "UDT_EditOnlyOwnItems"; + public const string ExcludeFromSearch = "UDT_ExcludeFromSearch"; + public const string UserRecordQuota = "UDT_UserRecordQuota"; + public const string Filter = "UDT_Filter"; + public const string Search = "UDT_Search"; + public const string ListOrForm = "UDT_ListNotFormsMode"; + //public const string ShowListRequiresPermission = "UDT_ShowListRequiresPermission"; + public const string SubmissionText = "UDT_Submission_succeeded"; + // public const string TrackingEnabled = "UDT_EnableTracking"; + public const string TrackingEmailFrom = "UDT_TokenTrackingFrom"; + public const string TrackingEmailReplyTo = "UDT_TokenTrackingReplyTo"; + public const string TrackingEmailTo = "UDT_TokenTracking"; + public const string TrackingEmailCc = "UDT_TokenTrackingCC"; + public const string TrackingEmailBcc = "UDT_TokenTrackingBCC"; + public const string TrackingScript = "UDT_XslTracking"; + public const string TrackingSubject = "UDT_TrackingSubject"; + public const string TrackingTriggerOnNew = "UDT_TriggerOnNew"; + public const string TrackingTriggerOnUpdate = "UDT_TriggerOnUpdate"; + public const string TrackingTriggerOnDelete = "UDT_TriggerOnDelete"; + public const string TrackingTextOnNew = "UDT_TrackingTextOnNew"; + public const string TrackingTextOnUpdate = "UDT_TrackingTextOnUpdate"; + public const string TrackingTextOnDelete = "UDT_TrackingTextOnDelete"; + public const string TrackingMessage = "UDT_TrackingMessage"; + public const string ShowSystemColumns = "UDT_ShowSystemColumns"; + public const string EditPrivateColumnsForAdmins = "UDT_EditPrivateColumnsForAdmins"; + public const string ShowAllColumnsForAdmins = "UDT_ShowAllColumnsForAdmins"; + // public const string TableFreeEditForm = "UDT_TableFreeEditForm"; + public const string TopCount = "UDT_TopCount"; + //public const string ControlFullWidth = "UDT_ControlFullWidth"; + public const string ForceDownload = "UDT_ForceDownload"; + public const string UponSubmitAction = "UDT_UponSubmitAction"; + public const string UponSubmitRedirect = "UDT_UponSubmitRedirect"; + public const string UseButtonsInForm = "UseButtonsInForm"; + } +} \ No newline at end of file diff --git a/Components/GravatarPropertyAccess.cs b/Components/GravatarPropertyAccess.cs new file mode 100644 index 0000000..64fd4cc --- /dev/null +++ b/Components/GravatarPropertyAccess.cs @@ -0,0 +1,62 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using DotNetNuke.Entities.Users; +using DotNetNuke.Services.Tokens; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public class GravatarPropertyAccess : IPropertyAccess + { + readonly string _email; + + public GravatarPropertyAccess(string email) + { + _email = email.Trim().ToLowerInvariant(); + } + + public CacheLevel Cacheability + { + get { return CacheLevel.notCacheable; } + } + + public string GetProperty(string strPropertyName, string strFormat, CultureInfo formatProvider, + UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) + { + strPropertyName = strPropertyName.ToLowerInvariant(); + switch (strPropertyName) + { + case "md5hash": + return PropertyAccess.FormatString(Md5Hash(_email), strFormat); + case "url": + return + PropertyAccess.FormatString( + string.Format("http://www.gravatar.com/avatar/{0}", Md5Hash(_email)), strFormat); + case "image": + return + PropertyAccess.FormatString( + string.Format("\"gravatar\"", + Md5Hash(_email)), strFormat); + default: + propertyNotFound = true; + return string.Empty; + } + } + + static string Md5Hash(string value) + { + using (var serviceProvider = new MD5CryptoServiceProvider()) + { + var bytesToHash = Encoding.ASCII.GetBytes(value); + bytesToHash = serviceProvider.ComputeHash(bytesToHash); + + var sb = new StringBuilder(); + foreach (var b in bytesToHash) + { + sb.Append(b.ToString("x2")); + } + return sb.ToString(); + } + } + } +} \ No newline at end of file diff --git a/Components/ModuleSecurity.cs b/Components/ModuleSecurity.cs new file mode 100644 index 0000000..b91e727 --- /dev/null +++ b/Components/ModuleSecurity.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections; +using System.Data; +using DotNetNuke.Common; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Host; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Users; +using DotNetNuke.Security; +using DotNetNuke.Security.Permissions; +using DotNetNuke.UI.Modules; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public class ModuleSecurity + { + readonly bool _hasEditRowPermission; + readonly bool _hasDeleteRowPermission; + readonly bool _hasAddRowPermission; + readonly bool _hasShowAllUserDefinedColumnsPermission; + readonly bool _hasEditPrivateColumnsPermission; + readonly bool _hasViewListPermission; + readonly bool _isOnlyAllowedToManipulateHisOwnData; + readonly bool _canEditModuleContent; + readonly bool _canManageModule; + + Components.Settings Settings { get; set; } + + //public ModuleSecurity(int moduleId, int tabId, Hashtable settings) + //{ + // var moduleController = new ModuleController(); + // var s = settings ?? moduleController.GetModuleSettings(moduleId); + // Settings = new Settings(s); + // return this.ModuleSecurity(moduleId, tabId, Settings); + //} + + public ModuleSecurity(int moduleId, int tabId, Components.Settings settings) + { + var moduleController = new ModuleController(); + Settings = settings ?? new Settings(moduleController.GetModuleSettings(moduleId)); + var moduleInfo = moduleController.GetModule(moduleId, tabId); + if (moduleInfo == null) return; + var mp = moduleInfo.ModulePermissions; + _hasEditRowPermission = ModulePermissionController.HasModulePermission(mp, PermissionName.HasEditRowPermission); + _hasDeleteRowPermission = ModulePermissionController.HasModulePermission(mp, PermissionName.HasDeleteRowPermission); + _hasAddRowPermission = ModulePermissionController.HasModulePermission(mp,PermissionName.HasAddRowPermission); + _hasEditPrivateColumnsPermission = ModulePermissionController.HasModulePermission(mp,PermissionName.EditRestricedFieldsPermission); + _hasShowAllUserDefinedColumnsPermission = ModulePermissionController.HasModulePermission(mp,PermissionName.ShowAllUserDefinedColumnsPermission); + _canEditModuleContent = ModulePermissionController.CanEditModuleContent(moduleInfo); + _canManageModule = ModulePermissionController.CanManageModule(moduleInfo); + + _hasViewListPermission = ModulePermissionController.HasModulePermission(mp, + PermissionName.ShowListPermission); + _isOnlyAllowedToManipulateHisOwnData = Settings.EditOnlyOwnItems; + } + + public ModuleSecurity(int moduleId, int tabId) : this(moduleId, tabId, null) + { + } + + public ModuleSecurity(ModuleInstanceContext context) : this(context.ModuleId, context.TabId, new Settings( context.Settings )) + { + } + + public bool IsAllowedToEditRow(bool isUsersOwnRow = true) + { + return _canEditModuleContent || + (_hasEditRowPermission && (! _isOnlyAllowedToManipulateHisOwnData || isUsersOwnRow)); + } + + public bool IsAllowedToDeleteRow(bool isUsersOwnRow = true) + { + return _canEditModuleContent || + (_hasDeleteRowPermission && (! _isOnlyAllowedToManipulateHisOwnData || isUsersOwnRow)); + } + + public bool IsAllowedToAddRow() + { + return _canEditModuleContent || _hasAddRowPermission; + } + + public bool IsAllowedToEditAllColumns() + { + return _hasEditPrivateColumnsPermission && + Settings.EditPrivateColumnsForAdmins || + _canEditModuleContent && Settings.EditPrivateColumnsForAdmins ; + } + + public bool IsAllowedToSeeAllUserDefinedColumns() + { + return _hasShowAllUserDefinedColumnsPermission && Settings.ShowAllColumnsForAdmins; + } + + public bool IsAllowedToAdministrateModule() + { + return _canManageModule; + } + + public bool IsAllowedToViewList() + { + switch (Settings.ListOrForm ) + { + case "Form": //List is normaly hidden + return _canEditModuleContent || _hasViewListPermission; + case "FormAndList": + case "ListAndForm": + return _hasViewListPermission; + default: + return false; + } + } + + public static bool IsAdministrator() + { + var administratorRoleName = Globals.GetPortalSettings().AdministratorRoleName; + return PortalSecurity.IsInRole(administratorRoleName); + } + + public static string RoleNames(UserInfo user) + { + string roles = user.Roles != null ? string.Format("|{0}", string.Join("|", user.Roles)) : ""; + roles += string.Format("|{0}", Globals.glbRoleAllUsersName); + if (IsAdministrator()) + { + roles += string.Format("|{0}", Globals.GetPortalSettings().AdministratorRoleName); + } + return string.Format("{0}|", roles); + } + + + public static string BestUserName(string userName, int portalId) + { + var cacheKey = string.Format("UDT_BestUserNameFor{0}", userName); + + var bestUserName = DataCache.GetCache(cacheKey).AsString(); + + if (bestUserName == string.Empty) + { + var ui = UserController.GetUserByName(portalId, userName); + bestUserName = ui == null ? userName.AsString("Unknown Account") : ui.DisplayName; + + // cache data + var intCacheTimeout = Convert.ToInt32(20*Convert.ToInt32(Host.PerformanceSetting)); + DataCache.SetCache(cacheKey, bestUserName, TimeSpan.FromMinutes(intCacheTimeout)); + } + + return bestUserName; + } + + public static int UserId(string username, int portalId) + { + var strCacheKey = string.Format("UDT_UserIDFor{0}", username); + + var id = DataCache.GetCache(strCacheKey).AsInt(); + + if (id == Null.NullInteger) + { + var ui = UserController.GetUserByName(portalId, username); + id = ui == null ? 0 : Convert.ToInt32(ui.UserID); + + // cache data + var intCacheTimeout = Convert.ToInt32(20*Convert.ToInt32(Host.PerformanceSetting)); + DataCache.SetCache(strCacheKey, id, TimeSpan.FromMinutes(intCacheTimeout)); + } + return id; + } + + + public static bool HasAddPermissonByQuota(DataTable fieldsTable, DataTable dataTable, int userRecordQuota, + string username) + { + if (userRecordQuota > 0) + { + string titleOfCreatedByColumn; + using ( + var schemaOfCreatedByColumn = new DataView(fieldsTable, + string.Format("[{0}]=\'{1}\'", FieldsTableColumn.Type, + DataTypeNames.UDT_DataType_CreatedBy), "", + DataViewRowState.CurrentRows)) + { + titleOfCreatedByColumn = schemaOfCreatedByColumn[0][FieldsTableColumn.Title].AsString(); + } + + + var isDataTableWithPreRenderedValues = + dataTable.Columns.Contains(titleOfCreatedByColumn + DataTableColumn.Appendix_Original); + if (isDataTableWithPreRenderedValues) + { + titleOfCreatedByColumn = titleOfCreatedByColumn + DataTableColumn.Appendix_Original; + } + + using ( + var dv = new DataView(dataTable, + string.Format("[{0}] = \'{1}\'", titleOfCreatedByColumn, + username.Replace("\'", "\'\'")), "", + DataViewRowState.CurrentRows)) + { + return dv.Count < userRecordQuota; + } + } + return true; + } + } +} \ No newline at end of file diff --git a/Components/Settings.cs b/Components/Settings.cs new file mode 100644 index 0000000..c33f94e --- /dev/null +++ b/Components/Settings.cs @@ -0,0 +1,215 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using DotNetNuke.Common.Utilities; +using Microsoft.VisualBasic; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public class Settings + { + readonly Hashtable _settings; + + public Settings(Hashtable settings) + { + _settings = settings; + } + + public bool EditOnlyOwnItems + { + get { return _settings[SettingName.EditOnlyOwnItems].AsBoolean(); } + } + + public bool EditPrivateColumnsForAdmins + { + get { return _settings[SettingName.EditPrivateColumnsForAdmins].AsBoolean(); } + } + + public string Filter + { + get { return _settings[SettingName.Filter].AsString(); } + } + + public bool ForceCaptchaForAnonymous + { + get { return _settings[SettingName.ForceCaptchaForAnonymous].AsBoolean(); } + } + + public string ListOrForm + { + get { return _settings[SettingName.ListOrForm].AsString("List"); } + } + + public bool OnlyFormIsShown + { + get { return ListOrForm == "Form"; } + } + + public bool OnlyListIsShown + { + get { return ListOrForm == "List"; } + } + + public int Paging + { + get { return _settings[SettingName.Paging ].AsInt(Null.NullInteger ); } + } + + public string RenderingMethod + { + get { return _settings[SettingName.RenderingMethod].AsString(); } + } + + public bool ShowAllColumnsForAdmins + { + get { return _settings[SettingName.ShowAllColumnsForAdmins].AsBoolean(); } + } + + public bool ShowNoRecordsUntilSearch + { + get { return _settings[SettingName.ShowNoRecordsUntilSearch].AsBoolean(); } + } + + public bool ShowSearchTextBox + { + get { return _settings[SettingName.ShowSearchTextBox].AsBoolean(); } + } + + public bool ShowSystemColumns + { + get { return _settings[SettingName.ShowSystemColumns].AsBoolean(); } + } + + public bool SimpleSearch + { + get { return _settings[SettingName.SimpleSearch].AsBoolean(); } + } + + public int SortFieldId + { + get { return _settings[SettingName.SortField].AsInt(Null.NullInteger); } + } + + public string ScriptByRenderingMethod(string renderingMethod) + { + return _settings[renderingMethod].AsString(); + } + + public string SortOrder + { + get { return _settings[SettingName.SortOrder].AsString(); } + } + + public string SubmissionText + { + get { return _settings[SettingName.SubmissionText].ToString(); } + } + + public int TopCount + { + get { return _settings[SettingName.TopCount].AsInt(0); } + } + + public string TrackingEmailFrom + { + get { return _settings[SettingName.TrackingEmailFrom].AsString(); } + } + + public string TrackingEmailTo + { + get { return _settings[SettingName.TrackingEmailTo].AsString(); } + } + + public string TrackingEmailCc + { + get { return _settings[SettingName.TrackingEmailCc].AsString(); } + } + + public string TrackingEmailBcc + { + get { return _settings[SettingName.TrackingEmailBcc].AsString(); } + } + + public string TrackingMessage + { + get { return _settings[SettingName.TrackingMessage].AsString(); } + } + + public string TrackingEmailReplyTo + { + get { return _settings[SettingName.TrackingEmailReplyTo].AsString(); } + } + + + + public string TrackingSubject + { + get { return _settings[SettingName.TrackingSubject].AsString(); } + } + + public string TrackingScript + { + get { return _settings[SettingName.TrackingScript].AsString(); } + } + + public string TrackingTextOnNew + { + get { return _settings[SettingName.TrackingTextOnNew].AsString(); } + } + + public string TrackingTextOnUpdate + { + get { return _settings[SettingName.TrackingTextOnUpdate].AsString(); } + } + + public string TrackingTextOnDelete + { + get { return _settings[SettingName.TrackingTextOnDelete].AsString(); } + } + + public bool TrackingTriggerOnNew + { + get { return _settings[SettingName.TrackingTriggerOnNew].AsBoolean(); } + } + public bool TrackingTriggerOnUpdate + { + get { return _settings[SettingName.TrackingTriggerOnUpdate].AsBoolean(); } + } + public bool TrackingTriggerOnDelete + { + get { return _settings[SettingName.TrackingTriggerOnDelete].AsBoolean(); } + } + + + public string UponSubmitAction + { + get { return _settings[SettingName.UponSubmitAction].AsString("Text"); } + } + + public string UponSubmitRedirect + { + get + { + var redirect = _settings[SettingName.UponSubmitRedirect].AsString(); + return redirect == string.Empty ? null : redirect; + } + } + + public bool UrlSearch + { + get { return _settings[SettingName.URLSearch].AsBoolean(); } + } + + public bool UseButtonsInForm + { + get { return _settings[SettingName.UseButtonsInForm].AsBoolean(); } + } + + public int UserRecordQuota + { + get { return _settings[SettingName.UserRecordQuota].AsInt(); } + } + } +} \ No newline at end of file diff --git a/Components/TokenReplace.cs b/Components/TokenReplace.cs new file mode 100644 index 0000000..e3f2c10 --- /dev/null +++ b/Components/TokenReplace.cs @@ -0,0 +1,35 @@ +using System.Web; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public class TokenReplace : Services.Tokens.TokenReplace + { + readonly bool _escapeApostrophe; + + public TokenReplace() : this(false) + { + } + + public TokenReplace(bool escapeApostrophe) + { + _escapeApostrophe = escapeApostrophe; + if (HttpContext.Current != null) + { + var request = HttpContext.Current.Request; + PropertySource["querystring"] = new FilteredNameValueCollectionPropertyAccess(request.QueryString); + PropertySource["form"] = new FilteredNameValueCollectionPropertyAccess(request.Form); + PropertySource["server"] = new FilteredNameValueCollectionPropertyAccess(request.ServerVariables); + } + } + + protected override string replacedTokenValue(string objectName, string propertyName, string formatString) + { + var returnvalue = base.replacedTokenValue(objectName, propertyName, formatString); + if (_escapeApostrophe) + { + returnvalue = returnvalue.Replace("\'", "\'\'"); + } + return returnvalue; + } + } +} \ No newline at end of file diff --git a/Components/TrackingController.cs b/Components/TrackingController.cs new file mode 100644 index 0000000..b9077b0 --- /dev/null +++ b/Components/TrackingController.cs @@ -0,0 +1,158 @@ +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.IO; +using System.Net.Mail; +using System.Text; +using System.Web; +using System.Xml; +using System.Xml.Xsl; +using DotNetNuke.Common; +using DotNetNuke.Entities.Host; +using DotNetNuke.Modules.UserDefinedTable.Interfaces; +using DotNetNuke.Services.Mail; +using MailPriority = DotNetNuke.Services.Mail.MailPriority; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public class TrackingController + { + public enum Trigger + { + @New, + Update, + Delete + } + + public static void OnAction(Trigger trigger, int rowId, UserDefinedTableController udtC) + { + if (ActionIsTriggered(trigger, udtC.Settings)) + { + var ds = udtC.GetRow(rowId,true,true); + ds.Tables.Add(udtC.Context()); + HandleAction(trigger, ds, udtC); + } + } + + static bool ActionIsTriggered(Trigger trigger, Settings settings) + { + return + ((trigger == Trigger.New && settings.TrackingTriggerOnNew) || + ((trigger == Trigger.Update) && settings.TrackingTriggerOnUpdate) || + ((trigger == Trigger.Delete) && settings.TrackingTriggerOnDelete)); + } + + + static void HandleAction(Trigger trigger, DataSet data, UserDefinedTableController udtC) + { + var settings = udtC.Settings; + var subject = settings.TrackingSubject; + var message = settings.TrackingMessage; + var from = GetEmailAddressList(settings.TrackingEmailFrom, data); + if (from.Split(';').Length > 1) + { + from = (from.Split(';')[0]); + } + var mailTo = GetEmailAddressList(settings.TrackingEmailTo, data); + var cc = GetEmailAddressList(settings.TrackingEmailCc, data); + var bcc = GetEmailAddressList(settings.TrackingEmailBcc, data); + var replyto = GetEmailAddressList(settings.TrackingEmailReplyTo, data); + var script = settings.TrackingScript; + + var triggerMessage = string.Empty; + switch (trigger) + { + case Trigger.New: + triggerMessage = settings.TrackingTextOnNew; + break; + case Trigger.Update: + triggerMessage = settings.TrackingTextOnUpdate; + break; + case Trigger.Delete: + triggerMessage = settings.TrackingTextOnDelete; + break; + } + + + if (script == "[AUTO]") + { + script = "~/DesktopModules/UserDefinedTable/XslStyleSheets/Tracking/Auto.xsl"; + } + else + { + script = Globals.GetPortalSettings().HomeDirectory + script; + } + subject = + ((new TokenReplace()).ReplaceEnvironmentTokens(subject, data.Tables[DataSetTableName.Data].Rows[0])); + + SendMail(from, mailTo, cc, bcc, replyto, subject, data.GetXml(), message, triggerMessage, script); + } + + + + static string GetEmailAddressList(string mailto, DataSet data) + { + var addresses = new List(); + foreach (var source in mailto.Split(';')) + { + if (source.StartsWith("[") && source.EndsWith("]")) + { + var fieldtitle = source.Substring(1, source.Length - 2); + var rows = + data.Tables[DataSetTableName.Fields].Select(string.Format("{0}=\'{1}\'", FieldsTableColumn.Title, + fieldtitle)); + if (rows.Length == 1) + { + fieldtitle = (string) (rows[0][FieldsTableColumn.Title]); + var type = DataType.ByName((string) (rows[0][FieldsTableColumn.Type])); + var emailAdressSource = type as IEmailAdressSource; + if (emailAdressSource != null) + { + addresses.Add((emailAdressSource).GetEmailAddress(fieldtitle, + data.Tables[DataSetTableName.Data] + .Rows[0])); + } + } + } + else + { + addresses.Add(source); + } + } + return (string.Join(";", addresses.ToArray())); + } + + static void SendMail(string from, string mailTo, string cc, string bcc, string replyto, string subject, + string data, string message, string trigger, string script) + { + var xslTrans = new XslCompiledTransform(); + xslTrans.Load(HttpContext.Current.Server.MapPath(script)); + using (XmlReader xmlData = new XmlTextReader(new StringReader(data))) + { + using (var bodyTextWriter = new StringWriter()) + { + if (from == string.Empty) + { + from = Globals.GetPortalSettings().Email; + } + + var xslArgs = new XsltArgumentList(); + xslArgs.AddParam("message", "", message); + xslArgs.AddParam("trigger", "", trigger); + xslTrans.Transform(xmlData, xslArgs, bodyTextWriter); + var body = bodyTextWriter.ToString(); + body = body.Replace("href=\"/", + string.Format("href=\"http://{0}/", + Globals.GetPortalSettings().PortalAlias.HTTPAlias.Split('/')[0])); + body = body.Replace("src=\"/", + string.Format("src=\"http://{0}/", + Globals.GetPortalSettings().PortalAlias.HTTPAlias.Split('/')[0])); + + var noAttachments = new List(); + Mail.SendMail(from, mailTo, cc, bcc, replyto, MailPriority.Normal, subject, MailFormat.Html, + Encoding.UTF8, body, noAttachments, "", "", "", "", Host.EnableSMTPSSL); + } + } + } + } +} \ No newline at end of file diff --git a/Components/UserDefinedTableController.cs b/Components/UserDefinedTableController.cs new file mode 100644 index 0000000..dac723d --- /dev/null +++ b/Components/UserDefinedTableController.cs @@ -0,0 +1,639 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Web; +using System.Xml; +using DotNetNuke.Common; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Users; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Services.Localization; +using DotNetNuke.Services.SystemDateTime; +using DotNetNuke.UI.Modules; + +namespace DotNetNuke.Modules.UserDefinedTable +{ + /// + /// The UserDefinedTableController class provides Business Layer methods of + /// UDT for managing, editing and diplaying User Defined Table + /// + /// + /// + /// ----------------------------------------------------------------------------- + public class UserDefinedTableController : BaseController + { + #region Constructors + + public UserDefinedTableController(int moduleId, int tabId, UserInfo userInfo) + { + Initialise(moduleId, tabId, userInfo); + } + + public UserDefinedTableController(int moduleid) + { + ModuleId = moduleid; + } + + public UserDefinedTableController() + { + } + + public UserDefinedTableController(ModuleInstanceContext moduleContext) + { + Initialise(moduleContext); + } + + public UserDefinedTableController(ModuleInfo moduleinfo) + { + Initialise(moduleinfo); + } + + #endregion + + #region Private Functions + + /// ----------------------------------------------------------------------------- + /// + /// add a new data row in the database + /// + /// ID of the created row (or 0, if creation failed) + int AddRow() + { + return DataProvider.Instance().AddRow(ModuleId); + } + + + void SetEditLinksAndVisibilityBasedOnPermissions(DataSet ds) + { + if (User != null && TabId != Null.NullInteger) + { + //Provide a permission aware EditLink as an additional column to the dataset + var security = new ModuleSecurity(ModuleId, TabId, Settings); + var createdByColumnName = ColumnNameByDataType(ds, DataTypeNames.UDT_DataType_CreatedBy); + + ds.Tables[DataSetTableName.Data].Columns.Add(DataTableColumn.EditLink, typeof (string)); + + var urlPattern = EditUrlPattern ?? Globals.NavigateURL(TabId, "edit", "mid=" + ModuleId, DataTableColumn.RowId + "={0}"); + + foreach (DataRow row in ds.Tables[DataSetTableName.Data].Rows) + { + var rowCreatorUserName = row[createdByColumnName].ToString(); + var isRowOwner = + Convert.ToBoolean((rowCreatorUserName == User.Username) && + rowCreatorUserName != Definition.NameOfAnonymousUser); + if (security.IsAllowedToEditRow(isRowOwner)) + { + row[DataTableColumn.EditLink] = string.Format(urlPattern, row[DataTableColumn.RowId]); + } + } + //Adjust visibility to actual permissions + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + row[FieldsTableColumn.Visible] = Convert.ToBoolean(row[FieldsTableColumn.Visible]) || + (security.IsAllowedToSeeAllUserDefinedColumns() && + (DataType.ByName(row[FieldsTableColumn.Type].ToString()). + IsUserDefinedField || + Settings.ShowSystemColumns)); + } + } + } + + DataSet BuildMainDataSet(DataTable fieldsTable, IDataReader dr, bool rowMode) + { + fieldsTable.Columns.Add(FieldsTableColumn.ValueColumn, typeof (string)); + fieldsTable.Columns.Add(FieldsTableColumn.SortColumn, typeof (string)); + var strFields = ""; + foreach (DataRow row in fieldsTable.Rows) + { + strFields += string.Format("{0}{1}|", (strFields != string.Empty ? "," : string.Empty), + row[FieldsTableColumn.Title]); + if (rowMode) + { + strFields += "String"; + } + else + { + //DataSet expects the FieldType to be in the namespace "System." + //so replace all UDT-specific field types by their .net-equivalent + strFields += DataType.ByName(row[FieldsTableColumn.Type].ToString()).SystemTypeName; + } + + //needed for generic Xsl Transformations - Data Names is XmlEncoded too + var xmlEncodedTitle = XmlConvert.EncodeName(row[FieldsTableColumn.Title].ToString()); + row[FieldsTableColumn.ValueColumn] = xmlEncodedTitle; + // gets altered in RenderValuesToHtmlInsideDataSet depending on Datatype + row[FieldsTableColumn.SortColumn] = xmlEncodedTitle; + } + + + var ds = Globals.BuildCrossTabDataSet("UserDefinedTable", dr, DataTableColumn.RowId + "|Int32", strFields, + DataTableColumn.RowId, FieldsTableColumn.Title, string.Empty, + DataTableColumn.Value, string.Empty, CultureInfo.InvariantCulture); + dr.Close(); + + ds.Tables[0].TableName = DataSetTableName.Data; + fieldsTable.TableName = DataSetTableName.Fields; + ds.Tables.Add(fieldsTable); + return ds; + } + + + static void UpdateData(int rowId, IDictionary values ) + { + DataProvider.Instance().UpdateData(rowId, values); + } + + #endregion + + #region Public Functions + + + + + /// ----------------------------------------------------------------------------- + /// + /// fills all missing values for a field in all rows with default values. + /// If not default is provided or all fields are already initialized, nothing is + /// changed. + /// + /// ID of the Field. + /// If this param is omitted, all fields will be applied. + /// Expression to be filled in, either constant or + /// containing tokens. + /// ----------------------------------------------------------------------------- + public void FillDefaultData(int fieldId, string defaultExpression) + { + var tr = new Services.Tokens.TokenReplace {ModuleId = ModuleId, ModuleInfo = Configuration}; + if (tr.ContainsTokens(defaultExpression)) + { + var ds = GetDataSet(false); + var createdByColumnName = ColumnNameByDataType(ds, DataTypeNames.UDT_DataType_CreatedBy); + + foreach (DataRow dr in ds.Tables[DataSetTableName.Data].Rows) + { + var user = (dr[createdByColumnName].ToString()); + if (user == Definition.NameOfAnonymousUser) + { + user = string.Empty; + } + tr.User = UserController.GetUserByName(PortalId, user); + var newValue = tr.ReplaceEnvironmentTokens(defaultExpression, dr); + DataProvider.Instance().UpdateData(Convert.ToInt32(dr["UserDefinedRowID"]), fieldId, newValue); + } + } + else + { + DataProvider.Instance().FillDefaultData(ModuleId, fieldId, defaultExpression); + } + DataProvider.Instance().FillDefaultData(ModuleId, fieldId, defaultExpression); + } + + public void RenderValuesToHtmlInsideDataSet(DataSet ds, bool filterScript = false) + { + foreach (var fieldType in DataType.AllDataTypes) + { + DataType.ByName(fieldType).RenderValuesToHtmlInsideDataSet(ds, ModuleId, filterScript ); + } + } + + + + /// ----------------------------------------------------------------------------- + /// + /// Gets all Data values of an UDT table (module) from the Database as DataSet + /// + /// All field values as DataSet (prerendered) + /// ----------------------------------------------------------------------------- + public DataSet GetDataSet() + { + return GetDataSet(true); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets all Data values of an UDT table (module) from the Database as DataSet + /// + /// All field values as DataSet (prerendered) + /// ----------------------------------------------------------------------------- + public DataSet GetDataSet(int moduleId) + { + Initialise(moduleId); + return GetDataSet(true); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets all Data values of an UDT table (module) from the Database as DataSet + /// + /// specifies, whether links, dates etc. shall be prerendered for XML output + /// All field values as DataSet + /// ----------------------------------------------------------------------------- + public DataSet GetDataSet(bool withPreRenderedValues) + { + var fieldsTable = FieldController.GetFieldsTable(ModuleId, addNewColumn: false, addAuditColumns: false); + DataSet ds; + using (var dr = DataProvider.Instance().GetRows(ModuleId)) + { + ds = BuildMainDataSet(fieldsTable, dr, !withPreRenderedValues); + } + var fieldSettingsTable = FieldSettingsController.GetFieldSettingsTable(ModuleId); + ds.Tables.Add(fieldSettingsTable); + + SetEditLinksAndVisibilityBasedOnPermissions(ds); + + if (withPreRenderedValues) + { + RenderValuesToHtmlInsideDataSet(ds); + } + ds.Namespace = "DotNetNuke/UserDefinedTable"; + return ds; + } + + public DataSet GetSchemaDataset() + { + var ds = GetRow(-1); + RenderValuesToHtmlInsideDataSet(ds); + ds.Namespace = "DotNetNuke/UserDefinedTable"; + return ds; + } + + + public DataTable Context() + { + return Context("", "", "", ""); + } + + public DataTable Context(string searchInput, string orderBy, string orderDirection, string paging) + { + return Context(Configuration, User, searchInput, orderBy, orderDirection, paging); + } + + /// ----------------------------------------------------------------------------- + /// + /// Provides a list of context variables for XML output + /// + /// DataTable with all context variables + /// ----------------------------------------------------------------------------- + public DataTable Context(ModuleInfo moduleInfo, UserInfo userInfo, string searchInput, string orderBy, + string orderDirection, string paging) + { + var request = HttpContext.Current.Request; + orderBy = orderBy.AsString("UserDefinedRowId"); + orderDirection = orderDirection.AsString("ascending"); + + var contextTable = new DataTable("Context"); + contextTable.Columns.Add("ModuleId", typeof (int)); + contextTable.Columns.Add("TabId", typeof (int)); + contextTable.Columns.Add("TabName", typeof(string)); + contextTable.Columns.Add("PortalId", typeof (int)); + contextTable.Columns.Add("UserName", typeof (string)); + contextTable.Columns.Add("BestUserName", typeof (string)); + //obsolete, please use DisplayName + contextTable.Columns.Add("DisplayName", typeof (string)); + contextTable.Columns.Add("ApplicationPath", typeof (string)); + contextTable.Columns.Add("HomePath", typeof (string)); + contextTable.Columns.Add("UserRoles", typeof (string)); + contextTable.Columns.Add("IsAdministratorRole", typeof (bool)); + contextTable.Columns.Add("Parameter", typeof (string)); + contextTable.Columns.Add("OrderBy", typeof (string)); + contextTable.Columns.Add("OrderDirection", typeof (string)); + contextTable.Columns.Add("CurrentCulture", typeof (string)); + contextTable.Columns.Add("LocalizedString_Search", typeof (string)); + contextTable.Columns.Add("LocalizedString_Page", typeof (string)); + contextTable.Columns.Add("LocalizedString_Of", typeof (string)); + contextTable.Columns.Add("LocalizedString_First", typeof (string)); + contextTable.Columns.Add("LocalizedString_Previous", typeof (string)); + contextTable.Columns.Add("LocalizedString_Next", typeof (string)); + contextTable.Columns.Add("LocalizedString_Last", typeof (string)); + contextTable.Columns.Add("NowInTicks", typeof (long)); + contextTable.Columns.Add("TodayInTicks", typeof (long)); + contextTable.Columns.Add("TicksPerDay", typeof (long)); + contextTable.Columns.Add("LocalizedDate", typeof (string)); + contextTable.Columns.Add("Now", typeof (DateTime)); + + if (paging != string.Empty) + { + contextTable.Columns.Add("Paging", typeof (int)); + } + var row = contextTable.NewRow(); + row["ModuleId"] = moduleInfo.ModuleID; + row["TabId"] = moduleInfo.TabID; + row["TabName"] = moduleInfo.ParentTab.TabName; + row["PortalId"] = moduleInfo.PortalID; + + // null username handled by extension method + row["DisplayName"] = userInfo.GetSafeDisplayname(); + row["UserName"] = userInfo.GetSafeUsername(); + + row["BestUserName"] = row["DisplayName"]; + var portalSettings = Globals.GetPortalSettings(); + row["HomePath"] = portalSettings.HomeDirectory; + row["ApplicationPath"] = request.ApplicationPath == "/" ? "" : request.ApplicationPath; + row["UserRoles"] = ModuleSecurity.RoleNames(userInfo); + if (ModuleSecurity.IsAdministrator()) + { + row["IsAdministratorRole"] = true; + } + row["Parameter"] = searchInput; + row["OrderBy"] = orderBy; + row["OrderDirection"] = orderDirection == "DESC" ? "descending" : "ascending"; + row["CurrentCulture"] = new Localization().CurrentCulture; + if (paging != string.Empty) + { + row["Paging"] = int.Parse(paging); + } + row["LocalizedString_Search"] = Localization.GetString("Search.Text", Definition.SharedRessources); + row["LocalizedString_Page"] = Localization.GetString("PagingPage.Text", Definition.SharedRessources); + row["LocalizedString_of"] = Localization.GetString("PagingOf.Text", Definition.SharedRessources); + row["LocalizedString_First"] = Localization.GetString("PagingFirst.Text", Definition.SharedRessources); + row["LocalizedString_Previous"] = Localization.GetString("PagingPrevious.Text", Definition.SharedRessources); + row["LocalizedString_Next"] = Localization.GetString("PagingNext.Text", Definition.SharedRessources); + row["LocalizedString_Last"] = Localization.GetString("PagingLast.Text", Definition.SharedRessources); + var d = SystemDateTime.GetCurrentTimeUtc(); + var timeZone = userInfo.Username != null + ? userInfo.Profile.PreferredTimeZone + : portalSettings.TimeZone; + d = TimeZoneInfo.ConvertTimeFromUtc( d, timeZone); + row["Now"] = d; + row["LocalizedDate"] = d.ToString("g", Thread.CurrentThread.CurrentCulture); + row["NowInTicks"] = d.Ticks; + row["TodayInTicks"] = d.Date.Ticks ; + row["TicksPerDay"] = TimeSpan.TicksPerDay; + contextTable.Rows.Add(row); + + return contextTable; + } + + /// ----------------------------------------------------------------------------- + /// + /// Returns the name of the first column with a given column type (valuable for Track Columns) + /// + /// DataSet with column definitions + /// type to be searched + /// name of the column + /// ----------------------------------------------------------------------------- + public string ColumnNameByDataType(DataSet ds, string dataType) + { + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == dataType) + { + return row[FieldsTableColumn.Title].ToString(); + } + } + return string.Empty; + } + + /// ----------------------------------------------------------------------------- + /// + /// deletes all data rows of a module in the database + /// + /// ----------------------------------------------------------------------------- + public void DeleteRows() + { + DataProvider.Instance().DeleteRows(ModuleId); + } + + /// ----------------------------------------------------------------------------- + /// + /// deletes a data row in the database + /// + /// ID of the row to be deleted + /// ----------------------------------------------------------------------------- + public void DeleteRow(int userDefinedRowId) + { + TrackingController.OnAction(TrackingController.Trigger.Delete, userDefinedRowId, this); + DataProvider.Instance().DeleteRow(userDefinedRowId, ModuleId); + } + + public bool FieldHasData(int fieldId) + { + return DataProvider.Instance().GetFieldDataCount(fieldId) > 0; + } + + public void UpdateRow(DataSet ds) + { + UpdateRow(ds, 0, false); + } + + public void UpdateRow(DataSet ds, int rowNr, bool isDataToImport) + { + var currentRow = ds.Tables[DataSetTableName.Data].Rows[rowNr]; + + var rowHasContent = false; + foreach (DataRow field in ds.Tables[DataSetTableName.Fields].Rows) + { + if (DataType.ByName(field[FieldsTableColumn.Type].ToString()).IsUserDefinedField) + { + var strColumnName = field[FieldsTableColumn.Title].ToString(); + var strValueColumn = ((isDataToImport && + ds.Tables[DataSetTableName.Data].Columns.Contains(strColumnName + + DataTableColumn. + Appendix_Original)) + ? strColumnName + DataTableColumn.Appendix_Original + : strColumnName); + rowHasContent = Convert.ToBoolean(currentRow[strValueColumn].AsString() != string.Empty); + if (rowHasContent) + { + break; + } + } + } + + var userDefinedRowId = Convert.ToInt32(currentRow[DataTableColumn.RowId]); + var isNew = isDataToImport || (userDefinedRowId == -1); + if (isNew && rowHasContent) + { + //New entries need AddRow first + userDefinedRowId = AddRow(); + currentRow[DataTableColumn.RowId] = userDefinedRowId; + } + + if (rowHasContent) + { + var values = new Dictionary(); + foreach (DataRow field in ds.Tables[DataSetTableName.Fields].Rows) + { + var strColumnName = field[FieldsTableColumn.Title].ToString(); + var strValueColumn = ((! isDataToImport && + ds.Tables[DataSetTableName.Data].Columns.Contains(strColumnName + + DataTableColumn. + Appendix_Original)) + ? strColumnName + DataTableColumn.Appendix_Original + : strColumnName); + if (ds.Tables[DataSetTableName.Data].Columns.Contains(strValueColumn)) + { + values.Add(field[FieldsTableColumn.Id].AsInt(), currentRow[strValueColumn].AsString()); + } + } + UpdateData(userDefinedRowId, values); + if (! isDataToImport) + { + TrackingController.OnAction( + isNew ? TrackingController.Trigger.New : TrackingController.Trigger.Update, userDefinedRowId, this); + } + } + else + { + DeleteRow(userDefinedRowId); + } + } + + public DataSet GetRow(int userDefinedRowId, bool withPreRenderedValues, bool filterScript=false) + { + var fieldsTable = FieldController.GetFieldsTable(ModuleId, false, false); + DataSet ds; + using (var dr = DataProvider.Instance().GetRow(userDefinedRowId, ModuleId)) + { + ds = BuildMainDataSet(fieldsTable, dr, !withPreRenderedValues ); + var fieldTablesettings = FieldSettingsController.GetFieldSettingsTable(ModuleId); + ds.Tables.Add(fieldTablesettings); + if (withPreRenderedValues) + { + RenderValuesToHtmlInsideDataSet(ds, filterScript ); + } + ds.Namespace = "DotNetNuke/UserDefinedTable"; + } + + return ds; + } + + public DataSet GetRow(int userDefinedRowId) + { + return GetRow(userDefinedRowId, false); + } + + + + /// ----------------------------------------------------------------------------- + /// + /// delete a whole table of a module. + /// + /// ----------------------------------------------------------------------------- + public void ResetModule() + { + DataProvider.Instance().Reset(ModuleId); + } + + #endregion + + #region "Obsolete Methods" + /// ----------------------------------------------------------------------------- + /// + /// get value for maximal field size + /// + /// the maximal Fieldsize (number of characters), that can be stored in data field + /// ----------------------------------------------------------------------------- + /// + [Obsolete("Please use FieldController")] + public static int GetMaxFieldSize() + { + return FieldController.GetMaxFieldSize(); + } + + /// ----------------------------------------------------------------------------- + /// + /// persists deletion of a field into the database + /// + /// ----------------------------------------------------------------------------- + [Obsolete("Please use FieldController")] + public void DeleteField(int userDefinedFieldId) + { + FieldController.DeleteField(userDefinedFieldId); + } + + /// + /// Persists a new column with Datatype string and Default Settings + /// + /// + /// + /// + /// + [Obsolete("Please use FieldController")] + public int AddField(string fieldtitle) + { + return FieldController.AddField(ModuleId, fieldtitle); + } + + [Obsolete("Please use FieldController")] + public int AddField(string fieldTitle, int before, string helpText, bool required, string fieldType, + string Default, bool visible, bool showOnEdit, bool searchable, bool isPrivateColumn, + bool multipleValues, string inputSettings, string outputSettings, bool normalizeFlag, + string validationRule, string validationMessage, string editStyle) + { + return FieldController.AddField(ModuleId, fieldTitle, before, helpText, required, fieldType, Default, visible, showOnEdit, searchable, isPrivateColumn, multipleValues, inputSettings, outputSettings, normalizeFlag, validationRule, validationMessage, editStyle); + } + /// ----------------------------------------------------------------------------- + [Obsolete("Please use FieldController")] + public void UpdateField(int userDefinedFieldId, string fieldTitle, string helpText, bool required, + string fieldType, string Default, bool visible, bool showOnEdit, bool searchable, + bool isPrivateColumn, bool multipleValues, string inputSettings, string outputSettings, + bool normalizeFlag, string validationRule, string validationMessage, string editStyle) + { + FieldController.UpdateField(userDefinedFieldId, fieldTitle, helpText, required, fieldType, Default, + visible, showOnEdit, searchable, isPrivateColumn, multipleValues, + inputSettings, outputSettings, normalizeFlag, validationRule, + validationMessage, editStyle); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets all field definitions for one UDT table (module) from the database + /// + /// All field settings as DataTable + /// ----------------------------------------------------------------------------- + [Obsolete("Please use FieldController")] + public DataTable GetFieldsTable() + { + return FieldController.GetFieldsTable(ModuleId, false); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets all field definitions for one UDT table (module) from the database + /// + /// specifies, whether a new column shall be added + /// All field settings as DataTable + /// ----------------------------------------------------------------------------- + [Obsolete("Please use FieldController")] + public DataTable GetFieldsTable(bool addNewColumn) + { + return FieldController.GetFieldsTable(ModuleId, addNewColumn, true); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets all field definitions for one UDT table (module) from the database + /// + /// specifies, whether a new column shall be added + /// specifies, whether colums for creation and update (user and timestamp) shall be added + /// All field settings as DataTable + /// ----------------------------------------------------------------------------- + [Obsolete("Please use FieldController")] + public DataTable GetFieldsTable(bool addNewColumn, bool addAuditColumns) + { + return FieldController.GetFieldsTable(ModuleId, addNewColumn, addAuditColumns); + } + + /// ----------------------------------------------------------------------------- + /// + /// swap the ordinal position of two columns in a table definition. + /// + /// ID of the first column + /// ID of the second column + /// ----------------------------------------------------------------------------- + [Obsolete("Please use FieldController.SetFieldOrder")] + public void SwapFieldOrder(int firstUserDefinedFieldId, int secondUserDefinedFieldId) + { + if (firstUserDefinedFieldId != secondUserDefinedFieldId) + { + DataProvider.Instance().SwapFieldOrder(firstUserDefinedFieldId, secondUserDefinedFieldId); + } + } +#endregion + } +} \ No newline at end of file diff --git a/Components/Utilities.cs b/Components/Utilities.cs new file mode 100644 index 0000000..3c8cd51 --- /dev/null +++ b/Components/Utilities.cs @@ -0,0 +1,204 @@ +using System; +using System.Data; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using DotNetNuke.Common.Utilities; +using DotNetNuke.ComponentModel; +using DotNetNuke.Entities.Icons; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Security.Permissions; +using DotNetNuke.Services.FileSystem; +using Microsoft.VisualBasic; +using Microsoft.VisualBasic.CompilerServices; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public static class Utilities + { + #region Public Methods + + /// ----------------------------------------------------------------------------- + /// + /// returns default, when value is nothing, otherwise tries to convert value to string and returns it. + /// + /// ----------------------------------------------------------------------------- + public static string AsString(this object value) + { + return value.AsString(""); + } + + public static string AsString(this object value, string @default ) + { + if (value == DBNull.Value ||value==null|| String.IsNullOrEmpty(value.ToString() )) + { + return @default; + } + return (value.ToString()); + } + + public static string AsString(this DataRow row, string columnname ) + { + return row.AsString(columnname, ""); + } + + public static string AsString(this DataRow row, string columnname, string @default) + { + object value = null; + if (row.Table.Columns.Contains(columnname)) + { + value = row[columnname]; + } + return AsString(value, @default); + } + + public static Boolean Like(this string text, string pattern) + { + return LikeOperator.LikeString(text, pattern, CompareMethod.Text); + } + + public static bool AsBoolean(this object value) + { + return value.AsBoolean(false); + } + + public static bool AsBoolean(this object value, bool @default) + { + if (value == null) + { + return @default; + } + if (value == DBNull.Value) + { + return @default; + } + if (value is bool) return (bool) value; + try + { + return Boolean.Parse(value.ToString()); + } + catch + { + return false; + } + } + + + /// ----------------------------------------------------------------------------- + /// + /// returns Null.NullInteger, when value is nothing, otherwise tries to convert value to Integer and returns it. + /// + /// object containing value to return + /// ----------------------------------------------------------------------------- + public static int AsInt(this object value) + { + return AsInt(value, 0); + } + + /// ----------------------------------------------------------------------------- + /// + /// returns default, when value is nothing, otherwise tries to convert value to Integer and returns it. + /// + /// object containing value to return + /// Default value + /// ----------------------------------------------------------------------------- + public static int AsInt(this object value, int @default) + { + if (value == null) + { + return @default; + } + if (value == DBNull.Value) + { + return @default; + } + if (value is int) return (int) value; + int i; + return Int32.TryParse(value.ToString(), out i) ? i : Null.NullInteger; + } + + public static bool ValidateRegEx(this string value, string pattern) + { + var r = new Regex(pattern); + return r.IsMatch(value); + } + + public static bool HasWritePermission(string folder, int portalid) + { + var folderInfo = FolderManager.Instance.GetFolder(portalid, folder); + return folder.StartsWith(Definition.XSLFolderName) || (folderInfo is FolderInfo && FolderPermissionController.CanAdminFolder((FolderInfo)folderInfo)); + } + + public static bool SaveScript(string fileContent, string fileName, IFolderInfo folder, bool forceOverWrite) + { + if (forceOverWrite || !FileManager.Instance.FileExists(folder,fileName )) + { + var utf8 = new UTF8Encoding(); + FileManager.Instance.AddFile(folder, fileName, new MemoryStream(utf8.GetBytes(fileContent)),forceOverWrite); + return true; + } + return false; + } + + static public string ReadStringFromFile(string homeFilePath, int portalId) + { + string filecontent; + var file = FileManager.Instance.GetFile(portalId, homeFilePath); + using (var fileStream = FileManager.Instance.GetFileContent(file)) + { + using (var tx = new StreamReader(fileStream)) + { + filecontent = tx.ReadToEnd(); + } + } + return filecontent; + } + + public static IFolderInfo GetFolder(PortalSettings portalsettings, string homeFolderName) + { + return GetFolder(portalsettings, homeFolderName, homeFolderName); + } + + public static IFolderInfo GetFolder(PortalSettings portalsettings, string homeFolderName, + string defaultFolderName) + { + var folder= FolderManager.Instance.GetFolder(portalsettings.PortalId, homeFolderName) ?? + FolderManager.Instance.AddFolder(portalsettings.PortalId, defaultFolderName); + return folder; + } + + public static string UrlHexEncode(this string value) + { + return BitConverter.ToString(Encoding.UTF8.GetBytes(value)).Replace("-", ""); + } + + public static string UrlHexDecode(this string value) + { + var i = 0; + var x = 0; + var bytes = new byte[value.Length/2 - 1 + 1]; + while (value.Length > i + 1) + { + var byteValue = Convert.ToInt32(value.Substring(i, 2), 16); + bytes[x] = Convert.ToByte((short) byteValue); + i += 2; + x++; + } + return Encoding.UTF8.GetString(bytes); + } + + #endregion + + public static string IconURL(string iconKey) + { + return IconController.IconURL(iconKey); + //switch (iconKey.ToLowerInvariant() ) + //{ + // case "wizard": + // iconKey = "icon_wizard_16px"; + // break; + //} + //return String.Format("~/images/{0}.gif", iconKey); + } + } +} \ No newline at end of file diff --git a/Components/XSLTemplatingUtilities.cs b/Components/XSLTemplatingUtilities.cs new file mode 100644 index 0000000..be454aa --- /dev/null +++ b/Components/XSLTemplatingUtilities.cs @@ -0,0 +1,216 @@ +using System; +using System.Data; +using System.IO; +using System.Text.RegularExpressions; +using System.Web; +using System.Xml; + +namespace DotNetNuke.Modules.UserDefinedTable.Components +{ + public class XslTemplatingUtilities + { + public const string SpacePlaceholder = "{5A255853-D9A0-4f46-9E9D-F661DC4874CD}"; + //Any Uncommon String would do + public const string HardSpace = " "; + + + public enum ContextValues + { + ApplicationPath, + CurrentCulture, + DisplayName, + HomePath, + IsAdministratorRole, + ModuleId, + OrderBy, + OrderDirection, + Parameter, + PortalId, + TabId, + TabName, + UserName, + UserRoles, + LocalizedSearchString, + NowInTicks, + TicksPerDay, + LocalizedDate, + Now + } + + static string LoadXslScriptTemplate(string listView, string detailView, string headerView, bool pagingEnabled, + bool sortingEnabled, bool searchEnabled, bool showDetailView, + string currentListType) + { + var templateDoc = new XmlDocument(); + templateDoc.Load( + HttpContext.Current.Request.MapPath("~/DesktopModules/UserDefinedTable/xslStyleSheets/xslScripts.xml")); + var xslTemplate = +// ReSharper disable PossibleNullReferenceException + HttpUtility.HtmlDecode(templateDoc.SelectSingleNode("/root/data[@name=\"XSLT\"]/value").InnerText); +// ReSharper restore PossibleNullReferenceException + xslTemplate = LoadXslScriptOption(templateDoc, xslTemplate, "paging", pagingEnabled); + xslTemplate = LoadXslScriptOption(templateDoc, xslTemplate, "sorting", sortingEnabled); + xslTemplate = LoadXslScriptOption(templateDoc, xslTemplate, "searching", searchEnabled); + xslTemplate = LoadXslScriptOption(templateDoc, xslTemplate, "detail", showDetailView); + xslTemplate = + (xslTemplate.Replace("[LISTVIEW]", listView).Replace("[DETAILVIEW]", detailView).Replace( + "[HEADERVIEW]", headerView)); + string opentag; + var opentagclass = string.Empty; + switch (currentListType) + { + case "table": + opentag = currentListType; + opentagclass = @" class=""dnnFormItem"""; + break; + case "ul": + case "ol": + opentag = currentListType; + break; + default: + opentag = ""; + break; + } + if (opentag == "") + { + xslTemplate = (xslTemplate.Replace("[OPENTAG]", "").Replace("[/OPENTAG]", "")); + } + else + { + xslTemplate = xslTemplate + .Replace("[OPENTAG]", string.Format("<{0}{1}>", opentag, opentagclass)) + .Replace("[/OPENTAG]", string.Format("", opentag)); + } + + return xslTemplate; + } + + static string LoadXslScriptOption(XmlDocument def, string xsl, string extension, bool isEnabled) + { +// ReSharper disable PossibleNullReferenceException + foreach (XmlElement element in def.SelectNodes(string.Format("root/data[@name=\"{0}\"]", extension))) +// ReSharper restore PossibleNullReferenceException + { + var placeholder = string.Format("{{{0}{1}}}", extension.ToUpperInvariant(), + element.Attributes["number"].InnerText); + xsl = xsl.Replace(placeholder, isEnabled ? HttpUtility.HtmlDecode(element.FirstChild.InnerText) : ""); + } + return xsl; + } + + public static string TransformTokenTextToXslScript(DataSet udtDataset, string tokentemplate) + { + return TransformTokenTextToXslScript(udtDataset, tokentemplate, string.Empty, string.Empty, false, false, + false, false, string.Empty); + } + + public static string TransformTokenTextToXslScript(DataSet udtDataset, string listView, string detailView, + string headerView, bool pagingEnabled, bool sortingEnabled, + bool searchEnabled, bool showDetailView, + string currentListType) + { + headerView = Regex.Replace(headerView, "\\[((?:\\w|\\s)+)\\]", + sortingEnabled + ? "" + : "$1"); + + + string template = LoadXslScriptTemplate(listView, detailView, headerView, pagingEnabled, sortingEnabled, + searchEnabled, showDetailView, currentListType); + template = + (template.Replace("[ ]", SpacePlaceholder).Replace(HardSpace, SpacePlaceholder).Replace(" ", + SpacePlaceholder)); + const string attributeRegexPattern = "(?<==\\s*[\'\"][^\'\"<>]*)(\\[{0}\\])(?=[^\'\"<>]*[\"\'])"; + foreach (DataColumn col in udtDataset.Tables[DataSetTableName.Data].Columns) + { + template = Regex.Replace(template, string.Format(attributeRegexPattern, col.ColumnName), + string.Format("{{udt:{0}}}", XmlConvert.EncodeName(col.ColumnName))); + template = template.Replace(string.Format("[{0}]", col.ColumnName), + string.Format( + "", + XmlConvert.EncodeName(col.ColumnName))); + } + foreach (var contextString in Enum.GetNames(typeof (ContextValues))) + { + template = Regex.Replace(template, string.Format(attributeRegexPattern, "Context:" + contextString), + string.Format("{{/udt:UserDefinedTable/udt:Context/udt:{0}}}", contextString)); + template = template.Replace(string.Format("[Context:{0}]", contextString), + string.Format( + "", + contextString)); + } + template = template.Replace("[UDT:EditLink]", ""); + template = template.Replace("[UDT:DetailView]", ""); + template = template.Replace("[UDT:ListView]", ""); + + + return PrettyPrint(template).Replace(SpacePlaceholder, HardSpace); + } + + public static string PrettyPrint(string template) + { + var doc = new XmlDocument(); + doc.LoadXml(template); + return PrettyPrint(doc); + } + + public static string PrettyPrint(XmlDocument doc) + { + using (var strXML = new StringWriter()) + { + using (var writer = new XmlTextWriter(strXML)) + { + try + { + writer.Formatting = Formatting.Indented; + doc.WriteTo(writer); + writer.Flush(); + writer.Close(); + return strXML.ToString().Replace(" + /// The ManageUserDefinedTable Class provides the UI for manageing the UserDefinedTable + /// + /// ----------------------------------------------------------------------------- + public partial class Configuration : ModuleUserControlBase, IActionable, IPostBackEventHandler + { +// ReSharper disable InconsistentNaming + protected LabelControl lblNormalizeFlag; + protected Panel dshRendering; + protected Panel dshFormsSettings; + protected Panel dshChangeTracking; + protected TextEditor teSubmissionSuccess; + protected TextEditor teTrackingMessage; + protected LabelControl lblMultipleValues; + protected LabelControl lblInputSettings; + protected LabelControl lblDefault; + protected LabelControl lblOutputSettings; + protected UrlControl XslUserDefinedUrlControl; + protected UrlControl XslTracking; + protected UrlControl urlOnSubmissionRedirect; + // ReSharper restore InconsistentNaming + + + ModuleController _objModules; + const string StrAuto = "[AUTO]"; + protected int RowCount; + UserDefinedTableController _udtController; + + #region Private Properties + + public ModuleController ModulesController + { + get { return _objModules ?? (_objModules = new ModuleController()); } + } + + UserDefinedTableController UdtController + { + get { return _udtController ?? (_udtController = new UserDefinedTableController(ModuleContext)); } + } + #endregion + + #region Private Methods + + void BindData() + { + BindSettings(); + } + + + + /// ----------------------------------------------------------------------------- + /// + /// Gets the module settings and binds it to the web controls + /// + /// ----------------------------------------------------------------------------- + void BindSettings() + { + var oldSelectedSortField = cboSortField.SelectedValue; + var fields = FieldController.GetFieldsTable(ModuleContext.ModuleId); + cboSortField.DataSource = new DataView(fields, "UserDefinedFieldId<>\'-1\'", string.Empty, + DataViewRowState.CurrentRows); + cboSortField.DataBind(); + cboSortField.Items.Insert(0, new ListItem(Localization.GetString("Not_Specified"), string.Empty)); + if (cboSortField.Items.FindByValue(oldSelectedSortField) != null) + { + cboSortField.Items.FindByValue(oldSelectedSortField).Selected = true; + } + chkExcludeFromSearch.Checked = ModuleContext.Settings[SettingName.ExcludeFromSearch].AsBoolean(); + cboSortField.ClearSelection(); + var sortFieldSetting = ModuleContext.Settings[SettingName.SortField].AsString(); + if (cboSortField.Items.FindByValue(sortFieldSetting) != null) + { + cboSortField.Items.FindByValue(sortFieldSetting).Selected = true; + } + cboSortOrder.ClearSelection(); + var sortOrderSetting = ModuleContext.Settings[SettingName.SortOrder].AsString(); + if (cboSortOrder.Items.FindByValue(sortOrderSetting) != null) + { + cboSortOrder.Items.FindByValue(sortOrderSetting).Selected = true; + } + + + txtFilter.Text = ModuleContext.Settings[SettingName.Filter].AsString(); + txtTopCount.Text = ModuleContext.Settings[SettingName.TopCount].AsString(); + chkShowSearchTextBox.Checked = ModuleContext.Settings[SettingName.ShowSearchTextBox].AsBoolean(); + chkUseButtons.Checked = ModuleContext.Settings[SettingName.UseButtonsInForm].AsBoolean(); + chkShowNoRecordsUntilSearch.Checked = ModuleContext.Settings[SettingName.ShowNoRecordsUntilSearch].AsBoolean(); + chkSimpleSearch.Checked = ModuleContext.Settings[SettingName.SimpleSearch].AsBoolean(); + chkURLSearch.Checked = ModuleContext.Settings[SettingName.URLSearch].AsBoolean(); + + cboPaging.ClearSelection(); + if (ModuleContext.Settings.ContainsKey(SettingName.Paging)) + { + if (cboPaging.Items.FindByValue(ModuleContext.Settings[SettingName.Paging].AsString()) != null) + { + cboPaging.SelectedValue = ModuleContext.Settings[SettingName.Paging].AsString(); + } + } + + var strRenderMethod = ModuleContext.Settings[SettingName.RenderingMethod].AsString(); + if (strRenderMethod == string.Empty) + { + strRenderMethod = RenderingMethod.GridRendering; + } + renderMethodRadioButtonList.SelectedValue = strRenderMethod; + + try + { + if (ModuleContext.Settings.ContainsKey(SettingName.XslUserDefinedStyleSheet)) + { + XslUserDefinedUrlControl.Url = + ModuleContext.Settings[SettingName.XslUserDefinedStyleSheet].AsString(); + } + } +// ReSharper disable EmptyGeneralCatchClause + catch +// ReSharper restore EmptyGeneralCatchClause + { + //Old StyleSheet removed + } + + //Expand sections only, if not all values set to default: + rblUsageListForm.SelectedValue = ModuleContext.Settings[SettingName.ListOrForm].AsString("List"); + //tracking + chkTrackingOnDelete.Checked = ModuleContext.Settings[SettingName.TrackingTriggerOnDelete].AsBoolean(); + chkTrackingOnNew.Checked = ModuleContext.Settings[SettingName.TrackingTriggerOnNew].AsBoolean(); + chkTrackingOnUpdate.Checked = ModuleContext.Settings[SettingName.TrackingTriggerOnUpdate].AsBoolean(); + + txtOnNew.Text = ModuleContext.Settings[SettingName.TrackingTextOnNew].AsString(); + txtOnUpdate.Text = ModuleContext.Settings[SettingName.TrackingTextOnUpdate].AsString(); + txtOnDelete.Text = ModuleContext.Settings[SettingName.TrackingTextOnDelete].AsString(); + txtTrackingEmailAddresses.Text = ModuleContext.Settings[SettingName.TrackingEmailTo].AsString(); + txtTrackingEmail_CC.Text = ModuleContext.Settings[SettingName.TrackingEmailCc].AsString(); + txtTrackingEmail_BCC.Text = ModuleContext.Settings[SettingName.TrackingEmailBcc].AsString(); + txtTrackingEmail_from.Text = ModuleContext.Settings[SettingName.TrackingEmailFrom].AsString(); + txtTrackingEmail_replyto.Text = ModuleContext.Settings[SettingName.TrackingEmailReplyTo].AsString(); + txtTrackingSubject.Text = ModuleContext.Settings[SettingName.TrackingSubject].AsString(); + var strTrackingScript = ModuleContext.Settings[SettingName.TrackingScript].AsString(StrAuto); + if (strTrackingScript == StrAuto) + { + rblBodyType.SelectedValue = "Auto"; + } + else + { + rblBodyType.SelectedValue = "XslScript"; + try + { + XslTracking.Url = strTrackingScript; + } +// ReSharper disable EmptyGeneralCatchClause + catch +// ReSharper restore EmptyGeneralCatchClause + { + //Old StyleSheet removed + } + } + + //form settings + rblOnSubmission.SelectedValue = ModuleContext.Settings[SettingName.UponSubmitAction].AsString("Form"); + urlOnSubmissionRedirect.Url = ModuleContext.Settings[SettingName.UponSubmitRedirect].AsString(); + } + + bool ValidateMailTo() + { + var fields = FieldController.GetFieldsTable(ModuleContext.ModuleId, false); + + return TestForValidEmailSources(fields, txtTrackingEmailAddresses.Text) && + TestForValidEmailSources(fields, txtTrackingEmail_CC.Text) && + TestForValidEmailSources(fields, txtTrackingEmail_BCC.Text) && + TestForValidEmailSources(fields, txtTrackingEmail_replyto.Text) && + TestForValidEmailSources(fields, txtTrackingEmail_from.Text); + } + + bool TestForValidEmailSources(DataTable fields, string emailSources) + { + foreach (var sx in emailSources.Split(';'.ToString(CultureInfo.InvariantCulture).ToCharArray())) + { + var source = sx.Trim(); + if (source.Length > 0) + { + if (source.StartsWith("[") && source.EndsWith("]")) + { + var fieldtitle = source.Substring(1, source.Length - 2); + var rows = fields.Select(string.Format("{0}=\'{1}\'", FieldsTableColumn.Title, fieldtitle)); + if (rows.Length == 1) + { + var type = DataType.ByName((string) (rows[0][FieldsTableColumn.Type])); + if (!(type is IEmailAdressSource)) + { + UI.Skins.Skin.AddModuleMessage(this, + string.Format( + Localization.GetString("NotEmailSource", + LocalResourceFile), fieldtitle), + ModuleMessage.ModuleMessageType.YellowWarning); + return false; + } + } + else if (rows.Length == 0) + { + UI.Skins.Skin.AddModuleMessage(this, + string.Format( + Localization.GetString("NotEmailSource", + LocalResourceFile), fieldtitle), + ModuleMessage.ModuleMessageType.YellowWarning); + return false; + } + } + else + { + if (! Mail.IsValidEmailAddress(source, ModuleContext.PortalId)) + { + UI.Skins.Skin.AddModuleMessage(this, + string.Format( + Localization.GetString("NotEmailAddress", + LocalResourceFile), source), + ModuleMessage.ModuleMessageType.YellowWarning); + return false; + } + } + } + } + return true; + } + + /// ----------------------------------------------------------------------------- + /// + /// Set the visibility of controls according to + /// + /// ----------------------------------------------------------------------------- + void ApplySettingsVisibility() + { + var isFormMode = rblUsageListForm.SelectedValue == "Form"; + rememberSettings.Visible = rblUsageListForm.SelectedValue.Contains("Form"); + plainFormSettingSet.Visible = isFormMode; + noFormSettings.Visible = !isFormMode; + rowOnSubmissionRedirect.Visible = rblOnSubmission.SelectedValue == "Redirect"; + rowSubmissionText.Visible = Convert.ToBoolean(! rowOnSubmissionRedirect.Visible); + + rowTrackingScript.Visible = Convert.ToBoolean(rblBodyType.SelectedValue == "XslScript"); + + switch (renderMethodRadioButtonList.SelectedValue) + { + case RenderingMethod.GridRendering: + rowUserDefined.Visible = false; + break; + + case RenderingMethod.UserdefinedXSL: + rowUserDefined.Visible = true; + break; + } + } + + int GetEditableFileId(string url) + { + if (LikeOperator.LikeString(url, "fileid=*", CompareMethod.Binary)) + { + var fileId = int.Parse(UrlUtils.GetParameterValue(url)); + var f = FileManager.Instance.GetFile(fileId); + if (Utilities.HasWritePermission(f.Folder, ModuleContext.PortalId)) + { + return fileId; + } + } + return - 1; + } + + void UpdateModuleSetting(string name, string value) + { + ModulesController.UpdateModuleSetting(ModuleContext.ModuleId, name, value); + ModuleContext.Settings[name] = value; + } + + void UpdateTabModuleSetting(string name, string value) + { + ModulesController.UpdateTabModuleSetting(ModuleContext.TabModuleId, name, value); + ModuleContext.Settings[name] = value; + } + + void SaveSettings() + { + try + { + UpdateModuleSetting(SettingName.ExcludeFromSearch, chkExcludeFromSearch.Checked.ToString(CultureInfo.InvariantCulture)); + + if (cboSortField.SelectedItem != null) + { + var sortOrder = cboSortField.SelectedIndex == 0 + ? string.Empty + : cboSortOrder.SelectedItem.Value.AsString("ASC"); + UpdateTabModuleSetting(SettingName.SortOrder, sortOrder); + UpdateTabModuleSetting(SettingName.SortField, cboSortField.SelectedItem.Value); + } + else + { + UpdateTabModuleSetting(SettingName.SortOrder, string.Empty); + UpdateTabModuleSetting(SettingName.SortField, string.Empty); + } + + + //save rendering and rendering specific values + var strRenderingMethod = renderMethodRadioButtonList.SelectedValue; + var strUserDefinedXsl = ""; + //var strPredefinedXsl = ""; + if (strRenderingMethod == RenderingMethod.UserdefinedXSL && XslUserDefinedUrlControl.Url != string.Empty) + { + var file = FileManager.Instance.GetFile(int.Parse(XslUserDefinedUrlControl.Url.Substring(7))); + if (file == null) + { + strRenderingMethod = RenderingMethod.GridRendering; + } + else + { + strUserDefinedXsl = file.Folder + file.FileName; + } + } + UpdateTabModuleSetting(SettingName.XslUserDefinedStyleSheet, strUserDefinedXsl); + UpdateTabModuleSetting(SettingName.RenderingMethod, strRenderingMethod); + //Paging + UpdateTabModuleSetting(SettingName.Paging, cboPaging.SelectedValue); + //Filter + UpdateTabModuleSetting(SettingName.Filter, txtFilter.Text); + if (txtTopCount.Text == string.Empty) + { + UpdateModuleSetting(SettingName.TopCount, string.Empty); + } + else if (Information.IsNumeric(txtTopCount.Text)) + { + var count = int.Parse(txtTopCount.Text); + if (count < 1) + { + count = 1; + } + if (count > 1000) + { + count = 1000; + } + UpdateModuleSetting(SettingName.TopCount, count.ToString(CultureInfo.InvariantCulture)); + } + UpdateTabModuleSetting(SettingName.TopCount, txtTopCount.Text); + //Search + UpdateTabModuleSetting(SettingName.ShowSearchTextBox, chkShowSearchTextBox.Checked.ToString(CultureInfo.InvariantCulture)); + UpdateTabModuleSetting(SettingName.ShowNoRecordsUntilSearch, chkShowNoRecordsUntilSearch.Checked.ToString(CultureInfo.InvariantCulture)); + UpdateTabModuleSetting(SettingName.SimpleSearch, chkSimpleSearch.Checked.ToString(CultureInfo.InvariantCulture)); + UpdateTabModuleSetting(SettingName.UseButtonsInForm, chkUseButtons.Checked.ToString(CultureInfo.InvariantCulture)); + UpdateTabModuleSetting(SettingName.URLSearch, chkURLSearch.Checked.ToString(CultureInfo.InvariantCulture)); + //forms or list + UpdateTabModuleSetting(SettingName.ListOrForm, rblUsageListForm.SelectedValue); + //form + UpdateTabModuleSetting(SettingName.SubmissionText, HttpUtility.HtmlDecode(teSubmissionSuccess.Text)); + UpdateTabModuleSetting(SettingName.UponSubmitRedirect, urlOnSubmissionRedirect.Url); + UpdateTabModuleSetting(SettingName.UponSubmitAction, rblOnSubmission.SelectedValue); + //tracking + var strTrackingEmailSkript = ""; + + if (rblBodyType.SelectedValue == "XslScript" && XslTracking.Url != string.Empty) + { + var file = FileManager.Instance.GetFile(int.Parse(XslTracking.Url.Substring(7))); + if (file != null) + { + strTrackingEmailSkript = file.Folder + file.FileName; + } + } + else + { + strTrackingEmailSkript = StrAuto; + } + + UpdateTabModuleSetting(SettingName.TrackingScript, strTrackingEmailSkript); + UpdateTabModuleSetting(SettingName.TrackingEmailTo, txtTrackingEmailAddresses.Text); + UpdateTabModuleSetting(SettingName.TrackingEmailCc, txtTrackingEmail_CC.Text); + UpdateTabModuleSetting(SettingName.TrackingEmailBcc, txtTrackingEmail_BCC.Text); + UpdateTabModuleSetting(SettingName.TrackingEmailReplyTo, txtTrackingEmail_replyto.Text); + UpdateTabModuleSetting(SettingName.TrackingEmailFrom, txtTrackingEmail_from.Text); + UpdateTabModuleSetting(SettingName.TrackingSubject, txtTrackingSubject.Text); + UpdateTabModuleSetting(SettingName.TrackingMessage, HttpUtility.HtmlDecode(teTrackingMessage.Text)); + UpdateTabModuleSetting(SettingName.TrackingTriggerOnDelete, chkTrackingOnDelete.Checked.ToString(CultureInfo.InvariantCulture)); + UpdateTabModuleSetting(SettingName.TrackingTriggerOnNew, chkTrackingOnNew.Checked.ToString(CultureInfo.InvariantCulture)); + UpdateTabModuleSetting(SettingName.TrackingTriggerOnUpdate, chkTrackingOnUpdate.Checked.ToString(CultureInfo.InvariantCulture)); + UpdateTabModuleSetting(SettingName.TrackingTextOnNew, txtOnNew.Text); + UpdateTabModuleSetting(SettingName.TrackingTextOnUpdate, txtOnUpdate.Text); + UpdateTabModuleSetting(SettingName.TrackingTextOnDelete, txtOnDelete.Text); + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + void SetHelpLinks() + { + var helpUrL = string.Format("javascript:OpenHelpWindow(\'{0}\')", + ResolveUrl( + "~/desktopmodules/userdefinedtable/HelpPopup.aspx?resourcekey=Help_Tokens_6")); + hlpToken2.NavigateUrl = helpUrL; + helpUrL = string.Format("javascript:OpenHelpWindow(\'{0}\')", + ResolveUrl( + "~/desktopmodules/userdefinedtable/HelpPopup.aspx?resourcekey=Help_HiddenColumns")); + hlpColumns2.NavigateUrl = helpUrL; + } + + #endregion + + #region Event Handlers + + protected override void OnInit(EventArgs e) + { + // Moved from BindSettings to handle issues with the RTE + teSubmissionSuccess.Text = + ModuleContext.Settings[SettingName.SubmissionText].AsString(Localization.GetString("SubmissionSuccess", + LocalResourceFile)); + teTrackingMessage.Text = ModuleContext.Settings[SettingName.TrackingMessage].AsString(); + cmdCancel.Click += cmdCancel_Click; + + cmdEditEmail.Click += cmdEditEmail_Click; + cmdEditXSL.Click += cmdEditXSL_Click; + cmdGenerateEmail.Click += cmdGenerateEmail_Click; + cmdGenerateXSL.Click += cmdGenerateXSL_Click; + cmdUpdate.Click += cmdUpdate_Click; + chkShowSearchTextBox.CheckedChanged += chkShowSearchTextBox_CheckedChanged; + + + Load += Page_Load; + Fields.LocalizeString = LocalizeString; + Fields.LocalResourceFile = LocalResourceFile; + Fields.ModuleContext = ModuleContext; + jQuery.RequestDnnPluginsRegistration(); + ClientAPI.RegisterClientReference(Page, ClientAPI.ClientNamespaceReferences.dnn); + } + + + void Page_Load(object sender, EventArgs e) + { + try + { + if (! Page.IsPostBack) + { + //Localize Grid + BindData(); + } + SetHelpLinks(); + ApplySettingsVisibility(); + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + + + void cmdCancel_Click(object sender, EventArgs e) + { + Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); + } + + + void cmdUpdate_Click(object sender, EventArgs e) + { + if (ValidateMailTo()) + { + var dnn = DotNetNuke.Application.DotNetNukeContext.Current.Application; + string dnnVersion = String.Format("{0}.{1}.{2}", + dnn.Version.Major.ToString("00"), + dnn.Version.Minor.ToString("00"), + dnn.Version.Revision.ToString("00")); + + if (System.String.Compare(dnnVersion, "07.02.02", System.StringComparison.Ordinal) < 0 && chkExcludeFromSearch.Checked) + { + DataProvider.Instance().DeleteSearchItems(ModuleContext.ModuleId); + } + SaveSettings(); + Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); + } + } + + + void cmdGenerateXSL_Click(object sender, EventArgs e) + { + SaveSettings(); + Response.Redirect(ModuleContext.EditUrl("GenerateXsl"), true); + } + + void cmdEditXSL_Click(object sender, EventArgs e) + { + var fileId = GetEditableFileId(XslUserDefinedUrlControl.Url.ToLowerInvariant()); + if (fileId > - 1) + { + SaveSettings(); + Response.Redirect(ModuleContext.EditUrl("FileID", fileId.ToString(CultureInfo.InvariantCulture), "GenerateXsl"), true); + } + } + + void chkShowSearchTextBox_CheckedChanged(object sender, EventArgs e) + { + var searchEnabled = chkShowSearchTextBox.Checked; + chkShowNoRecordsUntilSearch.Enabled = searchEnabled; + chkSimpleSearch.Enabled = searchEnabled; + chkURLSearch.Enabled = searchEnabled; + if (! searchEnabled) + { + chkShowNoRecordsUntilSearch.Checked = false; + chkSimpleSearch.Checked = false; + chkURLSearch.Checked = false; + } + } + + protected void cmdEditEmail_Click(object sender, EventArgs e) + { + var fileId = GetEditableFileId(XslTracking.Url.ToLowerInvariant()); + if (fileId > - 1) + { + SaveSettings(); + Response.Redirect(ModuleContext.EditUrl("FileID", fileId.ToString(CultureInfo.InvariantCulture), "GenerateXsl"), true); + } + } + + protected void cmdGenerateEmail_Click(object sender, EventArgs e) + { + SaveSettings(); + Response.Redirect(ModuleContext.EditUrl("tracking", "true", "GenerateXsl"), true); + } + + #endregion + + #region Optional Interfaces + + public ModuleActionCollection ModuleActions + { + get + { + var actions = new ModuleActionCollection(); + var url = string.Format("javascript:{0}", + Page.ClientScript.GetPostBackEventReference(this, "SaveSettingsAsDefault")); + actions.Add(ModuleContext.GetNextActionID(), + Localization.GetString("SaveSettingsAsDefault.Action", LocalResourceFile), "", "", + Utilities.IconURL("Save"), url, false, SecurityAccessLevel.Edit, true, false); + + url = string.Format("javascript:if (confirm(\'{0}\')) {1}", + Localization.GetString("ResetModuleTabSettings.Confirm", + LocalResourceFile).AsString().Replace("\'", "\\\'"), + Page.ClientScript.GetPostBackEventReference(this, "ResetModuleTabSettings")); + actions.Add(ModuleContext.GetNextActionID(), + Localization.GetString("ResetModuleTabSettings.Action", LocalResourceFile), "", "", + Utilities.IconURL("Restore"), url, false, SecurityAccessLevel.Edit, true, false); + + url = string.Format("javascript:if (confirm(\'{0}\')) {1}", + Localization.GetString("DeleteAll.Confirm", LocalResourceFile).AsString(). + Replace("\'", "\\\'"), + Page.ClientScript.GetPostBackEventReference(this, "DeleteAll")); + actions.Add(ModuleContext.GetNextActionID(), + Localization.GetString("DeleteAll.Action", LocalResourceFile), "", "", + Utilities.IconURL("Save"), url, false, SecurityAccessLevel.Edit, true, false); + return actions; + } + } + + public void RaisePostBackEvent(string eventArgument) + { + switch (eventArgument) + { + case "ResetModuleTabSettings": + ModulesController.DeleteTabModuleSettings(ModuleContext.TabModuleId); + break; + case "SaveSettingsAsDefault": + SaveSettings(); + var tabModuleSettings = ModulesController.GetTabModuleSettings(ModuleContext.TabModuleId); + + foreach (string key in tabModuleSettings.Keys) + { + ModulesController.UpdateModuleSetting(ModuleContext.ModuleId, key, + tabModuleSettings[key].ToString()); + } + break; + case "DeleteAll": + UdtController.DeleteRows(); + Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); + break; + } + } + + #endregion + } +} \ No newline at end of file diff --git a/Configuration.ascx.designer.cs b/Configuration.ascx.designer.cs new file mode 100644 index 0000000..350e7c0 --- /dev/null +++ b/Configuration.ascx.designer.cs @@ -0,0 +1,717 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable { + + + public partial class Configuration { + + /// + /// udtSection control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl udtSection; + + /// + /// Fields control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.Modules.UserDefinedTable.Controls.Fields Fields; + + /// + /// plPrivacy control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plPrivacy; + + /// + /// chkExcludeFromSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkExcludeFromSearch; + + /// + /// lblList control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl lblList; + + /// + /// rblUsageListForm control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.RadioButtonList rblUsageListForm; + + /// + /// rememberSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl rememberSettings; + + /// + /// plUseButtons control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plUseButtons; + + /// + /// chkUseButtons control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkUseButtons; + + /// + /// plainFormSettingSet control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl plainFormSettingSet; + + /// + /// lblOnSubmission control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl lblOnSubmission; + + /// + /// rblOnSubmission control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.RadioButtonList rblOnSubmission; + + /// + /// rowOnSubmissionRedirect control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl rowOnSubmissionRedirect; + + /// + /// lblOnSubmissionRedirect control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl lblOnSubmissionRedirect; + + /// + /// rowSubmissionText control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl rowSubmissionText; + + /// + /// lblSub control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl lblSub; + + /// + /// noFormSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl noFormSettings; + + /// + /// plRenderMethod control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plRenderMethod; + + /// + /// renderMethodRadioButtonList control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.RadioButtonList renderMethodRadioButtonList; + + /// + /// rowUserDefined control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl rowUserDefined; + + /// + /// plUserDefinedStyleSheet control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plUserDefinedStyleSheet; + + /// + /// cmdEditXSL control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdEditXSL; + + /// + /// cmdGenerateXSL control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdGenerateXSL; + + /// + /// lblSorting control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblSorting; + + /// + /// plSort control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plSort; + + /// + /// cboSortField control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList cboSortField; + + /// + /// plOrder control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plOrder; + + /// + /// cboSortOrder control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList cboSortOrder; + + /// + /// plPaging control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plPaging; + + /// + /// cboPaging control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList cboPaging; + + /// + /// lblSearchAndFilter control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblSearchAndFilter; + + /// + /// plFilterDataSet control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plFilterDataSet; + + /// + /// txtFilter control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtFilter; + + /// + /// hlpToken2 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink hlpToken2; + + /// + /// hlpColumns2 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink hlpColumns2; + + /// + /// rowSearchBox control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl rowSearchBox; + + /// + /// plShowSearchTextBox control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plShowSearchTextBox; + + /// + /// chkShowSearchTextBox control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkShowSearchTextBox; + + /// + /// plSimpleSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plSimpleSearch; + + /// + /// chkSimpleSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkSimpleSearch; + + /// + /// plShowNoRecordsUntilSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plShowNoRecordsUntilSearch; + + /// + /// chkShowNoRecordsUntilSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkShowNoRecordsUntilSearch; + + /// + /// plURLSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plURLSearch; + + /// + /// chkURLSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkURLSearch; + + /// + /// plTopCount control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plTopCount; + + /// + /// txtTopCount control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtTopCount; + + /// + /// errTopCount control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.RangeValidator errTopCount; + + /// + /// plTrackingOn control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plTrackingOn; + + /// + /// chkTrackingOnNew control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkTrackingOnNew; + + /// + /// chkTrackingOnUpdate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkTrackingOnUpdate; + + /// + /// chkTrackingOnDelete control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkTrackingOnDelete; + + /// + /// plTrackingEmailAddresses control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plTrackingEmailAddresses; + + /// + /// txtTrackingEmailAddresses control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtTrackingEmailAddresses; + + /// + /// plTrackingEmail_CC control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plTrackingEmail_CC; + + /// + /// txtTrackingEmail_CC control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtTrackingEmail_CC; + + /// + /// plTrackingEmail_BCC control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plTrackingEmail_BCC; + + /// + /// txtTrackingEmail_BCC control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtTrackingEmail_BCC; + + /// + /// plTrackingEmail_replyto control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plTrackingEmail_replyto; + + /// + /// txtTrackingEmail_replyto control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtTrackingEmail_replyto; + + /// + /// plTrackingEmail_from control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plTrackingEmail_from; + + /// + /// txtTrackingEmail_from control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtTrackingEmail_from; + + /// + /// plEmailSubject control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plEmailSubject; + + /// + /// txtTrackingSubject control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtTrackingSubject; + + /// + /// plTrackingMessage control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plTrackingMessage; + + /// + /// plOnNew control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plOnNew; + + /// + /// txtOnNew control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtOnNew; + + /// + /// plOnUpdate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plOnUpdate; + + /// + /// txtOnUpdate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtOnUpdate; + + /// + /// plOnDelete control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plOnDelete; + + /// + /// txtOnDelete control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtOnDelete; + + /// + /// plBody control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plBody; + + /// + /// rblBodyType control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.RadioButtonList rblBodyType; + + /// + /// rowTrackingScript control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl rowTrackingScript; + + /// + /// plTrackingScript control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plTrackingScript; + + /// + /// cmdEditEmail control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdEditEmail; + + /// + /// cmdGenerateEmail control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdGenerateEmail; + + /// + /// cmdUpdate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.WebControls.CommandButton cmdUpdate; + + /// + /// cmdCancel control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.WebControls.CommandButton cmdCancel; + } +} diff --git a/Controls/Field.ascx b/Controls/Field.ascx new file mode 100644 index 0000000..9731be6 --- /dev/null +++ b/Controls/Field.ascx @@ -0,0 +1,149 @@ +<%@ Control Language="C#"CodeBehind="Field.ascx.cs" Inherits="DotNetNuke.Modules.UserDefinedTable.Controls.Field" AutoEventWireup="false"%> +<%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %> +<%@ Import Namespace="DotNetNuke.Entities.Icons" %> +<%@ Register TagPrefix="dnn" Assembly="DotNetNuke" Namespace="DotNetNuke.UI.WebControls" %> +<%@ Register TagPrefix="dnn" Namespace="DotNetNuke.Web.Client.ClientResourceManagement" Assembly="DotNetNuke.Web.Client" %> + +<%@ Register src="FieldSettings.ascx" tagname="FieldSettings" tagprefix="fnl" %> + +
+
+
+ + + + +
+
+ + + + + +
+
+ + +
+
+ + +
+
+ + + +
+
+ + +
+
+ + +
+
+ + +
+ +

+ +
+
+
+ + + + + + + + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ + +
+
+ + +
+ +
+
+ +

+
+
+
+ + +
+ +
+ + +
+ +
+
+ +
    +
  • +
  • +
  • +
  • +
+
+ + + + + + \ No newline at end of file diff --git a/Controls/Field.ascx.cs b/Controls/Field.ascx.cs new file mode 100644 index 0000000..db5cdab --- /dev/null +++ b/Controls/Field.ascx.cs @@ -0,0 +1,430 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text.RegularExpressions; +using System.Web.UI; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Security; +using DotNetNuke.UI.Modules; +using DotNetNuke.UI.UserControls; + +namespace DotNetNuke.Modules.UserDefinedTable.Controls +{ + public partial class Field : UserControl + { + + protected LabelControl DefaultLabel; + protected LabelControl InputSettingsLabel; + protected LabelControl OutputSettingsLabel; + protected LabelControl NormalizeFlagLabel; + protected LabelControl MultipleValuesLabel; + protected LabelControl ShowOnEditLabel; + public class FieldTitelException:Exception + { + public FieldTitelException(string message) : base(message){} + } + + public Func LocalizeString { get; set; } + + protected override void OnInit(EventArgs e) + { + cmdCancel.Click += cmdCancel_Click; + cmdUpdate.Click += cmdUpdate_Click; + cboFieldType.SelectedIndexChanged += cboFieldType_SelectedIndexChanged; + Load += Page_Load; + SetHelpLinks(); + } + + void Page_Load(object sender, EventArgs e) + { + divError.Visible = false; + divWarning.Visible = false; + if (IsPostBack) + { + var selectedType = DataType.ByName(cboFieldType.SelectedValue); + FormFieldSettings.Show(selectedType); + ListFieldSettings.Show(selectedType); + } + } + + void cboFieldType_SelectedIndexChanged(object sender, EventArgs e) + { + var newType = DataType.ByName(cboFieldType.SelectedValue); + CheckCast(newType); + ShowOrHideSettingsByType(newType); + FormFieldSettings.Show(newType); + ListFieldSettings.Show(newType); + } + + void cmdUpdate_Click(object sender, EventArgs e) + { + try + { + if (Page.IsValid) + { + UpdateField(); + if (HideField != null) HideField(); + } + } + + catch (FieldTitelException ea) + { + ShowErrorMessage(ea.Message ); + } + } + + void ShowErrorMessage(string message) + { + divError.Controls.Add(new LiteralControl(message)); + divError.Visible = true; + } + + void ShowWarning(string message) + { + divWarning.Controls.Add(new LiteralControl(message)); + divWarning.Visible = true; + } + + + void cmdCancel_Click(object sender, EventArgs e) + { + if (HideField != null) HideField(); + } + + public event Action HideField; + + public DataRowView DataSource { get; set; } + + public ModuleInstanceContext ModuleContext { get; set; } + + protected IDictionary ContentDataTypes + { + get { return DataType.ContentDataTypes(); } + } + + protected IDictionary SystemDataTypes + { + get { return DataType.SystemDataTypes(); } + } + + public DataTable Settings { get; set; } + + void UpdateField() + { + var fieldOrder = (int)DataSource[FieldsTableColumn.Order]; + + var newFieldType = cboFieldType.SelectedItem.Value; + var newHelpText = txtHelpText.Text.Trim(); + var fieldTitle = GetFieldTitle(); + var inputSettings = GetInputSettings(); + var formerTitle = DataSource[FieldsTableColumn.Title].AsString(); + var formerType = DataType.ByName(DataSource[FieldsTableColumn.Type].AsString()); + var id = DataSource[FieldsTableColumn.Id].AsInt(); + if (IsAllowedFieldTitle(fieldTitle) && IsUniqueFieldTitle(fieldTitle, formerTitle)) + { + if (formerType.IsUserDefinedField) + { + if (IsNewField(id)) + { + id = FieldController.AddField(ModuleContext.ModuleId, fieldTitle, + fieldOrder, newHelpText, + chkRequired.Checked, newFieldType, txtDefault.Text, + chkDisplayOnList.Checked , chkShowOnEdit.Checked, + chkSearchable.Checked, chkRestrictedFormField.Checked, + chkMultipleValues.Checked, inputSettings, + txtOutputSettings.Text, chkNormalizeFlag.Checked, + txtValidationRule.Text, txtValidationMessage.Text, + txtEditStyle.Text); + if (txtDefault.Text != "") + { + new UserDefinedTableController(ModuleContext).FillDefaultData(id, txtDefault.Text); + } + } + else + { + FieldController.UpdateField(id, fieldTitle, newHelpText, chkRequired.Checked, + newFieldType, txtDefault.Text, chkDisplayOnList.Checked, + chkShowOnEdit.Checked, chkSearchable.Checked, + chkRestrictedFormField.Checked, chkMultipleValues.Checked, + inputSettings, + txtOutputSettings.Text, chkNormalizeFlag.Checked, + txtValidationRule.Text, txtValidationMessage.Text, + txtEditStyle.Text); + } + } + else + { + FieldController.UpdateField(id, + fieldTitle, newHelpText, true, formerType.Name, string.Empty, + chkDisplayOnList.Checked, chkShowOnEdit.Checked, chkSearchable.Checked, + chkRestrictedFormField.Checked, false, + string.Empty, + txtOutputSettings.Text, chkNormalizeFlag.Checked, + string.Empty, string.Empty, string.Empty ); + } + } + ListFieldSettings.Update( id, DataType.ByName(newFieldType)); + FormFieldSettings.Update( id, DataType.ByName(newFieldType)); + + } + + string GetFieldTitle() + { + var fieldTitle = txtFieldTitle.Text.Trim(); + if (!ModuleSecurity.IsAdministrator()) + { + fieldTitle = new PortalSecurity().InputFilter(fieldTitle, PortalSecurity.FilterFlag.NoScripting); + } + return fieldTitle; + } + + static bool IsNewField(int id) + { + return id == Null.NullInteger; + } + + string GetInputSettings() + { + var inputSettings = txtInputSettings.Text; + if (cboInputSettings.Visible) + { + inputSettings = cboInputSettings.SelectedValue; + } + if (rblListType.SelectedValue == "RadioButtons") + { + inputSettings += Definition.verticalRadioButtonEnabledToken; + } + if (rblListType.SelectedValue == "RadioButtonsHorizontal") + { + inputSettings += Definition.horizontalRadioButtonEnabledToken; + } + return inputSettings; + } + + bool IsAllowedFieldTitle(string title) + { + if (title.IndexOfAny(":,*?".ToCharArray()) > -1) + { + throw new FieldTitelException( LocalizeString("SpecialCharactersInFieldTitle.ErrorMessage") ); + } + if (title.Contains( DataTableColumn.Appendix_Prefix) ) + { + throw new FieldTitelException(LocalizeString("UDT_InFieldTitle.ErrorMessage")); + } + return title != string.Empty; + } + + bool IsUniqueFieldTitle(string fieldTitle, string oldfieldtitle) + { + oldfieldtitle = oldfieldtitle.ToLowerInvariant(); + var fields = FieldController.GetFieldsTable(ModuleContext.ModuleId); + var isUnique = !fields.Rows.Cast() + .Any( + field => + field[FieldsTableColumn.Title].ToString().ToLowerInvariant() == + fieldTitle.ToLowerInvariant() + && field[FieldsTableColumn.Title].ToString().ToLowerInvariant() != oldfieldtitle); + if (!isUnique) + { + throw new FieldTitelException(LocalizeString("UniqueFieldName.ErrorMessage")); + } + return true; + } + + void CheckCast(DataType newType) + { + var formerType = DataType.ByName(DataSource[FieldsTableColumn.Type].AsString("String")); + + var allowedCasts = formerType.SupportedCasts.Split("|".ToCharArray()); + if (allowedCasts.Any(n => newType.Name == n)) + { + return; + } + // Cast is not allowed, now we need to check whether data already exists for that column + var fieldId = DataSource[FieldsTableColumn.Id].AsInt(); + if (new UserDefinedTableController(ModuleContext).FieldHasData(fieldId)) + { + var message = LocalizeString("UnsupportedCast.ErrorMessage") + .AsString("You have changed the fieldtype for {2} from {0} to {1}. Note that this may cause an error"); + + var title = new PortalSecurity().InputFilter(txtFieldTitle.Text.Trim(), PortalSecurity.FilterFlag.NoScripting); + message = string.Format(message, formerType.GetLocalization(), + newType.GetLocalization(), title); + ShowWarning(message); + } + } + + void SetHelpLinks() + { + + var helpUrL = string.Format("javascript:OpenHelpWindow(\'{0}\')", + ResolveUrl("~/desktopmodules/userdefinedtable/HelpPopup.aspx?resourcekey=Help_Tokens_6")); + hlpToken.NavigateUrl = helpUrL; + + helpUrL = string.Format("javascript:OpenHelpWindow(\'{0}\')", + ResolveUrl("~/desktopmodules/userdefinedtable/HelpPopup.aspx?resourcekey=Help_HiddenColumns")); + hlpColumns.NavigateUrl = helpUrL; + } + + public void Bind() + { + txtFieldTitle.Text = DataSource[FieldsTableColumn.Title].AsString(); + + var type = DataType.ByName(DataSource[FieldsTableColumn.Type].AsString("String")); + cboFieldType.DataSource = type.IsUserDefinedField ? DataType.ContentDataTypes() : DataType.SystemDataTypes(); + cboFieldType.DataBind(); + cboFieldType.SelectedValue = type.Name; + lblType.Text = type.GetLocalization(); + + txtHelpText.Text = DataSource[FieldsTableColumn.HelpText].AsString(); + txtDefault.Text = DataSource[FieldsTableColumn.Default].AsString(); + var inputSettings = DataSource[FieldsTableColumn.InputSettings].AsString(); + + chkRequired.Checked = DataSource[FieldsTableColumn.Required].AsBoolean(); + chkDisplayOnList.Checked = DataSource[FieldsTableColumn.Visible].AsBoolean(); + chkRestrictedFormField.Checked = DataSource[FieldsTableColumn.IsPrivate].AsBoolean(); + chkSearchable.Checked = DataSource[FieldsTableColumn.Searchable].AsBoolean(); + + if (inputSettings.EndsWith(Definition.verticalRadioButtonEnabledToken)) + { + rblListType.SelectedValue = "RadioButtons"; + } + else if (inputSettings.EndsWith(Definition.horizontalRadioButtonEnabledToken)) + { + rblListType.SelectedValue = "RadioButtonsHorizontal"; + } + + txtInputSettings.Text = Regex.Replace(inputSettings, "-\\[\\[(?:h|v)RBL]]$", ""); + txtOutputSettings.Text = DataSource[FieldsTableColumn.OutputSettings].AsString(); + chkNormalizeFlag.Checked = DataSource[FieldsTableColumn.NormalizeFlag].AsBoolean(); + chkMultipleValues.Checked = DataSource[FieldsTableColumn.MultipleValues].AsBoolean(); + chkShowOnEdit.Checked = DataSource[FieldsTableColumn.ShowOnEdit].AsBoolean(); + txtValidationRule.Text = DataSource[FieldsTableColumn.ValidationRule].AsString(); + txtValidationMessage.Text = DataSource[FieldsTableColumn.ValidationMessage].AsString(); + txtEditStyle.Text = DataSource[FieldsTableColumn.EditStyle].AsString(); + if (cboInputSettings.Visible) + { + cboInputSettings.SelectedValue = inputSettings.AsString("String"); + } + ShowOrHideSettingsByType(type); + + var id = DataSource[FieldsTableColumn.Id].AsInt(); + DataBind(); + if (!IsPostBack) + { + FormFieldSettings.Show(type); + FormFieldSettings.BindData(id, Settings, type); + ListFieldSettings.Show(type); + ListFieldSettings.BindData(id, Settings, type); + } + + } + + + + void ShowOrHideSettingsByType(DataType selectedType) + { + cboFieldType.Visible = selectedType.IsUserDefinedField; + lblType.Visible = !selectedType.IsUserDefinedField; + chkRequired.Visible = selectedType.IsUserDefinedField; + imgRequired.Visible = !selectedType.IsUserDefinedField; + chkSearchable.Visible = selectedType.SupportsSearch; + lblSearchable.Visible = selectedType.SupportsSearch; + + + if (selectedType.SupportsDefaultValue) + { + panDefault.Visible = true; + DefaultLabel.Text = selectedType.GetLocalization("DefaultValue").AsString(DefaultLabel.Text); + DefaultLabel.HelpText = selectedType.GetLocalization("DefaultValue.Help").AsString(DefaultLabel.HelpText); + } + else + { + panDefault.Visible = false; + } + + if (selectedType.SupportsInputSettings) + { + panInputSettings.Visible = true; + var selectionSource = selectedType.InputSettingsList; + if (selectionSource == null) + { + txtInputSettings.Visible = true; + cboInputSettings.Visible = false; + } + else + { + cboInputSettings.DataSource = selectionSource; + var currValue = cboInputSettings.SelectedValue; + cboInputSettings.DataBind(); + if (currValue != "" && cboInputSettings.Items.FindByValue(currValue) != null) + { + cboInputSettings.SelectedValue = currValue; + } + else + { + cboInputSettings.SelectedValue = selectedType.InputSettingDefault; + } + txtInputSettings.Visible = false; + cboInputSettings.Visible = true; + } + InputSettingsLabel.Text = selectedType.GetLocalization("InputSetting").AsString(InputSettingsLabel.Text); + InputSettingsLabel.HelpText = + selectedType.GetLocalization("InputSetting.Help").AsString(InputSettingsLabel.HelpText); + rblListType.Visible = selectedType.InputSettingsIsValueList; + } + else + { + panInputSettings.Visible = false; + } + + if (selectedType.SupportsOutputSettings) + { + panOutputSettings.Visible = true; + OutputSettingsLabel.Text = selectedType.GetLocalization("OutputSetting").AsString(OutputSettingsLabel.Text); + OutputSettingsLabel.HelpText = + selectedType.GetLocalization("OutputSetting.Help").AsString(OutputSettingsLabel.HelpText); + } + else + { + panOutputSettings.Visible = false; + } + + if (selectedType.SupportsNormalizeFlag) + { + panNormalizeFlag.Visible = true; + NormalizeFlagLabel.Text = selectedType.GetLocalization("NormalizeFlag").AsString(NormalizeFlagLabel.Text); + NormalizeFlagLabel.HelpText = + selectedType.GetLocalization("NormalizeFlag.Help").AsString(NormalizeFlagLabel.HelpText); + } + else + { + panNormalizeFlag.Visible = false; + } + + if (selectedType.SupportsMultipleValues) + { + panMultipleValues.Visible = true; + MultipleValuesLabel.Text = selectedType.GetLocalization("MultipleValues").AsString(MultipleValuesLabel.Text); + MultipleValuesLabel.HelpText = + selectedType.GetLocalization("MultipleValues.Help").AsString(MultipleValuesLabel.HelpText); + } + else + { + panMultipleValues.Visible = false; + } + panShowOnEdit.Visible = selectedType.SupportsHideOnEdit; + if (selectedType.SupportsHideOnEdit ) + { + ShowOnEditLabel.Text = selectedType.GetLocalization("HideOnEdit").AsString(ShowOnEditLabel.Text); + ShowOnEditLabel.HelpText = selectedType.GetLocalization("HideOnEdit.Help").AsString(ShowOnEditLabel.HelpText); + } + panEditStyle.Visible = selectedType.SupportsEditStyle; + panValidationRule.Visible = selectedType.SupportsValidation; + panValidationMessage.Visible = selectedType.SupportsValidation; + panHelpText.Visible = selectedType.SupportsEditing; + } + } +} \ No newline at end of file diff --git a/Controls/Field.ascx.designer.cs b/Controls/Field.ascx.designer.cs new file mode 100644 index 0000000..c790f9b --- /dev/null +++ b/Controls/Field.ascx.designer.cs @@ -0,0 +1,429 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable.Controls { + + + public partial class Field { + + /// + /// divWarning control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl divWarning; + + /// + /// lblType control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblType; + + /// + /// lblFieldType control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblFieldType; + + /// + /// cboFieldType control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList cboFieldType; + + /// + /// txtFieldTitle control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtFieldTitle; + + /// + /// divError control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl divError; + + /// + /// panHelpText control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl panHelpText; + + /// + /// lblHelpText control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl lblHelpText; + + /// + /// txtHelpText control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtHelpText; + + /// + /// panDefault control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl panDefault; + + /// + /// txtDefault control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtDefault; + + /// + /// imgRequired control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Image imgRequired; + + /// + /// chkRequired control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkRequired; + + /// + /// chkDisplayOnList control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkDisplayOnList; + + /// + /// chkRestrictedFormField control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkRestrictedFormField; + + /// + /// lblSearchable control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl lblSearchable; + + /// + /// chkSearchable control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkSearchable; + + /// + /// lblFormsettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblFormsettings; + + /// + /// panInputSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl panInputSettings; + + /// + /// txtInputSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtInputSettings; + + /// + /// cboInputSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList cboInputSettings; + + /// + /// rblListType control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.RadioButtonList rblListType; + + /// + /// panMultipleValues control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl panMultipleValues; + + /// + /// chkMultipleValues control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkMultipleValues; + + /// + /// panValidationRule control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl panValidationRule; + + /// + /// lblValidationRule control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl lblValidationRule; + + /// + /// txtValidationRule control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtValidationRule; + + /// + /// panValidationMessage control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl panValidationMessage; + + /// + /// lblValidationMessage control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl lblValidationMessage; + + /// + /// txtValidationMessage control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtValidationMessage; + + /// + /// panEditStyle control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl panEditStyle; + + /// + /// lblEditStyle control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl lblEditStyle; + + /// + /// txtEditStyle control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtEditStyle; + + /// + /// panShowOnEdit control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl panShowOnEdit; + + /// + /// chkShowOnEdit control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkShowOnEdit; + + /// + /// FormFieldSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.Modules.UserDefinedTable.Controls.FieldSettings FormFieldSettings; + + /// + /// lblListSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblListSettings; + + /// + /// panOutputSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl panOutputSettings; + + /// + /// txtOutputSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtOutputSettings; + + /// + /// panNormalizeFlag control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl panNormalizeFlag; + + /// + /// chkNormalizeFlag control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkNormalizeFlag; + + /// + /// ListFieldSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.Modules.UserDefinedTable.Controls.FieldSettings ListFieldSettings; + + /// + /// cmdUpdate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.WebControls.CommandButton cmdUpdate; + + /// + /// cmdCancel control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.WebControls.CommandButton cmdCancel; + + /// + /// hlpToken control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink hlpToken; + + /// + /// hlpColumns control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink hlpColumns; + } +} diff --git a/Controls/FieldSettings.ascx b/Controls/FieldSettings.ascx new file mode 100644 index 0000000..0063f46 --- /dev/null +++ b/Controls/FieldSettings.ascx @@ -0,0 +1,15 @@ +<%@ Control Language="C#" CodeBehind="FieldSettings.ascx.cs" Inherits="DotNetNuke.Modules.UserDefinedTable.Controls.FieldSettings" %> +<%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %> + +<%@ Import Namespace="DotNetNuke.Modules.UserDefinedTable.Components" %> + + +
+ + + +
+
+
\ No newline at end of file diff --git a/Controls/FieldSettings.ascx.cs b/Controls/FieldSettings.ascx.cs new file mode 100644 index 0000000..e3eef03 --- /dev/null +++ b/Controls/FieldSettings.ascx.cs @@ -0,0 +1,84 @@ +using System.Data; +using System.Globalization; +using System.Linq; +using System.Web.UI.WebControls; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.UI.UserControls; + +namespace DotNetNuke.Modules.UserDefinedTable.Controls +{ + public partial class FieldSettings : System.Web.UI.UserControl + { + + public string Section { get; set; } + public string TypeName { get; set; } + public DataType SelectedType { get; set; } + + public void Show(DataType selectedType) + { + TypeName = selectedType.Name; + SelectedType = selectedType; + Repeater1.DataSource = selectedType.FieldSettingTypes.Where(t=>t.Section==Section); + Repeater1.DataBind(); + } + + public void BindData(int fieldId,DataTable settingsTable, DataType type) + { + + if (!IsPostBack) + { + var types = type.FieldSettingTypes.Where(t => t.Section == Section).ToArray(); + for (var i = 0; i < types.Count(); i++) + { + var key = types[i].Key; + var value = settingsTable.GetFieldSetting(key, fieldId); + if (!string.IsNullOrEmpty(value)) + { + var t = type.FieldSettingTypes.ElementAt(i).SystemType; + if (t == "Boolean") + { + var cb = Repeater1.Controls[i].FindControl("Checkbox") as CheckBox; + if (cb != null) cb.Checked = value.AsBoolean(); + } + else + { + var tb = Repeater1.Controls[i].FindControl("Textbox") as TextBox; + if (tb != null) tb.Text = value; + } + } + + } + } + } + + public void Update(int fieldId, DataType type) + { + var types = type.FieldSettingTypes.Where(t => t.Section == Section).ToArray(); + for (var i = 0; i < types.Count(); i++) + { + var value = string.Empty; + var t = types[i].SystemType; + if (t == "Boolean") + { + var cb = Repeater1.Controls[i].FindControl("Checkbox") as CheckBox; + if (cb != null) value = cb.Checked.ToString(CultureInfo.InvariantCulture); + } + else + { + var tb = Repeater1.Controls[i].FindControl("Textbox") as TextBox; + if (tb != null) value = tb.Text; + } + + if (t == "Int") + { + value = value.AsInt().ToString(CultureInfo.InvariantCulture); + } + + var key = types[i].Key; + if (types[i].VerifySetting (value)) + FieldSettingsController.UpdateFieldSetting(key, value, fieldId); + } + + } + } +} \ No newline at end of file diff --git a/Controls/FieldSettings.ascx.designer.cs b/Controls/FieldSettings.ascx.designer.cs new file mode 100644 index 0000000..4483ae8 --- /dev/null +++ b/Controls/FieldSettings.ascx.designer.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable.Controls { + + + public partial class FieldSettings { + + /// + /// Repeater1 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Repeater Repeater1; + } +} diff --git a/Controls/Fields.ascx b/Controls/Fields.ascx new file mode 100644 index 0000000..a6939e1 --- /dev/null +++ b/Controls/Fields.ascx @@ -0,0 +1,112 @@ +<%@ Control Language="C#" AutoEventWireup="false" CodeBehind="Fields.ascx.cs" Inherits="DotNetNuke.Modules.UserDefinedTable.Controls.Fields" %> +<%@ Import Namespace="DotNetNuke.Modules.UserDefinedTable.Components" %> + +<%@ Register TagPrefix="dnn" Assembly="DotNetNuke" Namespace="DotNetNuke.UI.WebControls" %> +<%@ Import Namespace="DotNetNuke.Entities.Icons" %> +<%@ Import Namespace="DotNetNuke.Modules.UserDefinedTable.Components" %> +<%@ Register src="Field.ascx" tagname="Field" tagprefix="fnl" %> + + + + + + + + + + + Edit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
  • + +
  • +
+ + \ No newline at end of file diff --git a/Controls/Fields.ascx.cs b/Controls/Fields.ascx.cs new file mode 100644 index 0000000..9f7df12 --- /dev/null +++ b/Controls/Fields.ascx.cs @@ -0,0 +1,172 @@ +using System; +using System.Data; +using System.Linq; +using System.Web.UI.WebControls; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Security; +using DotNetNuke.Services.Exceptions; +using DotNetNuke.Services.Localization; +using DotNetNuke.UI.Modules; +using DotNetNuke.UI.Skins.Controls; +using DotNetNuke.UI.Utilities; +using Globals = DotNetNuke.Common.Globals; + +namespace DotNetNuke.Modules.UserDefinedTable.Controls +{ + public partial class Fields : System.Web.UI.UserControl + { + public ModuleInstanceContext ModuleContext { get; set; } + public Func LocalizeString { get; set; } + + + public string LocalResourceFile { get; set; } + + protected Field Field; + + protected override void OnInit(EventArgs e) + { + Load += Page_Load; + grdFields.DeleteCommand += grdFields_DeleteCommand; + grdFields.ItemCreated += grdFields_ItemCreated; + grdFields.ItemDataBound += grdFields_ItemDataBound; + + } + + void SetFieldOrder() + { + var fidString = FieldOrder.Value.Replace(",,", ","); + var fids = fidString.Split(','); + var ids = fids.Select(fid => int.Parse(fid.Split('_')[1])); + FieldController.ChangeFieldOrder(ids); + BindFields(); + FieldOrder.Value = string.Empty; + } + protected string EditUrl(int id) + { + var url = Globals.NavigateURL(ModuleContext.TabId, "EditField", new[]{"mid=" + ModuleContext.ModuleId , "fieldId=" + id}); + if (ModuleContext.PortalSettings.EnablePopUps) + url = UrlUtils.PopUpUrl(url, this, ModuleContext.PortalSettings, false, false, 760, 950); + return url; + } + + protected string Shorten(string input) + { + if (input.Length > 50) + return input.Substring(0, 47) + "..."; + return input; + } + + protected void Page_Load(object sender, EventArgs e) + { + if (!Page.IsPostBack) + { + //Localize Grid + Localization.LocalizeDataGrid(ref grdFields, LocalResourceFile); + BindFields( ); + + } + else + { + if (Request["__EVENTARGUMENT"] == "FieldOrder") SetFieldOrder(); + } + } + + void grdFields_ItemDataBound(object sender, DataGridItemEventArgs e) + { + try + { + var data = (DataRowView)e.Item.DataItem; + if (data != null) + { + var id = string.Format("fid_{0}", data[FieldsTableColumn.Id]); + e.Item.Attributes.Add("id", id); + } + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + void grdFields_DeleteCommand(object source, DataGridCommandEventArgs e) + { + try + { + var fields = FieldController.GetFieldsTable(ModuleContext.ModuleId, false); + var fieldId = int.Parse(Convert.ToString(grdFields.DataKeys[e.Item.ItemIndex])); + var fieldType = + fields.Select(string.Format("UserDefinedFieldId={0}", fieldId))[0][FieldsTableColumn.Type].AsString(); + + if (DataType.ByName(fieldType).IsUserDefinedField) + { + FieldController.DeleteField(fieldId); + } + + grdFields.EditItemIndex = Convert.ToInt32(-1); + BindFields(); + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + void grdFields_ItemCreated(object sender, DataGridItemEventArgs e) + { + try + { + var cmdDeleteUserDefinedField = e.Item.FindControl("cmdDeleteUserDefinedField"); + + if (cmdDeleteUserDefinedField != null) + { + ClientAPI.AddButtonConfirm((WebControl)cmdDeleteUserDefinedField, + LocalizeString("DeleteField")); + } + + if (e.Item.ItemType == ListItemType.Header) + { + e.Item.Cells[1].Attributes.Add("scope", "col"); + e.Item.Cells[2].Attributes.Add("scope", "col"); + e.Item.Cells[3].Attributes.Add("scope", "col"); + } + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected DataType DataTypeByName(string name) + { + return DataType.ByName(name); + } + protected string GetTypeName(string name) + { + var type = DataType.ByName(name); + if (type.Name == name) + { + return type.GetLocalization(); + } + + name = new PortalSecurity().InputFilter(name, PortalSecurity.FilterFlag.NoMarkup); + UI.Skins.Skin.AddModuleMessage(this, + string.Format( + Localization.GetString("DataTypeNotInstalled", LocalResourceFile), + name), ModuleMessage.ModuleMessageType.RedError); + return string.Format("\"{0} {0}", name, + Globals.ApplicationPath); + } + void BindFields() + { + var fields = FieldController.GetFieldsTable(ModuleContext.ModuleId); + var rowCount = fields.Rows.Count; + + grdFields.DataSource = fields.DefaultView; + grdFields.DataBind(); + grdFields.Visible = Convert.ToBoolean(rowCount != 0); + + cmdAddField.NavigateUrl = EditUrl(-1); + } + } +} \ No newline at end of file diff --git a/Controls/Fields.ascx.designer.cs b/Controls/Fields.ascx.designer.cs new file mode 100644 index 0000000..5926917 --- /dev/null +++ b/Controls/Fields.ascx.designer.cs @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable.Controls { + + + public partial class Fields { + + /// + /// FieldOrder control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HiddenField FieldOrder; + + /// + /// grdFields control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DataGrid grdFields; + + /// + /// cmdAddField control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink cmdAddField; + } +} diff --git a/DataTypes/Abstract/DataType.cs b/DataTypes/Abstract/DataType.cs new file mode 100644 index 0000000..a6622d2 --- /dev/null +++ b/DataTypes/Abstract/DataType.cs @@ -0,0 +1,380 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.IO; +using System.Runtime.Serialization; +using System.Web.Hosting; +using System.Web.UI.WebControls; +using System.Xml; +using DotNetNuke.Framework; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Modules.UserDefinedTable.DataTypes; +using DotNetNuke.Services.Exceptions; +using DotNetNuke.Services.Localization; + +namespace DotNetNuke.Modules.UserDefinedTable +{ + /// ----------------------------------------------------------------------------- + /// + /// Abstraced (MustInherit) DataType Class + /// Defines the Interface and provides some Default Settings + /// Used for Definition and Rendering of Fields in the UserDefinedTable + /// + /// ----------------------------------------------------------------------------- + public abstract class DataType + { + #region Internal Utilities (Protected) + + protected enum DbTypes + { + @Int32, + @Decimal, + @DateTime, + @String, + @Boolean + } + + protected static IDictionary ListOfCommonDataTypes + { + get + { + var dic = new SortedDictionary(); + foreach (var typeName in Enum.GetNames(typeof (DbTypes))) + { + dic.Add(ByName(typeName).GetLocalization(), typeName); + } + return dic; + } + } + + #endregion + + #region Static Interface + + static IDictionary _colDataTypes; + static readonly object DataTypeLock = new object(); + + static IDictionary DataTypes + { + get + { + if (_colDataTypes == null) + { + lock (DataTypeLock) + { + _colDataTypes = new Dictionary(); + + var doc = new XmlDocument(); +// ReSharper disable AssignNullToNotNullAttribute + doc.Load(GetDataTypesConfigPath()); +// ReSharper restore AssignNullToNotNullAttribute +// ReSharper disable PossibleNullReferenceException + foreach (XmlElement elem in doc.SelectNodes("dataTypes/dataType")) +// ReSharper restore PossibleNullReferenceException + { + string systemTypeName; + if (elem.HasAttribute("typeName")) + { + systemTypeName = elem.GetAttribute("typeName"); + } + else + { + systemTypeName = string.Format("DotNetNuke.Modules.UserDefinedTable.DataTypes.DataType{0}", + elem.GetAttribute("name")); + } + try + { + var type = (DataType)(Reflection.CreateObject(systemTypeName, systemTypeName)); + _colDataTypes.Add(type.Name, type); + } + catch (Exception) + { + if (!systemTypeName.StartsWith("DotNetNuke.Modules.UserDefinedTable.DataTypes.")) + { + throw; + } + //Supporting old namespace + systemTypeName = systemTypeName.Replace( + "DotNetNuke.Modules.UserDefinedTable.DataTypes.", + "DotNetNuke.Modules.UserDefinedTable."); + var type = (DataType) (Reflection.CreateObject(systemTypeName, systemTypeName)); + _colDataTypes.Add(type.Name, type); + } + + } + } + } + return _colDataTypes; + } + } + + public static String GetDataTypesConfigPath() + { + var retval = ""; + + // if a file exists in Portals/_Default/ UserDefinedTable then use that one, otherwise use default file + var defaultConfig = + HostingEnvironment.MapPath(string.Format("~{0}/DataTypes.config", Definition.PathOfModule)); + var customConfig = + HostingEnvironment.MapPath(string.Format("~{0}/DataTypes.config", Definition.PathOfCustomConfig)); + + if (File.Exists(customConfig)) + retval = customConfig; + else + retval = defaultConfig; + + return retval; + } + + public static ICollection AllDataTypes + { + get { return DataTypes.Keys; } + } + + public static IDictionary ContentDataTypes() + { + IDictionary returnValue = new SortedDictionary(); + foreach (var type in DataTypes.Values) + { + if (type.IsUserDefinedField) + { + returnValue.Add(type.GetLocalization(), type.Name); + } + } + return returnValue; + } + + public static IDictionary SystemDataTypes() + { + IDictionary returnValue = new SortedDictionary(); + foreach (var type in DataTypes.Values) + { + if (! type.IsUserDefinedField) + { + returnValue.Add(type.GetLocalization(), type.Name); + } + } + return returnValue; + } + + + + + [Obsolete("Obsolte, please use ContentDataTypes instead")] + public static IDictionary UserDefinedDataTypes + { + get { return ContentDataTypes(); } + } + + [Obsolete("Obsolte, please use SystemDatatypes instead")] + public static IDictionary ObligateDataTypes + { + get { return SystemDataTypes(); } + } + + public static DataType ByName(string dataTypeName) + { + if (DataTypes.ContainsKey(dataTypeName)) + { + return DataTypes[dataTypeName]; + } + Exceptions.LogException( + new UnknownDataTypeException(string.Format("DataType \"{0}\" is not installed.", dataTypeName))); + return DataTypes[DataTypeNames.UDT_DataType_String]; + } + + #endregion + + #region Public Interface + + public virtual string GetLocalization(string setting = "") + { + string fieldtype = setting != string.Empty ? string.Concat(Name, "_", setting) : Name; + var result = Localization.GetString(fieldtype, LocalRescourceFile); + if (string.IsNullOrEmpty(result)) + { + Exceptions.LogException( + new MissingLocalizationForDataTypeException( + string.Format("No Rescource found for DataType \"{0}\", Setting \"{1}\".", Name, setting))); + return fieldtype; + } + return result; + } + + public virtual string LocalRescourceFile + { + get + { + return string.Format("{0}{1}{2}/SharedResources.resx", HostingEnvironment.ApplicationVirtualPath, + Definition.PathOfModule, Localization.LocalResourceDirectory); + } + } + + + public virtual EditControl EditControl + { + get + { + var typeName = ("DotNetNuke.Modules.UserDefinedTable.DataTypes.Edit" + Name); + return ((EditControl) (Reflection.CreateObject(typeName, typeName))); + } + } + + public virtual IEnumerable FieldSettingTypes + { + get { return new FieldSettingType[0]; } + } + + public virtual bool IsUserDefinedField + { + get { return true; } + } + + public virtual string SystemTypeName + { + get { return "String"; } + } + + public virtual bool SupportsDefaultValue + { + get { return false; } + } + + public virtual bool SupportsEditing + { + get { return false; } + } + + public virtual bool SupportsHideOnEdit + { + get { return false; } + } + + public virtual IDictionary InputSettingsList + { + get { return null; } + } + + public virtual bool SupportsInputSettings + { + get { return false; } + } + + public virtual bool InputSettingsIsValueList + { + get { return SupportsInputSettings; } + } + + public virtual string InputSettingDefault + { + get { return string.Empty; } + } + + public virtual bool SupportsOutputSettings + { + get { return false; } + } + + public virtual bool SupportsLateRendering + { + get { return false; } + } + + [Obsolete] + public virtual bool SupportsNormalizeFlag + { + get { return false; } + } + + public virtual bool SupportsMultipleValues + { + get { return false; } + } + + + public virtual bool SupportsValidation + { + get { return false; } + } + + public virtual bool SupportsEditStyle + { + get { return false; } + } + + public virtual bool SupportsSearch + { + get { return false; } + } + + public virtual string SupportedCasts + { + get { return string.Format("String|{0}", Name); } + } + + public virtual string SearchColumnAppendix + { + get { return ""; } + } + + public virtual bool IsSeparator + { + get { return false; } + } + + public virtual void SetStylesAndFormats(BoundField column, string format) + { + //No default formating + } + + public virtual void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + //By Default, nothing happens + } + + + public abstract string Name { get; } + + #endregion + + protected object GetFieldSetting (string key, int id, DataSet ds) + { + return ds.Tables[DataSetTableName.FieldSettings].GetFieldSetting(key, id); + } + } + + [Serializable] + public class UnknownDataTypeException : Exception + { + public UnknownDataTypeException() + { + } + + public UnknownDataTypeException(string message) : base(message) + { + } + + protected UnknownDataTypeException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } + } + + [Serializable] + public class MissingLocalizationForDataTypeException : Exception + { + public MissingLocalizationForDataTypeException() + { + } + + public MissingLocalizationForDataTypeException(string message) : base(message) + { + } + + protected MissingLocalizationForDataTypeException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} + diff --git a/DataTypes/Abstract/EditControl.cs b/DataTypes/Abstract/EditControl.cs new file mode 100644 index 0000000..520cdc1 --- /dev/null +++ b/DataTypes/Abstract/EditControl.cs @@ -0,0 +1,306 @@ +using System; +using System.Data; +using System.Globalization; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Xml; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Modules.UserDefinedTable.Interfaces; +using DotNetNuke.Security; +using DotNetNuke.Services.Localization; +using DotNetNuke.UI.Modules; + +// ReSharper disable CheckNamespace +namespace DotNetNuke.Modules.UserDefinedTable +// ReSharper restore CheckNamespace +{ + /// ----------------------------------------------------------------------------- + /// + /// Abstraced (MustInherit) EditControl + /// Defines the Interface and provides some Default Settings + /// Concrete Classes provides the UI to edit and validate data + /// + /// ----------------------------------------------------------------------------- + public abstract class EditControl : Control + { + public enum InputType + { + DropdownList, +// ReSharper disable InconsistentNaming + horizontalRadioButtons, + verticalRadioButtons + } + // ReSharper restore InconsistentNaming + #region Private Members + + string _customValidationMessage; + public DataTable FieldSettingsTable { get; private set; } + + #endregion + + #region Public Properties + public virtual void Initialise(string fieldTitle, string fieldType, int fieldId, int moduleId, + string controlHelpText, string defaultValue, bool required, string validationRule, + string validationMsg, string editStyle, string inputSettings, + string outputSettings, bool normalizeFlag, bool multipleValuesFlag, + bool inputFilterTags, bool inputFilterScript, InputType inputSettingsListType, + ModuleInstanceContext moduleContext) + { + Initialise(fieldTitle, fieldType, fieldId, moduleId, + controlHelpText, defaultValue, required, validationRule, + validationMsg, editStyle, inputSettings, + outputSettings, normalizeFlag, multipleValuesFlag, + inputFilterTags, inputFilterScript, inputSettingsListType, moduleContext, null, null); + } + + public virtual void Initialise(string fieldTitle, string fieldType, int fieldId, int moduleId, + string controlHelpText, string defaultValue, bool required, string validationRule, + string validationMsg, string editStyle, string inputSettings, + string outputSettings, bool normalizeFlag, bool multipleValuesFlag, + bool inputFilterTags, bool inputFilterScript, InputType inputSettingsListType, + ModuleInstanceContext moduleContext, DataTable fieldSettingsTable, + IFormEvents formEvents) + { + FieldTitle = fieldTitle; + FieldType = fieldType; + FieldId = fieldId; + ModuleId = moduleId; + HelpText = controlHelpText; + DefaultValue = defaultValue; + Required = required; + ValidationRule = validationRule; + _customValidationMessage = validationMsg; + InputSettings = inputSettings; + OutputSettings = outputSettings; + Style = editStyle; + NormalizeFlag = normalizeFlag; + MultipleValuesFlag = multipleValuesFlag; + FilterScript = inputFilterScript; + FilterTags = inputFilterTags; + ListInputType = inputSettingsListType; + ModuleContext = moduleContext; + FieldSettingsTable = fieldSettingsTable; + FormEvents = formEvents; + } + + protected IFormEvents FormEvents { get; set; } + + public string GetFieldSetting(string key) + { + return FieldSettingsTable.GetFieldSetting(key, FieldId); + } + + + public ModuleInstanceContext ModuleContext { get; private set; } + + public string DefaultValue { get; private set; } + + public bool FilterScript { get; private set; } + + public bool FilterTags { get; private set; } + + public string InputSettings { get; private set; } + + public InputType ListInputType { get; private set; } + + public int ModuleId { get; private set; } + + public bool NormalizeFlag { get; private set; } + + public bool MultipleValuesFlag { get; private set; } + + public string OutputSettings { get; private set; } + + public string Style { get; private set; } + + public abstract string Value { get; set; } + + protected static string LocalResourceFile + { + get + { + return string.Format("~/{0}{1}/SharedResources.resx", Definition.PathOfModule, + Localization.LocalResourceDirectory); + } + } + + protected static int PortalId + { + get { return PortalController.GetCurrentPortalSettings().PortalId; } + } + + protected bool IsNotAListOfValues + { + get { return !InputSettings.Contains(";"); } + } + + protected string[] InputValueList + { + get { return InputSettings.Split(new []{';'}); } + } + + public string FieldTitle { get; private set; } + + public string FieldType { get; private set; } + + public string HelpText { get; private set; } + + public Control ValueControl { get; set; } + + + public int FieldId { get; private set; } + + protected bool Required { get; private set; } + + public string ValidationRule { get; private set; } + + public string ValidationMessage { get; private set; } + + #endregion + + #region Validation & Helper functions + + protected virtual bool IsNull() + { + return Null.IsNull(Value); + } + + public bool IsValid() + { + //Is required and empty + if (Required && IsNull()) + { + ValidationMessage = Localization.GetString("Required2.ErrorMessage", LocalResourceFile); + + } + + //TypeValidation + else if (! IsValidType()) + { + ValidationMessage = Localization.GetString(string.Format("{0}.ErrorMessage", FieldType), + LocalResourceFile); + + } + //CustomValidation + else if (DataType.ByName(FieldType).SupportsValidation) + { + if (! IsValidCustom()) + { + ValidationMessage = _customValidationMessage; + } + } + + + var isValid = string.IsNullOrEmpty( ValidationMessage ); + if (!isValid) Controls.Add(new LiteralControl(string.Format("{0}", ValidationMessage))); + return isValid; + } + + bool IsValidCustom() + { + if (ValidationRule != string.Empty && Value != string.Empty) + { + return Value.ValidateRegEx(ValidationRule); + } + return true; + } + + protected virtual bool IsValidType() + { + return true; + } + + protected void AddListItems(ListControl control) + { + foreach (var v in InputSettings.Split(';')) + { + var item = new ListItem(); + + if (v.Contains("|")) + { + var pair = v.Split('|'); + + item.Text = pair[0].Trim(); + item.Value = pair[1].Trim(); + } + else + { + item.Value = v.Trim(); + } + item.Attributes["class"] = "dnnFormRadioButtons"; + control.Items.Add(item); + } + } + + protected static string ApplyScriptFilter(string input) + { + //portalsecurity tries to detect encoding, if the input contains "&[g,l]t;", it decodes the input first + //than it cleans up the input and encodes it again + + //workaraound + //1) encode helperstring + input (Enforces decoding inside inputfilter!) + input = HttpUtility.HtmlEncode(string.Concat("<>", input)); + //2) apply filter + input = new PortalSecurity().InputFilter(input, PortalSecurity.FilterFlag.NoScripting); + //3) return decoded String minus helperstring +// ReSharper disable PossibleNullReferenceException + return HttpUtility.HtmlDecode(input).Substring(2); +// ReSharper restore PossibleNullReferenceException + } + + protected static string CleanID(string name) + { + return XmlConvert.EncodeName(name.Replace(" ", "_")); + } + + #endregion + + protected DateTime ServerTime(string value) + { + var dateTime = DateTime.Parse(value); + return value.Contains("+") + ? dateTime + : TimeZoneInfo.ConvertTimeFromUtc( dateTime, ModuleContext.PortalSettings.TimeZone ); + } + + protected ListControl GetListControl() + { + ListControl ctlListControl; + switch (ListInputType) + { + case InputType.horizontalRadioButtons: + if (MultipleValuesFlag) + ctlListControl = new CheckBoxList + { + RepeatDirection = RepeatDirection.Horizontal, + RepeatLayout = RepeatLayout.Flow + }; + else + ctlListControl = new RadioButtonList + { + RepeatDirection = RepeatDirection.Horizontal, + RepeatLayout = RepeatLayout.Flow + }; + break; + case InputType.verticalRadioButtons: + if (MultipleValuesFlag) + ctlListControl = new CheckBoxList(); + else + { + ctlListControl = new RadioButtonList {RepeatLayout = RepeatLayout.Table }; + } + break; + default: + if (MultipleValuesFlag) + ctlListControl = new ListBox{SelectionMode=ListSelectionMode.Multiple}; + else + ctlListControl = new DropDownList(); + break; + } + return ctlListControl; + } + } +} diff --git a/DataTypes/Boolean.cs b/DataTypes/Boolean.cs new file mode 100644 index 0000000..ea45a12 --- /dev/null +++ b/DataTypes/Boolean.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections; +using System.Data; +using System.Globalization; +using System.Web.UI; +using System.Web.UI.WebControls; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Services.Localization; +using Microsoft.VisualBasic; +using Microsoft.VisualBasic.CompilerServices; +using Globals = DotNetNuke.Common.Globals; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "Boolean" + /// + /// ----------------------------------------------------------------------------- + public class EditBoolean : EditControl + { + CheckBox _checkBox; + + public EditBoolean() + { + Init += EditBoolean_Init; + } + + public override string Value + { + get + { + return _checkBox.Checked.ToString(CultureInfo.InvariantCulture); + } + set + { + value = value.ToLowerInvariant(); + _checkBox.Checked = + Convert.ToBoolean((LikeOperator.LikeString(value, "true", CompareMethod.Binary)) || + (LikeOperator.LikeString(value, "on", CompareMethod.Binary)) || + (LikeOperator.LikeString(value, "yes", CompareMethod.Binary))); + } + } + + protected override bool IsNull() + { + return (bool.FalseString == Value); + } + + void EditBoolean_Init(object sender, EventArgs e) + { + _checkBox = new CheckBox(); + _checkBox.Style.Value = Style; + _checkBox.ID = CleanID(FieldTitle); + ValueControl = _checkBox; + Controls.Add(_checkBox); + if (! string.IsNullOrEmpty(OutputSettings)) + { + Controls.Add(new LiteralControl(string.Format(" {0}", OutputSettings))); + } + + Value = DefaultValue; + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Boolean" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeBoolean : DataType + { + public override void SetStylesAndFormats(BoundField column, string format) + { + column.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; + column.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + } + + public override string Name + { + get { return "Boolean"; } + } + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + var colBoolean = new ArrayList(); + var tableData = ds.Tables[DataSetTableName.Data]; + foreach (DataRow row in ds.Tables["Fields"].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == "Boolean") + { + var title = row[FieldsTableColumn.Title].ToString(); + colBoolean.Add(title); + tableData.Columns.Add(new DataColumn(title + DataTableColumn.Appendix_Original, typeof (string))); + tableData.Columns.Add(new DataColumn(title + DataTableColumn.Appendix_LocalizedValue, + typeof (string))); + tableData.Columns.Add(new DataColumn(title + DataTableColumn.Appendix_Caption, typeof (string))); + } + } + if (colBoolean.Count > 0) + { + foreach (DataRow row in ds.Tables["Data"].Rows) + { + foreach (string fieldName in colBoolean) + { + var strBoolean = (row[fieldName].ToString().ToLowerInvariant()); + var alt = Localization.GetString(((strBoolean.AsBoolean()) ? "Yes" : "No")); + string strFieldvalue; + switch (strBoolean) + { + case "true": + strFieldvalue = string.Format("\"{1}\"/", + Globals.ApplicationPath, alt); + break; + case "false": + strFieldvalue = string.Format("\"{1}\"/", + Globals.ApplicationPath, alt); + break; + default: + strFieldvalue = ""; + break; + } + row[fieldName] = strFieldvalue; + row[fieldName + DataTableColumn.Appendix_Original] = strBoolean; + row[fieldName + DataTableColumn.Appendix_Caption] = strBoolean; + } + } + } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsEditing + { + get { return true; } + } + + public override bool SupportsEditStyle + { + get { return true; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/ChangedAt.cs b/DataTypes/ChangedAt.cs new file mode 100644 index 0000000..c2fc36f --- /dev/null +++ b/DataTypes/ChangedAt.cs @@ -0,0 +1,76 @@ +using DotNetNuke.Services.SystemDateTime; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "ChangedAt" + /// + /// ----------------------------------------------------------------------------- + public class EditChangedAt : EditCreatedAt + { + public override string Value + { + get { return SystemDateTime.GetCurrentTimeUtc().ToString("s"); } + + set { base.Value = value; } + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "ChangedAt" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeChangedAt : DataTypeDateTime + { + public override string Name + { + get { return "ChangedAt"; } + } + + public override bool SupportsEditStyle + { + get { return false; } + } + + public override bool IsUserDefinedField + { + get { return false; } + } + + public override bool SupportsDefaultValue + { + get { return false; } + } + + public override bool SupportsInputSettings + { + get { return false; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + + public override bool SupportsHideOnEdit + { + get { return true; } + } + + public override bool SupportsValidation + { + get { return false; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/ChangedBy.cs b/DataTypes/ChangedBy.cs new file mode 100644 index 0000000..703905a --- /dev/null +++ b/DataTypes/ChangedBy.cs @@ -0,0 +1,38 @@ +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "ChangedBy" + /// + /// ----------------------------------------------------------------------------- + public class EditChangedBy : EditCreatedBy + { + public override string Value + { + get { return CurrentUserName(); } + set { base.Value = value; } + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "ChangedBy" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeChangedBy : DataTypeCreatedBy + { + public override string Name + { + get { return "ChangedBy"; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/CreatedAt.cs b/DataTypes/CreatedAt.cs new file mode 100644 index 0000000..4451d01 --- /dev/null +++ b/DataTypes/CreatedAt.cs @@ -0,0 +1,111 @@ + using System; +using System.Web.UI; + using DotNetNuke.Services.SystemDateTime; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "CreatedAt" + /// + /// ----------------------------------------------------------------------------- + public class EditCreatedAt : EditControl + { + const string TimeStamp = "TimeStamp"; + + public EditCreatedAt() + { + Load += EditCreatedAt_Load; + } + + public override string Value + { + get + { + if (ViewState[TimeStamp] == null) + { + return SystemDateTime.GetCurrentTimeUtc().ToString("s"); + } + return DateTime.Parse((string)ViewState[TimeStamp]).ToString("s"); + } + set + { + if (value != string.Empty) + { + ViewState[TimeStamp] = value; + Controls.Add( + new LiteralControl(string.Format("{0:g}", ServerTime(value)))); + } + } + } + + + void EditCreatedAt_Load(object sender, EventArgs e) + { + if (Page.IsPostBack) + { + if (ViewState[TimeStamp]!=null) + { + Controls.Add( + new LiteralControl(string.Format("{0}", ServerTime((string)ViewState[TimeStamp])))); + } + } + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "CreatedAt" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeCreatedAt : DataTypeDateTime + { + public override string Name + { + get { return "CreatedAt"; } + } + + public override bool IsUserDefinedField + { + get { return false; } + } + + public override bool SupportsDefaultValue + { + get { return false; } + } + public override bool SupportsEditStyle + { + get { return false; } + } + + public override bool SupportsInputSettings + { + get { return false; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + + public override bool SupportsValidation + { + get { return false; } + } + + public override bool SupportsHideOnEdit + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/CreatedBy.cs b/DataTypes/CreatedBy.cs new file mode 100644 index 0000000..2052e4c --- /dev/null +++ b/DataTypes/CreatedBy.cs @@ -0,0 +1,223 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Web; +using System.Web.UI; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Entities.Users; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Modules.UserDefinedTable.Interfaces; +using Globals = DotNetNuke.Common.Globals; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "CreatedBy" + /// + /// ----------------------------------------------------------------------------- + public class EditCreatedBy : EditControl + { + protected string Editor="Editor"; + + public EditCreatedBy() + { + Load += Page_Load; + } + + + + public override string Value + { + get { + return (ViewState[Editor]!=null) ? (string) ViewState[Editor] : CurrentUserName(); + } + set + { + if (value != string.Empty) + { + ViewState[Editor] = value; + Controls.Add( + new LiteralControl("" + ModuleSecurity.BestUserName(value, PortalId) + + "")); + } + } + } + + protected static string CurrentUserName() + { + var result = UserController.GetCurrentUserInfo().Username; + if (string.IsNullOrEmpty(result)) + { + result = Definition.NameOfAnonymousUser; + } + return result; + } + + void Page_Load(object sender, EventArgs e) + { + if (Page.IsPostBack) + { + if (ViewState[Editor]!=null) + { + Controls.Add( + new LiteralControl("" + + ModuleSecurity.BestUserName(ViewState[Editor].ToString(), PortalId) + + "")); + } + } + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Createdby" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeCreatedBy : DataType, IEmailAdressSource, IUserSource + { + readonly FieldSettingType[] _fieldSettingTypes = new[] + { + new FieldSettingType {Key = "AsLink", Section = "List", SystemType = "Boolean"}, + new FieldSettingType {Key = "OpenInNewWindow", Section = "List", SystemType = "Boolean"}, + new FieldSettingType {Key = "PreferDisplayName", Section = "List", SystemType = "Boolean"} + }; + public override IEnumerable FieldSettingTypes + { + get + { + return _fieldSettingTypes; + } + } + public override bool IsUserDefinedField + { + get { return false; } + } + + public override string Name + { + get { return "CreatedBy"; } + } + + public override bool SupportsHideOnEdit + { + get { return true; } + } + + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + var colCreatedBy = new ArrayList(); + var tableData = ds.Tables[DataSetTableName.Data]; + var asLink=false; + var openInNewWindow=false; + var preferDisplayName=false; + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == Name) + { + var fieldId = (int) row[FieldsTableColumn.Id]; + asLink = GetFieldSetting("AsLink", fieldId, ds).AsBoolean( ); + openInNewWindow = GetFieldSetting("OpenInNewWindow", fieldId, ds).AsBoolean(); + preferDisplayName = GetFieldSetting("PreferDisplayName", fieldId, ds).AsBoolean(); + var title = row[FieldsTableColumn.Title].ToString(); + colCreatedBy.Add(title); + tableData.Columns.Add(new DataColumn(title + DataTableColumn.Appendix_Original, typeof (string))); + tableData.Columns.Add(new DataColumn(title + DataTableColumn.Appendix_Caption, typeof (string))); + tableData.Columns.Add(new DataColumn(title + DataTableColumn.Appendix_Url, typeof (string))); + } + } + if (colCreatedBy.Count > 0) + { + var portalId = Null.NullInteger; + var tabId = Null.NullInteger; + if (HttpContext.Current != null) + { + var portalSettings = PortalController.GetCurrentPortalSettings(); + portalId = portalSettings.PortalId; + tabId = portalSettings.ActiveTab.TabID; + } + + foreach (DataRow row in tableData.Rows) + { + foreach (string fieldName in colCreatedBy) + { + var strCreatedBy = row[fieldName].ToString(); + var strCaption = strCreatedBy; + var strUrl = string.Empty; + + if (!preferDisplayName) + { + strCaption = ModuleSecurity.BestUserName(strCreatedBy, portalId); + } + if (asLink) + { + var userId = ModuleSecurity.UserId(strCreatedBy, portalId); + if (userId > 0) + { + strUrl = HttpUtility.HtmlEncode(Globals.LinkClick(("userid=" + userId), tabId,moduleId)); + } + } + + string strFieldvalue; + if (asLink && strUrl != string.Empty) + { + strFieldvalue = string.Format("{1}", strUrl, strCaption, + (openInNewWindow ? " target=\"_blank\"" : "")); + } + else + { + strFieldvalue = strCaption; + } + row[fieldName] = strFieldvalue; + row[fieldName + DataTableColumn.Appendix_Original] = strCreatedBy; + row[fieldName + DataTableColumn.Appendix_Caption] = strCaption; + if (strUrl != string.Empty) + { + row[fieldName + DataTableColumn.Appendix_Url] = strUrl; + } + } + } + } + } + + public override bool SupportsSearch + { + get { return true; } + } + + public string GetEmailAddress(string fieldName, DataRow row) + { + return GetAddress(fieldName, row); + } + + public string GetAddress(string fieldName, DataRow row) + { + return GetUser(fieldName, row).Email; + } + + public UserInfo GetUser(string fieldName, DataRow row) + { + var username = (row.Table.Columns.Contains(fieldName + DataTableColumn.Appendix_Original) + ? row[fieldName + DataTableColumn.Appendix_Original] + : row[fieldName]).AsString(); + if (username != string.Empty) + { + var userInfo = UserController.GetUserByName(Globals.GetPortalSettings().PortalId, username); + return userInfo; + } + return new UserInfo(); + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/Currency.cs b/DataTypes/Currency.cs new file mode 100644 index 0000000..22cd8ca --- /dev/null +++ b/DataTypes/Currency.cs @@ -0,0 +1,132 @@ +using System; +using System.Globalization; +using System.Web.UI.WebControls; +using DotNetNuke.Entities.Portals; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit & Validation Control for DataType "Currency" + /// + /// ----------------------------------------------------------------------------- + public class EditCurrency : EditString + { + protected override bool IsValidType() + { + decimal d; + return Value == string.Empty || decimal.TryParse(Value, out d); + } + + public override string Value + { + get + { + string returnValue; + try + { + returnValue = string.Empty; + var culture = new CultureInfo("en-US"); + if (base.Value != "") + { + returnValue = (decimal.Parse(base.Value)).ToString(culture); + } + } + catch + { + returnValue = base.Value; + } + return returnValue; + } + set + { + var culture = new CultureInfo("en-US"); + if (value != "") + { + value = (decimal.Parse(value, culture).ToString("#,###,##0.00")); + } + base.Value = value; + } + } + + void EditCurrency_Init(object sender, EventArgs e) + { + CtlValueBox.Attributes.Add("style", "text-align:right"); + CtlValueBox.Width = new Unit("10em"); + var ctlSym = new Label + { + CssClass = "Normal", + Text = + string.Format(" {0}", + OutputSettings == string.Empty + ? PortalController.GetCurrentPortalSettings().Currency + : OutputSettings) + }; + Controls.Add(ctlSym); + } + + public EditCurrency() + { + Init += EditCurrency_Init; + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Currency" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeCurrency : DataTypeDecimal + { + public override void SetStylesAndFormats(BoundField column, string format) + { + base.SetStylesAndFormats(column, format); + column.DataFormatString = string.Format("{{0:#,###,##0.00 \'{0}\'}}", + format == string.Empty ? PortalController.GetCurrentPortalSettings().Currency : format); + } + + public override string Name + { + get { return "Currency"; } + } + + public override string SupportedCasts + { + get { return string.Format("{0}Decimal", base.SupportedCasts); } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsEditing + { + get { return true; } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + + public override bool SupportsValidation + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/Date.cs b/DataTypes/Date.cs new file mode 100644 index 0000000..019b54f --- /dev/null +++ b/DataTypes/Date.cs @@ -0,0 +1,258 @@ +using System; +using System.Collections; +using System.Data; +using System.Web.UI.WebControls; +using System.Xml; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Web.UI.WebControls; +using Microsoft.VisualBasic; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit & Validation Control for DataType "Date" + /// + /// ----------------------------------------------------------------------------- + public class EditDate : EditControl + { + + protected WebControl CtlValueBox; + + void EditDate_Init(object sender, EventArgs e) + { + if (IsNotAListOfValues) + { + var ctlDate = new DnnDatePicker {MinDate = DateTime.MinValue,MaxDate=DateTime.MaxValue }; + if (! string.IsNullOrEmpty(Style)) + { + ctlDate.Style.Value = Style; + } + ctlDate.ID = CleanID(string.Format("{0}_date", FieldTitle)); + if (Required) ctlDate.DateInput.CssClass = "dnnFormRequired"; + + Controls.Add(ctlDate); + CtlValueBox = ctlDate; + ValueControl = ctlDate; + } + else + { + var ctlListControl = GetListControl(); + + foreach (var v in InputValueList) + { + if (Information.IsDate(v)) + { + var d = DateTime.Parse(v.Trim()); + ctlListControl.Items.Add(new ListItem(d.ToString("d"), d.ToString("s"))); + } + } + if (! Required) + { + ctlListControl.Items.Add(new ListItem("", "")); + } + ctlListControl.CssClass = "NormalTextBox"; + if (!String.IsNullOrEmpty(Style)) CtlValueBox.Style.Value = Style; + ctlListControl.ID = CleanID(string.Format("{0}_date", FieldTitle)); + Controls.Add(ctlListControl); + CtlValueBox = ctlListControl; + } + Value = DefaultValue; + } + + + + public override string Value + { + get + { + string returnValue; + if (CtlValueBox is DnnDatePicker) + { + var dnnDatePicker = (DnnDatePicker)CtlValueBox; + returnValue = dnnDatePicker.SelectedDate.HasValue ? dnnDatePicker.SelectedDate.Value.ToString("s"):"" ; + } + else + { + returnValue = ((DropDownList) CtlValueBox).SelectedValue; + } + if (returnValue != string.Empty) + { + if (Information.IsDate(returnValue)) + { + returnValue = DateTime.Parse(returnValue).ToString("s"); + } + } + else + { + returnValue = Null.NullString; + } + return returnValue; + } + set + { + if (Information.IsDate(value)) + { + var d = DateTime.Parse(value); + if (CtlValueBox is DnnDatePicker ) + { + ((DnnDatePicker)CtlValueBox).SelectedDate= DateTime.Parse(value); + } + else + { + var ctlComboBox = (ListControl) CtlValueBox; + if (ctlComboBox.Items.FindByValue(d.ToString("s")) != null) + { + ctlComboBox.SelectedValue = d.ToString("s"); + } + } + } + else + { + if (CtlValueBox is DnnDatePicker) + { + //((DnnDatePicker)CtlValueBox).Text = string.Empty; + } + else + { + var ctlComboBox = (ListControl) CtlValueBox; + if (Required) + { + ctlComboBox.SelectedIndex = 0; + } + else + { + ctlComboBox.SelectedValue = ""; + } + } + } + } + } + + + public EditDate() + { + Init += EditDate_Init; + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Date" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeDate : DataType + { + public override void SetStylesAndFormats(BoundField column, string format) + { + column.DataFormatString = format != "" ? string.Format("{{0:{0}}}", format) : "{0:d}"; + column.HeaderStyle.HorizontalAlign = HorizontalAlign.Right; + column.ItemStyle.HorizontalAlign = HorizontalAlign.Right; + } + + public override string Name + { + get { return "Date"; } + } + + public override string SystemTypeName + { + get { return "DateTime"; } + } + + struct FieldSetting + { + public string FormatString; + public string Title; + } + + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + var fields = new ArrayList(); + //List of columns that contains URLs + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == Name) + { + var fieldTitle = row[FieldsTableColumn.Title].ToString(); + var fieldSetting = new FieldSetting + { + FormatString = + row[FieldsTableColumn.OutputSettings].AsString("d"), + Title = fieldTitle + }; + fields.Add(fieldSetting); + var localizedValueColumnName = fieldTitle + DataTableColumn.Appendix_LocalizedValue; + ds.Tables[DataSetTableName.Data].Columns.Add(localizedValueColumnName, typeof (string)); + ds.Tables[DataSetTableName.Data].Columns.Add(fieldTitle + DataTableColumn.Appendix_Ticks, + typeof (long)); + row[FieldsTableColumn.ValueColumn] = XmlConvert.EncodeName(localizedValueColumnName); + } + } + foreach (DataRow row in ds.Tables[DataSetTableName.Data].Rows) + { + foreach (FieldSetting field in fields) + { + if (Information.IsDate(row[field.Title])) + { + var d = Convert.ToDateTime(row[field.Title]); + var format = "{1:" + field.FormatString + "}"; + row[field.Title + DataTableColumn.Appendix_LocalizedValue] = string.Format(format, d.Ticks/10000000, d); + row[field.Title + DataTableColumn.Appendix_Ticks] = d.Ticks; + } + } + } + } + + public override string SupportedCasts + { + get { return string.Format("{0}|Date|DateTime|Time", base.SupportedCasts); } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsEditing + { + get { return true; } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + public override bool SupportsEditStyle + { + get { return true; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + + public override bool SupportsValidation + { + get { return true; } + } + + public override bool SupportsSearch + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/DateTime.cs b/DataTypes/DateTime.cs new file mode 100644 index 0000000..5c15221 --- /dev/null +++ b/DataTypes/DateTime.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Globalization; +using System.Threading; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Xml; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Entities.Users; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Services.Localization; +using Microsoft.VisualBasic; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "DateTime" + /// A composition from the Controls Date and Time + /// + /// ----------------------------------------------------------------------------- + public class EditDateTime : EditControl + { + EditTime _ctlTime; + EditDate _ctlDate; + bool _convertTimezone; + + public override string Value + { + get + { + if (_ctlDate.Value == "" && _ctlTime.Value == "") + { + return ""; + } + if (Information.IsDate(_ctlDate.Value) && Information.IsDate(_ctlTime.Value)) + { + var d = DateTime.Parse(_ctlDate.Value); + var T = DateTime.Parse(_ctlTime.Value); + d = new DateTime(d.Year, d.Month, d.Day, T.Hour, T.Minute, T.Second); + var timeZone = _convertTimezone + ? UserController.GetCurrentUserInfo().Profile.PreferredTimeZone + : ModuleContext.PortalSettings.TimeZone; + d = TimeZoneInfo.ConvertTimeToUtc( d, timeZone); + return d.ToString("s"); + } + return string.Format("{0} {1}", _ctlDate.Value, _ctlTime.Value); + //invalid Value + } + + set + { + if (Information.IsDate(value)) + { + var d = DateTime.Parse(value); + if (value.Contains("+")) d = TimeZoneInfo.ConvertTimeToUtc(d); + var timeZone = _convertTimezone + ? UserController.GetCurrentUserInfo().Profile.PreferredTimeZone + : ModuleContext.PortalSettings.TimeZone; + value = TimeZoneInfo.ConvertTimeFromUtc(d,timeZone ).ToString( "s"); + } + _ctlDate.Value = value; + _ctlTime.Value = value; + } + } + + protected override bool IsValidType() + { + if (_ctlTime.Value == string.Empty && _ctlDate.Value == string.Empty) + { + return true; + } + try + { + // ReSharper disable ReturnValueOfPureMethodIsNotUsed + DateTime.ParseExact(_ctlDate.Value, new[] {"d", "D", "s"}, Thread.CurrentThread.CurrentCulture, DateTimeStyles.None); + DateTime.ParseExact(_ctlTime.Value, new[] {"t", "T", "s"}, Thread.CurrentThread.CurrentCulture, DateTimeStyles.None); + // ReSharper restore ReturnValueOfPureMethodIsNotUsed + return true; + } + catch (Exception) + { + return false; + } + } + + void EditDateTime_Init(object sender, EventArgs e) + { + _ctlDate = new EditDate(); + _ctlDate.Initialise(FieldTitle, FieldType, FieldId, ModuleId, HelpText, DefaultValue, Required, + ValidationRule, ValidationMessage, Style, InputSettings, OutputSettings, NormalizeFlag, + MultipleValuesFlag, FilterTags, FilterScript, ListInputType, ModuleContext, FieldSettingsTable, FormEvents ); + Controls.Add(_ctlDate); + Controls.Add(new LiteralControl("  ")); + var ctlTimeLbl = new Label + { + Text = string.Format("{0}: ", Localization.GetString("Time", LocalResourceFile)), + CssClass = "SubHead" + }; + Controls.Add(ctlTimeLbl); + _ctlTime = new EditTime(); + _ctlTime.Initialise(FieldTitle, FieldType, FieldId, ModuleId, HelpText, DefaultValue, Required, + ValidationRule, ValidationMessage, Style, InputSettings, OutputSettings, NormalizeFlag, + MultipleValuesFlag, FilterTags, FilterScript, ListInputType, ModuleContext, FieldSettingsTable, FormEvents ); + Controls.Add(_ctlTime); + _convertTimezone = GetFieldSetting("ConvertToUserDateTime").AsBoolean(); + Value = DefaultValue; + } + + public EditDateTime() + { + Init += EditDateTime_Init; + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "DateTime" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeDateTime : DataTypeDate + { + readonly FieldSettingType[] _fieldSettingTypes = new[] + { + new FieldSettingType {Key = "ConvertToUserDateTime", Section = "List", SystemType = "Boolean"} + }; + + public override IEnumerable FieldSettingTypes + { + get + { + return _fieldSettingTypes; + } + } + public override void SetStylesAndFormats(BoundField column, string format) + { + base.SetStylesAndFormats(column, format); + column.DataFormatString = format != string.Empty ? string.Format("{{0:{0}}}", format) : "{0:g}"; + } + + public override string Name + { + get { return "DateTime"; } + } + + struct FieldSetting + { + public string Title; + public bool ConvertToUserTime; + public string FormatString; + } + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + var fields = new ArrayList(); + //List of columns that contains DateTime values + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == Name) + { + var fieldId = (int)row[FieldsTableColumn.Id]; + var field = new FieldSetting + { + ConvertToUserTime = GetFieldSetting("ConvertToUserDateTime", fieldId, ds).AsBoolean(), + Title = row[FieldsTableColumn.Title].ToString(), + FormatString = row[FieldsTableColumn.OutputSettings].AsString("g") + }; + fields.Add(field); + var renderedValueColumnName = field.Title + DataTableColumn.Appendix_LocalizedValue; + ds.Tables[DataSetTableName.Data].Columns.Add(renderedValueColumnName, typeof (string)); + ds.Tables[DataSetTableName.Data].Columns.Add(field.Title + DataTableColumn.Appendix_Ticks, typeof (long)); + row[FieldsTableColumn.ValueColumn] = XmlConvert.EncodeName(renderedValueColumnName); + } + } + + + if (HttpContext.Current != null) + { + var serverTimeZone = PortalController.GetCurrentPortalSettings().TimeZone; + var userTimeZone = UserController.GetCurrentUserInfo().Profile.PreferredTimeZone; + + foreach (DataRow row in ds.Tables[DataSetTableName.Data].Rows) + { + foreach (FieldSetting field in fields) + { + if (Information.IsDate(row[field.Title])) + { + var d = Convert.ToDateTime(row[field.Title]); + var timeZone = field.ConvertToUserTime ? userTimeZone : serverTimeZone; + d = TimeZoneInfo.ConvertTimeFromUtc(d, timeZone); + row[field.Title] = d; + var format = "{1:" + field.FormatString + "}"; + row[field.Title + DataTableColumn.Appendix_LocalizedValue] = string.Format(format,d.Ticks/10000000,d); + row[field.Title + DataTableColumn.Appendix_Ticks] = d.Ticks; + } + } + } + } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsInputSettings + { + get { return false; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + + public override bool SupportsValidation + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/Decimal.cs b/DataTypes/Decimal.cs new file mode 100644 index 0000000..b5c4009 --- /dev/null +++ b/DataTypes/Decimal.cs @@ -0,0 +1,136 @@ +using System; +using System.Globalization; +using System.Web.UI.WebControls; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "Decimal" + /// + /// ----------------------------------------------------------------------------- + public class EditDecimal : EditString + { + protected override bool IsValidType() + { + decimal d; + return Value == string.Empty || decimal.TryParse(Value, out d); + } + + public override string Value + { + get + { + string returnValue; + try + { + returnValue = string.Empty; + var culture = new CultureInfo("en-US"); + if (base.Value != string.Empty) + { + returnValue = (decimal.Parse(base.Value)).ToString(culture); + } + } + catch + { + returnValue = base.Value; + } + return returnValue; + } + set + { + var culture = new CultureInfo("en-US"); + if (value != "") + { + value = (decimal.Parse(value, culture).ToString("#,###,###,##0.####")); + } + base.Value = value; + } + } + + void EditDecimal_Init(object sender, EventArgs e) + { + CtlValueBox.Attributes.Add("style", "text-align:right"); + CtlValueBox.Width = new Unit("10em"); + } + + public EditDecimal() + { + Init += EditDecimal_Init; + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Decimal" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeDecimal : DataType + { + public override void SetStylesAndFormats(BoundField column, string format) + { + column.DataFormatString = format == string.Empty ? "{0:#,###,##0.0###}" : string.Format("{{0:{0}}}", format); + column.HeaderStyle.HorizontalAlign = HorizontalAlign.Right; + column.ItemStyle.HorizontalAlign = HorizontalAlign.Right; + } + + public override string Name + { + get { return "Decimal"; } + } + + public override string SystemTypeName + { + get { return "Decimal"; } + } + + public override string SupportedCasts + { + get { return string.Format("{0}|Currency", base.SupportedCasts); } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsEditing + { + get { return true; } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + + public override bool SupportsEditStyle + { + get { return true; } + } + + public override bool SupportsValidation + { + get { return true; } + } + + public override bool SupportsSearch + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/Download.cs b/DataTypes/Download.cs new file mode 100644 index 0000000..7a1f240 --- /dev/null +++ b/DataTypes/Download.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Web; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Services.FileSystem; +using Globals = DotNetNuke.Common.Globals; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "Download" + /// + /// ----------------------------------------------------------------------------- + public class EditDownload : EditURL + { + void EditDownload_Load(object sender, EventArgs e) + { + if (! Page.IsPostBack && IsNotAListOfValues) + { + CtlUrl.ShowUrls = false; + CtlUrl.ShowTabs = false; + CtlUrl.ShowTrack = true; + } + } + + public EditDownload() + { + Load += EditDownload_Load; + } + + public override string Value + { + get + { + string returnValue; + if (IsNotAListOfValues) + { + var urlController = new UrlController(); + urlController.UpdateUrl(PortalId, CtlUrl.Url, CtlUrl.UrlType, CtlUrl.Log, CtlUrl.Track, CtlUrl.ModuleID, + CtlUrl.NewWindow); + returnValue = CtlUrl.Url + (CtlUrl.NewWindow ? "|options=W" : ""); + } + else + { + var fi =FileManager.Instance.GetFile(PortalId, CtlValueBox.SelectedValue); + returnValue = fi != null ? string.Format("FileID={0}", fi.FileId) : ""; + } + return returnValue; + } + set + { + if (IsNotAListOfValues) + { + CtlUrl.Url = UrlUtil.StripURL(value); + ValueIsSet = true; + } + else //If CStrN(Value) <> "" Then + { + try + { + CtlValueBox.SelectedValue = value; + ValueIsSet = true; + } +// ReSharper disable EmptyGeneralCatchClause + catch +// ReSharper restore EmptyGeneralCatchClause + { + } + } + } + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Download" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeDownload : DataType + { + readonly FieldSettingType[] _fieldSettingTypes = new[] + { + new FieldSettingType {Key = "Abbreviate", Section = "List", SystemType = "Boolean"}, + new FieldSettingType {Key = "ShowOpenInNewWindow", Section = "List", SystemType = "Boolean"}, + new FieldSettingType {Key = "EnforceDownload", Section = "List", SystemType = "Boolean"} + }; + + public override IEnumerable FieldSettingTypes + { + get + { + return _fieldSettingTypes; + } + } + public override string Name + { + get { return "Download"; } + } + + struct FieldSettings + { + public string Title; + public string OutputFormat; + public bool Abbreviate; + public bool ShowOpenInNewWindow; + public bool EnforceDownload; + } + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + if (ds != null) + { + var fields = new ArrayList(); + //List of columns that contains URLs + var tableData = ds.Tables[DataSetTableName.Data]; + var tokenReplace = new TokenReplace {ModuleId = moduleId}; + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == Name) + { + var fieldId = (int)row[FieldsTableColumn.Id]; + var field = new FieldSettings + { + Title = row[FieldsTableColumn.Title].ToString(), + OutputFormat = row[FieldsTableColumn.OutputSettings].AsString(), + Abbreviate = GetFieldSetting("Abbreviate", fieldId, ds).AsBoolean(), + ShowOpenInNewWindow = GetFieldSetting("ShowOpenInNewWindow", fieldId, ds).AsBoolean(), + EnforceDownload = GetFieldSetting("EnforceDownload", fieldId, ds).AsBoolean() + }; + fields.Add(field); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Url, typeof (string))); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Caption, + typeof (string))); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Original, + typeof (string))); + } + } + if (fields.Count > 0) + { + var portalSettings = PortalController.GetCurrentPortalSettings(); + + + foreach (DataRow row in tableData.Rows) + { + foreach (FieldSettings field in fields) + { + var strFieldvalue = string.Empty; + var strFileId = row[field.Title].ToString(); + var openInNewWindow = !field.ShowOpenInNewWindow || UrlUtil.OpenUrlInNewWindow(strFileId); + strFileId = UrlUtil.StripURL(strFileId); + var strUrl = ""; + //Link readable by browsers + + var strCaption = string.Empty; + if (strFileId != string.Empty) + { + strUrl = + HttpUtility.HtmlEncode(Globals.LinkClick(strFileId, portalSettings.ActiveTab.TabID, + moduleId)); + var fName = ""; + var strDisplayName = ""; + if (strFileId.Like("FileID=*")) + { + var f =FileManager.Instance.GetFile(int.Parse(UrlUtils.GetParameterValue(strFileId))); + if (f != null) + { + fName = f.FileName; + if (field.Abbreviate) + { + strDisplayName = (f.Folder + fName); + } + else + { + strDisplayName = fName; + } + } + } + else + { + fName = Globals.ResolveUrl(strUrl); + strDisplayName = field.Abbreviate + ? fName.Substring(Convert.ToInt32(fName.LastIndexOf("/", StringComparison.Ordinal) + 1)) + : fName; + } + strCaption = field.OutputFormat; + strCaption = string.IsNullOrEmpty(strCaption) + ? fName + : tokenReplace.ReplaceEnvironmentTokens(strCaption, row); + if (field.EnforceDownload) + { + strUrl += "&forcedownload=true"; + } + strFieldvalue = string.Format("{3}", strDisplayName, + strUrl, (openInNewWindow ? " target=\"_blank\"" : ""), + strCaption); + } + row[field.Title] = strFieldvalue; + row[field.Title + DataTableColumn.Appendix_Caption] = strCaption; + row[field.Title + DataTableColumn.Appendix_Original] = strFileId; + row[field.Title + DataTableColumn.Appendix_Url] = strUrl; + } + } + } + } + } + + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsEditing + { + get { return true; } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + + public override bool SupportsLateRendering + { + get { return true; } + } + + public override bool SupportsSearch + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/EMail.cs b/DataTypes/EMail.cs new file mode 100644 index 0000000..828bda6 --- /dev/null +++ b/DataTypes/EMail.cs @@ -0,0 +1,192 @@ +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Web; +using DotNetNuke.Common; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Modules.UserDefinedTable.Interfaces; +using DotNetNuke.Services.Mail; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "EMail" + /// + /// ----------------------------------------------------------------------------- + public class EditEMail : EditString + { + protected override bool IsValidType() + { + if (Value == string.Empty) + { + return true; + } + if (StrValRule == string.Empty) + { + return Mail.IsValidEmailAddress(Value, PortalId); + } + return true; + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Email" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeEMail : DataType, IEmailAdressSource + { + readonly FieldSettingType[] _fieldSettingTypes = new[] + { + new FieldSettingType {Key = "NoLink", Section = "List", SystemType = "Boolean"} + }; + + public override IEnumerable FieldSettingTypes + { + get + { + return _fieldSettingTypes; + } + } + + struct FieldSetting + { + public string Title; + public string OutputFormat; + public bool AsLink; + } + + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + var fields = new ArrayList(); + //List of columns that contains eMail addresses + var tableData = ds.Tables[DataSetTableName.Data]; + var tokenReplace = new TokenReplace {ModuleId = moduleId}; + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == Name) + { + var fieldId = (int)row[FieldsTableColumn.Id]; + var field = new FieldSetting + { + Title = row[FieldsTableColumn.Title].ToString(), + OutputFormat = row[FieldsTableColumn.OutputSettings].AsString(), + AsLink = !GetFieldSetting("NoLink", fieldId, ds).AsBoolean() + }; + fields.Add(field); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Original, + typeof (string))); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Caption, typeof (string))); + } + } + if (fields.Count > 0) + { + foreach (DataRow row in tableData.Rows) + { + foreach (FieldSetting field in fields) + { + //Link shown to the user + //Link readable by browsers + var strUrl = row[field.Title].ToString().Trim(); + //strip optional parameter like subject or body for display: + var strLink = strUrl.IndexOf("?", System.StringComparison.Ordinal) != - 1 ? strUrl.Substring(0, strUrl.IndexOf("?", System.StringComparison.Ordinal)) : strUrl; + + if (strLink != string.Empty) + { + var strCaption = field.OutputFormat; + if (! string.IsNullOrEmpty(strCaption)) + { + strCaption = string.Format(tokenReplace.ReplaceEnvironmentTokens(strCaption, row), + strLink); + } + else + { + strCaption = strLink; + } + + string strFieldvalue; + if (strCaption != string.Empty && field.AsLink ) + { + strFieldvalue = string.Format("{1}", + HttpUtility.UrlEncode(strUrl), strCaption); + } + else + { + strFieldvalue = strLink; + } + + row[field.Title] = noScript ? strFieldvalue : (Globals.CloakText(strFieldvalue)); + row[field.Title + DataTableColumn.Appendix_Caption] = strCaption; + row[field.Title + DataTableColumn.Appendix_Original] = strUrl; + } + } + } + } + } + + public override string Name + { + get { return "EMail"; } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsEditing + { + get { return true; } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + public override bool SupportsEditStyle + { + get { return true; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + + public override bool SupportsValidation + { + get { return true; } + } + + public override bool SupportsSearch + { + get { return true; } + } + + public string GetEmailAddress(string fieldName, DataRow row) + { + return GetAddress(fieldName, row); + } + + public string GetAddress(string fieldName, DataRow row) + { + if (row.Table.Columns.Contains(fieldName + DataTableColumn.Appendix_Original)) + { + return row[fieldName + DataTableColumn.Appendix_Original].AsString(); + } + return row[fieldName].AsString(); + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/Expression.cs b/DataTypes/Expression.cs new file mode 100644 index 0000000..0c53869 --- /dev/null +++ b/DataTypes/Expression.cs @@ -0,0 +1,224 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Security; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "Expression" - a calculated column + /// + /// ----------------------------------------------------------------------------- + public class EditExpression : EditControl + { + public override string Value + { + get { return string.Empty; } + set + { + //do nothing + } + } + + string CalculateCurrentExpression() + { + var udt = new UserDefinedTableController(ModuleContext); + int rowId; + int.TryParse(HttpContext.Current.Request.QueryString[DataTableColumn.RowId], out rowId); + var ds = udt.GetRow(rowId, true); + DataRow currentrow; + if (ds.Tables[DataSetTableName.Data].Rows.Count == 1) + { + currentrow = ds.Tables[DataSetTableName.Data].Rows[0]; + } + else + { + currentrow = ds.Tables[DataSetTableName.Data].NewRow(); + ds.Tables[DataSetTableName.Data].Rows.Add(currentrow); + } + return currentrow[FieldTitle].ToString(); + } + + + void EditExpression_Init(object sender, EventArgs e) + { + Control ctl; + if (GetFieldSetting( "RenderInForm").AsBoolean( )) + { + //HtmlEncode is not called, as we are expecting that CalculateCurrentExpression usually returns markup. + ctl = new LiteralControl(CalculateCurrentExpression()); + } + else + { + ctl = + new LiteralControl(string.Format( + "({0})", + HttpUtility.HtmlEncode(DefaultValue))); + } + Controls.Add(ctl); + } + + public EditExpression() + { + Init += EditExpression_Init; + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Expression" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeExpression : DataType + { + readonly FieldSettingType[] _fieldSettingTypes = new[] + { + new FieldSettingType {Key = "RenderInForm", Section = "Form", SystemType = "Boolean"} + }; + + public override IEnumerable FieldSettingTypes + { + get + { + return _fieldSettingTypes; + } + } + + public override string Name + { + get { return "Expression"; } + } + + + public override void SetStylesAndFormats(BoundField column, string format) + { + base.SetStylesAndFormats(column, format); + if (format != string.Empty) + { + column.DataFormatString = string.Format("{{0:{0}}}", format); + } + } + + static string WarningMessage(string message, int moduleId) + { + message = new PortalSecurity().InputFilter(message.Replace("\'", "\'\'"), PortalSecurity.FilterFlag.NoMarkup); + var tabId = Convert.ToInt32(- 1); + if (HttpContext.Current != null && HttpContext.Current.Request.QueryString["tabid"] != null) + { + tabId = int.Parse(HttpContext.Current.Request.QueryString["tabid"]); + } + if (tabId > - 1 && new ModuleSecurity(moduleId, tabId).IsAllowedToAdministrateModule()) + { + return string.Format("\'{0}\'", message); + } + return string.Format("\'{0}\'", "Expression failed"); + } + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + var tokenReplace = new TokenReplace {ModuleId = moduleId}; + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == Name) + { + var fieldId = (int)row[FieldsTableColumn.Id]; + var columnName = row[FieldsTableColumn.Title].ToString(); + try + { + var typestring = row[FieldsTableColumn.InputSettings].AsString(); + var expression = tokenReplace.ReplaceEnvironmentTokens( + row[FieldsTableColumn.Default].AsString("String")); + + ds.Tables[DataSetTableName.Data].Columns.Remove(columnName); + var dc = new DataColumn(columnName, GetType(typestring)); + ds.Tables[DataSetTableName.Data].Columns.Add(dc); + dc.Expression = expression; + } + catch (SyntaxErrorException ex) + { + ds.Tables[DataSetTableName.Data].Columns.Remove(columnName); + var dc = new DataColumn(columnName, typeof (string)); + ds.Tables[DataSetTableName.Data].Columns.Add(dc); + ds.Tables[DataSetTableName.Data].Columns[columnName].Expression = + WarningMessage(ex.Message, moduleId); + } + catch (EvaluateException ex) + { + ds.Tables[DataSetTableName.Data].Columns.Remove(columnName); + var dc = new DataColumn(columnName, typeof (string)); + ds.Tables[DataSetTableName.Data].Columns.Add(dc); + ds.Tables[DataSetTableName.Data].Columns[columnName].Expression = + WarningMessage(ex.Message, moduleId); + } + catch (ArgumentNullException ex) + { + var dc = new DataColumn(columnName, typeof (string)); + ds.Tables[DataSetTableName.Data].Columns.Add(dc); + ds.Tables[DataSetTableName.Data].Columns[columnName].Expression = + WarningMessage(ex.Message, moduleId); + } + } + } + } + + static Type GetType(string typestring) + { + return Type.GetType(("System." + typestring)); + } + + public override IDictionary InputSettingsList + { + get { return ListOfCommonDataTypes; } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + public override bool InputSettingsIsValueList + { + get { return false; } + } + + public override string InputSettingDefault + { + get { return "String"; } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + + public override bool SupportsHideOnEdit + { + get { return true; } + } + + public override bool SupportsSearch + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/FieldSettingType.cs b/DataTypes/FieldSettingType.cs new file mode 100644 index 0000000..6d49696 --- /dev/null +++ b/DataTypes/FieldSettingType.cs @@ -0,0 +1,18 @@ +using System; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + public class FieldSettingType + { + public String Key { get; set; } + public Boolean Localizeable { get; set; } + public String SystemType { get; set; } + public String Section { get; set; } + Func _verifySetting; + public Func VerifySetting + { + get { return _verifySetting ?? (input => true); } + set { _verifySetting = value; } + } + } +} \ No newline at end of file diff --git a/DataTypes/Image.cs b/DataTypes/Image.cs new file mode 100644 index 0000000..372deb9 --- /dev/null +++ b/DataTypes/Image.cs @@ -0,0 +1,279 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.IO; +using System.Web; +using DotNetNuke.Common; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Security; +using DotNetNuke.Services.FileSystem; +using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "Image" + /// + /// ----------------------------------------------------------------------------- + public class EditImage : EditURL + { + void EditImage_Load(object sender, EventArgs e) + { + if (! Page.IsPostBack && IsNotAListOfValues) + { + CtlUrl.Required = Required; + CtlUrl.FileFilter = Globals.glbImageFileTypes; + CtlUrl.ShowLog = false; + CtlUrl.ShowTrack = false; + CtlUrl.ShowTabs = false; + CtlUrl.ShowUrls = true; + CtlUrl.ShowFiles = true; + CtlUrl.ShowNewWindow = false; + } + } + + public EditImage() + { + Load += EditImage_Load; + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Image" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeImage : DataType + { + readonly FieldSettingType[] _fieldSettingTypes= new[] + { + new FieldSettingType {Key = "AltCaption", Section = "List", SystemType = "String"}, + new FieldSettingType {Key = "AsLink", Section = "List", SystemType = "Boolean"}, + new FieldSettingType {Key = "Width", Section = "List", SystemType = "Int"}, + new FieldSettingType {Key = "Height", Section = "List", SystemType = "Int"} + }; + + public override IEnumerable FieldSettingTypes + { + get + { + return _fieldSettingTypes; + } + } + public override string Name + { + get { return "Image"; } + } + + + + struct FieldSetting + { + public string Title; + public string AltCaption; + public bool AsLink; + public int Width; + public int Height; + } + + struct ImageFields + { + public string Value; + + public string Original; + public string Url; + } + + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + var fields = new ArrayList(); + var tableData = ds.Tables[DataSetTableName.Data]; + var tokenReplace = new TokenReplace {ModuleId = moduleId}; + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == Name) + { + var fieldId = (int) row[FieldsTableColumn.Id]; + var field = new FieldSetting + { + Title = row[FieldsTableColumn.Title].ToString(), + AltCaption = GetFieldSetting("AltCaption",fieldId,ds).AsString(), + AsLink = GetFieldSetting("AsLink", fieldId, ds).AsBoolean(), + Width = GetFieldSetting("Width", fieldId, ds).AsInt(), + Height = GetFieldSetting("Height", fieldId, ds).AsInt(), + }; + fields.Add(field); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Url, typeof (string))); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Caption, typeof (string))); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Original, + typeof (string))); + } + } + + if (fields.Count > 0) + { + var portalSecurity = new PortalSecurity(); + var portalId = Null.NullInteger; + if (HttpContext.Current != null) + { + var portalSettings = PortalController.GetCurrentPortalSettings(); + portalId = portalSettings.PortalId; + } + + var cache = new Dictionary(); + foreach (DataRow row in ds.Tables[DataSetTableName.Data].Rows) + { + foreach (FieldSetting setting in fields) + { + var altCaption = GetAltAttributeForImage(row, setting, tokenReplace); + var storedValue = row[setting.Title].ToString(); + ImageFields imageFields; + if (cache.ContainsKey( storedValue )) + imageFields = cache[storedValue]; + else { + imageFields = GetImageFields(storedValue, setting, portalId); + cache[storedValue] = imageFields; + } + row[setting.Title] = String.Format( imageFields.Value,altCaption ); + row[setting.Title + DataTableColumn.Appendix_Caption] = altCaption ; + row[setting.Title + DataTableColumn.Appendix_Original] = imageFields.Original; + row[setting.Title + DataTableColumn.Appendix_Url] = imageFields.Url; + } + } + } + } + + static string GetAltAttributeForImage(DataRow row, FieldSetting setting, TokenReplace tokenReplace) + { + var altTag = setting.AltCaption; + if (altTag == string.Empty) + { + altTag = setting.Title; + } + else + { + if (altTag != string.Empty) + { + altTag = tokenReplace.ReplaceEnvironmentTokens(altTag, row); + } + } + altTag = new PortalSecurity().InputFilter(altTag, PortalSecurity.FilterFlag.NoMarkup); + return altTag; + } + + static ImageFields GetImageFields(string value, FieldSetting setting, int portalId) + { + var strFieldvalue = value; + var url = string.Empty; + var imageUrl = string.Empty; + var path = string.Empty; + if (strFieldvalue != string.Empty) + { + if (strFieldvalue.StartsWith("http:") || strFieldvalue.StartsWith("https:")) + { + imageUrl = strFieldvalue; + url = imageUrl; + } + else + { + var fileInfo = strFieldvalue.StartsWith("FileID=") + ? FileManager.Instance.GetFile(int.Parse(UrlUtils.GetParameterValue(strFieldvalue))) + : FileManager.Instance.GetFile(portalId, strFieldvalue); + if (fileInfo != null) + { + imageUrl = FileManager.Instance.GetUrl(fileInfo); + path = Path.Combine(fileInfo.Folder, fileInfo.FileName); + } + var parms = ""; + if (setting.Width > 0) + { + parms = string.Format("{0}&w={1}", parms, setting.Width); + } + if (setting.Height > 0) + { + parms = string.Format("{0}&h={1}", parms, setting.Height); + } + if (parms != "") + { + url = string.Format("{0}?image={1}{2}&PortalId={3}", + Globals.ResolveUrl(string.Format("~{0}MakeThumbnail.ashx", + Definition.PathOfModule)), + HttpUtility.UrlEncode(path), parms, + portalId); + } + else + { + url = imageUrl; + } + } + + url = HttpUtility.HtmlEncode(url); + if (setting.AsLink) + { + strFieldvalue = + string.Format( + "\"{1}\"", + imageUrl, "{0}", url); + } + else + { + strFieldvalue = string.Format("\"{0}\"", "{0}", + url); + } + } + var imageFields = new ImageFields + { + Value = strFieldvalue, + + Original = value, + Url = url + }; + return imageFields; + } + + public override string SupportedCasts + { + get { return string.Format("{0}|URL", base.SupportedCasts); } + } + + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsEditing + { + get { return true; } + } + + public override bool SupportsOutputSettings + { + get { return false; } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + public override bool SupportsSearch + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/Int32.cs b/DataTypes/Int32.cs new file mode 100644 index 0000000..b321100 --- /dev/null +++ b/DataTypes/Int32.cs @@ -0,0 +1,132 @@ +using System; +using System.Globalization; +using System.Web.UI.WebControls; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "Int32" + /// + /// ----------------------------------------------------------------------------- + public class EditInt32 : EditString + { + protected override bool IsValidType() + { + int i; + return Value == string.Empty || int.TryParse(Value, out i); + } + + public override string Value + { + get + { + string returnValue; + try + { + returnValue = string.Empty; + if (base.Value != "") + { + returnValue = (int.Parse(base.Value)).ToString(CultureInfo.CurrentCulture); + } + //normalize format + } + catch + { + returnValue = base.Value; + } + return returnValue; + } + set + { + var culture = new CultureInfo("en-US"); + if (value != "") + { + value = (int.Parse(value, culture).ToString("#,###,###,##0")); + } + base.Value = value; + } + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + CtlValueBox.Attributes.Add("style", "text-align:right"); + CtlValueBox.Width = new Unit("10em"); + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Int32" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeInt32 : DataType + { + public override void SetStylesAndFormats(BoundField column, string format) + { + column.DataFormatString = format == string.Empty ? "{0:#,###,##0}" : string.Format("{{0:{0}}}", format); + column.HeaderStyle.HorizontalAlign = HorizontalAlign.Right; + column.ItemStyle.HorizontalAlign = HorizontalAlign.Right; + } + + public override string Name + { + get { return "Int32"; } + } + + public override string SystemTypeName + { + get { return "Int32"; } + } + + public override string SupportedCasts + { + get { return string.Format("{0}|Decimal|Currency", base.SupportedCasts); } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsEditing + { + get { return true; } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + + public override bool SupportsValidation + { + get { return true; } + } + + public override bool SupportsSearch + { + get { return true; } + } + + public override bool SupportsEditStyle + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/LookUp.cs b/DataTypes/LookUp.cs new file mode 100644 index 0000000..6039cd9 --- /dev/null +++ b/DataTypes/LookUp.cs @@ -0,0 +1,202 @@ +using System.Collections; +using System.Data; +using System.Web; +using System.Web.UI.WebControls; +using System.Xml; +using DotNetNuke.Common; +using DotNetNuke.Entities.Users; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Modules.UserDefinedTable.Interfaces; +using DotNetNuke.Services.Tokens; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit & Validation Control for DataType "Info" + /// + /// ----------------------------------------------------------------------------- + public class EditLookUp : EditExpression + { + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Expression" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeLookUp : DataType + { + class TokenReplace : BaseCustomTokenReplace + { + readonly int _moduleId; + + public TokenReplace(int moduleId) + { + if (HttpContext.Current != null) + { + AccessingUser = (UserInfo) (HttpContext.Current.Items["UserInfo"]); + } + else + { + AccessingUser = new UserInfo(); + } + CurrentAccessLevel = Scope.DefaultSettings; + _moduleId = moduleId; + } + + public string GetValue(string tokenText, DataRow row, string sourceColumn, string sourceType) + { + PropertySource.Clear(); + switch (sourceType.ToLowerInvariant()) + { + case "createdby": + case "changedby": + case "userlink": + var userInfo = ((IUserSource) (ByName(sourceType))).GetUser(sourceColumn, row); + if (userInfo == null) + { + return ""; + } + PropertySource["user"] = userInfo; + PropertySource["profile"] = new ProfilePropertyAccess(userInfo); + break; + case "download": + case "url": + case "image": + var strFileId = row[sourceColumn + DataTableColumn.Appendix_Original].AsString(); + if (strFileId != string.Empty) + { + PropertySource["file"] = new DownloadPropertyAccess(strFileId, + Globals.GetPortalSettings().PortalId, + _moduleId); + } + break; + default: + if ((ByName(sourceType)) is IEmailAdressSource) + { + var email = ((IEmailAdressSource) (ByName(sourceType))).GetEmailAddress(sourceColumn, row); + if (! string.IsNullOrEmpty(email)) + { + PropertySource["gravatar"] = new GravatarPropertyAccess(email); + } + } + else + { + return ""; + } + break; + } + + return ReplaceTokens(tokenText); + } + } + + + public override string Name + { + get { return "LookUp"; } + } + + + public override void SetStylesAndFormats(BoundField column, string format) + { + base.SetStylesAndFormats(column, format); + if (format != string.Empty) + { + column.DataFormatString = string.Format("{{0:{0}}}", format); + } + } + + + struct FieldSetting + { + public string Title; + public string SourceColumn; + public string SourceType; + public string TokenText; + } + + string GetTypeName(DataTable fieldsTable, string columnName) + { + using ( + var dv = new DataView(fieldsTable, string.Format("{0}=\'{1}\'", FieldsTableColumn.Title, columnName), "", + DataViewRowState.CurrentRows)) + { + return dv[0][FieldsTableColumn.Type].AsString(); + } + } + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + var fields = new ArrayList(); + //List of columns that contains URLs + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == Name) + { + var fieldSetting = new FieldSetting + { + Title = row[FieldsTableColumn.Title].ToString(), + SourceColumn = row[FieldsTableColumn.InputSettings].AsString() + }; + if (! string.IsNullOrEmpty(fieldSetting.SourceColumn)) + { + fieldSetting.TokenText = row[FieldsTableColumn.Default].AsString(); + fieldSetting.SourceType = GetTypeName(ds.Tables[DataSetTableName.Fields], + fieldSetting.SourceColumn); + fields.Add(fieldSetting); + row[FieldsTableColumn.ValueColumn] = XmlConvert.EncodeName(fieldSetting.Title); + } + } + } + foreach (DataRow row in ds.Tables[DataSetTableName.Data].Rows) + { + foreach (FieldSetting field in fields) + { + row[field.Title] = new TokenReplace(moduleId).GetValue(field.TokenText, row, field.SourceColumn, + field.SourceType); + } + } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + public override bool InputSettingsIsValueList + { + get { return false; } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsOutputSettings + { + get { return false; } + } + + public override bool SupportsHideOnEdit + { + get { return true; } + } + + public override bool SupportsSearch + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/Separator.cs b/DataTypes/Separator.cs new file mode 100644 index 0000000..fc39a4e --- /dev/null +++ b/DataTypes/Separator.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using System.Data; +using DotNetNuke.Modules.UserDefinedTable.Components; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + /// ----------------------------------------------------------------------------- + /// + /// DataType "Separator" + /// + /// + /// No EditSeparator required + /// + /// ----------------------------------------------------------------------------- + public class DataTypeSeparator : DataType + { + public override string Name + { + get { return "Separator"; } + } + + readonly FieldSettingType[] _fieldSettingTypes = new[] + { + new FieldSettingType {Key = "IsCollapsible", Section = "List", SystemType = "Boolean"} + }; + public override IEnumerable FieldSettingTypes { get { return _fieldSettingTypes; }} + + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + //it never shows up + if (row[FieldsTableColumn.Type].ToString() == Name) + { + row[FieldsTableColumn.Visible] = false; + } + } + } + + public override bool IsSeparator + { + get { return (true); } + } + } +} \ No newline at end of file diff --git a/DataTypes/String.cs b/DataTypes/String.cs new file mode 100644 index 0000000..337eeb3 --- /dev/null +++ b/DataTypes/String.cs @@ -0,0 +1,170 @@ +using System; +using System.Web.UI.WebControls; +using DotNetNuke.Common.Utilities; +using System.Linq; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "String" + /// + /// ----------------------------------------------------------------------------- + public class EditString : EditControl + { + protected WebControl CtlValueBox; + protected string StrValRule = string.Empty; + protected string StrValMsg = string.Empty; + + public EditString() + { + Init += EditString_Init; + } + + void EditString_Init(object sender, EventArgs e) + { + if (IsNotAListOfValues) + { + var ctlTextBox = new TextBox {TextMode = TextBoxMode.SingleLine, Rows = 1}; + CtlValueBox = ctlTextBox; + if (ValidationRule != "") + { + StrValRule = ValidationRule; + StrValMsg = ValidationMessage; + } + } + else + { + var ctlListControl = GetListControl(); + AddListItems(ctlListControl); + CtlValueBox = ctlListControl; + } + Value = DefaultValue; + if (Required) CtlValueBox.CssClass = "dnnFormRequired"; + if (!String.IsNullOrEmpty( Style)) CtlValueBox.Style.Value = Style; + CtlValueBox.ID = CleanID(FieldTitle); + ValueControl = CtlValueBox; + Controls.Add(CtlValueBox); + } + + + public override string Value + { + get + { + string returnValue; + if (CtlValueBox is TextBox) + { + returnValue = FilterScript + ? ApplyScriptFilter(((TextBox) CtlValueBox).Text) + : ((TextBox) CtlValueBox).Text; + if (FilterTags) + { + returnValue = HtmlUtils.StripTags(returnValue, true); + } + } + else + { + if (MultipleValuesFlag) + returnValue = ((ListControl) CtlValueBox).Items + .Cast() + .Where(i => i.Selected) + .Aggregate( "",(c,i)=>c + i.Value +";") + .TrimEnd(';'); + else + returnValue = ((ListControl)CtlValueBox).SelectedValue; + } + return returnValue; + } + set + { + if (CtlValueBox is TextBox) + { + ((TextBox) CtlValueBox).Text = value; + } + else + { + var ctlListControl = (ListControl) CtlValueBox; + if (MultipleValuesFlag) + { + var existingItems = value.Split(';') + .Select(entry => ctlListControl.Items.FindByValue(entry)) + .Where(entry=>entry!=null); + foreach (var item in existingItems) + { + item.Selected = true; + } + } + + else + if (ctlListControl.Items.FindByValue(value) != null) + { + ctlListControl.SelectedValue = value; + } + } + } + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "String" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeString : DataType + { + public override string Name + { + get { return "String"; } + } + + public override string SupportedCasts + { + get { return string.Format("{0}|TextHtml", base.SupportedCasts); } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsEditing + { + get { return true; } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + public override bool SupportsValidation + { + get { return true; } + } + + public override bool SupportsSearch + { + get { return true; } + } + + public override bool SupportsEditStyle + { + get { return true; } + } + + public override bool SupportsMultipleValues + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/TextHtml.cs b/DataTypes/TextHtml.cs new file mode 100644 index 0000000..db6b321 --- /dev/null +++ b/DataTypes/TextHtml.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Web.UI.WebControls; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Modules.HTMLEditorProvider; +using DotNetNuke.Modules.UserDefinedTable.Components; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit & Validation Control for DataType "TextHtml" + /// + /// ----------------------------------------------------------------------------- + public class EditTextHtml : EditControl + { + protected HtmlEditorProvider RichTextEditor; + protected TextBox TxtBox; + protected string DefValue = ""; + bool _useRichTextEditor; + + public override string Value + { + get + { + string returnValue = _useRichTextEditor ? HttpUtility.HtmlDecode(RichTextEditor.Text) : TxtBox.Text; + if (FilterScript) + { + returnValue = ApplyScriptFilter(returnValue); + } + if (FilterTags) + { + returnValue = HtmlUtils.StripTags(returnValue, true); + } + //FCK returns

 

if no input was made + if (returnValue == "

 

") + { + returnValue = ""; + } + return returnValue; + } + + set + { + if (_useRichTextEditor) + { + RichTextEditor.Text =value; + } + else + { + TxtBox.Text = value; + } + } + } + + public EditTextHtml() + { + Init += Page_Init; + } + + void Page_Init(object sender, EventArgs e) + { + _useRichTextEditor = !GetFieldSetting("PlainText").AsBoolean() && !FilterTags; + if (FilterScript) + { + } + + DefValue = DefaultValue; + + if (_useRichTextEditor) + { + + var pnlEditor = new Panel {CssClass = "dnnLeft"}; + + RichTextEditor = HtmlEditorProvider.Instance(); + var controlId = CleanID(string.Format("{0}", FieldTitle)); + RichTextEditor.ControlID = controlId; + RichTextEditor.Initialize(); + //RichTextEditor.Height = ControlStyle.Height; + //RichTextEditor.Width = ControlStyle.Width; + if (RichTextEditor.Height.IsEmpty) + { + RichTextEditor.Height = new Unit(250); + } + + RichTextEditor.Width = new Unit(400); + + Controls.Clear(); + var htmlEditorControl = RichTextEditor.HtmlEditorControl; + pnlEditor.Controls.Add(htmlEditorControl); + RichTextEditor.Text = DefValue; + Controls.Add(pnlEditor); + ValueControl = FindControl(controlId ); + } + else + { + TxtBox = new TextBox { TextMode = TextBoxMode.MultiLine, Rows = 7, Text = DefValue, ID = CleanID(FieldTitle) }; + Controls.Add(TxtBox); + + ValueControl = TxtBox; + } + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "TextHtml" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeTextHtml : DataType + { + readonly FieldSettingType[] _fieldSettingTypes = new[] + { + new FieldSettingType {Key = "PlainText", Section = "Form", SystemType = "Boolean"} + }; + + public override IEnumerable FieldSettingTypes + { + get + { + return _fieldSettingTypes; + } + } + + public override string Name + { + get { return "TextHtml"; } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsEditing + { + get { return true; } + } + + public override bool SupportsValidation + { + get { return true; } + } + + public override bool SupportsSearch + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/Time.cs b/DataTypes/Time.cs new file mode 100644 index 0000000..35ef7fa --- /dev/null +++ b/DataTypes/Time.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Web; +using System.Web.UI.WebControls; +using System.Xml; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Entities.Users; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Web.UI.WebControls; +using Microsoft.VisualBasic; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "Time" + /// + /// ----------------------------------------------------------------------------- + public class EditTime : EditControl + { + DnnTimePicker _ctlTime; + + + public override string Value + { + get + { + string returnValue; + var selectedDate = _ctlTime.SelectedDate; + + if (selectedDate.HasValue ) + { + var d = selectedDate.Value ; + returnValue = d.ToString("s"); + } + else + { + returnValue = Null.NullString; + } + return returnValue; + } + set + { + if (value == string.Empty) + { + + } + else + { + var d = DateTime.Parse(value); + _ctlTime.SelectedDate = d; + } + } + } + + + + void EditTime_Init(object sender, EventArgs e) + { + //Time-Textbox + _ctlTime = new DnnTimePicker + { + MinDate = DateTime.MinValue, + ID = CleanID(string.Format("{0}_time", FieldTitle)) + }; + + if (! string.IsNullOrEmpty(Style)) + { + _ctlTime.Style.Value = Style; + } + Controls.Add(_ctlTime); + Value = DefaultValue; + ValueControl = _ctlTime; + } + + public EditTime() + { + Init += EditTime_Init; + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Date" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeTime : DataTypeDate + { + public override void SetStylesAndFormats(BoundField column, string format) + { + base.SetStylesAndFormats(column, format.AsString("t")); + } + + public override string Name + { + get { return "Time"; } + } + + struct FieldSetting + { + public string Title; + public string FormatString; + } + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + var fields = new ArrayList(); + //List of columns that contains URLs + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == Name) + { + var fieldId = (int) row[FieldsTableColumn.Id]; + var field = new FieldSetting + { + Title = row[FieldsTableColumn.Title].ToString(), + FormatString = row[FieldsTableColumn.OutputSettings].AsString("t") + }; + fields.Add(field); + var renderedValueColumnName = field.Title + DataTableColumn.Appendix_LocalizedValue; + ds.Tables[DataSetTableName.Data].Columns.Add(renderedValueColumnName, typeof (string)); + ds.Tables[DataSetTableName.Data].Columns.Add(field.Title + DataTableColumn.Appendix_Ticks, + typeof (long)); + row[FieldsTableColumn.ValueColumn] = XmlConvert.EncodeName(renderedValueColumnName); + } + } + if (HttpContext.Current != null) + { + var serverTimeZone = PortalController.GetCurrentPortalSettings().TimeZone; + var userTimeZone = UserController.GetCurrentUserInfo().Profile.PreferredTimeZone; + foreach (DataRow row in ds.Tables[DataSetTableName.Data].Rows) + { + foreach (FieldSetting field in fields) + { + if (Information.IsDate(row[field.Title])) + { + var d = Convert.ToDateTime(row[field.Title]); + + var format = "{1:" + field.FormatString + "}"; + row[field.Title + DataTableColumn.Appendix_LocalizedValue] = string.Format(format, d.Ticks/10000000,d); + row[field.Title + DataTableColumn.Appendix_Ticks] = d.Ticks; + } + } + } + } + } + + public override bool SupportsEditStyle + { + get { return true; } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + public override bool SupportsValidation + { + get { return true; } + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/URL.cs b/DataTypes/URL.cs new file mode 100644 index 0000000..3dfc3c5 --- /dev/null +++ b/DataTypes/URL.cs @@ -0,0 +1,492 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Web; +using System.Web.UI.HtmlControls; +using System.Web.UI.WebControls; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Entities.Tabs; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Services.FileSystem; +using DotNetNuke.Services.Localization; +using DotNetNuke.UI.UserControls; +using Globals = DotNetNuke.Common.Globals; +using TabInfo = DotNetNuke.Entities.Tabs.TabInfo; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit and Validation Control for DataType "Url" + /// + /// ----------------------------------------------------------------------------- +// ReSharper disable InconsistentNaming + public class EditURL : EditControl +// ReSharper restore InconsistentNaming + { + protected UrlControl CtlUrl; + protected ListControl CtlValueBox; + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + Load += EditURL_Load; + InitEditControl(); + } + + void InitEditControl() + { + if (IsNotAListOfValues) + { + CtlUrl = (UrlControl) (Page.LoadControl("~/controls/URLControl.ascx")); + CtlUrl.ID = CleanID(string.Format("{0}_url", FieldTitle)); + var container = new HtmlGenericControl("div"); + container.Attributes.Add("class", "dnnLeft"); + container.Controls.Add(CtlUrl ); + Controls.Add(container ); + ValueControl = CtlValueBox; + } + else + { + ListControl ctlListControl; + switch (ListInputType) + { + case InputType.horizontalRadioButtons: + ctlListControl = new RadioButtonList + { + RepeatDirection = RepeatDirection.Horizontal, + RepeatLayout = RepeatLayout.Flow + }; + break; + case InputType.verticalRadioButtons: + ctlListControl = new RadioButtonList { RepeatLayout = RepeatLayout.Flow }; + break; + default: + ctlListControl = new DropDownList(); + break; + } + AddListItems(ctlListControl); + CtlValueBox = ctlListControl; + CtlValueBox.CssClass = "NormalTextBox"; + CtlValueBox.ID = CleanID(FieldTitle); + ValueControl = CtlValueBox; + var container = new HtmlGenericControl("div"); + container.Attributes.Add("class", "dnnLeft"); + container.Controls.Add(CtlValueBox); + Controls.Add(container) ; + ValueControl = CtlValueBox; + } + } + + + void EditURL_Load(object sender, EventArgs e) + { + //we need to intilialize only once + if (! Page.IsPostBack) + { + if (IsNotAListOfValues) + { + CtlUrl.Required = Required; + CtlUrl.ShowLog = false; + CtlUrl.ShowTrack = false; + CtlUrl.ShowNewWindow = GetFieldSetting("ShowOpenInNewWindow").AsBoolean(); + } + if (! ValueIsSet) + { + Value = DefaultValue; + } + } + } + + protected bool ValueIsSet + { + get + { + if (ViewState["ValueIsSet"] != null) + { + return Convert.ToBoolean(ViewState["ValueIsSet"]); + } + return false; + } + set { ViewState["ValueIsSet"] = value; } + } + + + public override string Value + { + get + { + string returnValue; + if (IsNotAListOfValues) + { + var mc = new ModuleController(); + var settings = mc.GetModuleSettings(ModuleId); + + var urlController = new UrlController(); + urlController.UpdateUrl(PortalId, CtlUrl.Url, CtlUrl.UrlType, CtlUrl.Log, + settings[SettingName.URLDownloadTracking].AsBoolean(), CtlUrl.ModuleID, + CtlUrl.NewWindow); + returnValue = CtlUrl.Url + (CtlUrl.NewWindow ? "|options=W" : ""); + } + else + { + returnValue = CtlValueBox.SelectedValue; + } + return returnValue; + } + set + { + if (IsNotAListOfValues) + { + CtlUrl.Url = UrlUtil.StripURL(value); + ValueIsSet = true; + } + else + { + try + { + CtlValueBox.SelectedValue = value; + ValueIsSet = true; + } +// ReSharper disable EmptyGeneralCatchClause + catch +// ReSharper restore EmptyGeneralCatchClause + { + } + } + } + } + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Url" + /// + /// ----------------------------------------------------------------------------- +// ReSharper disable InconsistentNaming + public class DataTypeURL : DataType +// ReSharper restore InconsistentNaming + { + public override string Name + { + get { return "URL"; } + } + + readonly FieldSettingType[] _fieldSettingTypes = new[] + { + new FieldSettingType {Key = "Abbreviate", Section = "List", SystemType = "Boolean"}, + new FieldSettingType {Key = "ShowOpenInNewWindow", Section = "List", SystemType = "Boolean"}, + new FieldSettingType {Key = "EnforceDownload", Section = "List", SystemType = "Boolean"}, + new FieldSettingType {Key = "TrackDownloads", Section = "List", SystemType = "Boolean"} + }; + + public override IEnumerable FieldSettingTypes + { + get { return _fieldSettingTypes; } + } + + struct FieldSetting + { + public string Title; + public string OutputFormat; + public bool Abbreviate; + public bool ShowOpenInNewWindow; + public bool EnforceDownload; + public bool TrackDownloads; + } + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + if (ds != null) + { + var fields = new ArrayList(); + var tableData = ds.Tables[DataSetTableName.Data]; + var tokenReplace = new TokenReplace {ModuleId = moduleId}; + PrepareHiddenColumns(ds, fields, tableData); + + if (fields.Count <= 0) + { + return; + } + + var portalSettings = PortalController.GetCurrentPortalSettings(); + + var tabCtrl = new TabController(); + foreach (DataRow row in tableData.Rows) + { + foreach (FieldSetting field in fields) + { + FillTypeColumns(moduleId, tokenReplace, portalSettings, tabCtrl, row, field); + } + } + } + } + + void FillTypeColumns(int moduleId, TokenReplace objTokenReplace, PortalSettings portalSettings, + TabController tabCtrl, + DataRow row, FieldSetting field) + { + var link = row[field.Title].ToString(); + //Link showed to the user + bool openInNewWindow; + if (field.ShowOpenInNewWindow ) //mit URL gepeicherten Wert lesen + { + openInNewWindow = UrlUtil.OpenUrlInNewWindow(link); + } + else + { + switch (Globals.GetURLType(UrlUtil.StripURL(link))) + { + case TabType.File: + openInNewWindow = true; + break; + case TabType.Tab: //link to internal tab + openInNewWindow = false; + break; + default: + openInNewWindow = link.Like( Globals.ApplicationMapPath + "*"); + break; + } + } + + //set caption: + var caption = field.OutputFormat; + if (! string.IsNullOrEmpty(caption)) + { + caption = objTokenReplace.ReplaceEnvironmentTokens(caption, row); + } + var isLink = true; + var url = ""; + //Link readable by browsers + link = UrlUtil.StripURL(link); + if (link != string.Empty) + { + switch (Globals.GetURLType(link)) + { + case TabType.Tab: + var tab = tabCtrl.GetTab(int.Parse(link), portalSettings.PortalId, false); + if (tab != null) + { + if (caption == string.Empty) + { + if (! field.Abbreviate) + { + var strPath = string.Empty; + if (tab.BreadCrumbs != null && tab.BreadCrumbs.Count > 0) + { + foreach (TabInfo b in tab.BreadCrumbs) + { + var strLabel = b.TabName; + if (strPath != string.Empty) + { + strPath += + string.Format( + "\"Spacer\"/", + Globals.ApplicationPath); + } + strPath += strLabel; + } + } + caption = tab.TabPath.Replace("//", + string.Format( + "\"Spacer\"/", + Globals.ApplicationPath)); + } + else + { + caption = tab.TabName; + } + } + url =field.EnforceDownload + ? Globals.LinkClick(link, portalSettings.ActiveTab.TabID, moduleId) + : Globals.NavigateURL(int.Parse(link)); + } + else + { + caption = Localization.GetString("PageNotFound.ErrorMessage", + Globals.ResolveUrl( + string.Format("~{0}{1}/SharedResources.resx", + Definition.PathOfModule, + Localization.LocalResourceDirectory))); + url = string.Empty; + isLink = false; + } + break; + case TabType.File: + if (caption == string.Empty) + { + if (link.ToLowerInvariant().StartsWith("fileid=")) + { + var file = FileManager.Instance.GetFile(int.Parse(link.Substring(7))); + if (file != null) + { + if (! field.Abbreviate) + { + caption = file.Folder + file.FileName; + } + else + { + caption = file.FileName; + } + } + } + else if (field.Abbreviate && link.IndexOf("/", StringComparison.Ordinal) > - 1) + { + caption = link.Substring(Convert.ToInt32(link.LastIndexOf("/", StringComparison.Ordinal) + 1)); + } + else + { + caption = link; + } + } + url = Globals.LinkClick(link, portalSettings.ActiveTab.TabID, moduleId); + break; + + case TabType.Url: + case TabType.Normal: + if (caption == string.Empty) + { + if (field.Abbreviate && link.IndexOf("/", StringComparison.Ordinal) > - 1) + { + caption = link.Substring(Convert.ToInt32(link.LastIndexOf("/", StringComparison.Ordinal) + 1)); + } + else + { + caption = link; + } + } + if (!field.TrackDownloads)url = link; + break; + } + + + if (field.EnforceDownload) url += "&forcedownload=true"; + + string strFieldvalue; + if (isLink) + { + strFieldvalue = string.Format("{1}", HttpUtility.HtmlEncode(url), + caption, (openInNewWindow ? " target=\"_blank\"" : "")); + } + else + { + strFieldvalue = caption; + } + row[field.Title] = strFieldvalue; + row[field.Title + DataTableColumn.Appendix_Caption] = caption; + row[field.Title + DataTableColumn.Appendix_Original] = link; + row[field.Title + DataTableColumn.Appendix_Url] = url; + } + } + + void PrepareHiddenColumns(DataSet ds, ArrayList fields, DataTable tableData) + { + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == Name) + { + var fieldId = (int)row[FieldsTableColumn.Id]; + var field = new FieldSetting + { + Title = row[FieldsTableColumn.Title].ToString(), + OutputFormat = row[FieldsTableColumn.OutputSettings].AsString(), + Abbreviate = GetFieldSetting("Abbreviate", fieldId, ds).AsBoolean(), + ShowOpenInNewWindow = GetFieldSetting("ShowOpenInNewWindow", fieldId, ds).AsBoolean(), + TrackDownloads = GetFieldSetting("TrackDownloads", fieldId, ds).AsBoolean(), + EnforceDownload = GetFieldSetting("EnforceDownload", fieldId, ds).AsBoolean() + }; + fields.Add(field); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Url, typeof (string))); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Caption, typeof (string))); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Original, + typeof (string))); + } + } + } + + public override string SupportedCasts + { + get { return string.Format("{0}|Image", base.SupportedCasts); } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsEditing + { + get { return true; } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + public override bool SupportsOutputSettings + { + get { return true; } + } + + public override bool SupportsSearch + { + get { return true; } + } + } + + #endregion + + #region URL Utilities + + /// ----------------------------------------------------------------------------- + /// + /// Utilities for DataType "Url" with enclosed options. + /// StripURL returns URL string with options stripped off. + /// Options are appended delimited by "|" and preceeded by "options=". + /// Supported options: + /// W open in new window + /// + /// ----------------------------------------------------------------------------- + public class UrlUtil + { + public static string StripURL(string strUrl) + { + var i = Convert.ToInt32(strUrl.AsString().IndexOf("|", StringComparison.Ordinal)); + if (i > 0) + { + return strUrl.Substring(0, i); + } + return strUrl; + } + + public static bool OpenUrlInNewWindow(string strUrl) + { + var strLinkOptions = ""; + //link + var i = Convert.ToInt32(strUrl.AsString().IndexOf("|options=", StringComparison.Ordinal)); + if (i >= 0 && i <= strUrl.Length - 9) + { + strLinkOptions = strUrl.Substring(i + 9); + i = strLinkOptions.IndexOf("|", StringComparison.Ordinal); + if (i >= 0) + { + strLinkOptions = strLinkOptions.Substring(0, i - 1); + } + } + return strLinkOptions.IndexOf("W", StringComparison.Ordinal) >= 0; + } + } + + #endregion +} \ No newline at end of file diff --git a/DataTypes/UserLink.cs b/DataTypes/UserLink.cs new file mode 100644 index 0000000..fed35f6 --- /dev/null +++ b/DataTypes/UserLink.cs @@ -0,0 +1,365 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Web; +using System.Web.UI.HtmlControls; +using System.Web.UI.WebControls; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Entities.Users; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Modules.UserDefinedTable.Interfaces; +using DotNetNuke.UI.UserControls; +using Microsoft.VisualBasic; +using Globals = DotNetNuke.Common.Globals; + +namespace DotNetNuke.Modules.UserDefinedTable.DataTypes +{ + + #region EditControl + + /// ----------------------------------------------------------------------------- + /// + /// Edit & Validation Control for DataType "Url" + /// + /// ----------------------------------------------------------------------------- + public class EditUserLink : EditControl + { + protected UrlControl CtlUrl; + protected ListControl CtlValueBox; + + void EditUserLink_Init(object sender, EventArgs e) + { + if (IsNotAListOfValues) + { + CtlUrl = (UrlControl) (Page.LoadControl("~/controls/URLControl.ascx")); + CtlUrl.ID = CleanID(string.Format("{0}_url", FieldTitle)); + var container = new HtmlGenericControl("div"); + container.Attributes.Add("class", "dnnLeft"); + container.Controls.Add(CtlUrl); + ValueControl = CtlUrl ; + Controls.Add(container ); + } + else + { + var ctlListControl = GetListControl(); + AddListItems(ctlListControl); + foreach (var username in InputValueList) + { + var user = UserController.GetUserByName(PortalId, username); + if (user == null && Information.IsNumeric(username)) //check for valid userID: + { + user = new UserController().GetUser(PortalId, int.Parse(username)); + } + if (user != null) + { + var item = new ListItem + { + Text = NormalizeFlag ? user.Username : user.DisplayName, + Value = string.Format("UserId={0}", user.UserID) + }; + ctlListControl.Items.Add(item); + } + } + CtlValueBox = ctlListControl; + CtlValueBox.CssClass = "NormalTextBox"; + CtlValueBox.ID = CleanID(FieldTitle); + Controls.Add(CtlValueBox); + } + } + + public EditUserLink() + { + Load += EditUserLink_Load; + Init += EditUserLink_Init; + } + + void EditUserLink_Load(object sender, EventArgs e) + { + //we need to initialize once only + if (!Page.IsPostBack) + { + if (IsNotAListOfValues) + { + var mc = new ModuleController(); + var settings = mc.GetModuleSettings(ModuleId); + var showInNewWindow = settings[SettingName.URLNewWindow].AsBoolean(); + //The following code must be executed during load, because the URLcontrol uses the viewstate + CtlUrl.UrlType = "M"; + CtlUrl.ShowUsers = true; + CtlUrl.ShowFiles = false; + CtlUrl.ShowTabs = false; + CtlUrl.ShowUrls = false; + CtlUrl.ShowUpLoad = false; + CtlUrl.ShowLog = false; + CtlUrl.ShowTrack = false; + CtlUrl.Required = Required; + CtlUrl.ShowNewWindow = showInNewWindow; + } + + if (!ValueIsSet && DefaultValue.Length > 0) + { + var user = UserController.GetUserByName(PortalId, DefaultValue); + if (user == null && Information.IsNumeric(DefaultValue)) //check for valid userID: + { + user = new UserController().GetUser(PortalId, int.Parse(DefaultValue)); + } + + Value = string.Format("UserId={0}", user.UserID); + } + } + } + + protected bool ValueIsSet + { + get + { + if (ViewState["ValueIsSet"] != null) + { + return Convert.ToBoolean(ViewState["ValueIsSet"]); + } + return false; + } + set { ViewState["ValueIsSet"] = value; } + } + + + public override string Value + { + get + { + string returnValue; + if (IsNotAListOfValues) + { + var urls = new UrlController(); + urls.UpdateUrl(PortalId, CtlUrl.Url, CtlUrl.UrlType, CtlUrl.Log, CtlUrl.Track, CtlUrl.ModuleID, + CtlUrl.NewWindow); + var strLinkOptions = ""; + if (CtlUrl.NewWindow) + { + strLinkOptions = "|options=W"; + } + returnValue = CtlUrl.Url + strLinkOptions; + } + else + { + returnValue = CtlValueBox.SelectedValue; + } + return returnValue; + } + set + { + if (IsNotAListOfValues) + { + CtlUrl.Url = UrlUtil.StripURL(value); + ValueIsSet = true; + } + else + { + try + { + CtlValueBox.SelectedValue = value; + ValueIsSet = true; + } + catch + { + } + } + } + + } + + } + + #endregion + + #region DataType + + /// ----------------------------------------------------------------------------- + /// + /// MetaData and Formating for DataType "Url" + /// + /// ----------------------------------------------------------------------------- + public class DataTypeUserLink : DataType, IUserSource, IEmailAdressSource + { + public override string Name + { + get { return "UserLink"; } + } + + readonly FieldSettingType[] _fieldSettingTypes = new[] + { + new FieldSettingType {Key = "ShowUserName", Section = "List", SystemType = "Boolean"}, + new FieldSettingType {Key = "TokenText", Section = "List", SystemType = "String"}, + new FieldSettingType {Key = "OpenInNewWindow", Section = "List", SystemType = "Boolean"} + }; + public override IEnumerable FieldSettingTypes { get { return _fieldSettingTypes; }} + + struct FieldSetting + { + public string Title; + public string TokenText; + public bool ShowUserName; + public bool OpenInNewWindow; + } + + public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript) + { + if (ds != null) + { + var fields = new ArrayList(); + var tableData = ds.Tables[DataSetTableName.Data]; + var tokenReplace = new TokenReplace {ModuleId = moduleId}; + foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) + { + if (row[FieldsTableColumn.Type].ToString() == Name) + { + var fieldId = (int)row[FieldsTableColumn.Id]; + var field = new FieldSetting + { + Title = row[FieldsTableColumn.Title].ToString(), + TokenText = GetFieldSetting("TokenText", fieldId, ds).AsString(), + ShowUserName = GetFieldSetting("ShowUserName", fieldId, ds).AsBoolean(), + OpenInNewWindow = GetFieldSetting("OpenInNewWindow", fieldId, ds).AsBoolean() + + }; + fields.Add(field); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Url,typeof (string))); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Original,typeof (string))); + tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Caption,typeof (string))); + } + } + + if (fields.Count > 0) + { + PortalSettings portalSettings = null; + if (HttpContext.Current != null) + { + portalSettings = PortalController.GetCurrentPortalSettings(); + } + var mc = new ModuleController(); + var settings = mc.GetModuleSettings(moduleId); + + foreach (DataRow row in tableData.Rows) + { + foreach (FieldSetting field in fields) + { + var strFieldvalue = string.Empty; + //Link showed to the user + var link = row[field.Title].ToString(); + + + //set caption: + var caption = field.TokenText; + var url = string.Empty; + //Link readable by browsers + + link = UrlUtil.StripURL(link); + if (link != string.Empty) //valid link + { + //var isLink = true; + var intUser = Convert.ToInt32(-1); + if (link.Like( "userid=*") && portalSettings != null) + { + try + { + intUser = int.Parse(link.Substring(7)); + tokenReplace.User = new UserController().GetUser(portalSettings.PortalId, + intUser); + } + catch + { + } + } + if (intUser == -1) + { + tokenReplace.User = new UserInfo {Username = "???"}; + } + + + if (caption == string.Empty) + { + caption = field.ShowUserName ? "[User:DisplayName]" : "[User:UserName]"; + } + + caption = tokenReplace.ReplaceEnvironmentTokens(caption, row); + if (caption == string.Empty) //DisplayName empty + { + caption = tokenReplace.ReplaceEnvironmentTokens("[User:username]"); + } + + url = + HttpUtility.HtmlEncode(Globals.LinkClick(link, portalSettings.ActiveTab.TabID, + moduleId)); + + strFieldvalue = string.Format("{1}", + url, + caption, + (field.OpenInNewWindow ? " target=\"_blank\"" : "")); + + } + row[field.Title] = strFieldvalue; + row[field.Title + DataTableColumn.Appendix_Original] = link; + row[field.Title + DataTableColumn.Appendix_Url] = url; + row[field.Title + DataTableColumn.Appendix_Caption] = caption; + } + } + } + } + } + + public override string SupportedCasts + { + get { return string.Format("{0}|UserLink", base.SupportedCasts); } + } + + public override bool SupportsDefaultValue + { + get { return true; } + } + + public override bool SupportsEditing + { + get { return true; } + } + + public override bool SupportsInputSettings + { + get { return true; } + } + + + public override bool SupportsSearch + { + get { return true; } + } + + public UserInfo GetUser(string fieldName, DataRow row) + { + var strUserid = (row.Table.Columns.Contains(fieldName + DataTableColumn.Appendix_Original) + ? row[fieldName + DataTableColumn.Appendix_Original] + : row[fieldName]).AsString(); + if (strUserid != string.Empty) + { + var userInfo = new UserController().GetUser(Globals.GetPortalSettings().PortalId, + int.Parse(strUserid.Substring(7))); + return userInfo; + } + return null; + } + + public string GetEmailAddress(string fieldName, DataRow row) + { + return GetAddress(fieldName, row); + } + + public string GetAddress(string fieldName, DataRow row) + { + return GetUser(fieldName, row).Email; + } + } + + #endregion + } diff --git a/Default.ascx.cs b/Default.ascx.cs new file mode 100644 index 0000000..6936961 --- /dev/null +++ b/Default.ascx.cs @@ -0,0 +1,136 @@ +using System; +using System.IO; +using DotNetNuke.Entities.Icons; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Modules.Actions; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Security; +using DotNetNuke.Services.Localization; + + +namespace DotNetNuke.Modules.UserDefinedTable +{ + public partial class Default : PortalModuleBase, IActionable + { + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + InitViews(); + } + + + void InitViews() + { + var sec = new ModuleSecurity(ModuleId, TabId, new Components.Settings(Settings)); + + switch (ModuleContext.Settings[SettingName.ListOrForm].AsString("Unknown")) + { + case "List": + LoadControlByKey("List"); + break; + case "Form": + if (Request.QueryString["show"].AsString() == "records" && sec.IsAllowedToViewList()) + { + LoadControlByKey("List"); + } + else + { + LoadControlByKey("Edit"); + } + break; + + case "FormAndList": + LoadControlByKey("Edit"); + if (sec.IsAllowedToViewList()) + { + LoadControlByKey("List"); + } + break; + case "ListAndForm": + if (sec.IsAllowedToViewList()) + { + LoadControlByKey("List"); + } + LoadControlByKey("Edit"); + break; + default: + LoadControlByKey(IsNewModuleInstance() ? "TemplateList" : "List"); + break; + } + } + + public bool IsNewModuleInstance() + { + var settings = ModuleContext.Settings; + var mc = new ModuleController(); + var minSettings = 0; + if (settings.ContainsKey(SettingName.ExcludeFromSearch)) minSettings++; + if (settings.ContainsKey(SettingName.CalculatedColumnsRenderExpressionInForm)) minSettings++; + if (settings.ContainsKey(SettingName.UseButtonsInForm)) minSettings++; + + if (settings.Count > minSettings) return false; + mc.UpdateModuleSetting( ModuleId,SettingName.UseButtonsInForm, bool.TrueString ); + mc.UpdateModuleSetting(ModuleId, SettingName.ExcludeFromSearch, bool.TrueString); + mc.UpdateModuleSetting(ModuleId, SettingName.CalculatedColumnsRenderExpressionInForm, bool.TrueString); + return true; + } + + void LoadControlByKey(string controlKey) + { + var moduleToLoad = ModuleControlController.GetModuleControlByControlKey(controlKey, + ModuleContext.Configuration. + ModuleDefID); + if (moduleToLoad != null) + { + var controlSrc = string.Format("~/{0}", moduleToLoad.ControlSrc); + var view = (PortalModuleBase) (LoadControl(controlSrc)); + view.ID = Path.GetFileNameWithoutExtension(controlSrc); + view.ModuleContext.Configuration = ModuleContext.Configuration; + PlaceHolderControl.Controls.Add(view); + } + } + + + + public ModuleActionCollection ModuleActions + { + get + { + var viewType = ModuleContext.Settings[SettingName.ListOrForm].AsString("Undefined"); + var actions = new ModuleActionCollection(); + foreach (var view in PlaceHolderControl.Controls ) + { + if ((view) is IActionable) + { + var viewactions = ((IActionable) view).ModuleActions; + foreach (ModuleAction action in viewactions) + { + action.ID = GetNextActionID(); + actions.Add(action); + } + } + } + actions.Add(GetNextActionID(), + Localization.GetString(ModuleActionType.ContentOptions, LocalResourceFile), + ModuleActionType.ModuleSettings, "", "settings.gif", EditUrl("Manage"), false, + SecurityAccessLevel.Edit, true, false); + if (viewType != "Undefined") + { + actions.Add(GetNextActionID(), Localization.GetString("CreateTemplate.Action", LocalResourceFile), + "CreateTemplate", "", Utilities.IconURL("Save"), EditUrl("CreateTemplate"), + false, SecurityAccessLevel.Admin, true, false); + } + + actions.Add(GetNextActionID(), Localization.GetString("ExportCSV.Action", LocalResourceFile), + ModuleActionType.ExportModule, "", ResolveUrl("~/images/action_export.gif"), + EditUrl("", "", "ExportCSV", "moduleid=" + ModuleId), false, + SecurityAccessLevel.Edit, true, false); + actions.Add(GetNextActionID(), Localization.GetString("ImportCSV.Action", LocalResourceFile), + ModuleActionType.ImportModule, "", ResolveUrl("~/images/action_import.gif"), + EditUrl("", "", "ImportCSV", "moduleid=" + ModuleId), false, + SecurityAccessLevel.Edit, true, false); + return actions; + } + } + } +} \ No newline at end of file diff --git a/Default.ascx.designer.cs b/Default.ascx.designer.cs new file mode 100644 index 0000000..470f51e --- /dev/null +++ b/Default.ascx.designer.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable { + + + public partial class Default { + + /// + /// PlaceHolderControl control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl PlaceHolderControl; + } +} diff --git a/ExportCSV.ascx b/ExportCSV.ascx new file mode 100644 index 0000000..f1674d0 --- /dev/null +++ b/ExportCSV.ascx @@ -0,0 +1,30 @@ +<%@ Control Language="C#" CodeBehind="ExportCSV.ascx.cs" Inherits="DotNetNuke.Modules.UserDefinedTable.ExportCsv" AutoEventWireup="false" %> +<%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %> +
+
+ + +
+
+ + +
+
+ + + + + +
+
    +
  • +
  • +
  • +
  • +
+ +
\ No newline at end of file diff --git a/ExportCSV.ascx.cs b/ExportCSV.ascx.cs new file mode 100644 index 0000000..4e5e1dd --- /dev/null +++ b/ExportCSV.ascx.cs @@ -0,0 +1,219 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.IO; +using System.Linq; +using System.Text; +using System.Web.UI.WebControls; +using DotNetNuke.Common; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Modules.UserDefinedTable.CSV; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Services.Exceptions; +using DotNetNuke.Services.FileSystem; +using DotNetNuke.Services.Localization; +using DotNetNuke.UI.Skins.Controls; + + +namespace DotNetNuke.Modules.UserDefinedTable +{ + public partial class ExportCsv : PortalModuleBase + { + #region Private Members + + int _moduleId = Convert.ToInt32(- 1); + + #endregion + + #region Event Handlers + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + cmdCancel.Click += cmdCancel_Click; + cmdExport.Click += cmdExport_Click; + Load += Page_Load; + } + void Page_Load(object sender, EventArgs e) + { + try + { + if (Request.QueryString["moduleid"] != null) + { + _moduleId = int.Parse(Request.QueryString["moduleid"]); + } + + if (! Page.IsPostBack) + { + cboFolders.Items.Insert(0, + new ListItem( + string.Format("<{0}>", Localization.GetString("None_Specified")), "-")); + var folders = FolderManager.Instance.GetFolders(UserInfo, "READ, WRITE"); + foreach (FolderInfo folder in folders) + { + var folderItem = new ListItem + { + Text = folder.FolderPath == Null.NullString + ? Localization.GetString("Root", LocalResourceFile) + : folder.FolderPath, + Value = folder.FolderPath + }; + cboFolders.Items.Add(folderItem); + } + + var moduleController = new ModuleController(); + var objModule = moduleController.GetModule(_moduleId, TabId, false); + if (objModule != null) + { + txtFile.Text = CleanName(objModule.ModuleTitle); + } + } + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + void cmdCancel_Click(object sender, EventArgs e) + { + try + { + Response.Redirect(Globals.NavigateURL(), true); + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + void cmdExport_Click(object sender, EventArgs e) + { + try + { + if (cboFolders.SelectedIndex != 0 && txtFile.Text != "") + { + var strFile = CleanName(string.Format("{0}.csv", txtFile.Text)); + var strMessage = ExportModule(_moduleId, strFile, cboFolders.SelectedItem.Value, + rblDelimiter.SelectedValue); + if (strMessage == "") + { + Response.Redirect(Globals.NavigateURL(), true); + } + else + { + UI.Skins.Skin.AddModuleMessage(this, strMessage, ModuleMessage.ModuleMessageType.RedError); + } + } + else + { + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("Validation", LocalResourceFile), + ModuleMessage.ModuleMessageType.RedError); + } + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + #endregion + + #region Private Methods + + string ExportModule(int moduleId, string fileName, string folder, string delimiter) + { + var strMessage = ""; + + var moduleController = new ModuleController(); + var moduleInfo = moduleController.GetModule(moduleId, TabId, false); + var extension = Path.GetExtension(fileName); + if (extension != null && (extension.ToUpper() == ".CSV" && moduleInfo != null)) + { + + + try + { + ExportData(folder, fileName , delimiter); + } + catch (Exception ex) + { + strMessage = string.Format("Error occurred: {0}", ex.Message); + } + } + + return strMessage; + } + + static string CleanName(string name) + { + var strName = name; + + var badChars = Path.GetInvalidPathChars(); + + return badChars.Aggregate(strName, (current, badChar) => current.Replace(badChar.ToString(), "")); + } + + void ExportData(string folder, string strFileName, string delimiter) + { + var ds = new UserDefinedTableController(_moduleId, TabId, UserInfo).GetDataSet(true); + var data = ds.Tables[0]; + var fields = ds.Tables[1]; + + WriteData(data, fields, folder, strFileName, delimiter); + } + + void WriteData(DataTable data, DataTable fields, string folder, string fileName, string delimiter) + { + + using (var sw = new StringWriter()) + { + var columns = new List(); + //Writing top line with column names + foreach (DataRow row in fields.Rows) + { + var typeName = (row[FieldsTableColumn.Type].ToString()); + //ignore system fields + if (DataType.ByName(typeName).IsUserDefinedField) + { + columns.Add(row[FieldsTableColumn.Title].ToString()); + } + } + + //write colums name as first line + CSVWriter.WriteCSV(columns.ToArray(), sw, delimiter); + + //writing data + foreach (DataRow row in data.Rows) + { + var values = new List(); + //getting values for all colums + foreach (var fieldTitle in columns) + { + var valueName = ((data.Columns.Contains(fieldTitle + DataTableColumn.Appendix_Original)) + ? fieldTitle + DataTableColumn.Appendix_Original + : fieldTitle); + var value = row[valueName].AsString(); + values.Add(value); + } + CSVWriter.WriteCSV(values.ToArray(), sw, delimiter); + + } + WriteFile(folder, fileName, sw); + } + } + + void WriteFile(string folder, string fileName, StringWriter sw) + { + using (var memStream = new MemoryStream()) + { + var bytes = Encoding.UTF8.GetBytes(sw.ToString()); + memStream.Write(bytes, 0, bytes.Length); + var f = FolderManager.Instance.GetFolder(PortalId, folder); + FileManager.Instance.AddFile(f, fileName, memStream, true); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/ExportCSV.ascx.designer.cs b/ExportCSV.ascx.designer.cs new file mode 100644 index 0000000..23b2bc0 --- /dev/null +++ b/ExportCSV.ascx.designer.cs @@ -0,0 +1,87 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable { + + + public partial class ExportCsv { + + /// + /// plFolder control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plFolder; + + /// + /// cboFolders control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList cboFolders; + + /// + /// plFile control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plFile; + + /// + /// txtFile control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtFile; + + /// + /// plDelimiter control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plDelimiter; + + /// + /// rblDelimiter control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.RadioButtonList rblDelimiter; + + /// + /// cmdExport control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdExport; + + /// + /// cmdCancel control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdCancel; + } +} diff --git a/FieldEditor.ascx b/FieldEditor.ascx new file mode 100644 index 0000000..33fcfa3 --- /dev/null +++ b/FieldEditor.ascx @@ -0,0 +1,3 @@ +<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FieldEditor.ascx.cs" Inherits="DotNetNuke.Modules.UserDefinedTable.FieldEditor" %> +<%@ Register src="Controls/Field.ascx" tagname="Field" tagprefix="fnl" %> + \ No newline at end of file diff --git a/FieldEditor.ascx.cs b/FieldEditor.ascx.cs new file mode 100644 index 0000000..6150728 --- /dev/null +++ b/FieldEditor.ascx.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.UI.Modules; + +namespace DotNetNuke.Modules.UserDefinedTable +{ + public partial class FieldEditor : ModuleUserControlBase + { + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + Field.HideField += Field_HideField; + var fieldId = Request.QueryString["fieldId"]; + var fields = FieldController.GetFieldsTable(ModuleContext.ModuleId, fieldId=="-1" ); + var filter = string.Format("{0}={1}", FieldsTableColumn.Id, fieldId); + Field.DataSource = new DataView(fields, filter, "", DataViewRowState.CurrentRows)[0]; + var fieldSettings = FieldSettingsController.GetFieldSettingsTable(ModuleContext.ModuleId); + Field.Settings = fieldSettings; + Field.Bind(); + Field.Visible = true; + Field.LocalizeString = LocalizeString; + Field.ModuleContext = ModuleContext; + + } + + + void Field_HideField() + { + Response.Redirect(ModuleContext.EditUrl("Manage")); + } + } +} \ No newline at end of file diff --git a/FieldEditor.ascx.designer.cs b/FieldEditor.ascx.designer.cs new file mode 100644 index 0000000..5411088 --- /dev/null +++ b/FieldEditor.ascx.designer.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable { + + + public partial class FieldEditor { + + /// + /// Field control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.Modules.UserDefinedTable.Controls.Field Field; + } +} diff --git a/Form.ascx.cs b/Form.ascx.cs new file mode 100644 index 0000000..6e7c583 --- /dev/null +++ b/Form.ascx.cs @@ -0,0 +1,574 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Web.UI; +using System.Web.UI.HtmlControls; +using System.Web.UI.WebControls; +using System.Xml; +using DotNetNuke.Entities.Icons; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Modules.Actions; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Modules.UserDefinedTable.Interfaces; +using DotNetNuke.Security; +using DotNetNuke.Services.Exceptions; +using DotNetNuke.Services.Localization; +using DotNetNuke.UI.Skins.Controls; +using DotNetNuke.UI.Utilities; +using DotNetNuke.UI.WebControls; +using Globals = DotNetNuke.Common.Globals; + +namespace DotNetNuke.Modules.UserDefinedTable +{ + public partial class EditForm : PortalModuleBase, IActionable, IFormEvents + { + + EditControls _editControls; + int _userDefinedRowId; + CaptchaControl _ctlCaptcha; + bool _hasUpdatePermission; + bool _hasDeletePermission; + + readonly IDictionary _labelcontrols= new Dictionary(); + readonly IDictionary _propertylabelcontrols = new Dictionary(); + UserDefinedTableController _udtController; + UserDefinedTableController UdtController + { + get { return _udtController ?? (_udtController = new UserDefinedTableController(ModuleContext)); } + } + + DataSet _data; + DataSet Data + { + get + { + if (_data == null) + { + if (! int.TryParse(Request.QueryString[DataTableColumn.RowId], out _userDefinedRowId)) + { + _userDefinedRowId = Convert.ToInt32(- 1); + } + _data = UdtController.GetRow(_userDefinedRowId); + } + return _data; + } + } + + DataRow CurrentRow + { + get + { + if (Data.Tables[DataSetTableName.Data].Rows.Count == 0) + { + var r = Data.Tables[DataSetTableName.Data].NewRow(); + r[DataTableColumn.RowId] = _userDefinedRowId; + Data.Tables[DataSetTableName.Data].Rows.Add(r); + } + return Data.Tables[DataSetTableName.Data].Rows[0]; + } + } + + Components.Settings _settings; + new Components.Settings Settings + { get { return _settings ?? (_settings = new Components.Settings(ModuleContext.Settings)); } } + + + bool IsNewRow + { + get { return _userDefinedRowId == - 1; } + } + + #region Private Methods + + + void BuildCssForm (IEnumerable editForm) + { + EditFormPlaceholder.Visible = true; + Control currentContainer = EditFormPlaceholder; + foreach (var currentField in editForm) + { + if (currentField.IsCollapsible) + { + EditFormPlaceholder.Controls.Add(GetSeparatorFormPattern(currentField.Title, true)); + var fieldset = new HtmlGenericControl("fieldset"); + currentContainer = fieldset; + fieldset.Visible = currentField.Visible; + EditFormPlaceholder.Controls.Add(currentContainer); + } + else if (currentField.IsSeparator && currentField.Visible) + { + + EditFormPlaceholder.Controls.Add(GetSeparatorFormPattern(currentField.Title)); + currentContainer = EditFormPlaceholder; + } + else + { + var divFormItem = new HtmlGenericControl("div"); + divFormItem.Attributes.Add("class", string.Format("dnnFormItem")); + divFormItem.Controls.Add(GetLabel(currentField.Title, currentField.Help, currentField.EditControl)); + if (currentField.EditControl != null) + { + divFormItem.Controls.Add(currentField.EditControl); + } + divFormItem.Visible = currentField.Visible; + if (!currentField.IsUserDefinedField) currentContainer = EditFormPlaceholder; + currentContainer.Controls.Add(divFormItem); + } + } + } + + + Control GetLabel(string title, string help, Control editcontrol) + { + + if (help == string.Empty) + { + var l = new Label + { + Text = string.Format("{0}", title), + AssociatedControlID = editcontrol.ID + }; + + var d = new HtmlGenericControl("div"); + d.Attributes.Add("class", "dnnFormLabelWithoutHelp"); + d.Controls.Add(l); + + _labelcontrols.Add(l, editcontrol); + return d; + } + var label = new PropertyLabelControl + { + ID = string.Format("{0}_label", XmlConvert.EncodeName(title)), + Caption = title, + HelpText = help, + EditControl = editcontrol, + }; + _propertylabelcontrols.Add(label, editcontrol); + return label; + } + + static Control GetSeparatorFormPattern(string title, bool expendable=false) + { + return title == string.Empty + ? new LiteralControl("

") + : (expendable + ? new LiteralControl(string.Format("

{0}

", title)) + : new LiteralControl(string.Format("

{0}

", title))); + } + void CheckPermission(bool isUsersOwnItem = true) + { + var security = new ModuleSecurity(ModuleContext); + if ( + !((! IsNewRow && security.IsAllowedToEditRow(isUsersOwnItem)) || + (IsNewRow && security.IsAllowedToAddRow() && (security.IsAllowedToAdministrateModule() || HasAddPermissonByQuota() )))) + { + if (IsNested()) + { + cmdUpdate.Enabled = false; + + divForm.Visible = true; + } + else + { + Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); + } + } + else + { + _hasUpdatePermission = true; + } + _hasDeletePermission = Convert.ToBoolean(security.IsAllowedToDeleteRow(isUsersOwnItem) && ! IsNewRow); + cmdDelete.Visible = _hasDeletePermission; + } + + bool IsNested() + { + return (Parent.Parent ) is PortalModuleBase; + } + + bool HasAddPermissonByQuota() + { + var userquota = Settings.UserRecordQuota ; + if (userquota > 0 && Request.IsAuthenticated ) + { + var ds = UdtController.GetDataSet(false); + return ModuleSecurity.HasAddPermissonByQuota(ds.Tables[DataSetTableName.Fields], + ds.Tables[DataSetTableName.Data], userquota, + UserInfo.GetSafeUsername()); + } + return true; + } + + void CheckPermission(string createdBy) + { + CheckPermission(ModuleContext.PortalSettings.UserInfo.Username == createdBy && + createdBy != Definition.NameOfAnonymousUser); + } + + bool CaptchaNeeded() + { + return ModuleContext.PortalSettings.UserId == - 1 && Settings.ForceCaptchaForAnonymous ; + } + + void ShowUponSubmit() + { + var message = new HtmlGenericControl("div") + {InnerHtml = Settings.SubmissionText }; + message.Attributes["class"] = "dnnFormMessage dnnFormSuccess"; + MessagePlaceholder. Controls.Add(message); + } + + void BuildEditForm() + { + var fieldSettingsTable = FieldSettingsController.GetFieldSettingsTable(ModuleId); + var editForm = new List(); + FormColumnInfo currentField; + var security = new ModuleSecurity(ModuleContext); + + _editControls = new EditControls(ModuleContext); + + foreach (DataRow dr in Data.Tables[DataSetTableName.Fields].Rows) + { + var fieldTitle = dr[FieldsTableColumn.Title].AsString(); + var dataTypeName = dr[FieldsTableColumn.Type].AsString(); + var dataType = DataType.ByName(dataTypeName); + + var isColumnEditable = + Convert.ToBoolean((! dataType.SupportsHideOnEdit || + Convert.ToBoolean(dr[FieldsTableColumn.ShowOnEdit])) && + (! Convert.ToBoolean(dr[FieldsTableColumn.IsPrivate]) || + security.IsAllowedToEditAllColumns())); + + //If Column is hidden, the Fieldtype falls back to "String" as the related EditControl works perfect even if it is not visibile + //EditControls of other user defined datatypes may use core controls (e.g. UrlControl or RTE) which are not rock solid regarding viewstate. + if (! isColumnEditable && dataType.IsUserDefinedField) + { + dataTypeName = "String"; + } + + currentField = new FormColumnInfo {IsUserDefinedField = dataType.IsUserDefinedField}; + + if (dataType.IsSeparator) + { + var fieldId = (int)dr[FieldsTableColumn.Id]; + currentField.IsCollapsible = Data.Tables[DataSetTableName.FieldSettings].GetFieldSetting("IsCollapsible", fieldId).AsBoolean(); + currentField.IsSeparator = true; + if (dr[FieldsTableColumn.Visible].AsBoolean()) + { + currentField.Title = fieldTitle; + } + currentField.Visible = isColumnEditable; + } + else + { + currentField.Help = dr[FieldsTableColumn.HelpText].AsString(); + currentField.Title = dr[FieldsTableColumn.Title].AsString(); + currentField.Required = + Convert.ToBoolean(dr[FieldsTableColumn.Required].AsBoolean() && + dataType.IsUserDefinedField); + + //advanced Settings: Dynamic control + currentField.EditControl = _editControls.Add(dr[FieldsTableColumn.Title].AsString(), + dataTypeName, Convert.ToInt32(dr[FieldsTableColumn.Id]), + dr[FieldsTableColumn.HelpText].AsString(), + dr[FieldsTableColumn.Default].AsString(), + dr[FieldsTableColumn.Required].AsBoolean(), + dr[FieldsTableColumn.ValidationRule].AsString(), + dr[FieldsTableColumn.ValidationMessage].AsString(), + dr[FieldsTableColumn.EditStyle].AsString(), + dr[FieldsTableColumn.InputSettings].AsString(), + dr[FieldsTableColumn.OutputSettings].AsString(), + dr[FieldsTableColumn.NormalizeFlag].AsBoolean(), + dr[FieldsTableColumn.MultipleValues].AsBoolean(), + fieldSettingsTable, + this ); + currentField.Visible = isColumnEditable; + } + editForm.Add(currentField); + } + + if (CaptchaNeeded()) + { + _ctlCaptcha = new CaptchaControl + { + ID = "Captcha", + CaptchaWidth = Unit.Pixel(130), + CaptchaHeight = Unit.Pixel(40), + ToolTip = Localization.GetString("CaptchaToolTip", LocalResourceFile), + ErrorMessage = Localization.GetString("CaptchaError", LocalResourceFile) + }; + currentField = new FormColumnInfo + { + Title = Localization.GetString("Captcha", LocalResourceFile), + EditControl = _ctlCaptcha, + Visible = true, + IsUserDefinedField = false + }; + editForm.Add(currentField); + } + BuildCssForm(editForm); + //Change captions of buttons in Form mode + if (IsNewRow && Settings.ListOrForm.Contains("Form")) + { + cmdUpdate.Attributes["resourcekey"] = "cmdSend.Text"; + } + } + + #endregion + + #region Event Handlers + + + protected override void OnInit(EventArgs e) + { + Page.RegisterRequiresViewStateEncryption(); + BuildEditForm(); + cmdCancel.Click += cmdCancel_Click; + cmdDelete.Click += cmdDelete_Click; + cmdUpdate.Click += cmdUpdate_Click; + + Load += Page_Load; + PreRender += EditForm_PreRender; + } + + void EditForm_PreRender(object sender, EventArgs e) + { + foreach (var labelcontrol in _labelcontrols) + { + var label = labelcontrol.Key; + var control = (EditControl) labelcontrol.Value; + if (control.ValueControl != null) label.AssociatedControlID = control.ValueControl.ID; + } + foreach(var labelcontrol in _propertylabelcontrols ) + { + var label = labelcontrol.Key; + var control = labelcontrol.Value as EditControl ; + if (control!=null && control.ValueControl != null) label.EditControl = control.ValueControl; + } + } + + void Page_Load(object sender, EventArgs e) + { + try + { + + + if (Page.IsPostBack == false) + { + EnsureActionButton(); + ClientAPI.AddButtonConfirm(cmdDelete, Localization.GetString("DeleteItem", LocalResourceFile)); + } + + if (! IsNewRow) + { + if (! Page.IsPostBack) + { + //Clear all default values + foreach (var edit in _editControls.Values) + { + edit.Value = ""; + } + } + foreach (DataRow field in Data.Tables[DataSetTableName.Fields].Rows) + { + var dataTypeName = field[FieldsTableColumn.Type].AsString(); + var dataType = DataType.ByName(dataTypeName); + var value = CurrentRow[field[FieldsTableColumn.Title].ToString()].ToString(); + if (! dataType.IsSeparator) + { + if (! Page.IsPostBack) + { + _editControls[field[FieldsTableColumn.Title].ToString()].Value = value; + } + if (field[FieldsTableColumn.Type].ToString() == "CreatedBy") + { + CheckPermission(value); + } + } + } + } + else //New Entry + { + //Default Values already have been set in BuildEditForms + cmdDelete.Visible = false; + CheckPermission(); + if (! Page.IsPostBack && Request.QueryString["OnSubmit"].AsInt() == ModuleContext.ModuleId) + { + ShowUponSubmit(); + } + } + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + CheckPermission(false); + } + } + + void cmdCancel_Click(object sender, EventArgs e) + { + try + { + if (Settings.ListOrForm.Contains("Form") && IsNewRow ) + { + Response.Redirect(Request.RawUrl); + } + else + { + Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); + } + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + void cmdUpdate_Click(object sender, EventArgs e) + { + if (_hasUpdatePermission) + { + try + { + //warning message of validation has failed + var warningMessage = string.Empty; + warningMessage = _editControls.Values.Where(edit => ! edit.IsValid()) + .Aggregate(warningMessage, + (current, edit) => current + string.Format( + "
  • {0}
    {1}
  • ", + edit.FieldTitle, + edit.ValidationMessage)); + if (CaptchaNeeded() && ! _ctlCaptcha.IsValid) + { + warningMessage += string.Format("
  • {0}
    {1}
  • ", + Localization.GetString("Captcha.Text", LocalResourceFile), + Localization.GetString("CaptchaError.Text", LocalResourceFile)); + } + + if (warningMessage == string.Empty) + { + //'Save values for every field separately + foreach (var edit in _editControls.Values) + { + var value = edit.Value; + CurrentRow[edit.FieldTitle] = value; + } + + UdtController.UpdateRow(Data); + RecordUpdated(); + + switch (Settings.ListOrForm) + { + case "List": + Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); + break; + case "FormAndList": + case "ListAndForm": + var url = IsNewRow + ? Request.RawUrl + : Globals.NavigateURL(ModuleContext.TabId); + Response.Redirect(url, + true); + break; + case "Form": + switch (Settings.UponSubmitAction ) + { + case "Text": + divForm.Visible = false; + ShowUponSubmit(); + break; + case "Form": + Response.Redirect( + Globals.NavigateURL(ModuleContext.TabId, "", + string.Format("OnSubmit={0}", ModuleId)), true); + break; + default: + var strRedirectUrl = Settings.UponSubmitRedirect ?? Globals.NavigateURL(ModuleContext.TabId); + Response.Redirect(Globals.LinkClick(strRedirectUrl, ModuleContext.TabId, + ModuleContext.ModuleId)); + break; + } + break; + } + } + else + { + var moduleControl = (PortalModuleBase) (((Parent.Parent) is PortalModuleBase) ? Parent.Parent : this); + UI.Skins.Skin.AddModuleMessage(moduleControl, string.Format("
      {0}
    ", warningMessage), + ModuleMessage.ModuleMessageType.RedError); + } + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + } + + void cmdDelete_Click(object sender, EventArgs e) + { + if (_hasDeletePermission) + { + try + { + UdtController.DeleteRow(_userDefinedRowId); + RecordDeleted(); + Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + } + + #endregion + + #region Optional Interfaces + public void EnsureActionButton() + { + var useButtons = Settings.UseButtonsInForm; + var sec = new ModuleSecurity(ModuleId, TabId, Settings ); + if (sec.IsAllowedToViewList() && Settings.OnlyFormIsShown ) + { + var url = Globals.NavigateURL(TabId, "", "show=records"); + var title = Localization.GetString("List.Action", LocalResourceFile); + cmdShowRecords.NavigateUrl = url; + cmdShowRecords.Text = title; + cmdShowRecords.Visible = useButtons; + } + + } + + /// ----------------------------------------------------------------------------- + /// + /// Add the "ManageUDT" link to the current action list. + /// + /// ModuleActionCollection + /// ----------------------------------------------------------------------------- + public ModuleActionCollection ModuleActions + { + get + { + var useButtons = Settings.UseButtonsInForm; + var cmdName = useButtons ? "" : ModuleActionType.AddContent; + var actions = new ModuleActionCollection(); + var sec = new ModuleSecurity(ModuleId, TabId,Settings ); + if (sec.IsAllowedToViewList() && Settings.OnlyFormIsShown ) + { + var url = Globals.NavigateURL(TabId, "", "show=records"); + var title = Localization.GetString("List.Action", LocalResourceFile); + actions.Add(ModuleContext.GetNextActionID(), + title,cmdName, + "", Utilities.IconURL("View"), url, false, SecurityAccessLevel.View, true, false); + } + return actions; + } + } + public event Action RecordUpdated = delegate { }; + public event Action RecordDeleted = delegate { }; + #endregion + + } +} \ No newline at end of file diff --git a/Form.ascx.designer.cs b/Form.ascx.designer.cs new file mode 100644 index 0000000..b196708 --- /dev/null +++ b/Form.ascx.designer.cs @@ -0,0 +1,78 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable { + + + public partial class EditForm { + + /// + /// divForm control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl divForm; + + /// + /// EditFormPlaceholder control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl EditFormPlaceholder; + + /// + /// cmdUpdate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdUpdate; + + /// + /// cmdCancel control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdCancel; + + /// + /// cmdDelete control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdDelete; + + /// + /// cmdShowRecords control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink cmdShowRecords; + + /// + /// MessagePlaceholder control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl MessagePlaceholder; + } +} diff --git a/FormAndList.csproj b/FormAndList.csproj new file mode 100644 index 0000000..7c49fcf --- /dev/null +++ b/FormAndList.csproj @@ -0,0 +1,411 @@ + + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {DDE04CE2-57E6-4B1C-BF12-C36FCC7B7333} + {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + DotNetNuke.Modules.UserDefinedTable + DotNetNuke.Modules.UserDefinedTable + v3.5 + On + Binary + On + On + + + + + + + + + + + 4.0 + + + + + + true + full + true + true + ..\..\bin\ + DotNetNuke.Modules.UserDefinedTable.xml + 1591,660,661 + AllRules.ruleset + + + pdbonly + false + true + true + ..\..\bin\ + DotNetNuke.Modules.UserDefinedTable.xml + 1591,660,661 + AllRules.ruleset + + + + ..\..\lib\DotNetNuke.dll + False + + + False + ..\..\lib\DotNetNuke.Web.dll + False + + + False + ..\..\lib\DotNetNuke.Web.Client.dll + False + + + ..\..\lib\DotNetNuke.WebUtility.dll + False + + + ..\..\lib\Microsoft.ApplicationBlocks.Data.dll + + + + + + + + + + + + + + + + + False + ..\..\lib\Telerik.Web.UI.dll + False + + + + + + + + + + + + + + + + + + + + + + + + + + + Field.ascx + ASPXCodeBehind + + + Field.ascx + + + Fields.ascx + ASPXCodeBehind + + + Fields.ascx + + + FieldSettings.ascx + ASPXCodeBehind + + + FieldSettings.ascx + + + + + + + ExportCSV.ascx + + + ExportCSV.ascx + ASPXCodeBehind + + + FieldEditor.ascx + ASPXCodeBehind + + + FieldEditor.ascx + + + ImportCSV.ascx + + + ImportCSV.ascx + ASPXCodeBehind + + + + + + + MakeThumbnail.ashx + + + Code + + + + + + + + + + + + + + + + + + + + + + + + Default.ascx + + + Default.ascx + ASPXCodeBehind + + + Form.ascx + + + Form.ascx + ASPXCodeBehind + + + HelpPopup.aspx + + + HelpPopup.aspx + ASPXCodeBehind + + + Configuration.ascx + + + Configuration.ascx + ASPXCodeBehind + + + + + Settings.ascx + + + Settings.ascx + ASPXCodeBehind + + + ShowXml.ashx + + + Template.ascx + + + Template.ascx + ASPXCodeBehind + + + TemplateList.ascx + + + TemplateList.ascx + ASPXCodeBehind + + + + + + Token2Xsl.ascx + + + Token2Xsl.ascx + ASPXCodeBehind + + + List.ascx + + + List.ascx + ASPXCodeBehind + + + + + + Designer + + + Designer + + + Designer + + + Designer + + + Designer + + + Designer + + + Designer + + + Designer + + + Designer + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Designer + + + + + + + + + + + + + + + + + + + Designer + + + + + + + + zip + FormAndList + FormAndList + $(MSBuildProjectDirectory)\BuildScripts + + + + + + + + + + + True + + + + + + zip + FormAndList + FormAndList + $(MSBuildProjectDirectory)\BuildScripts + + + + + \ No newline at end of file diff --git a/FormAndList.dnn b/FormAndList.dnn new file mode 100644 index 0000000..3873876 --- /dev/null +++ b/FormAndList.dnn @@ -0,0 +1,297 @@ + + + + Form and List + Create a simple form or a view of repetitive and simple data. + desktopmodules/userdefinedtable/icon_fnl_32px.gif + + DotNetNuke + DotNetNuke Corporation + http://www.dotnetnuke.com + support@dotnetnuke.com + + + + + 06.01.00 + + true + + + + DesktopModules\UserDefinedTable + + + + + + + + + + + + + + + + + + + + + + + + + + DNN_UserDefinedTable + UserDefinedTable + DotNetNuke.Modules.UserDefinedTable.BusinessController, DotNetNuke.Modules.UserDefinedTable + + + + + + + Form and List + -1 + + + + DesktopModules/UserDefinedTable/Default.ascx + False + + View + + http://www.dotnetnuke.com/default.aspx?tabid=787 + False + 0 + + + CreateTemplate + DesktopModules/UserDefinedTable/Template.ascx + True + + Admin + + + False + 0 + + + Edit + DesktopModules/UserDefinedTable/Form.ascx + False + Edit User Defined Table + Anonymous + + http://www.dotnetnuke.com/default.aspx?tabid=787 + False + 0 + + + EditField + DesktopModules/UserdefinedTable/FieldEditor.ascx + False + + Edit + + + False + + + ExportCSV + DesktopModules/UserDefinedTable/ExportCSV.ascx + False + Export to CSV + Edit + + + False + 0 + + + GenerateXsl + DesktopModules/UserDefinedTable/Token2Xsl.ascx + False + Generate XSL + Edit + + http://www.dotnetnuke.com/default.aspx?tabid=787 + False + 0 + + + ImportCSV + DesktopModules/UserDefinedTable/ImportCSV.ascx + False + Import from CSV + Edit + + + False + 0 + + + List + DesktopModules/UserDefinedTable/List.ascx + True + + Edit + + + False + 0 + + + Manage + DesktopModules/UserdefinedTable/Configuration.ascx + False + Manage UDT + Edit + + http://www.dotnetnuke.com/default.aspx?tabid=787 + False + 0 + + + Settings + DesktopModules/UserDefinedTable/Settings.ascx + False + More Permission Settings + Admin + + http://www.dotnetnuke.com/default.aspx?tabid=787 + False + 0 + + + TemplateList + DesktopModules/UserDefinedTable/TemplateList.ascx + True + + Edit + + + False + 0 + + + + + + + + + + + + + + + + + + bin + dotnetnuke.modules.userdefinedtable.dll + + + + + + + DesktopModules/UserDefinedTable + + Resources.zip + + + + + + + \ No newline at end of file diff --git a/HelpPopup.aspx.cs b/HelpPopup.aspx.cs new file mode 100644 index 0000000..192e249 --- /dev/null +++ b/HelpPopup.aspx.cs @@ -0,0 +1,34 @@ +using System; +using System.Diagnostics; +using DotNetNuke.Framework; +using DotNetNuke.Services.Localization; + +namespace DotNetNuke.Modules.UserDefinedTable +{ + public partial class HelpPopup : PageBase + { + #region Vom Web Form Designer generierter Code + + [DebuggerStepThrough] + void InitializeComponent() + { + } + + void Page_Init(object sender, EventArgs e) + { + InitializeComponent(); + } + + #endregion + + void Page_Load(object sender, EventArgs e) + { + var content = Request.QueryString["resourcekey"]; + if (content.ToLowerInvariant() == "help_hiddencolumns" || content.ToLowerInvariant() == "help_tokens_6") + { + Title = Localization.GetString(content + "_Title", LocalResourceFile); + lblContent.Text = Localization.GetString(content + "_Body", LocalResourceFile); + } + } + } +} \ No newline at end of file diff --git a/HelpPopup.aspx.designer.cs b/HelpPopup.aspx.designer.cs new file mode 100644 index 0000000..138cda7 --- /dev/null +++ b/HelpPopup.aspx.designer.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable { + + + public partial class HelpPopup { + + /// + /// Form1 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlForm Form1; + + /// + /// lblContent control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblContent; + } +} diff --git a/ImportCSV.ascx b/ImportCSV.ascx new file mode 100644 index 0000000..53741db --- /dev/null +++ b/ImportCSV.ascx @@ -0,0 +1,32 @@ +<%@ Control Language="C#" CodeBehind="ImportCSV.ascx.cs" Inherits="DotNetNuke.Modules.UserDefinedTable.ImportCsv" AutoEventWireup="false"%> +<%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %> + + +
    +
    + + +
    +
    + + +
    +
    + + + + + +
    +
      +
    • + +
    • +
    • + +
    • +
    +
    diff --git a/ImportCSV.ascx.cs b/ImportCSV.ascx.cs new file mode 100644 index 0000000..8e5c0c6 --- /dev/null +++ b/ImportCSV.ascx.cs @@ -0,0 +1,242 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.IO; +using System.Web.UI.WebControls; +using DotNetNuke.Common; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Services.Exceptions; +using DotNetNuke.Services.FileSystem; +using DotNetNuke.Services.Localization; +using DotNetNuke.UI.Skins.Controls; +using Microsoft.VisualBasic.FileIO; +namespace DotNetNuke.Modules.UserDefinedTable +{ + public partial class ImportCsv : PortalModuleBase + { + #region Private Members + + int _moduleId = Convert.ToInt32(- 1); + + #endregion + + #region Event Handlers + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + Load += Page_Load; + cboFolders.SelectedIndexChanged += cboFolders_SelectedIndexChanged; + cmdCancel.Click += cmdCancel_Click; + cmdImport.Click += cmdImport_Click; + } + + void Page_Load(object sender, EventArgs e) + { + try + { + if (Request.QueryString["moduleid"] != null) + { + _moduleId = int.Parse(Request.QueryString["moduleid"]); + } + + if (! Page.IsPostBack) + { + cboFolders.Items.Insert(0, + new ListItem( + string.Format("<{0}>", Localization.GetString("None_Specified")), "-")); + var folders = FolderManager.Instance.GetFolders(UserInfo, "READ, WRITE"); + + foreach (var folder in folders) + { + var folderItem = new ListItem + { + Text = + folder.FolderPath == Null.NullString + ? Localization.GetString("Root", LocalResourceFile) + : folder.FolderPath, + Value = folder.FolderPath + }; + cboFolders.Items.Add(folderItem); + } + } + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + void cboFolders_SelectedIndexChanged(object sender, EventArgs e) + { + cboFiles.Items.Clear(); + if (cboFolders.SelectedIndex != 0) + { + var objModules = new ModuleController(); + var objModule = objModules.GetModule(_moduleId, TabId, false); + + if (objModule != null) + { + var arrFiles = Globals.GetFileList(PortalId, "csv", false, cboFolders.SelectedItem.Value); + + + foreach (FileItem objFile in arrFiles) + { + cboFiles.Items.Add(new ListItem(objFile.Text, objFile.Text)); + } + } + } + } + + void cmdCancel_Click(object sender, EventArgs e) + { + try + { + Response.Redirect(Globals.NavigateURL(), true); + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + void cmdImport_Click(object sender, EventArgs e) + { + try + { + if (cboFiles.SelectedItem != null) + { + var objModules = new ModuleController(); + var objModule = objModules.GetModule(_moduleId, TabId, false); + if (objModule != null) + { + var strMessage = ImportModule(_moduleId, cboFiles.SelectedItem.Value, + cboFolders.SelectedItem.Value, rblDelimiter.SelectedValue); + if (strMessage == "") + { + Response.Redirect(Globals.NavigateURL(), true); + } + else + { + UI.Skins.Skin.AddModuleMessage(this, strMessage, ModuleMessage.ModuleMessageType.RedError); + } + } + } + else + { + UI.Skins.Skin.AddModuleMessage(this, "Please specify the file to import", + ModuleMessage.ModuleMessageType.RedError); + } + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + #endregion + + #region Private Methods + + string ImportModule(int moduleId, string fileName, string folder, string delimiter) + { + var strMessage = ""; + + var mc = new ModuleController(); + var moduleInfo = mc.GetModule(moduleId, TabId, false); + + if (Path.GetExtension(fileName).ToUpper() == ".CSV" && moduleInfo != null) + { + var udtController = new UserDefinedTableController(ModuleContext ); + + var file = FileManager.Instance.GetFile(PortalId, Path.Combine(folder, fileName)); + using (var stream = FileManager.Instance.GetFileContent(file)) + { + // Open the stream and read it back. + using (var reader = new TextFieldParser(stream)) + { + reader.TextFieldType = FieldType.Delimited; + reader.SetDelimiters(delimiter); + + DataSet ds = null; + DataTable dataTable = null; + string colChangedBy = null; + string colChangedAt = null; + string colCreatedBy = null; + string colCreatedAt = null; + var obligateDataTypesCount = DataType.SystemDataTypes().Count; + + try + { + while (!reader.EndOfData) + { + var linecsv = reader.ReadFields(); + if (dataTable == null) + { + ds = CreateFields(linecsv, udtController); + dataTable = ds.Tables[DataSetTableName.Data]; + colChangedBy = udtController.ColumnNameByDataType(ds, DataTypeNames.UDT_DataType_ChangedBy); + colChangedAt = udtController.ColumnNameByDataType(ds, DataTypeNames.UDT_DataType_ChangedAt); + colCreatedBy = udtController.ColumnNameByDataType(ds, DataTypeNames.UDT_DataType_CreatedBy); + colCreatedAt = udtController.ColumnNameByDataType(ds, DataTypeNames.UDT_DataType_CreatedAt); + } + else + { + var insertTime = DateTime.Now.ToString("s"); + var newRow = dataTable.NewRow(); + newRow[DataTableColumn.RowId] = -1; + newRow[colChangedBy] = UserInfo.Username; + newRow[colCreatedBy] = UserInfo.Username; + newRow[colChangedAt] = insertTime; + newRow[colCreatedAt] = insertTime; + dataTable.Rows.Add(FillRow(linecsv, newRow, obligateDataTypesCount)); + } + } + + if (ds != null) + { + for (var rowNr = 0; rowNr <= dataTable.Rows.Count - 1; rowNr++) + { + udtController.UpdateRow(ds, rowNr, isDataToImport: true); + } + mc.UpdateModuleSetting(moduleId, SettingName.ListOrForm, "List"); + } + } + catch (Exception ex) + { + strMessage = string.Format(Localization.GetString("importError", LocalResourceFile), ex.Message); + } + } + } + + + } + + return strMessage; + } + + DataSet CreateFields(IEnumerable columns, UserDefinedTableController udtController) + { + udtController.ResetModule(); + FieldController.GetFieldsTable(ModuleId ); + foreach (var column in columns) + { + FieldController.AddField(ModuleId, column); + } + return udtController.GetRow(- 1, false); + } + + DataRow FillRow(string[] data, DataRow row, int start) + { + for (var counter = 0; counter <= data.Length - 1; counter++) + { + row[counter + start + 1] = data[counter]; + } + return row; + } + + #endregion + } +} \ No newline at end of file diff --git a/ImportCSV.ascx.designer.cs b/ImportCSV.ascx.designer.cs new file mode 100644 index 0000000..880faaf --- /dev/null +++ b/ImportCSV.ascx.designer.cs @@ -0,0 +1,87 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable { + + + public partial class ImportCsv { + + /// + /// plFolder control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plFolder; + + /// + /// cboFolders control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList cboFolders; + + /// + /// plFile control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plFile; + + /// + /// cboFiles control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList cboFiles; + + /// + /// plDelimiter control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plDelimiter; + + /// + /// rblDelimiter control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.RadioButtonList rblDelimiter; + + /// + /// cmdImport control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdImport; + + /// + /// cmdCancel control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdCancel; + } +} diff --git a/Interfaces/IEmailAdressSource.cs b/Interfaces/IEmailAdressSource.cs new file mode 100644 index 0000000..e23b1e9 --- /dev/null +++ b/Interfaces/IEmailAdressSource.cs @@ -0,0 +1,9 @@ +using System.Data; + +namespace DotNetNuke.Modules.UserDefinedTable.Interfaces +{ + public interface IEmailAdressSource + { + string GetEmailAddress(string fieldName, DataRow row); + } +} \ No newline at end of file diff --git a/Interfaces/IFormEvents.cs b/Interfaces/IFormEvents.cs new file mode 100644 index 0000000..655fa40 --- /dev/null +++ b/Interfaces/IFormEvents.cs @@ -0,0 +1,10 @@ +using System; + +namespace DotNetNuke.Modules.UserDefinedTable.Interfaces +{ + public interface IFormEvents + { + event Action RecordUpdated ; + event Action RecordDeleted ; + } +} \ No newline at end of file diff --git a/Interfaces/IPortable2.cs b/Interfaces/IPortable2.cs new file mode 100644 index 0000000..b9b020c --- /dev/null +++ b/Interfaces/IPortable2.cs @@ -0,0 +1,11 @@ +namespace DotNetNuke.Modules.UserDefinedTable.Interfaces +{ + public interface IPortable2 + { + bool ManagesModuleSettings { get; } + bool ManagesTabModuleSettings { get; } + string ExportModule(int moduleId, int tabId); + string ExportModule(int moduleId, int tabId, int maxNumberOfItems); + void ImportModule(int moduleId, int tabId, string content, string version, int userId, bool isInstance); + } +} \ No newline at end of file diff --git a/Interfaces/IUserSource.cs b/Interfaces/IUserSource.cs new file mode 100644 index 0000000..086538e --- /dev/null +++ b/Interfaces/IUserSource.cs @@ -0,0 +1,10 @@ +using System.Data; +using DotNetNuke.Entities.Users; + +namespace DotNetNuke.Modules.UserDefinedTable.Interfaces +{ + public interface IUserSource + { + UserInfo GetUser(string fieldName, DataRow row); + } +} \ No newline at end of file diff --git a/License.htm b/License.htm new file mode 100644 index 0000000..99b15ec --- /dev/null +++ b/License.htm @@ -0,0 +1,20 @@ + Copyright (c) 2012 DotNetNuke Corporation
    +
    + 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. + + diff --git a/List.ascx.cs b/List.ascx.cs new file mode 100644 index 0000000..1cb1ebe --- /dev/null +++ b/List.ascx.cs @@ -0,0 +1,1034 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Xml; +using System.Xml.Xsl; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Icons; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Modules.Actions; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Security; +using DotNetNuke.Security.Permissions; +using DotNetNuke.Services.Exceptions; +using DotNetNuke.Services.FileSystem; +using DotNetNuke.Services.Localization; +using DotNetNuke.UI.Skins.Controls; +using Microsoft.VisualBasic; +using Globals = DotNetNuke.Common.Globals; + +namespace DotNetNuke.Modules.UserDefinedTable +{ + /// ----------------------------------------------------------------------------- + /// + /// The UserDefinedTable Class provides the UI for displaying the UserDefinedTable + /// + /// ----------------------------------------------------------------------------- + public partial class List : PortalModuleBase, IActionable, IPostBackEventHandler + { + #region Search + + class SearchManager + { + readonly List _parent; + readonly PlaceHolder _searchPlaceHolder; + readonly LinkButton _cmdSearch; + readonly LinkButton _cmdResetSearch; + + enum SearchControlTypes + { + Columns = 1, + @Operator = 2, + Search = 3 + } + + public SearchManager(List parent) + { + _parent = parent; + _cmdSearch = parent.cmdSearch; + _cmdSearch.Click += cmdSearch_Click; + _cmdResetSearch = parent.cmdResetSearch; + _cmdResetSearch.Click += cmdResetSearch_Click; + _searchPlaceHolder = parent.phSearchSentence; + } + + public bool IsSearching + { + get + { + return _parent.ViewState["IsSearching"].AsBoolean() || + ! string.IsNullOrEmpty(_parent.Request.QueryString[string.Format("u{0}q", _parent.ModuleId)]); + } + private set { _parent.ViewState["IsSearching"] = value; } + } + + TextBox TxtSearch + { + get { return ((TextBox) (SearchControl(SearchControlTypes.Search))); } + } + + DropDownList DrpSearchMode + { + get { return ((DropDownList) (SearchControl(SearchControlTypes.Operator))); } + } + + DropDownList DrpSearchableColumns + { + get { return ((DropDownList) (SearchControl(SearchControlTypes.Columns))); } + } + + public string Filter() + { + var searchString = string.Empty; + + if (TxtSearch.Text == string.Empty) + { + return string.Empty; + } + var dataSet = _parent.DataSet; + foreach (DataRow row in dataSet.Tables[DataSetTableName.Fields].Rows) + { + if (TxtSearch.Visible && Convert.ToBoolean(row[FieldsTableColumn.Searchable])) + { + var fieldTitle = row[FieldsTableColumn.Title].ToString(); + if (DrpSearchableColumns.SelectedValue == "allcolumns" || + DrpSearchableColumns.SelectedValue == fieldTitle) + { + //add to search expression: + if (searchString != string.Empty) + { + searchString += " OR "; + } + + if (_parent.Settings.UrlSearch && + dataSet.Tables[DataSetTableName.Data].Columns.Contains(fieldTitle + + DataTableColumn.Appendix_Url)) + { + fieldTitle += DataTableColumn.Appendix_Url; + } + else if ( + dataSet.Tables[DataSetTableName.Data].Columns.Contains(fieldTitle + + DataTableColumn. + Appendix_Caption)) + { + fieldTitle += DataTableColumn.Appendix_Caption; + } + + if (dataSet.Tables[DataSetTableName.Data].Columns[fieldTitle].DataType == + typeof (string)) + { + searchString += string.Format("([{0}] Like \'[UDT:Search]\')", fieldTitle); + } + else + { + searchString += + string.Format("(Convert([{0}], \'System.String\') Like \'[UDT:Search]\')", + fieldTitle); + } + } + } + } + var searchpattern = TxtSearch.Text; + if (DrpSearchMode.Visible) + { + switch (DrpSearchMode.SelectedValue) + { + case "contain": + searchpattern = string.Format("*{0}*", searchpattern); + break; + case "startwith": + searchpattern = string.Format("{0}*", searchpattern); + break; + case "endwith": + searchpattern = string.Format("*{0}", searchpattern); + break; + case "equal": + break; + } + } + else + { + if (searchpattern.StartsWith("|") && searchpattern.EndsWith("|")) + { + searchpattern = searchpattern.Substring(1, Convert.ToInt32(searchpattern.Length - 2)); + } + else if (searchpattern.StartsWith("|")) + { + searchpattern = string.Format("{0}*", searchpattern.Substring(1)); + } + else if (searchpattern.EndsWith("|")) + { + searchpattern = string.Format("*{0}", + searchpattern.Substring(0, + Convert.ToInt32(searchpattern.Length - + 1))); + } + else + { + searchpattern = string.Format("*{0}*", searchpattern); + } + } + return searchString.Replace("[UDT:Search]", EscapeSearchInput(searchpattern)); + } + + static string EscapeSearchInput(string input) + { + return input.Replace("\'", "\'\'"); + } + + void Reset() + { + TxtSearch.Text = ""; + DrpSearchMode.SelectedValue = "contain"; + DrpSearchableColumns.SelectedIndex = 0; + } + + public bool DataBindingNeeded() + { + var isSearchable = _parent.DataSet.Tables[DataSetTableName.Fields].Rows + .Cast() + .Any(row => row[FieldsTableColumn.Searchable].AsBoolean()); + + if (isSearchable) + { + _parent.panSearch.Visible = true; + if (! _parent.Settings.SimpleSearch ) + { + _parent.plSearch.Visible = false; + } + else + { + foreach (Control c in _searchPlaceHolder.Controls) + { + c.Visible = c.ID == "txtSearch"; + } + } + if (IsSearching == false && + ! _parent.Settings.ShowNoRecordsUntilSearch ) + { + IsSearching = true; + //always set flag to true, if ShowNoRecordsUntilSearch is not checked + } + } + + _parent.cmdResetSearch.Visible = + TxtSearch.Text != "" || DrpSearchMode.SelectedValue != "contain"; + + //'Show Datagrid if + //' - Module has no search columns OR + //' - IsSearching = True OR + //' - search box is not empty + return (! isSearchable || IsSearching || TxtSearch.Text != ""); + } + + public void LoadControls() + { + _searchPlaceHolder.Controls.Clear(); + const string regexPattern = "(?<=\\{)(?\\d)(?=\\})|(?[^\\{\\}]+)"; + foreach ( + Match m in + new Regex(regexPattern).Matches(Localization.GetString("SearchSentence", + _parent.LocalResourceFile))) + { + if (m.Result("${text}").AsString() != string.Empty) + { + _searchPlaceHolder.Controls.Add(new LiteralControl(m.Result("${text}"))); + } + if (m.Result("${control}").AsString() != string.Empty) + { + var controlType = (SearchControlTypes) (int.Parse(m.Result("${control}"))); + SearchControl(controlType); + } + } + //ensure Search Controls + SearchControl(SearchControlTypes.Columns); + SearchControl(SearchControlTypes.Operator); + SearchControl(SearchControlTypes.Search); + } + + Control SearchControl(SearchControlTypes controlType) + { + var moduleId = _parent.ModuleId; + switch (controlType) + { + case SearchControlTypes.Columns: + var drpSearchableColumns = + (DropDownList) (_searchPlaceHolder.FindControl("drpSearchableColumns")); + if (drpSearchableColumns == null) + { + var drp = new DropDownList {ID = "drpSearchableColumns", CssClass = "NormalTextBox"}; + _searchPlaceHolder.Controls.Add(drp); + var lbl = new Label {ID = "lblSearchableColumn"}; + lbl.Font.Bold = true; + lbl.Visible = false; + _searchPlaceHolder.Controls.Add(lbl); + LoadColumns(); + drpSearchableColumns = drp; + if (! string.IsNullOrEmpty(_parent.Request.QueryString[string.Format("u{0}c", moduleId)])) + { + drpSearchableColumns.SelectedValue = + _parent.Request.QueryString[string.Format("u{0}c", moduleId)].UrlHexDecode(); + } + } + return drpSearchableColumns; + case SearchControlTypes.Operator: + var drpSearchMode = (DropDownList) (_searchPlaceHolder.FindControl("drpSearchMode")); + if (drpSearchMode == null) + { + var drp = new DropDownList {ID = "drpSearchMode", CssClass = "NormalTextBox"}; + drp.Items.Add( + new ListItem(Localization.GetString("SearchMode.Contain", _parent.LocalResourceFile), + "contain")); + drp.Items.Add( + new ListItem(Localization.GetString("SearchMode.StartWith", _parent.LocalResourceFile), + "startwith")); + drp.Items.Add( + new ListItem(Localization.GetString("SearchMode.EndWith", _parent.LocalResourceFile), + "endwith")); + drp.Items.Add( + new ListItem(Localization.GetString("SearchMode.Equal", _parent.LocalResourceFile), + "equal")); + _searchPlaceHolder.Controls.Add(drp); + drpSearchMode = drp; + if (! string.IsNullOrEmpty(_parent.Request.QueryString[string.Format("u{0}m", moduleId)])) + { + drpSearchMode.SelectedValue = + _parent.Request.QueryString[string.Format("u{0}m", moduleId)]; + } + } + return drpSearchMode; + case SearchControlTypes.Search: + var txtSearch = (TextBox) (_searchPlaceHolder.FindControl("txtSearch")); + if (txtSearch == null) + { + txtSearch = new TextBox {ID = "txtSearch"}; + _searchPlaceHolder.Controls.Add(txtSearch); + if (! string.IsNullOrEmpty(_parent.Request.QueryString[string.Format("u{0}q", moduleId)])) + { + txtSearch.Text = + _parent.Request.QueryString[string.Format("u{0}q", moduleId)].UrlHexDecode(); + } + } + return txtSearch; + } + return null; + } + + void LoadColumns() + { + DrpSearchableColumns.Items.Clear(); + DrpSearchableColumns.Items.Add( + new ListItem(Localization.GetString("AllColumns", _parent.LocalResourceFile), "allcolumns")); + + var fieldTitle = string.Empty; + foreach (DataRow row in _parent.DataSet.Tables[DataSetTableName.Fields].Rows) + { + var searchable = Convert.ToBoolean(row[FieldsTableColumn.Searchable]); + if (searchable) + { + fieldTitle = row[FieldsTableColumn.Title].ToString(); + if (fieldTitle != "allcolumns") + { + DrpSearchableColumns.Items.Add(new ListItem(fieldTitle, fieldTitle)); + } + } + } + + if (DrpSearchableColumns.Items.Count == 2) + { + //display label instead of dropdownlist if there is only one searchable column + DrpSearchableColumns.Items.RemoveAt(0); + //remove "all searchable columns" + DrpSearchableColumns.Visible = false; + var lblSearchableColumn = (Label) (_searchPlaceHolder.FindControl("lblSearchableColumn")); + lblSearchableColumn.Text = fieldTitle; + lblSearchableColumn.Visible = true; + } + } + + void cmdSearch_Click(object sender, EventArgs e) + { + if (! _parent.RenderMethod.StartsWith("UDT_Xsl")) + { + _parent.CurrentPage = 1; + IsSearching = true; + } + else + { + var @params = new List(); + var moduleId = _parent.ModuleId; + if (! string.IsNullOrEmpty(TxtSearch.Text)) + { + @params.Add(string.Format("u{0}q={1}", moduleId, TxtSearch.Text.UrlHexEncode())); + if (! _parent.Settings.SimpleSearch ) + { + @params.Add(string.Format("u{0}c={1}", moduleId, + DrpSearchableColumns.SelectedValue.UrlHexEncode())); + @params.Add(string.Format("u{0}m={1}", moduleId, DrpSearchMode.SelectedValue)); + } + var url = Globals.NavigateURL(_parent.TabId, "", @params.ToArray()); + _parent.Response.Redirect(url); + } + // Such paramter + } + } + + void cmdResetSearch_Click(object sender, EventArgs e) + { + if (! _parent.RenderMethod.StartsWith("UDT_Xsl")) + { + Reset(); + _parent.CurrentPage = 1; + IsSearching = false; + } + else + { + _parent.Response.Redirect(Globals.NavigateURL(_parent.TabId)); + } + } + } + + #endregion + + #region Private Members + + DataSet _dataSet; + SearchManager _search; + + Components.Settings _settings; + new Components.Settings Settings + { get { return _settings ?? (_settings = new Components.Settings(ModuleContext.Settings)); } } + #endregion + + #region Private Properties + + UserDefinedTableController _udtController; + + UserDefinedTableController UdtController + { + get { return _udtController ?? (_udtController = new UserDefinedTableController(ModuleContext)); } + } + + DataSet DataSet + { + get { return _dataSet ?? (_dataSet = UdtController.GetDataSet()); } + } + + string RenderMethod + { + get { return string.Format("UDT_{0}", Settings.RenderingMethod ); } + } + + #region properties Only Needed in Grid Mode + + int CurrentPage + { + get + { + if (ViewState["CurrentPage"] == null) + { + return 1; + } + return Convert.ToInt32(ViewState["CurrentPage"]); + } + set { ViewState["CurrentPage"] = value; } + } + + string SortField + { + get + { + if (ViewState["SortField"] == null) + { + if (Settings.SortFieldId!=Null.NullInteger ) + { + ViewState["SortField"] = GetFieldTitle(Settings.SortFieldId ); + } + } + return ViewState["SortField"].AsString(); + } + set { ViewState["SortField"] = value; } + } + + + string SortOrder + { + get + { + if (ViewState["SortOrder"] == null) + { + return Settings.SortOrder; + } + return ViewState["SortOrder"].AsString(); + } + set { ViewState["SortOrder"] = value; } + } + + #endregion + + #endregion + + #region Data Binding + + void BindData() + { + if (!SchemaIsDefined() ) + { + ShowModuleMessage("NoFieldsDefined.ErrorMessage", ModuleContext.EditUrl("Manage"), "No fields defined"); + } + else + { + var mustBind = true; + if (Settings.ShowSearchTextBox) + { + if (! _search.DataBindingNeeded()) + { + ctlPagingControl.TotalRecords = 0; + ctlPagingControl.Visible = false; + lblNoRecordsFound.Visible = false; + mustBind = false; + } + } + else + { + panSearch.Visible = false; + } + + if (mustBind) + { + switch (RenderMethod) + { + case SettingName.XslUserDefinedStyleSheet: + var styleSheet = (string) ModuleContext.Settings[RenderMethod]; + if (string.IsNullOrEmpty( styleSheet )) + { + BindDataToDataGrid(); + } + else + BindDataUsingXslTransform(styleSheet); + break; + case SettingName.XslPreDefinedStyleSheet: + + var oldStyleSheet = (string) ModuleContext.Settings[RenderMethod]; + var newStyleSheet = CopyScriptToPortal(oldStyleSheet); + + var mc = new ModuleController(); + mc.UpdateTabModuleSetting(TabModuleId, SettingName.RenderingMethod, "XslUserDefinedStyleSheet"); + mc.UpdateTabModuleSetting(TabModuleId,SettingName.XslUserDefinedStyleSheet , newStyleSheet ); + + BindDataUsingXslTransform(newStyleSheet); + + break; + default: //grid rendering + BindDataToDataGrid(); + break; + } + } + } + } + + string CopyScriptToPortal(string styleSheet) + { + var path = MapPath(styleSheet); + var filename = Path.GetFileName(path); + + var folderManager = FolderManager.Instance; + if (!folderManager.FolderExists(PortalId, "XslStyleSheets")) + folderManager.AddFolder(PortalId, "XslStyleSheets"); + + const string legacyPath = "XslStyleSheets/UDT Legacy"; + + var folderInfo = folderManager.FolderExists(PortalId, legacyPath)? + folderManager.GetFolder(PortalId, legacyPath) : + folderManager.AddFolder(PortalId, legacyPath); + + using (var source= new FileStream(path,FileMode.Open )) + { + var fileInfo = !FileManager.Instance.FileExists(folderInfo, filename) + ? FileManager.Instance.AddFile(folderInfo, filename, source) + : FileManager.Instance.GetFile(folderInfo, filename); + return string.Format("{0}/{1}", legacyPath, fileInfo.FileName); + } + } + + void ShowModuleMessage(string keyForLocalization, string parameter, string fallBackMessage) + { + //Dummy text + var strMessageFormat = Localization.GetString(keyForLocalization, LocalResourceFile).AsString(); + if (strMessageFormat != string.Empty) + { + fallBackMessage = string.Format(strMessageFormat, parameter); + } + ShowModuleMessage(fallBackMessage); + } + + /// ----------------------------------------------------------------------------- + /// + /// BindDataToDataGrid fetchs the data from the database and binds it to the grid + /// + /// ----------------------------------------------------------------------------- + void BindDataToDataGrid() + { + PopulateDataGridColumns(); + + var dataTable = DataSet.Tables[DataSetTableName.Data]; + + dataTable + .FilterAndSort( GetRowFilter(Settings.Filter, _search.Filter()), SortField, SortOrder) + .Top(Settings.TopCount); + + //Paging + var paging = new + { + PageSize = Settings.Paging, + AllowPaging = Settings.Paging != Null.NullInteger, + PageIndex = Convert.ToInt32( + Math.Min(CurrentPage, Math.Ceiling(((double)dataTable.Rows.Count / Settings.Paging))) - 1), + TotalRecords = dataTable.Rows.Count + }; + + dataTable.Page( paging.PageIndex, paging.PageSize); + + + using (var data = new DataView(dataTable)) + { + if (data.Count > 0) + { + lblNoRecordsFound.Visible = false; + + try + { + grdData.DataSource = data; + grdData.DataBind(); + } + catch (FormatException e) + { + HandleException(e, "Databind Exception"); + } + grdData.Visible = true; + ctlPagingControl.Visible = paging.AllowPaging; + ctlPagingControl.PageSize = paging.PageSize; + ctlPagingControl.CurrentPage = paging.PageIndex + 1; + ctlPagingControl.TotalRecords = paging.TotalRecords; + } + else + { + if (_search.IsSearching) + { + lblNoRecordsFound.Visible = true; + } + ctlPagingControl.TotalRecords = 0; + ctlPagingControl.Visible = false; + } + } + } + + + PortalModuleBase GetModuleControl() + { + return (PortalModuleBase) (((Parent.Parent ) is PortalModuleBase) ? Parent.Parent : this); + } + + /// ----------------------------------------------------------------------------- + /// + /// set up Fielddefinitions for Datagrid + /// + /// ----------------------------------------------------------------------------- + void PopulateDataGridColumns() + { + for (var intColumn = grdData.Columns.Count - 1; intColumn >= 1; intColumn--) + { + grdData.Columns.RemoveAt(intColumn); + } + foreach (DataRow row in DataSet.Tables[DataSetTableName.Fields].Rows) + { + //Add Fields dynamically to the grdData + var colField = new BoundField + { + HeaderText = row[FieldsTableColumn.Title].ToString(), + DataField = row[FieldsTableColumn.Title].ToString(), + HtmlEncode = false, + Visible = Convert.ToBoolean(row[FieldsTableColumn.Visible]), + SortExpression = string.Format("{0}|ASC", row[FieldsTableColumn.Title]) + }; + //Add a sorting indicator to the headertext + if ( row[FieldsTableColumn.Title].ToString() == SortField && colField.Visible) + { + if (SortOrder == "ASC") + { + colField.HeaderText += + string.Format( + "\"Sorted", + (Request.ApplicationPath == "/" ? string.Empty : Request.ApplicationPath), SortField); + } + else + { + colField.HeaderText += + string.Format( + "\"Sorted", + (Request.ApplicationPath == "/" ? string.Empty : Request.ApplicationPath), SortField); + } + } + //Column settings depending on the fieldtype + DataType.ByName(row[FieldsTableColumn.Type].ToString()). + SetStylesAndFormats(colField,row[FieldsTableColumn.OutputSettings].AsString()); + grdData.Columns.Add(colField); + } + var editLinkNeed = DataSet.Tables[DataSetTableName.Data].Rows + .Cast() + .Any(row => ! string.IsNullOrEmpty(row[DataTableColumn.EditLink] as string)); + if (! editLinkNeed) + { + grdData.Columns.RemoveAt(0); + } + } + + + /// ----------------------------------------------------------------------------- + /// + /// BindDataUsingXslTransform fetchs the data from the database and binds it to the grid + /// + /// ----------------------------------------------------------------------------- + void BindDataUsingXslTransform(string styleSheet) + { + try + { + DataSet.Tables.Add(UdtController.Context("", + Settings.SortFieldId.ToString(), + Settings.SortOrder , + Settings.Paging.ToString())); + + DataSet.Tables[DataSetTableName.Data] + .FilterAndSort(GetRowFilter(Settings.Filter, _search.Filter()), SortField, SortOrder) + .Top(Settings.TopCount); + + var xslTrans = new XslCompiledTransform(); + + var script = Utilities.ReadStringFromFile(styleSheet, PortalId); + var reader = new XmlTextReader(new StringReader(script)); + xslTrans.Load(reader); + + using (XmlReader xmlData = new XmlTextReader(new StringReader(DataSet.GetXml()))) + { + using (var stringWriter = new StringWriter()) + { + //Dynamic UDT Params. Add all Request parameters that starts with "UDT_{moduleid}_Param*" as "Param*" named XSL parameter + var args = new XsltArgumentList(); + var udtParameterPrefix = string.Format(Definition.QueryStringParameter,ModuleContext.ModuleId); + foreach (string paramKey in Request.Params.Keys) + { + if (paramKey != null && paramKey.ToLowerInvariant().StartsWith(udtParameterPrefix)) + { + args.AddParam(paramKey.ToLowerInvariant().Substring(udtParameterPrefix.Length - 5), + string.Empty, Request[paramKey]); + } + } + xslTrans.Transform(xmlData, args, stringWriter); + XslOutput.Controls.Add(new LiteralControl(stringWriter.ToString())); + } + } + + XslOutput.Visible = true; + } + catch (Exception exc) + { + HandleException(exc, + string.Format("{0}
    StyleSheet:{1}", + Localization.GetString("XslFailed.ErrorMessage", LocalResourceFile), + styleSheet)); + BindDataToDataGrid(); + } + } + + void HandleException(Exception exc, string localizedMessage) + { + var message = new PortalSecurity().InputFilter(exc.Message, PortalSecurity.FilterFlag.NoScripting); + message = string.Format("{0}
    Error Description: {1}", localizedMessage, message); + ShowModuleMessage(message); + Exceptions.LogException(exc); + } + + void ShowModuleMessage(string message) + { + var moduleControl = GetModuleControl(); + var modSecurity = new ModuleSecurity(ModuleContext); + if (modSecurity.IsAllowedToAdministrateModule()) + { + UI.Skins.Skin.AddModuleMessage(moduleControl, message,ModuleMessage.ModuleMessageType.YellowWarning); + } + } + + + + + #endregion + + #region Private Subs and Functions + + string GetRowFilter(string filter, string search) + { + var tokenReplace = new TokenReplace(escapeApostrophe: true) {ModuleInfo = ModuleContext.Configuration}; + if (filter != string.Empty) + { + filter = tokenReplace.ReplaceEnvironmentTokens(filter); + } + if (filter != string.Empty && search != string.Empty) + { + return string.Format("{0} AND ({1})", filter, search); + } + return filter + search; + } + + string GetFieldTitle(int fieldId) + { + using ( + var dv = new DataView(DataSet.Tables[DataSetTableName.Fields]) + {RowFilter = string.Format("{0}={1}", FieldsTableColumn.Id, fieldId)}) + { + if (dv.Count > 0) + { + return (string) (dv[0][FieldsTableColumn.Title]); + } + return ""; + } + } + + + bool IsKnownField(string fieldName) + { + var fieldstable = DataSet.Tables[DataSetTableName.Fields]; + fieldName = fieldName.Replace("\'", "\'\'"); + return fieldstable.Select(string.Format("{0}=\'{1}\'", FieldsTableColumn.Title, fieldName)).Length >= 0; + } + + #endregion + + #region Event Handlers + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + ModuleContext.HelpURL = string.Format("http://www.dotnetnuke.com/{0}?tabid=457", Globals.glbDefaultPage); + + Load += Page_Load; + PreRender += Page_PreRender; + ctlPagingControl.PageChanged += ctlPagingControl_CurrentPageChanged; + grdData.Sorting += grdData_Sorting; + + try + { + _search = new SearchManager(this); + _search.LoadControls(); + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + } + + void Page_Load(object sender, EventArgs e) + { + try + { + if (! IsPostBack) + { + CurrentPage = 1; + EnsureActionButton(); + } + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void ctlPagingControl_CurrentPageChanged(object sender, EventArgs e) + { + CurrentPage = ctlPagingControl.CurrentPage; + } + + protected void grdData_Sorting(object sender, GridViewSortEventArgs e) + { + try + { + var strSort = e.SortExpression.Split('|'); + + var newSortField = strSort[0]; + if (IsKnownField(newSortField)) + { + if ((newSortField == SortField && SortOrder == "ASC") || + (newSortField != SortField && strSort[1] == "DESC")) + { + SortOrder = "DESC"; + } + else + { + SortOrder = "ASC"; + } + SortField = newSortField; + } + } + catch (Exception exc) //Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + + protected void Page_PreRender(object sender, EventArgs e) + { + try + { + BindData(); + } + catch (Exception exc) + { + HandleException(exc, Localization.GetString("DataBindingFailed.ErrorMessage", LocalResourceFile)); + } + } + + #endregion + + #region Optional Interfaces + + public void EnsureActionButton() + { + + var modSecurity = new ModuleSecurity(ModuleContext); + var useButtons = Settings.UseButtonsInForm ; + + if (Settings.OnlyFormIsShown ) + { + var url = Globals.NavigateURL(ModuleContext.TabId); + var title = Localization.GetString("BackToForm.Action", LocalResourceFile); + + ActionLink.NavigateUrl = url; + ActionLink.Text = title; + placeholderActions.Visible = useButtons; + } + else if (Settings.OnlyListIsShown && modSecurity.IsAllowedToAddRow() && SchemaIsDefined() && + (modSecurity.IsAllowedToAdministrateModule() || HasAddPermissonByQuota())) + { + var url = ModuleContext.EditUrl(); + var title = Localization.GetString(ModuleActionType.AddContent, LocalResourceFile); + + ActionLink.NavigateUrl = url; + ActionLink.Text = title; + placeholderActions.Visible = useButtons; + } + } + + public ModuleActionCollection ModuleActions + { + get + { + var actions = new ModuleActionCollection(); + try + { + var modSecurity = new ModuleSecurity(ModuleContext); + var useButtons = Settings.UseButtonsInForm ; + var cmdName = useButtons ? "": ModuleActionType.AddContent; + + try + { + if (Settings.OnlyFormIsShown ) + { + var url = Globals.NavigateURL(ModuleContext.TabId); + var title = Localization.GetString("BackToForm.Action", LocalResourceFile); + actions.Add(ModuleContext.GetNextActionID(), + title, + cmdName, "", Utilities.IconURL("Lt"), + url, false, SecurityAccessLevel.View, true, + false); + + } + else if (Settings.OnlyListIsShown && modSecurity.IsAllowedToAddRow() && SchemaIsDefined() && + (modSecurity.IsAllowedToAdministrateModule() || HasAddPermissonByQuota())) + { + var url = ModuleContext.EditUrl(); + var title = Localization.GetString(ModuleActionType.AddContent, LocalResourceFile); + actions.Add(ModuleContext.GetNextActionID(), + title, + cmdName , "",Utilities.IconURL("Add"), url, + false, SecurityAccessLevel.View, true, false); + } + + } +// ReSharper disable EmptyGeneralCatchClause + catch +// ReSharper restore EmptyGeneralCatchClause + { + // This try/catch is to avoid loosing control about your current UDT module - if an error happens inside GetDatSet, it will be raised and handled again inside databind + } + + actions.Add(ModuleContext.GetNextActionID(), + Localization.GetString("ShowXML.Action", LocalResourceFile), "", "", + ResolveUrl("~/images/XML.gif"), + (ResolveUrl(string.Format("~{0}ShowXml.ashx", Definition.PathOfModule)) + "?tabid=" + + ModuleContext.TabId + "&mid=" + ModuleContext.ModuleId), false, + SecurityAccessLevel.Edit, true, true); + //Add 'DeleteAll' command: + if (DataSet.Tables[DataSetTableName.Data].Rows.Count > 0) + { + var urlDelete = Page.ClientScript.GetPostBackEventReference(this, "DeleteAll"); + urlDelete = string.Format("javascript:if (confirm(\'{0}\')) {1}", + Localization.GetString("DeleteAll.Confirm", LocalResourceFile).AsString().Replace( + "\'", "\\\'"), urlDelete); + actions.Add(ModuleContext.GetNextActionID(), + Localization.GetString("DeleteAll.Action", LocalResourceFile), "", "", + Utilities.IconURL("Delete"), urlDelete, false, SecurityAccessLevel.Edit, true, + false); + } + + if (RenderMethod == SettingName.XslUserDefinedStyleSheet) + { + actions.Add(ModuleContext.GetNextActionID(), + Localization.GetString("EditXsl.Action", LocalResourceFile), "", "", + Utilities.IconURL("Wizard"), + ModuleContext.EditUrl("Edit", "Current", "GenerateXsl"), false, + SecurityAccessLevel.Edit, + true, false); + } + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + return actions; + } + } + + + + bool SchemaIsDefined() + { + return DataSet.Tables[DataSetTableName.Fields].Rows.Count > 4; + } + + bool HasAddPermissonByQuota() + { + return ModuleSecurity.HasAddPermissonByQuota(DataSet.Tables[DataSetTableName.Fields], + DataSet.Tables[DataSetTableName.Data], + Settings.UserRecordQuota , + ModuleContext.PortalSettings.UserInfo.GetSafeUsername()); + } + + public void RaisePostBackEvent(string eventArgument) + { + var modSecurity = new ModuleSecurity(ModuleContext); + if (eventArgument == "DeleteAll" && modSecurity.IsAllowedToAdministrateModule()) + { + UdtController.DeleteRows(); + Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/List.ascx.designer.cs b/List.ascx.designer.cs new file mode 100644 index 0000000..0725428 --- /dev/null +++ b/List.ascx.designer.cs @@ -0,0 +1,118 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +using System.Data; + +namespace DotNetNuke.Modules.UserDefinedTable { + + + public partial class List { + + /// + /// panSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Panel panSearch; + + /// + /// phSearchSentence control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.PlaceHolder phSearchSentence; + + /// + /// cmdSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdSearch; + + /// + /// cmdResetSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdResetSearch; + + /// + /// plSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UserControl plSearch; + + /// + /// lblNoRecordsFound control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblNoRecordsFound; + + /// + /// grdData control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.GridView grdData; + + /// + /// ctlPagingControl control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.WebControls.PagingControl ctlPagingControl; + + /// + /// XslOutput control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.PlaceHolder XslOutput; + + /// + /// placeholderActions control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl placeholderActions; + + /// + /// ActionLink control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink ActionLink; + + + } +} diff --git a/MakeThumbnail.ashx.cs b/MakeThumbnail.ashx.cs new file mode 100644 index 0000000..6acefe1 --- /dev/null +++ b/MakeThumbnail.ashx.cs @@ -0,0 +1,168 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using System.Web; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Services.Exceptions; +using DotNetNuke.Services.FileSystem; + +namespace DotNetNuke.Modules.UserDefinedTable +{ + /// + /// Summary description for MakeThumbnail + /// + public class MakeThumbnail : IHttpHandler + { + public void ProcessRequest(HttpContext context) + { + var intMaxWidth = 0; + var intMaxHeight = 0; + Bitmap sourceImage = null; + Bitmap newImage = null; + var request = context.Request; + Stream sourceImageStream = null; + + try + { + // Get max. width, if any + if (request.Params["w"] != string.Empty) + { + intMaxWidth = request.QueryString["w"].AsInt(); + } + + // Get max. height, if any + if (request.Params["h"] != string.Empty) + { + intMaxHeight = request.QueryString["h"].AsInt(); + } + + // Get source image path + var strFilepath = request.Params["image"]; + //only virtual paths are valid! + + var ps = PortalController.GetCurrentPortalSettings(); + + + + // Check cache for thumbnail + //add prefix to identify cache item as belonging to UDT + var cacheKey = "UDT_TN" + strFilepath + intMaxWidth + "x" + intMaxHeight; + var image = DataCache.GetCache(cacheKey); + ImageFormat iFormat; + if (image == null) + { + // Get source Image + var file = FileManager.Instance.GetFile(ps.PortalId, strFilepath); + sourceImageStream = FileManager.Instance.GetFileContent(file); + sourceImage = new Bitmap(sourceImageStream); + + iFormat = ImageFormat.Jpeg; + var intSourceWidth = sourceImage.Width; + var intSourceHeight = sourceImage.Height; + if ((intMaxWidth > 0 && intMaxWidth < intSourceWidth) || + (intMaxHeight > 0 && intMaxHeight < intSourceHeight)) + { + // Resize image: + double aspect = sourceImage.PhysicalDimension.Width / sourceImage.PhysicalDimension.Height; + + int newWidth; + int newHeight; + if (intMaxWidth == 0) + { + newWidth = (int)(intMaxHeight * aspect); + newHeight = intMaxHeight; + } + else if (intMaxHeight == 0) + { + newWidth = intMaxWidth; + newHeight = (int)(intMaxWidth / aspect); + } + else if ((intSourceWidth / intMaxWidth) >= (intSourceHeight / intMaxHeight)) + { + newWidth = intMaxWidth; + newHeight = (int)(intMaxWidth / aspect); + } + else + { + newWidth = (int)(intMaxHeight * aspect); + newHeight = intMaxHeight; + } + + newImage = new Bitmap(newWidth, newHeight); + using (var g = Graphics.FromImage(newImage)) + { + g.InterpolationMode = InterpolationMode.HighQualityBicubic; + g.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight); + g.DrawImage(sourceImage, 0, 0, newWidth, newHeight); + } + + //Cache thumbnail clone (Disposing a cached image will destroy its cache too) + DataCache.SetCache(cacheKey, newImage.Clone()); + } + else //use original width (no maxwidth given or image is narrow enough: + { + newImage = sourceImage; + } + } + else + { + // Get (cloned) cached thumbnail + newImage = (Bitmap)((Bitmap)image).Clone(); + iFormat = ImageFormat.Jpeg; + } + + // Send image to the browser. + context.Response.ContentType = GetContentType(iFormat); + newImage.Save(context.Response.OutputStream, iFormat); + } + finally + { + // Clean up + if (newImage != null) newImage.Dispose(); + if (sourceImage != null) sourceImage.Dispose(); + if (sourceImageStream != null) sourceImageStream.Dispose(); + } + } + + public bool IsReusable + { + get { return false; } + } + + static string GetContentType(ImageFormat iFormat) + { + string contentType; + + if (iFormat.Guid.Equals(ImageFormat.Jpeg.Guid)) + { + contentType = "image/jpeg"; + } + else if (iFormat.Guid.Equals(ImageFormat.Gif.Guid)) + { + contentType = "image/gif"; + } + else if (iFormat.Guid.Equals(ImageFormat.Png.Guid)) + { + contentType = "image/png"; + } + else if (iFormat.Guid.Equals(ImageFormat.Tiff.Guid)) + { + contentType = "image/tiff"; + } + else if (iFormat.Guid.Equals(ImageFormat.Bmp.Guid)) + { + contentType = "image/x-ms-bmp"; + } + else + { + contentType = "image/jpeg"; + } + return contentType; + } + } +} \ No newline at end of file diff --git a/Providers/DataProviders/sqldataprovider/03.01.00.sqldataprovider b/Providers/DataProviders/sqldataprovider/03.01.00.sqldataprovider new file mode 100644 index 0000000..f2ac665 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/03.01.00.sqldataprovider @@ -0,0 +1,370 @@ +/************************************************************/ +/***** SqlDataProvider *****/ +/***** *****/ +/***** *****/ +/***** Note: To manually execute this script you must *****/ +/***** perform a search and replace operation *****/ +/***** for {databaseOwner} and {objectQualifier} *****/ +/***** *****/ +/************************************************************/ + +/** Create UserDefinedTable Tables **/ + +if not exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedRows]') and OBJECTPROPERTY(id, N'IsTable') = 1) + BEGIN + CREATE TABLE {databaseOwner}[{objectQualifier}UserDefinedRows] + ( + [UserDefinedRowId] [int] NOT NULL IDENTITY(1, 1), + [ModuleId] [int] NOT NULL + ) + + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedRows] ADD CONSTRAINT [PK_{objectQualifier}UserDefinedRows] PRIMARY KEY CLUSTERED ([UserDefinedRowId]) + CREATE NONCLUSTERED INDEX [IX_{objectQualifier}UserDefinedRows] ON {databaseOwner}[{objectQualifier}UserDefinedRows] ([ModuleId]) + + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedRows] WITH NOCHECK ADD CONSTRAINT [FK_{objectQualifier}UserDefinedRows_{objectQualifier}Modules] FOREIGN KEY ([ModuleId]) REFERENCES {databaseOwner}[{objectQualifier}Modules] ([ModuleID]) ON DELETE CASCADE + END +GO + +if not exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedFields]') and OBJECTPROPERTY(id, N'IsTable') = 1) + BEGIN + CREATE TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] + ( + [UserDefinedFieldId] [int] NOT NULL IDENTITY(1, 1), + [ModuleId] [int] NOT NULL, + [FieldTitle] [varchar] (50) NOT NULL, + [Visible] [bit] NOT NULL, + [FieldOrder] [int] NOT NULL DEFAULT (0), + [FieldType] [varchar] (20) NOT NULL + ) + + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] ADD CONSTRAINT [PK_{objectQualifier}UserDefinedTable] PRIMARY KEY CLUSTERED ([UserDefinedFieldId]) + CREATE NONCLUSTERED INDEX [IX_{objectQualifier}UserDefinedFields] ON {databaseOwner}[{objectQualifier}UserDefinedFields] ([ModuleId]) + + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] WITH NOCHECK ADD CONSTRAINT [FK_{objectQualifier}UserDefinedFields_{objectQualifier}Modules] FOREIGN KEY ([ModuleId]) REFERENCES {databaseOwner}[{objectQualifier}Modules] ([ModuleID]) ON DELETE CASCADE + + END +GO + +if not exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedData]') and OBJECTPROPERTY(id, N'IsTable') = 1) + BEGIN + CREATE TABLE {databaseOwner}[{objectQualifier}UserDefinedData] + ( + [UserDefinedDataId] [int] NOT NULL IDENTITY(1, 1), + [UserDefinedFieldId] [int] NOT NULL, + [UserDefinedRowId] [int] NOT NULL, + [FieldValue] [nvarchar] (2000) NOT NULL + ) + + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedData] ADD CONSTRAINT [PK_{objectQualifier}UserDefinedData] PRIMARY KEY CLUSTERED ([UserDefinedDataId]) + CREATE NONCLUSTERED INDEX [IX_{objectQualifier}UserDefinedData] ON {databaseOwner}[{objectQualifier}UserDefinedData] ([UserDefinedFieldId]) + CREATE NONCLUSTERED INDEX [IX_{objectQualifier}UserDefinedData_1] ON {databaseOwner}[{objectQualifier}UserDefinedData] ([UserDefinedRowId]) + + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedData] WITH NOCHECK ADD CONSTRAINT [FK_{objectQualifier}UserDefinedData_{objectQualifier}UserDefinedFields] FOREIGN KEY ([UserDefinedFieldId]) REFERENCES {databaseOwner}[{objectQualifier}UserDefinedFields] ([UserDefinedFieldId]) + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedData] WITH NOCHECK ADD CONSTRAINT [FK_{objectQualifier}UserDefinedData_{objectQualifier}UserDefinedRows] FOREIGN KEY ([UserDefinedRowId]) REFERENCES {databaseOwner}[{objectQualifier}UserDefinedRows] ([UserDefinedRowId]) ON DELETE CASCADE + END +GO + + +/** Drop Existing Stored Procedures **/ + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}AddUserDefinedRow]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}AddUserDefinedRow +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}AddUserDefinedData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}AddUserDefinedData +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}AddUserDefinedField]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}AddUserDefinedField +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}DeleteUserDefinedRow]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}DeleteUserDefinedRow +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}DeleteUserDefinedData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}DeleteUserDefinedData +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}DeleteUserDefinedField]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}DeleteUserDefinedField +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}GetUserDefinedRow]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}GetUserDefinedRow +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}GetUserDefinedData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}GetUserDefinedData +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}GetUserDefinedField]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}GetUserDefinedField +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}GetUserDefinedRows]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}GetUserDefinedRows +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}GetUserDefinedFields]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}GetUserDefinedFields +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}UpdateUserDefinedData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}UpdateUserDefinedData +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}UpdateUserDefinedField]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}UpdateUserDefinedField +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}UpdateUserDefinedFieldOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}UpdateUserDefinedFieldOrder +GO + + +/** Create Stored Procedures **/ + +create procedure {databaseOwner}{objectQualifier}AddUserDefinedRow + + @ModuleId int + +as + +insert into {databaseOwner}{objectQualifier}UserDefinedRows ( + ModuleId +) +values ( + @ModuleId +) + +select SCOPE_IDENTITY() + +GO + + +create procedure {databaseOwner}{objectQualifier}AddUserDefinedData + + @UserDefinedRowId int, + @UserDefinedFieldId int, + @FieldValue nvarchar(2000) + +as + +insert into {databaseOwner}{objectQualifier}UserDefinedData ( + UserDefinedFieldId, + UserDefinedRowId, + FieldValue +) +values ( + @UserDefinedFieldId, + @UserDefinedRowId, + @FieldValue +) + +select SCOPE_IDENTITY() + +GO + + +create procedure {databaseOwner}{objectQualifier}AddUserDefinedField + + @ModuleId int, + @FieldTitle varchar(50), + @Visible bit, + @FieldType varchar(20) + +as + +insert into {databaseOwner}{objectQualifier}UserDefinedFields ( + ModuleId, + FieldTitle, + Visible, + FieldType + ) +values ( + @ModuleId, + @FieldTitle, + @Visible, + @FieldType +) + +select SCOPE_IDENTITY() + +GO + +create procedure {databaseOwner}{objectQualifier}DeleteUserDefinedRow + + @UserDefinedRowId int + +as + +delete +from {databaseOwner}{objectQualifier}UserDefinedRows +where UserDefinedRowId = @UserDefinedRowId + +GO + +create procedure {databaseOwner}{objectQualifier}DeleteUserDefinedData + + @UserDefinedRowId int, + @UserDefinedFieldId int + +as + +delete +from {databaseOwner}{objectQualifier}UserDefinedData +where UserDefinedFieldId = @UserDefinedFieldId +and UserDefinedRowId = @UserDefinedRowId + +GO + +create procedure {databaseOwner}{objectQualifier}DeleteUserDefinedField + + @UserDefinedFieldId int + +as + +delete +from {databaseOwner}{objectQualifier}UserDefinedFields +where UserDefinedFieldId = @UserDefinedFieldId + +GO + +create procedure {databaseOwner}{objectQualifier}GetUserDefinedRow + + @UserDefinedRowId int, + @ModuleId int + +as + +select + FieldTitle, + FieldValue +from {databaseOwner}{objectQualifier}UserDefinedData +inner join {databaseOwner}{objectQualifier}UserDefinedFields on {databaseOwner}{objectQualifier}UserDefinedData.UserDefinedFieldId = {objectQualifier}UserDefinedFields.UserDefinedFieldId +where {databaseOwner}{objectQualifier}UserDefinedData.UserDefinedRowId = @UserDefinedRowId +and {databaseOwner}{objectQualifier}UserDefinedFields.ModuleId = @ModuleId + +GO + + +create procedure {databaseOwner}{objectQualifier}GetUserDefinedData + + @UserDefinedRowId int, + @UserDefinedFieldId int + +as + +select * +from {databaseOwner}{objectQualifier}UserDefinedData +where UserDefinedFieldId = @UserDefinedFieldId +and UserDefinedRowId = @UserDefinedRowId + +GO + +create procedure {databaseOwner}{objectQualifier}GetUserDefinedField + + @UserDefinedFieldId int + +as + +select + UserDefinedFieldId, + ModuleID, + FieldTitle, + Visible, + FieldOrder, + FieldType +from {objectQualifier}UserDefinedFields +where UserDefinedFieldId = @UserDefinedFieldId + +GO + + +create procedure {databaseOwner}{objectQualifier}GetUserDefinedRows + + @ModuleId int + +as + +select + D.UserDefinedRowId, + FieldTitle, + FieldValue +from {databaseOwner}{objectQualifier}UserDefinedRows R +left outer join {databaseOwner}{objectQualifier}UserDefinedData D on R.UserDefinedRowId = D.UserDefinedRowId +inner join {databaseOwner}{objectQualifier}UserDefinedFields F on D.UserDefinedFieldId = F.UserDefinedFieldId +where R.ModuleId = @ModuleId + +GO + +create procedure {databaseOwner}{objectQualifier}GetUserDefinedFields + +@ModuleId int + +as + +select + UserDefinedFieldId, + ModuleID, + FieldTitle, + Visible, + FieldOrder, + FieldType +from {databaseOwner}{objectQualifier}UserDefinedFields +where ModuleId = @ModuleId +order by FieldOrder + +GO + +create procedure {databaseOwner}{objectQualifier}UpdateUserDefinedData + + @UserDefinedRowId int, + @UserDefinedFieldId int, + @FieldValue nvarchar(2000) + +as + +update {databaseOwner}{objectQualifier}UserDefinedData +set FieldValue = @FieldValue +where UserDefinedFieldId = @UserDefinedFieldId +and UserDefinedRowId = @UserDefinedRowId + +GO + +create procedure {databaseOwner}{objectQualifier}UpdateUserDefinedField + + @UserDefinedFieldId int, + @FieldTitle varchar(50), + @Visible bit, + @FieldType varchar(20) + +as + +update {databaseOwner}{objectQualifier}UserDefinedFields +set FieldTitle = @FieldTitle, + Visible = @Visible, + FieldType = @FieldType +where UserDefinedFieldId = @UserDefinedFieldId + +GO + +create procedure {databaseOwner}{objectQualifier}UpdateUserDefinedFieldOrder + + @UserDefinedFieldId int, + @FieldOrder int + +as + +update {databaseOwner}{objectQualifier}UserDefinedFields +set FieldOrder = @FieldOrder +where UserDefinedFieldId = @UserDefinedFieldId + +GO + + +/************************************************************/ +/***** SqlDataProvider *****/ +/************************************************************/ \ No newline at end of file diff --git a/Providers/DataProviders/sqldataprovider/03.01.01.sqldataprovider b/Providers/DataProviders/sqldataprovider/03.01.01.sqldataprovider new file mode 100644 index 0000000..62c2cb8 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/03.01.01.sqldataprovider @@ -0,0 +1,33 @@ +/************************************************************/ +/***** SqlDataProvider *****/ +/***** *****/ +/***** *****/ +/***** Note: To manually execute this script you must *****/ +/***** perform a search and replace operation *****/ +/***** for {databaseOwner} and {objectQualifier} *****/ +/***** *****/ +/************************************************************/ + +/** Update stored procedure **/ + +if exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}DeleteUserDefinedRow]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) + drop procedure {databaseOwner}{objectQualifier}DeleteUserDefinedRow +GO + +create procedure {databaseOwner}{objectQualifier}DeleteUserDefinedRow + + @UserDefinedRowId int, + @ModuleID int + + +as + +delete +from {objectQualifier}UserDefinedRows +where UserDefinedRowId = @UserDefinedRowId and ModuleId=@ModuleID + +GO + +/************************************************************/ +/***** SqlDataProvider *****/ +/************************************************************/ \ No newline at end of file diff --git a/Providers/DataProviders/sqldataprovider/03.02.00.sqldataprovider b/Providers/DataProviders/sqldataprovider/03.02.00.sqldataprovider new file mode 100644 index 0000000..f81e193 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/03.02.00.sqldataprovider @@ -0,0 +1,333 @@ +/************************************************************/ +/***** *****/ +/***** SqlDataProvider *****/ +/***** Install/Upgrade for UserDefinedTable 3.2.0 *****/ +/***** [mhamburger 11/20/2005 *****/ +/***** [sleupold] 04/25/2006 *****/ +/***** *****/ +/***** *****/ +/***** Note: To manually execute this script you must *****/ +/***** perform a search and replace operation *****/ +/***** for {databaseOwner} and {objectQualifier} *****/ +/***** or use 'SQL' from Host Menu and run this. *****/ +/***** *****/ +/************************************************************/ + +SET QUOTED_IDENTIFIER ON +GO +SET ANSI_NULLS ON +GO + +/** Remove obsolete stored procedures from previous versions **/ + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}AddUserDefinedData]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}AddUserDefinedData] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}AddUserDefinedField]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}AddUserDefinedField] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}AddUserDefinedRow]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}AddUserDefinedRow] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}DeleteUserDefinedData]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}DeleteUserDefinedData] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}DeleteUserDefinedField]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}DeleteUserDefinedField] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}DeleteUserDefinedRow]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}DeleteUserDefinedRow] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}GetUserDefinedData]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}GetUserDefinedData] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}GetUserDefinedField]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}GetUserDefinedField] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}GetUserDefinedFields]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}GetUserDefinedFields] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}GetUserDefinedRow]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}GetUserDefinedRow] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}GetUserDefinedRows]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}GetUserDefinedRows] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UpdateUserDefinedData]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UpdateUserDefinedData] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UpdateUserDefinedField]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UpdateUserDefinedField] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UpdateUserDefinedFieldOrder]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UpdateUserDefinedFieldOrder] +GO + +/** Remove existing stored PROCEDURE **/ + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddData]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddData] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddField]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddRow]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddRow] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_DeleteData]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_DeleteData] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_DeleteField]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_DeleteField] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_DeleteRow]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_DeleteRow] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetData]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetData] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetField]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetFields]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetRow]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetRow] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetRows]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetRows] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateData]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateData] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] +GO + +IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldOrder]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldOrder] +GO + +/** UPDATE tables **/ + +IF (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedFields]'),'Required','AllowsNull')) IS NULL +ALTER TABLE {databaseOwner}{objectQualifier}UserDefinedFields +ADD Required bit NOT NULL DEFAULT (0), [Default] nvarchar(2000) DEFAULT ('') NOT NULL +GO + +/** Create new stored PROCEDUREs **/ + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_AddData +@UserDefinedRowId int, +@UserDefinedFieldId int, +@FieldValue nvarchar(2000) +AS +INSERT INTO {databaseOwner}{objectQualifier}UserDefinedData ( + UserDefinedFieldId, + UserDefinedRowId, + FieldValue +) +VALUES ( + @UserDefinedFieldId, + @UserDefinedRowId, + @FieldValue +) +SELECT SCOPE_IDENTITY() +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_AddField +@ModuleId int, +@FieldTitle varchar(50), +@Required bit, +@FieldType varchar(20), +@default nvarchar(2000), +@Visible bit +AS +INSERT INTO {databaseOwner}{objectQualifier}UserDefinedFields ( + ModuleId, + FieldTitle, + Required, + FieldType, + [Default], + Visible +) +VALUES ( + @ModuleId, + @FieldTitle, + @Required, + @FieldType, + @default, + @Visible +) +SELECT SCOPE_IDENTITY() +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_AddRow +@ModuleId int +AS +INSERT INTO {databaseOwner}{objectQualifier}UserDefinedRows ( + ModuleId +) +VALUES ( + @ModuleId +) +SELECT SCOPE_IDENTITY() +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_DeleteData +@UserDefinedRowId int, +@UserDefinedFieldId int +AS +DELETE +FROM {objectQualifier}UserDefinedData +WHERE UserDefinedFieldId = @UserDefinedFieldId +AND UserDefinedRowId = @UserDefinedRowId +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_DeleteField +@UserDefinedFieldId int +AS +DELETE +FROM {databaseOwner}{objectQualifier}UserDefinedFields +WHERE UserDefinedFieldId = @UserDefinedFieldId +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_DeleteRow + + @UserDefinedRowId int, + @ModuleID int +AS +DELETE +FROM {databaseOwner}{objectQualifier}UserDefinedRows +WHERE UserDefinedRowId = @UserDefinedRowId AND ModuleId=@ModuleID +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_GetData +@UserDefinedRowId int, +@UserDefinedFieldId int +AS +SELECT * +FROM {databaseOwner}{objectQualifier}UserDefinedData +WHERE UserDefinedFieldId = @UserDefinedFieldId +AND UserDefinedRowId = @UserDefinedRowId +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_GetField +@UserDefinedFieldId int +AS +SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + Required, + FieldOrder, + FieldType, + [default], + Visible +FROM {databaseOwner}{objectQualifier}UserDefinedFields +WHERE UserDefinedFieldId = @UserDefinedFieldId +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_GetFields +@ModuleId int +AS +SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + Required, + FieldOrder, + FieldType, + [default], + Visible +FROM {databaseOwner}{objectQualifier}UserDefinedFields +WHERE ModuleId = @ModuleId +ORDER by FieldOrder +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_GetRow +@UserDefinedRowId int, +@ModuleId int +AS +SELECT F.FieldTitle, + D.FieldValue, + F.FieldType +FROM {databaseOwner}{objectQualifier}UserDefinedData D +INNER JOIN {databaseOwner}{objectQualifier}UserDefinedFields F on D.UserDefinedFieldId = F.UserDefinedFieldId +WHERE D.UserDefinedRowId = @UserDefinedRowId +AND F.ModuleId = @ModuleId +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_GetRows +@ModuleId int +AS +SELECT R.UserDefinedRowId, + F.FieldTitle, + D.FieldValue +FROM {databaseOwner}{objectQualifier}UserDefinedRows R +LEFT OUTER JOIN {databaseOwner}{objectQualifier}UserDefinedData D on R.UserDefinedRowId = D.UserDefinedRowId +INNER JOIN {databaseOwner}{objectQualifier}UserDefinedFields F on D.UserDefinedFieldId = F.UserDefinedFieldId +WHERE R.ModuleId = @ModuleId +ORDER by R.UserDefinedRowID +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_UpdateData +@UserDefinedRowId int, +@UserDefinedFieldId int, +@FieldValue nvarchar(2000) +AS +UPDATE {databaseOwner}{objectQualifier}UserDefinedData +SET FieldValue = @FieldValue +WHERE UserDefinedFieldId = @UserDefinedFieldId +AND UserDefinedRowId = @UserDefinedRowId +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_UpdateField +@UserDefinedFieldId int, +@FieldTitle varchar(50), +@Required bit, +@FieldType varchar(20), +@default nvarchar(2000), +@Visible bit +AS +UPDATE {databaseOwner}{objectQualifier}UserDefinedFields +SET FieldTitle = @FieldTitle, + Required = @Required, + FieldType = @FieldType, + [default] = @default, + Visible = @Visible +WHERE UserDefinedFieldId = @UserDefinedFieldId +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_UpdateFieldOrder +@UserDefinedFieldId int, +@FieldOrder int +AS +UPDATE {databaseOwner}{objectQualifier}UserDefinedFields +SET FieldOrder = @FieldOrder +WHERE UserDefinedFieldId = @UserDefinedFieldId +GO diff --git a/Providers/DataProviders/sqldataprovider/03.03.00.sqldataprovider b/Providers/DataProviders/sqldataprovider/03.03.00.sqldataprovider new file mode 100644 index 0000000..6c965a1 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/03.03.00.sqldataprovider @@ -0,0 +1,329 @@ +/************************************************************/ +/***** SqlDataProvider *****/ +/***** Install/Upgrade for UserDefinedTable 3.3.0 *****/ +/***** [sleupold] 04/25/2006 *****/ +/***** *****/ +/***** *****/ +/***** Note: To manually execute this script you must *****/ +/***** perform a search AND replace operation *****/ +/***** for {databaseOwner} AND {objectQualifier} *****/ +/***** or use 'SQL' FROM Host Menu AND run this. *****/ +/***** *****/ +/***** *****/ +/************************************************************/ + +SET QUOTED_IDENTIFIER ON +GO +SET ANSI_NULLS ON +GO + +/** Add extended settings for UDT fields **/ + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddData] +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetFields]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldOrder] +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_SwapFieldOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_SwapFieldOrder] +GO + + +/** Optimize indexes AND PK **/ + +IF EXISTS (SELECT name FROM sys.indexes + WHERE name = 'IX_{objectQualifier}UserDefinedData') +DROP INDEX [IX_{objectQualifier}UserDefinedData] on {objectQualifier}UserDefinedData +GO + +IF EXISTS (SELECT name FROM sys.indexes + WHERE name = 'IX_{objectQualifier}UserDefinedData_1') +DROP INDEX [IX_{objectQualifier}UserDefinedData_1] on {objectQualifier}UserDefinedData +GO + +IF EXISTS (SELECT name FROM sys.indexes + WHERE name = 'PK_{objectQualifier}UserDefinedData') +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedData] DROP CONSTRAINT [PK_{objectQualifier}UserDefinedData] +GO + +IF NOT (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedData]'),'UserDefinedDataId','AllowsNull')) IS NULL + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedData] DROP COLUMN [UserDefinedDataId] +GO + +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedData] WITH NOCHECK ADD +CONSTRAINT [PK_{objectQualifier}UserDefinedData] PRIMARY KEY CLUSTERED ([UserDefinedFieldId], [UserDefinedRowId]) +GO + +IF EXISTS (SELECT name FROM sys.indexes + WHERE name = 'IX_{objectQualifier}UserDefinedFields') +DROP INDEX [IX_{objectQualifier}UserDefinedFields] on {objectQualifier}UserDefinedFields +GO + + +CREATE UNIQUE INDEX [IX_{objectQualifier}UserDefinedFields] ON {databaseOwner}[{objectQualifier}UserDefinedFields] (ModuleId, FieldOrder) +GO + +/** update existing tables **/ + +IF (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedFields]'),'ExtendedSettings','AllowsNull')) IS NULL +ALTER TABLE {databaseOwner}{objectQualifier}UserDefinedFields +ADD ExtendedSettings nvarchar(2000) DEFAULT ('') NOT NULL +GO + +/** add fields Created at/by & last updated at/by **/ + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFields] + (ModuleID, FieldTitle, Visible, FieldOrder, FieldType, Required) + SELECT ModuleID, + 'Created by' AS fTitle, + 0 AS vis, + MAX(FieldOrder) + 1 AS NewOrder, + 'CreatedBy' as fType, + 1 AS req + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE NOT ModuleID IN (SELECT ModuleID FROM {databaseOwner}[{objectQualifier}UserDefinedFields] WHERE FieldType = 'CreatedBy') + GROUP BY ModuleID +GO + + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFields] + (ModuleID, FieldTitle, Visible, FieldOrder, FieldType, Required, [Default]) + SELECT ModuleID, + 'Created at' ASfTitle, + 0 AS vis, + MAX(FieldOrder) + 1 AS NewOrder, + 'CreatedAt' as fType, + 1 AS req, + Convert(nVarChar, GetDate(), 126) AS now + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE NOT ModuleID IN (SELECT ModuleID FROM {databaseOwner}[{objectQualifier}UserDefinedFields] WHERE FieldType = 'CreatedAt') + GROUP BY ModuleID +GO + + + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFields] + (ModuleID, FieldTitle, Visible, FieldOrder, FieldType, Required) + SELECT ModuleID, + 'Last updated by' AS fTitle, + 0 AS vis, + MAX(FieldOrder) + 1 AS NewOrder, + 'ChangedBy' as fType, + 1 AS req + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE NOT ModuleID IN (SELECT ModuleID FROM {databaseOwner}[{objectQualifier}UserDefinedFields] WHERE FieldType = 'ChangedBy') + GROUP BY ModuleID +GO + + + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFields] + (ModuleID, FieldTitle, Visible, FieldOrder, FieldType, Required, [Default]) + SELECT ModuleID, + 'Last updated at' AS fTitle, + 0 AS vis, + MAX(FieldOrder) + 1 AS NewOrder, + 'ChangedAt' as fType, + 1 AS req, + Convert(nVarChar, GetDate(), 126) AS now + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE NOT ModuleID IN (SELECT ModuleID FROM {databaseOwner}[{objectQualifier}UserDefinedFields] WHERE FieldType = 'ChangedAt') +GROUP BY ModuleID +GO + + +/** DROP rows without values **/ + + DELETE {databaseOwner}{objectQualifier}UserDefinedRows + FROM {databaseOwner}{objectQualifier}UserDefinedRows R + LEFT JOIN {databaseOwner}{objectQualifier}UserDefinedData D + ON D.UserDefinedRowId = R.UserDefinedRowId + WHERE D.UserDefinedRowId IS NUll +GO + +/** add default values for existing records **/ + + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedData] (UserDefinedFieldId, UserDefinedRowId, FieldValue) + SELECT F.UserDefinedFieldId, R.UserDefinedRowId, 'UDT-Import' As aUserName + FROM ({databaseOwner}{objectQualifier}UserDefinedFields F + INNER JOIN {databaseOwner}{objectQualifier}UserDefinedRows R ON F.ModuleID = R.ModuleID) + LEFT JOIN {databaseOwner}{objectQualifier}UserDefinedData D ON F.UserDefinedFieldId = D.UserDefinedFieldId AND R.UserDefinedRowId = D.UserDefinedRowId + WHERE FieldType IN ('CreatedBy', 'ChangedBy') AND D.UserDefinedFieldId IS Null +GO + + + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedData] (UserDefinedFieldId, UserDefinedRowId, FieldValue) + SELECT F.UserDefinedFieldId, R.UserDefinedRowId, Convert(nVarChar, GetDate(), 126) AS theDate + FROM ({databaseOwner}{objectQualifier}UserDefinedFields F + INNER JOIN {databaseOwner}{objectQualifier}UserDefinedRows R ON F.ModuleID = R.ModuleID) + LEFT JOIN {databaseOwner}{objectQualifier}UserDefinedData D ON F.UserDefinedFieldId = D.UserDefinedFieldId AND R.UserDefinedRowId = D.UserDefinedRowId + WHERE FieldType IN ('CreatedAt', 'ChangedAt') AND D.UserDefinedFieldId IS Null +GO + +/** move AND rename Settings FROM ModuleSettings to TabModuleSettings **/ + +INSERT INTO {databaseOwner}{objectQualifier}TabModuleSettings (TabModuleID, SettingName, SettingValue) +SELECT TM.TabModuleID, 'UDT_' + MS.SettingName AS SN, MS.SettingValue +FROM {databaseOwner}{objectQualifier}TabModules TM +INNER JOIN {databaseOwner}{objectQualifier}ModuleSettings MS +INNER JOIN {databaseOwner}{objectQualifier}ModuleDefinitions MD +INNER JOIN {databaseOwner}{objectQualifier}Modules M + ON MD.ModuleDefID = M.ModuleDefID + ON MS.ModuleID = M.ModuleID + ON TM.ModuleID = M.ModuleID +WHERE MD.FriendlyName = N'User Defined Table' AND MS.SettingName IN (N'AlternatingItemStyleBackColor', N'sortfield', N'sortorder', N'Paging') +GO + + +DELETE MS +FROM {databaseOwner}{objectQualifier}ModuleSettings MS +INNER JOIN {databaseOwner}{objectQualifier}Modules M ON MS.ModuleID = M.ModuleID +INNER JOIN {databaseOwner}{objectQualifier}ModuleDefinitions MD ON M.ModuleDefID = MD.ModuleDefID +WHERE MD.FriendlyName = N'User Defined Table' AND MS.SettingName IN (N'AlternatingItemStyleBackColor', N'sortfield', N'sortorder', N'Paging') +GO + + +UPDATE MS +SET MS.SettingName = 'UDT_' + MS.SettingName +FROM {databaseOwner}{objectQualifier}ModuleSettings MS +INNER JOIN {databaseOwner}{objectQualifier}Modules M ON MS.ModuleID = M.ModuleID +INNER JOIN {databaseOwner}{objectQualifier}ModuleDefinitions MD ON M.ModuleDefID = MD.ModuleDefID +WHERE MD.FriendlyName = N'User Defined Table' +AND MS.SettingName IN (N'ImageWidth', N'URLFullPath') +GO + +/** create new stored procedures **/ + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] +@UserDefinedFieldId INT +AS +SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + Required, + FieldOrder, + FieldType, + [default], + Visible, + ExtendedSettings +FROM UserDefinedFields +WHERE UserDefinedFieldId = @UserDefinedFieldId +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] +@ModuleId INT +AS +SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + Required, + FieldOrder, + FieldType, + [default], + Visible, + ExtendedSettings +FROM {objectQualifier}UserDefinedFields +WHERE ModuleId = @ModuleId +ORDER BY FieldOrder +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] +@ModuleId INT, +@FieldTitle VARCHAR(50), +@Required BIT, +@FieldType VARCHAR(20), +@default NVARCHAR(2000), +@Visible BIT, +@ExtendedSettings nvarchar(2000) +AS +DECLARE @InsPos INT +SET @InsPos = (SELECT MAX(FieldOrder) AS MaxPos FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE ModuleID = @ModuleID GROUP BY ModuleID) + 1 +IF @insPos IS Null SET @InsPos = 1 +INSERT INTO {databaseOwner}{objectQualifier}UserDefinedFields ( + ModuleId, + FieldTitle, + Required, + FieldType, + FieldOrder, + [Default], + Visible, + ExtendedSettings +) +VALUES ( + @ModuleId, + @FieldTitle, + @Required, + @FieldType, + @InsPos, + @default, + @Visible, + @ExtendedSettings +) +SELECT SCOPE_IDENTITY() +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] +@UserDefinedFieldId INT, +@FieldTitle VARCHAR(50), +@Required BIT, +@FieldType VARCHAR(20), +@default NVARCHAR(2000), +@Visible BIT, +@ExtendedSettings NVARCHAR(2000) +AS +UPDATE {databaseOwner}{objectQualifier}UserDefinedFields +SET FieldTitle = @FieldTitle, + Required = @Required, + FieldType = @FieldType, + [default] = @default, + Visible = @Visible, + ExtendedSettings = @ExtendedSettings +WHERE UserDefinedFieldId = @UserDefinedFieldId +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_SwapFieldOrder] +@FirstUserDefinedFieldId INT, +@SecndUserDefinedFieldId INT +AS +DECLARE @Pos1 INT +DECLARE @Pos2 INT +SET @Pos1 = (SELECT FieldOrder FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE UserDefinedFieldId = @FirstUserDefinedFieldId) +SET @Pos2 = (SELECT FieldOrder FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE UserDefinedFieldId = @SecndUserDefinedFieldId) + +UPDATE {databaseOwner}{objectQualifier}UserDefinedFields SET FieldOrder = -1 WHERE UserDefinedFieldId = @SecndUserDefinedFieldId +UPDATE {databaseOwner}{objectQualifier}UserDefinedFields SET FieldOrder = @Pos2 WHERE UserDefinedFieldId = @FirstUserDefinedFieldId +UPDATE {databaseOwner}{objectQualifier}UserDefinedFields SET FieldOrder = @Pos1 WHERE UserDefinedFieldId = @SecndUserDefinedFieldId +GO + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_AddData +@UserDefinedRowId INT, +@UserDefinedFieldId INT, +@FieldValue nvarchar(2000) +AS +INSERT INTO {databaseOwner}{objectQualifier}UserDefinedData ( + UserDefinedFieldId, + UserDefinedRowId, + FieldValue +) +VALUES ( + @UserDefinedFieldId, + @UserDefinedRowId, + @FieldValue +) +GO + diff --git a/Providers/DataProviders/sqldataprovider/03.03.04.sqldataprovider b/Providers/DataProviders/sqldataprovider/03.03.04.sqldataprovider new file mode 100644 index 0000000..9934366 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/03.03.04.sqldataprovider @@ -0,0 +1,119 @@ +/************************************************************/ +/***** SqlDataProvider *****/ +/***** Install/Upgrade for UserDefinedTable 3.3.4 *****/ +/***** [sleupold] 08/06/2006 *****/ +/***** *****/ +/***** *****/ +/***** Note: To manually execute this script you must *****/ +/***** perform a search AND replace operation *****/ +/***** for {databaseOwner} AND {objectQualifier} *****/ +/***** or use 'SQL' FROM Host Menu AND run this. *****/ +/***** *****/ +/***** *****/ +/************************************************************/ + +SET QUOTED_IDENTIFIER ON +GO +SET ANSI_NULLS ON +GO + + +/** check for compatible DNN version **/ +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'UDT_Install_Semaphore') AND OBJECTPROPERTY(id, N'IsTable') = 1) +DROP Table UDT_Install_Semaphore +GO + +CREATE TABLE UDT_Install_Semaphore (value INT PRIMARY KEY) +GO + +DECLARE @dnnVer INT +SET @dnnver = (SELECT TOP 1 Major*10000+Minor*100+Build FROM {databaseOwner}[{objectQualifier}Version] ORDER BY Major DESC, Minor DESC, Build DESC) +IF @dnnver < 30203 OR ( @dnnver >= 40000 AND @dnnver <40004) + BEGIN + INSERT INTO UDT_Install_Semaphore (value) VALUES (0) + RAISERROR ('Incompatible DotNetNuke framework version installed. Please upgrade to V. 3.3 or V. 4.1 or re-install previous version of this module!', 16, 1) + END + ELSE + INSERT INTO UDT_Install_Semaphore (value) VALUES (1) +GO + +/** Convert DataType for FieldTitle from VARCHAR to NVARCHAR in order to allow usage of Unicode characters **/ +IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND (SELECT UserType FROM syscolumns WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedFields]') AND Name = 'FieldTitle')=2 + ALTER TABLE {databaseOwner}{objectQualifier}UserDefinedFields + ALTER COLUMN FieldTitle NVARCHAR(50) +GO + +IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] +GO + +IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] +GO + +IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldOrder] +GO + +IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_SwapFieldOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_SwapFieldOrder] +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] +@ModuleId INT, +@FieldTitle NVARCHAR(50), +@Required BIT, +@FieldType VARCHAR(20), +@default NVARCHAR(2000), +@Visible BIT, +@ExtendedSettings NVARCHAR(2000) +AS +DECLARE @InsPos INT +SET @InsPos = (SELECT MAX(FieldOrder) AS MaxPos FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE ModuleID = @ModuleID GROUP BY ModuleID) + 1 +IF @insPos IS Null SET @InsPos = 1 +INSERT INTO {databaseOwner}{objectQualifier}UserDefinedFields ( + ModuleId, + FieldTitle, + Required, + FieldType, + FieldOrder, + [Default], + Visible, + ExtendedSettings +) +VALUES ( + @ModuleId, + @FieldTitle, + @Required, + @FieldType, + @InsPos, + @default, + @Visible, + @ExtendedSettings +) +SELECT SCOPE_IDENTITY() +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] +@UserDefinedFieldId INT, +@FieldTitle NVARCHAR(50), +@Required BIT, +@FieldType VARCHAR(20), +@default NVARCHAR(2000), +@Visible BIT, +@ExtendedSettings NVARCHAR(2000) +AS +UPDATE {databaseOwner}{objectQualifier}UserDefinedFields +SET FieldTitle = @FieldTitle, + Required = @Required, + FieldType = @FieldType, + [default] = @default, + Visible = @Visible, + ExtendedSettings = @ExtendedSettings +WHERE UserDefinedFieldId = @UserDefinedFieldId +GO + + +/** delete version table **/ +DROP TABLE UDT_Install_Semaphore +GO diff --git a/Providers/DataProviders/sqldataprovider/03.03.05.sqldataprovider b/Providers/DataProviders/sqldataprovider/03.03.05.sqldataprovider new file mode 100644 index 0000000..52a2790 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/03.03.05.sqldataprovider @@ -0,0 +1,86 @@ +/************************************************************/ +/***** SqlDataProvider *****/ +/***** Install/Upgrade for UserDefinedTable 3.3.5 *****/ +/***** [sleupold] 08/19/2006 *****/ +/***** *****/ +/***** *****/ +/***** Note: To manually execute this script you must *****/ +/***** perform a search AND replace operation *****/ +/***** for {databaseOwner} AND {objectQualifier} *****/ +/***** or use 'SQL' FROM Host Menu AND run this. *****/ +/***** *****/ +/***** *****/ +/************************************************************/ + +SET QUOTED_IDENTIFIER ON +GO +SET ANSI_NULLS ON +GO + + +/** check for compatible DNN version **/ +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'UDT_Install_Semaphore') AND OBJECTPROPERTY(id, N'IsTable') = 1) +DROP Table UDT_Install_Semaphore +GO + +CREATE TABLE UDT_Install_Semaphore (value INT PRIMARY KEY) +GO + +DECLARE @dnnVer INT +SET @dnnver = (SELECT TOP 1 Major*10000+Minor*100+Build FROM {databaseOwner}[{objectQualifier}Version] ORDER BY Major DESC, Minor DESC, Build DESC) +IF @dnnver < 30203 OR ( @dnnver >= 40000 AND @dnnver <40004) + BEGIN + INSERT INTO UDT_Install_Semaphore (value) VALUES (0) + RAISERROR ('Incompatible DotNetNuke framework version installed. Please upgrade to V. 3.3.x or V. 4.3.x or re-install previous version of this module!', 16, 1) + END + ELSE + INSERT INTO UDT_Install_Semaphore (value) VALUES (1) +GO + +/** Convert DataType for FieldValue from NVARCHAR to NTEXT in order to allow large Texts **/ +IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND (SELECT Type FROM syscolumns WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedData]') AND Name = 'FieldValue')<>35 + ALTER TABLE {databaseOwner}{objectQualifier}UserDefinedData + ALTER COLUMN FieldValue NTEXT NOT NULL +GO + +--Remove this value (06.00.05) because it is not compatible with SQL Azure and 06.00.03 changes to nvarchar(max) instead +--sp_tableoption N'{databaseOwner}[{objectQualifier}UserDefinedData]', 'text in row', 'ON' + +IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddData] +GO + +IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateData] +GO + + +CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_AddData +@UserDefinedRowId int, +@UserDefinedFieldId int, +@FieldValue nText +AS +INSERT INTO {databaseOwner}{objectQualifier}UserDefinedData + ( UserDefinedFieldId, UserDefinedRowId, FieldValue) + VALUES (@UserDefinedFieldId, @UserDefinedRowId, @FieldValue) +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateData] +@UserDefinedRowId int, +@UserDefinedFieldId int, +@FieldValue nText +AS + DELETE FROM {databaseOwner}[{objectQualifier}UserDefinedData] + WHERE UserDefinedFieldId = @UserDefinedFieldId + AND UserDefinedRowId = @UserDefinedRowId + + IF @FieldValue NOT LIKE '' + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedData] + ( UserDefinedFieldId, UserDefinedRowId, FieldValue) + VALUES (@UserDefinedFieldId, @UserDefinedRowId,@FieldValue) +GO + + +/** delete version table **/ +DROP TABLE UDT_Install_Semaphore +GO diff --git a/Providers/DataProviders/sqldataprovider/03.03.06.sqldataprovider b/Providers/DataProviders/sqldataprovider/03.03.06.sqldataprovider new file mode 100644 index 0000000..e857077 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/03.03.06.sqldataprovider @@ -0,0 +1,39 @@ +/************************************************************/ +/***** SqlDataProvider *****/ +/***** Install/Upgrade for UserDefinedTable 3.3.6 *****/ +/***** [sleupold] 10/12/2006 *****/ +/***** *****/ +/***** *****/ +/***** Note: To manually execute this script you must *****/ +/***** perform a search AND replace operation *****/ +/***** for {databaseOwner} AND {objectQualifier} *****/ +/***** or use 'SQL' FROM Host Menu AND run this. *****/ +/***** *****/ +/***** *****/ +/************************************************************/ + +SET QUOTED_IDENTIFIER ON +GO +SET ANSI_NULLS ON +GO + + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldOrder] +GO + + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_SwapFieldOrder] +@FirstUserDefinedFieldId INT, +@SecndUserDefinedFieldId INT +AS +DECLARE @Pos1 INT +DECLARE @Pos2 INT +SET @Pos1 = (SELECT FieldOrder FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE UserDefinedFieldId = @FirstUserDefinedFieldId) +SET @Pos2 = (SELECT FieldOrder FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE UserDefinedFieldId = @SecndUserDefinedFieldId) + +UPDATE {databaseOwner}{objectQualifier}UserDefinedFields SET FieldOrder = -1 WHERE UserDefinedFieldId = @SecndUserDefinedFieldId +UPDATE {databaseOwner}{objectQualifier}UserDefinedFields SET FieldOrder = @Pos2 WHERE UserDefinedFieldId = @FirstUserDefinedFieldId +UPDATE {databaseOwner}{objectQualifier}UserDefinedFields SET FieldOrder = @Pos1 WHERE UserDefinedFieldId = @SecndUserDefinedFieldId +GO + diff --git a/Providers/DataProviders/sqldataprovider/03.03.07.sqldataprovider b/Providers/DataProviders/sqldataprovider/03.03.07.sqldataprovider new file mode 100644 index 0000000..06a595a --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/03.03.07.sqldataprovider @@ -0,0 +1,297 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 3.3.7 *****/ + /***** [sleupold] 10/23/2006 *****/ + /***** [scullmann] 10/27/2006 *****/ + /***** [sleupold] 12/16/2006 *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ + + SET QUOTED_IDENTIFIER ON + GO + SET ANSI_NULLS ON + GO + + + /** check for compatible DNN version **/ + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'UDT_Install_Semaphore') AND OBJECTPROPERTY(id, N'IsTable') = 1) + DROP Table UDT_Install_Semaphore + GO + + CREATE TABLE UDT_Install_Semaphore (value INT PRIMARY KEY) + GO + + DECLARE @dnnVer INT + SET @dnnver = (SELECT TOP 1 Major*10000+Minor*100+Build FROM {databaseOwner}[{objectQualifier}Version] ORDER BY Major DESC, Minor DESC, Build DESC) + IF @dnnver < 30305 OR ( @dnnver >= 40000 AND @dnnver < 40305) + BEGIN + INSERT INTO UDT_Install_Semaphore (value) VALUES (0) + RAISERROR ('Incompatible DotNetNuke framework version installed. Please upgrade to V. 3.3.5+ or V. 4.3.5+ or re-install previous version of this module!', 16, 1) + END + ELSE + INSERT INTO UDT_Install_Semaphore (value) VALUES (1) + GO + + /* update table structure: */ + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] + ALTER COLUMN [Default] nvarchar(2000) Null + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedFields]'),'OutputSettings','AllowsNull')) IS NULL + EXECUTE sp_rename N'{databaseOwner}[{objectQualifier}UserDefinedFields].ExtendedSettings', N'OutputSettings', 'COLUMN' + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND NOT (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedFields]'),'OutputSettings','AllowsNull')) IS NULL + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] + ALTER COLUMN OutputSettings nvarchar(2000) Null + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedFields]'),'InputSettings','AllowsNull')) IS NULL + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] ADD + InputSettings nvarchar(2000), + ValidationRule nvarchar(512) NULL, + ValidationMessage nvarchar(512) NULL + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedFields]'),'NormalizeFlag','AllowsNull')) IS NULL + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] ADD + NormalizeFlag Bit Not Null Default (0) + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedFields]'),'HelpText','AllowsNull')) IS NULL + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] ADD + HelpText nvarchar(512) NULL + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 + BEGIN + UPDATE {databaseOwner}[{objectQualifier}UserDefinedFields] + SET InputSettings = OutputSettings, + OutputSettings= Null + WHERE FieldType IN ('Int32', 'Decimal', 'Currency', 'String') + AND InputSettings IS Null + AND NOT OutputSettings Is Null + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 + UPDATE {databaseOwner}[{objectQualifier}UserDefinedFields] + SET [Default] = OutputSettings, + OutputSettings= Null + WHERE FieldType = 'Expression' + AND InputSettings IS Null + AND NOT OutputSettings Is Null + END + + GO + + + /* replace stored procedures with updated versions: */ + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] + @ModuleId INT, + @FieldTitle NVARCHAR(50), + @BeforePos INT, + @HelpText NVARCHAR(512), + @Required BIT, + @FieldType VARCHAR(20), + @Default NVARCHAR(2000), + @Visible BIT, + @InputSettings NVARCHAR(2000), + @OutputSettings NVARCHAR(2000), + @NormalizeFlag BIT, + @ValidationRule NVARCHAR(512), + @ValidationMessage NVARCHAR(512) + AS + DECLARE @InsPos INT + /* find insert position and adjust field order of subsequent fields: */ + SET @InsPos = (SELECT MAX(FieldOrder) AS MaxPos FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE ModuleID = @ModuleID GROUP BY ModuleID) + 1 + IF @InsPos IS Null SET @InsPos = 1 + IF @BeforePos Is Null SET @BeforePos = @InsPos + IF @InsPos > @BeforePos BEGIN + UPDATE {databaseOwner}[{objectQualifier}UserDefinedFields] + SET FieldOrder = FieldOrder + 1 + WHERE ModuleID = @ModuleID AND FieldOrder >= @BeforePos + SET @InsPos = @BeforePos + END + + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFields] ( + ModuleId, + FieldTitle, + HelpText, + Required, + FieldType, + FieldOrder, + [Default], + Visible, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage + ) + VALUES ( + @ModuleId, + @FieldTitle, + @HelpText, + @Required, + @FieldType, + @InsPos, + @Default, + @Visible, + @InputSettings, + @OutputSettings, + @NormalizeFlag, + @ValidationRule, + @ValidationMessage + ) + SELECT SCOPE_IDENTITY() + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] + @UserDefinedFieldId INT + AS + SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + HelpText, + Required, + FieldOrder, + FieldType, + [default], + Visible, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE UserDefinedFieldId = @UserDefinedFieldId + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetFields]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] + @ModuleId INT + AS + SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + HelpText, + Required, + FieldOrder, + FieldType, + [default], + Visible, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE ModuleId = @ModuleId + ORDER BY FieldOrder + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldOrder] + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_SwapFieldOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_SwapFieldOrder] + GO + + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_SwapFieldOrder] + @FirstUserDefinedFieldId INT, + @SecndUserDefinedFieldId INT + AS + DECLARE @Pos1 INT + DECLARE @Pos2 INT + SET @Pos1 = (SELECT FieldOrder FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE UserDefinedFieldId = @FirstUserDefinedFieldId) + SET @Pos2 = (SELECT FieldOrder FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE UserDefinedFieldId = @SecndUserDefinedFieldId) + + UPDATE {objectQualifier}UserDefinedFields SET FieldOrder = -1 WHERE UserDefinedFieldId = @SecndUserDefinedFieldId + UPDATE {objectQualifier}UserDefinedFields SET FieldOrder = @Pos2 WHERE UserDefinedFieldId = @FirstUserDefinedFieldId + UPDATE {objectQualifier}UserDefinedFields SET FieldOrder = @Pos1 WHERE UserDefinedFieldId = @SecndUserDefinedFieldId + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] + @UserDefinedFieldId INT, + @FieldTitle NVARCHAR(50), + @HelpText NVARCHAR(512), + @Required BIT, + @FieldType VARCHAR(20), + @default NVARCHAR(2000), + @Visible BIT, + @InputSettings NVARCHAR(2000), + @OutputSettings NVARCHAR(2000), + @NormalizeFlag BIT, + @ValidationRule NVARCHAR(512), + @ValidationMessage NVARCHAR(512) + + AS + UPDATE {databaseOwner}[{objectQualifier}UserDefinedFields] + SET FieldTitle = @FieldTitle, + HelpText = @HelpText, + Required = @Required, + FieldType = @FieldType, + [default] = @default, + Visible = @Visible, + InputSettings = @InputSettings, + OutputSettings = @OutputSettings, + NormalizeFlag = @NormalizeFlag, + ValidationRule = @ValidationRule, + ValidationMessage = @ValidationMessage + WHERE UserDefinedFieldId = @UserDefinedFieldId + GO + + /** Clean up settings. Move all TabSettings out of ModuleSettings if not present inside Tabsettings **/ + IF (SELECT value FROM UDT_Install_Semaphore) = 1 + INSERT INTO {databaseOwner}{objectQualifier}TabModuleSettings (TabModuleID, SettingName, SettingValue) + SELECT TM.TabModuleID, MS.SettingName, MS.SettingValue + FROM {databaseOwner}{objectQualifier}TabModules AS TM INNER JOIN + {databaseOwner}{objectQualifier}ModuleSettings AS MS ON TM.ModuleID = MS.ModuleID LEFT OUTER JOIN + {databaseOwner}{objectQualifier}TabModuleSettings AS TS ON TM.TabModuleID = TS.TabModuleID AND MS.SettingName = TS.SettingName + WHERE (TS.TabModuleID IS NULL) AND (TS.SettingName IS NULL) AND + MS.SettingName IN ( N'UDT_SortField', N'UDT_SortOrder', N'UDT_Paging', N'UDT_Filter', N'UDT_Search', + N'UDT_UsedCssClasses', N'UDT_XslPreDefinedStyleSheet', N'UDT_XslUserDefinedStyleSheet', N'UDT_RenderingMethod') + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 + UPDATE {databaseOwner}{objectQualifier}UserDefinedFields + SET NormalizeFlag = SettingValue + FROM {databaseOwner}{objectQualifier}ModuleSettings AS MS INNER JOIN + {databaseOwner}{objectQualifier}UserDefinedFields AS UDF ON MS.ModuleID = UDF.ModuleId + WHERE SettingName = N'UDT_URLFullPath' AND FieldType = 'URL' AND SettingValue = N'True' + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 + DELETE FROM {databaseOwner}{objectQualifier}ModuleSettings + WHERE SettingName IN ( N'UDT_SortField', N'UDT_SortOrder', N'UDT_Paging', N'UDT_Filter', N'UDT_Search', + N'UDT_UsedCssClasses', N'UDT_XslPreDefinedStyleSheet', N'UDT_XslUserDefinedStyleSheet', N'UDT_RenderingMethod', N'UDT_URLFullPath') + GO + + /** delete version table **/ + DROP TABLE UDT_Install_Semaphore + GO diff --git a/Providers/DataProviders/sqldataprovider/03.04.00.sqldataprovider b/Providers/DataProviders/sqldataprovider/03.04.00.sqldataprovider new file mode 100644 index 0000000..1039b3c --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/03.04.00.sqldataprovider @@ -0,0 +1,237 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 3.4.0 *****/ + /***** [sleupold] 01/22/2007 *****/ + /***** [sleupold] 02/23/2007 *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ + + SET QUOTED_IDENTIFIER ON + GO + SET ANSI_NULLS ON + GO + + + /** check for compatible DNN version **/ + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'UDT_Install_Semaphore') AND OBJECTPROPERTY(id, N'IsTable') = 1) + DROP Table UDT_Install_Semaphore + GO + + CREATE TABLE UDT_Install_Semaphore (value INT PRIMARY KEY, flag BIT NOT Null) + GO + + DECLARE @dnnVer INT + SET @dnnver = (SELECT TOP 1 Major*10000+Minor*100+Build FROM {databaseOwner}[{objectQualifier}Version] ORDER BY Major DESC, Minor DESC, Build DESC) + IF @dnnver < 30305 OR ( @dnnver >= 40000 AND @dnnver < 40305) + BEGIN + INSERT INTO UDT_Install_Semaphore (value, Flag) VALUES (0, 0) + RAISERROR ('Incompatible DotNetNuke framework version installed. Please upgrade to V. 3.3.5+ or V. 4.3.5+ or re-install previous version of this module!', 16, 1) + END + ELSE + INSERT INTO UDT_Install_Semaphore (value, Flag) VALUES (1, 0) + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedFields]'),'Searchable','AllowsNull')) IS NULL + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] + ADD Searchable BIT DEFAULT 0 Not Null + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedFields]'),'ShowOnEdit','AllowsNull')) IS NULL + BEGIN + UPDATE UDT_Install_Semaphore SET flag = 1 + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] + ADD ShowOnEdit BIT DEFAULT 1 Not Null + END + GO + + IF (SELECT Flag FROM UDT_Install_Semaphore) = 1 + UPDATE {databaseOwner}[{objectQualifier}UserDefinedFields] + SET ShowOnEdit = 0 + WHERE (FieldType Like 'Created%' OR FieldType Like 'Changed%') AND visible = 0 + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_DeleteRows]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_DeleteRows] + GO + + CREATE PROCEDURE {databaseOwner}{objectQualifier}UserDefinedTable_DeleteRows + @ModuleID int + AS + DELETE + FROM {databaseOwner}{objectQualifier}UserDefinedRows + WHERE ModuleId=@ModuleID + GO + + /* replace stored procedures with updated versions: */ + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] + @ModuleId INT, + @FieldTitle NVARCHAR(50), + @BeforePos INT, + @HelpText NVARCHAR(512), + @Required BIT, + @FieldType VARCHAR(20), + @Default NVARCHAR(2000), + @Visible BIT, + @ShowOnEdit BIT, + @Searchable BIT, + @InputSettings NVARCHAR(2000), + @OutputSettings NVARCHAR(2000), + @NormalizeFlag BIT, + @ValidationRule NVARCHAR(512), + @ValidationMessage NVARCHAR(512) + AS + DECLARE @InsPos INT + /* find insert position and adjust field order of subsequent fields: */ + SET @InsPos = (SELECT MAX(FieldOrder) AS MaxPos FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE ModuleID = @ModuleID GROUP BY ModuleID) + 1 + IF @InsPos IS Null SET @InsPos = 1 + IF @BeforePos Is Null SET @BeforePos = @InsPos + IF @InsPos > @BeforePos BEGIN + UPDATE [{objectQualifier}UserDefinedFields] + SET FieldOrder = FieldOrder + 1 + WHERE ModuleID = @ModuleID AND FieldOrder >= @BeforePos + SET @InsPos = @BeforePos + END + + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFields] ( + ModuleId, + FieldTitle, + HelpText, + Required, + FieldType, + FieldOrder, + [Default], + Visible, + ShowOnEdit, + Searchable, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage + ) + VALUES ( + @ModuleId, + @FieldTitle, + @HelpText, + @Required, + @FieldType, + @InsPos, + @Default, + @Visible, + @ShowOnEdit, + @Searchable, + @InputSettings, + @OutputSettings, + @NormalizeFlag, + @ValidationRule, + @ValidationMessage + ) + SELECT SCOPE_IDENTITY() + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] + @UserDefinedFieldId INT, + @FieldTitle NVARCHAR(50), + @HelpText NVARCHAR(512), + @Required BIT, + @FieldType VARCHAR(20), + @default NVARCHAR(2000), + @Visible BIT, + @ShowOnEdit BIT, + @Searchable BIT, + @InputSettings NVARCHAR(2000), + @OutputSettings NVARCHAR(2000), + @NormalizeFlag BIT, + @ValidationRule NVARCHAR(512), + @ValidationMessage NVARCHAR(512) + + AS + UPDATE {databaseOwner}[{objectQualifier}UserDefinedFields] + SET FieldTitle = @FieldTitle, + HelpText = @HelpText, + Required = @Required, + FieldType = @FieldType, + [default] = @default, + Visible = @Visible, + ShowOnEdit = @ShowOnEdit, + Searchable = @Searchable, + InputSettings = @InputSettings, + OutputSettings = @OutputSettings, + NormalizeFlag = @NormalizeFlag, + ValidationRule = @ValidationRule, + ValidationMessage = @ValidationMessage + WHERE UserDefinedFieldId = @UserDefinedFieldId + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] + @UserDefinedFieldId INT + AS + SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + HelpText, + Required, + FieldOrder, + FieldType, + [default], + Visible, + ShowOnEdit, + Searchable, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE UserDefinedFieldId = @UserDefinedFieldId + GO + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetFields]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] + @ModuleId INT + AS + SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + HelpText, + Required, + FieldOrder, + FieldType, + [default], + Visible, + ShowOnEdit, + Searchable, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE ModuleId = @ModuleId + ORDER BY FieldOrder + GO + + /** delete version table **/ + DROP TABLE UDT_Install_Semaphore + GO diff --git a/Providers/DataProviders/sqldataprovider/03.05.00.sqldataprovider b/Providers/DataProviders/sqldataprovider/03.05.00.sqldataprovider new file mode 100644 index 0000000..5a09705 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/03.05.00.sqldataprovider @@ -0,0 +1,68 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 3.4.1 *****/ + /***** [sleupold] 08/04/2007 *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ + + SET QUOTED_IDENTIFIER ON + GO + SET ANSI_NULLS ON + GO + + + /** check for compatible DNN version **/ + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'UDT_Install_Semaphore') AND OBJECTPROPERTY(id, N'IsTable') = 1) + DROP Table UDT_Install_Semaphore + GO + + CREATE TABLE UDT_Install_Semaphore (value INT PRIMARY KEY, flag BIT NOT Null) + GO + + DECLARE @dnnVer INT + SET @dnnver = (SELECT TOP 1 Major*10000+Minor*100+Build FROM {databaseOwner}[{objectQualifier}Version] ORDER BY Major DESC, Minor DESC, Build DESC) + IF @dnnver < 30305 OR ( @dnnver >= 40000 AND @dnnver < 40305) + BEGIN + INSERT INTO UDT_Install_Semaphore (value, Flag) VALUES (0, 0) + RAISERROR ('Incompatible DotNetNuke framework version installed. Please upgrade to V. 3.3.5+ or V. 4.3.5+ or re-install previous version of this module!', 16, 1) + END + ELSE + INSERT INTO UDT_Install_Semaphore (value, Flag) VALUES (1, 0) + GO + + /* replace stored procedures with updated versions: */ + + IF (SELECT value FROM UDT_Install_Semaphore) = 1 AND exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_FillDefaultData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_FillDefaultData] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_FillDefaultData] + @ModuleID INT, + @FieldId INT, /* can be null for any field */ + @DefaultValue NVarChar /*can be Null to copy default expression (no evaluation!) */ + AS + IF @DefaultValue is Null + INSERT INTO {databaseOwner}{objectQualifier}UserDefinedData (UserDefinedFieldId, UserDefinedRowId, FieldValue) + SELECT F.UserDefinedFieldId, R.UserDefinedRowId, [Default] + FROM ({databaseOwner}{objectQualifier}UserDefinedFields F + INNER JOIN {databaseOwner}{objectQualifier}UserDefinedRows R ON F.ModuleId = R.ModuleId) + LEFT JOIN {databaseOwner}{objectQualifier}UserDefinedData D ON F.UserDefinedFieldId = D.UserDefinedFieldId AND R.UserDefinedRowId = D.UserDefinedRowId + WHERE (D.UserDefinedRowID Is Null) AND ([Default] IS Not Null) AND (@ModuleID = F.ModuleId) AND (@FieldId IS Null OR F.UserDefinedFieldId = @FieldId) + ELSE + INSERT INTO {databaseOwner}{objectQualifier}UserDefinedData (UserDefinedFieldId, UserDefinedRowId, FieldValue) + SELECT @FieldId, R.UserDefinedRowId, @DefaultValue + FROM ({databaseOwner}{objectQualifier}UserDefinedFields F + INNER JOIN {databaseOwner}{objectQualifier}UserDefinedRows R ON F.ModuleId = R.ModuleId) + LEFT JOIN {databaseOwner}{objectQualifier}UserDefinedData D ON F.UserDefinedFieldId = D.UserDefinedFieldId AND R.UserDefinedRowId = D.UserDefinedRowId + WHERE (D.UserDefinedRowID Is Null) AND (@ModuleID = F.ModuleId) AND (@FieldId IS Null OR F.UserDefinedFieldId = @FieldId) + GO + + /** delete version table **/ + DROP TABLE UDT_Install_Semaphore + GO diff --git a/Providers/DataProviders/sqldataprovider/04.05.00.sqldataprovider b/Providers/DataProviders/sqldataprovider/04.05.00.sqldataprovider new file mode 100644 index 0000000..3a8718d --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/04.05.00.sqldataprovider @@ -0,0 +1,193 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 4.5.0 *****/ + /***** [scullmann] 09/29/2007 *****/ + /***** *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ + + IF (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedFields]'),'PrivateField','AllowsNull')) IS NULL + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] + ADD PrivateField BIT DEFAULT 0 Not Null + + GO + + /* replace stored procedures with updated versions: */ + + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] + @ModuleId INT, + @FieldTitle NVARCHAR(50), + @BeforePos INT, + @HelpText NVARCHAR(512), + @Required BIT, + @FieldType VARCHAR(20), + @Default NVARCHAR(2000), + @Visible BIT, + @ShowOnEdit BIT, + @Searchable BIT, + @Private BIT, + @InputSettings NVARCHAR(2000), + @OutputSettings NVARCHAR(2000), + @NormalizeFlag BIT, + @ValidationRule NVARCHAR(512), + @ValidationMessage NVARCHAR(512) + AS + DECLARE @InsPos INT + /* find insert position and adjust field order of subsequent fields: */ + SET @InsPos = (SELECT MAX(FieldOrder) AS MaxPos FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE ModuleID = @ModuleID GROUP BY ModuleID) + 1 + IF @InsPos IS Null SET @InsPos = 1 + IF @BeforePos Is Null SET @BeforePos = @InsPos + IF @InsPos > @BeforePos BEGIN + UPDATE [{objectQualifier}UserDefinedFields] + SET FieldOrder = FieldOrder + 1 + WHERE ModuleID = @ModuleID AND FieldOrder >= @BeforePos + SET @InsPos = @BeforePos + END + + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFields] ( + ModuleId, + FieldTitle, + HelpText, + Required, + FieldType, + FieldOrder, + [Default], + Visible, + ShowOnEdit, + Searchable, + PrivateField, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage + ) + VALUES ( + @ModuleId, + @FieldTitle, + @HelpText, + @Required, + @FieldType, + @InsPos, + @Default, + @Visible, + @ShowOnEdit, + @Searchable, + @Private, + @InputSettings, + @OutputSettings, + @NormalizeFlag, + @ValidationRule, + @ValidationMessage + ) + SELECT SCOPE_IDENTITY() + GO + + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] + @UserDefinedFieldId INT, + @FieldTitle NVARCHAR(50), + @HelpText NVARCHAR(512), + @Required BIT, + @FieldType VARCHAR(20), + @default NVARCHAR(2000), + @Visible BIT, + @ShowOnEdit BIT, + @Searchable BIT, + @Private BIT, + @InputSettings NVARCHAR(2000), + @OutputSettings NVARCHAR(2000), + @NormalizeFlag BIT, + @ValidationRule NVARCHAR(512), + @ValidationMessage NVARCHAR(512) + + AS + UPDATE {databaseOwner}[{objectQualifier}UserDefinedFields] + SET FieldTitle = @FieldTitle, + HelpText = @HelpText, + Required = @Required, + FieldType = @FieldType, + [default] = @default, + Visible = @Visible, + ShowOnEdit = @ShowOnEdit, + Searchable = @Searchable, + PrivateField = @Private, + InputSettings = @InputSettings, + OutputSettings = @OutputSettings, + NormalizeFlag = @NormalizeFlag, + ValidationRule = @ValidationRule, + ValidationMessage = @ValidationMessage + WHERE UserDefinedFieldId = @UserDefinedFieldId + GO + + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] + @UserDefinedFieldId INT + AS + SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + HelpText, + Required, + FieldOrder, + FieldType, + [default], + Visible, + ShowOnEdit, + Searchable, + PrivateField, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE UserDefinedFieldId = @UserDefinedFieldId + GO + + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetFields]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] + @ModuleId INT + AS + SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + HelpText, + Required, + FieldOrder, + FieldType, + [default], + Visible, + ShowOnEdit, + Searchable, + PrivateField, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE ModuleId = @ModuleId + ORDER BY FieldOrder + GO + + diff --git a/Providers/DataProviders/sqldataprovider/05.00.00.sqldataprovider b/Providers/DataProviders/sqldataprovider/05.00.00.sqldataprovider new file mode 100644 index 0000000..3b410a8 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/05.00.00.sqldataprovider @@ -0,0 +1,77 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 5.0.0 *****/ + /***** [scullmann] 03/03/2008 *****/ + /***** *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ + + SET QUOTED_IDENTIFIER ON + GO + SET ANSI_NULLS ON + GO + + + + + /* replace stored procedures with updated versions: */ + + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetRow]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetRow] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetRow] + @UserDefinedRowId int, + @ModuleId int + AS + SELECT + D.UserDefinedRowId, + F.FieldTitle, + D.FieldValue + FROM {databaseOwner}[{objectQualifier}UserDefinedData] D + INNER JOIN {databaseOwner}[{objectQualifier}UserDefinedFields] F on D.UserDefinedFieldId = F.UserDefinedFieldId + WHERE D.UserDefinedRowId = @UserDefinedRowId + AND F.ModuleId = @ModuleId + GO + + + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_DeleteField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_DeleteField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_DeleteField] + @UserDefinedFieldId int + AS + DELETE FROM {databaseOwner}[{objectQualifier}UserDefinedData] + WHERE (UserDefinedFieldId = @UserDefinedFieldId) + DELETE FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE UserDefinedFieldId = @UserDefinedFieldId + GO + + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_Reset]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_Reset] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_Reset] + @ModuleId INT + AS + DELETE FROM {databaseOwner}[{objectQualifier}UserDefinedRows] WHERE (ModuleId = @ModuleId) + DELETE FROM {databaseOwner}[{objectQualifier}UserDefinedFields] WHERE (ModuleId = @ModuleId) + GO + + /* User Defined Table is now "Form and List" */ + UPDATE MD + SET + FriendlyName = 'Form and List' + FROM + {databaseOwner}[{objectQualifier}DesktopModules] AS DM INNER JOIN + {databaseOwner}[{objectQualifier}ModuleDefinitions] AS MD + ON DM.DesktopModuleID = MD.DesktopModuleID + WHERE + (DM.ModuleName = N'DNN_UserDefinedTable') AND (MD.FriendlyName = N'User Defined Table') diff --git a/Providers/DataProviders/sqldataprovider/05.00.02.sqldataprovider b/Providers/DataProviders/sqldataprovider/05.00.02.sqldataprovider new file mode 100644 index 0000000..bbb4c4f --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/05.00.02.sqldataprovider @@ -0,0 +1,58 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 5.0.2 *****/ + /***** [scullmann] 03/03/2008 *****/ + /***** *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ + + SET QUOTED_IDENTIFIER ON + GO + SET ANSI_NULLS ON + GO + + /* replace stored procedures with updated versions: */ + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_FillDefaultData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_FillDefaultData] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_FillDefaultData] + @ModuleID INT, + @FieldId INT, /* can be null for any field */ + @DefaultValue NText /*can be Null to copy default expression (no evaluation!) */ + AS + IF @DefaultValue is Null + INSERT INTO {databaseOwner}{objectQualifier}UserDefinedData (UserDefinedFieldId, UserDefinedRowId, FieldValue) + SELECT F.UserDefinedFieldId, R.UserDefinedRowId, [Default] + FROM ({databaseOwner}{objectQualifier}UserDefinedFields F + INNER JOIN {databaseOwner}{objectQualifier}UserDefinedRows R ON F.ModuleId = R.ModuleId) + LEFT JOIN {databaseOwner}{objectQualifier}UserDefinedData D ON F.UserDefinedFieldId = D.UserDefinedFieldId AND R.UserDefinedRowId = D.UserDefinedRowId + WHERE (D.UserDefinedRowID Is Null) AND ([Default] IS Not Null) AND (@ModuleID = F.ModuleId) AND (@FieldId IS Null OR F.UserDefinedFieldId = @FieldId) + ELSE + INSERT INTO {databaseOwner}{objectQualifier}UserDefinedData (UserDefinedFieldId, UserDefinedRowId, FieldValue) + SELECT @FieldId, R.UserDefinedRowId, @DefaultValue + FROM ({databaseOwner}{objectQualifier}UserDefinedFields F + INNER JOIN {databaseOwner}{objectQualifier}UserDefinedRows R ON F.ModuleId = R.ModuleId) + LEFT JOIN {databaseOwner}{objectQualifier}UserDefinedData D ON F.UserDefinedFieldId = D.UserDefinedFieldId AND R.UserDefinedRowId = D.UserDefinedRowId + WHERE (D.UserDefinedRowID Is Null) AND (@ModuleID = F.ModuleId) AND (@FieldId IS Null OR F.UserDefinedFieldId = @FieldId) + GO + + /* replace stored procedures with updated versions: */ + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetFieldDataCount]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFieldDataCount] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFieldDataCount] + @FieldId INT + AS + SELECT COUNT(*) FROM {databaseOwner}[{objectQualifier}UserDefinedData] WHERE (UserDefinedFieldId = @FieldId) + + + + \ No newline at end of file diff --git a/Providers/DataProviders/sqldataprovider/05.01.00.sqldataprovider b/Providers/DataProviders/sqldataprovider/05.01.00.sqldataprovider new file mode 100644 index 0000000..c2c9465 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/05.01.00.sqldataprovider @@ -0,0 +1,23 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 5.1.0 *****/ + /***** *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ + + + /* Change Host Settings: Add csv extension to allowed file extensions */ + UPDATE {databaseOwner}[{objectQualifier}HostSettings] + SET SettingValue = SettingValue + N',csv' + WHERE (SettingName = N'FileExtensions') + AND (SettingValue Not like N'csv,%') + AND (SettingValue Not like N'%,csv,%') + AND (SettingValue Not like N'%,csv') + GO + \ No newline at end of file diff --git a/Providers/DataProviders/sqldataprovider/05.01.01.sqldataprovider b/Providers/DataProviders/sqldataprovider/05.01.01.sqldataprovider new file mode 100644 index 0000000..bf0e4d9 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/05.01.01.sqldataprovider @@ -0,0 +1,197 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 5.1.1 *****/ + /***** *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ + + + IF (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedFields]'),'EditStyle','AllowsNull')) IS NULL + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] + ADD EditStyle NVarChar(512) + GO + + /* replace stored procedures with updated versions: */ + + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] + @ModuleId INT, + @FieldTitle NVARCHAR(50), + @BeforePos INT, + @HelpText NVARCHAR(512), + @Required BIT, + @FieldType VARCHAR(20), + @Default NVARCHAR(2000), + @Visible BIT, + @ShowOnEdit BIT, + @Searchable BIT, + @Private BIT, + @InputSettings NVARCHAR(2000), + @OutputSettings NVARCHAR(2000), + @NormalizeFlag BIT, + @ValidationRule NVARCHAR(512), + @ValidationMessage NVARCHAR(512), + @EditStyle NVarChar(512) + AS + DECLARE @InsPos INT + /* find insert position and adjust field order of subsequent fields: */ + SET @InsPos = (SELECT MAX(FieldOrder) AS MaxPos FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE ModuleID = @ModuleID GROUP BY ModuleID) + 1 + IF @InsPos IS Null SET @InsPos = 1 + IF @BeforePos Is Null SET @BeforePos = @InsPos + IF @InsPos > @BeforePos BEGIN + UPDATE [{objectQualifier}UserDefinedFields] + SET FieldOrder = FieldOrder + 1 + WHERE ModuleID = @ModuleID AND FieldOrder >= @BeforePos + SET @InsPos = @BeforePos + END + + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFields] ( + ModuleId, + FieldTitle, + HelpText, + Required, + FieldType, + FieldOrder, + [Default], + Visible, + ShowOnEdit, + Searchable, + PrivateField, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage, + EditStyle + ) + VALUES ( + @ModuleId, + @FieldTitle, + @HelpText, + @Required, + @FieldType, + @InsPos, + @Default, + @Visible, + @ShowOnEdit, + @Searchable, + @Private, + @InputSettings, + @OutputSettings, + @NormalizeFlag, + @ValidationRule, + @ValidationMessage, + @EditStyle + ) + SELECT SCOPE_IDENTITY() + GO + + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] + @UserDefinedFieldId INT, + @FieldTitle NVARCHAR(50), + @HelpText NVARCHAR(512), + @Required BIT, + @FieldType VARCHAR(20), + @default NVARCHAR(2000), + @Visible BIT, + @ShowOnEdit BIT, + @Searchable BIT, + @Private BIT, + @InputSettings NVARCHAR(2000), + @OutputSettings NVARCHAR(2000), + @NormalizeFlag BIT, + @ValidationRule NVARCHAR(512), + @ValidationMessage NVARCHAR(512), + @EditStyle NVarChar(512) + + AS + UPDATE {databaseOwner}[{objectQualifier}UserDefinedFields] + SET FieldTitle = @FieldTitle, + HelpText = @HelpText, + Required = @Required, + FieldType = @FieldType, + [default] = @default, + Visible = @Visible, + ShowOnEdit = @ShowOnEdit, + Searchable = @Searchable, + PrivateField = @Private, + InputSettings = @InputSettings, + OutputSettings = @OutputSettings, + NormalizeFlag = @NormalizeFlag, + ValidationRule = @ValidationRule, + ValidationMessage = @ValidationMessage, + EditStyle=@EditStyle + WHERE UserDefinedFieldId = @UserDefinedFieldId + GO + + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] + @UserDefinedFieldId INT + AS + SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + HelpText, + Required, + FieldOrder, + FieldType, + [default], + Visible, + ShowOnEdit, + Searchable, + PrivateField, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage, + EditStyle + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE UserDefinedFieldId = @UserDefinedFieldId + GO + + IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetFields]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) + DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] + GO + + CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] + @ModuleId INT + AS + SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + HelpText, + Required, + FieldOrder, + FieldType, + [default], + Visible, + ShowOnEdit, + Searchable, + PrivateField, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage, + EditStyle + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] + WHERE ModuleId = @ModuleId + ORDER BY FieldOrder + GO \ No newline at end of file diff --git a/Providers/DataProviders/sqldataprovider/05.02.00.sqldataprovider b/Providers/DataProviders/sqldataprovider/05.02.00.sqldataprovider new file mode 100644 index 0000000..3a8cee2 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/05.02.00.sqldataprovider @@ -0,0 +1,216 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 5.2.0 *****/ + /***** *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ + +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] +ALTER COLUMN [InputSettings] NVARCHAR(MAX) +GO + +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] +ALTER COLUMN [HelpText] NVARCHAR(MAX) +GO + +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] +ALTER COLUMN [FieldTitle] NVARCHAR(2000) +GO + + IF (SELECT COLUMNPROPERTY( OBJECT_ID(N'{databaseOwner}[{objectQualifier}UserDefinedFields]'),'MultipleValues','AllowsNull')) IS NULL +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] +ADD MultipleValues bit NOT NULL DEFAULT 0 +GO + + +/* replace stored procedures with updated versions: */ + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] +@ModuleId INT, +@FieldTitle NVARCHAR(2000), +@BeforePos INT, +@HelpText NVARCHAR(MAX), +@Required BIT, +@FieldType VARCHAR(20), +@Default NVARCHAR(2000), +@Visible BIT, +@ShowOnEdit BIT, +@Searchable BIT, +@Private BIT, +@MultipleValues BIT, +@InputSettings NVARCHAR(MAX), +@OutputSettings NVARCHAR(2000), +@NormalizeFlag BIT, +@ValidationRule NVARCHAR(512), +@ValidationMessage NVARCHAR(512), +@EditStyle NVarChar(512) +AS +DECLARE @InsPos INT +/* find insert position and adjust field order of subsequent fields: */ +SET @InsPos = (SELECT MAX(FieldOrder) AS MaxPos FROM {databaseOwner}{objectQualifier}UserDefinedFields WHERE ModuleID = @ModuleID GROUP BY ModuleID) + 1 +IF @InsPos IS Null SET @InsPos = 1 +IF @BeforePos Is Null SET @BeforePos = @InsPos +IF @InsPos > @BeforePos BEGIN + UPDATE [{objectQualifier}UserDefinedFields] + SET FieldOrder = FieldOrder + 1 + WHERE ModuleID = @ModuleID AND FieldOrder >= @BeforePos + SET @InsPos = @BeforePos + END + +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFields] ( + ModuleId, + FieldTitle, + HelpText, + Required, + FieldType, + FieldOrder, + [Default], + Visible, + ShowOnEdit, + Searchable, + PrivateField, + MultipleValues, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage, + EditStyle +) +VALUES ( + @ModuleId, + @FieldTitle, + @HelpText, + @Required, + @FieldType, + @InsPos, + @Default, + @Visible, + @ShowOnEdit, + @Searchable, + @Private, + @MultipleValues, + @InputSettings, + @OutputSettings, + @NormalizeFlag, + @ValidationRule, + @ValidationMessage, + @EditStyle +) +SELECT SCOPE_IDENTITY() +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] +@UserDefinedFieldId INT, +@FieldTitle NVARCHAR(2000), +@HelpText NVARCHAR(512), +@Required BIT, +@FieldType VARCHAR(20), +@default NVARCHAR(2000), +@Visible BIT, +@ShowOnEdit BIT, +@Searchable BIT, +@Private BIT, +@MultipleValues BIT, +@InputSettings NVARCHAR(2000), +@OutputSettings NVARCHAR(2000), +@NormalizeFlag BIT, +@ValidationRule NVARCHAR(512), +@ValidationMessage NVARCHAR(512), +@EditStyle NVarChar(512) + +AS +UPDATE {databaseOwner}[{objectQualifier}UserDefinedFields] +SET FieldTitle = @FieldTitle, + HelpText = @HelpText, + Required = @Required, + FieldType = @FieldType, + [default] = @default, + Visible = @Visible, + ShowOnEdit = @ShowOnEdit, + Searchable = @Searchable, + PrivateField = @Private, + MultipleValues = @MultipleValues, + InputSettings = @InputSettings, + OutputSettings = @OutputSettings, + NormalizeFlag = @NormalizeFlag, + ValidationRule = @ValidationRule, + ValidationMessage = @ValidationMessage, + EditStyle=@EditStyle +WHERE UserDefinedFieldId = @UserDefinedFieldId +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] +@UserDefinedFieldId INT +AS +SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + HelpText, + Required, + FieldOrder, + FieldType, + [default], + Visible, + ShowOnEdit, + Searchable, + PrivateField, + MultipleValues, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage, + EditStyle +FROM {databaseOwner}[{objectQualifier}UserDefinedFields] +WHERE UserDefinedFieldId = @UserDefinedFieldId +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetFields]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] +@ModuleId INT +AS +SELECT UserDefinedFieldId, + ModuleID, + FieldTitle, + HelpText, + Required, + FieldOrder, + FieldType, + [default], + Visible, + ShowOnEdit, + Searchable, + PrivateField, + MultipleValues, + InputSettings, + OutputSettings, + NormalizeFlag, + ValidationRule, + ValidationMessage, + EditStyle +FROM {databaseOwner}[{objectQualifier}UserDefinedFields] +WHERE ModuleId = @ModuleId +ORDER BY FieldOrder +GO \ No newline at end of file diff --git a/Providers/DataProviders/sqldataprovider/06.00.00.sqldataprovider b/Providers/DataProviders/sqldataprovider/06.00.00.sqldataprovider new file mode 100644 index 0000000..75c39eb --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/06.00.00.sqldataprovider @@ -0,0 +1,343 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 6.0.0 *****/ + /***** *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_SetFieldOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_SetFieldOrder] +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_SetFieldOrder] + @UserDefinedFieldId INT, + @FieldOrder INT + as + DECLARE @id INT + DECLARE @Pos INT + SET @id = (SELECT UDF.UserDefinedFieldId + FROM {databaseOwner}[{objectQualifier}UserDefinedFields] AS UDF INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS ModuleFields ON UDF.ModuleId = ModuleFields.ModuleId + WHERE (UDF.FieldOrder = @FieldOrder) AND (ModuleFields.UserDefinedFieldId = @UserDefinedFieldId)) + SET @Pos = (SELECT FieldOrder FROM {databaseOwner}[{objectQualifier}UserDefinedFields] WHERE UserDefinedFieldId = @UserDefinedFieldId) + + UPDATE {databaseOwner}[{objectQualifier}UserDefinedFields] SET FieldOrder = -1 WHERE UserDefinedFieldId = @id + UPDATE {databaseOwner}[{objectQualifier}UserDefinedFields] SET FieldOrder = @FieldOrder WHERE UserDefinedFieldId = @UserDefinedFieldId + UPDATE {databaseOwner}[{objectQualifier}UserDefinedFields] SET FieldOrder = @Pos WHERE UserDefinedFieldId = @Id +GO + +if not exists (select * from dbo.sysobjects where id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedFieldSettings]') and OBJECTPROPERTY(id, N'IsTable') = 1) + BEGIN + CREATE TABLE {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + ( + FieldId int NOT NULL, + SettingName nvarchar(50) NOT NULL, + SettingValue nvarchar(MAX) NULL + ) + + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] ADD CONSTRAINT + [PK_{objectQualifier}UserDefinedFieldSettings] PRIMARY KEY CLUSTERED + (FieldId, SettingName) + + ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + ADD CONSTRAINT [FK_{objectQualifier}UserDefinedFieldSettings_{objectQualifier}UserDefinedFields] FOREIGN KEY + (FieldId) REFERENCES {databaseOwner}[{objectQualifier}UserDefinedFields] (UserDefinedFieldId) ON DELETE CASCADE + END +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_GetFieldSettings]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFieldSettings] +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldSetting]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldSetting] +GO + +Create PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFieldSettings] +@ModuleId int +AS +SELECT UDFS.FieldId, UDFS.SettingName, UDFS.SettingValue +FROM {databaseOwner}[{objectQualifier}UserDefinedFields] UDF INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] UDFS ON UDF.UserDefinedFieldId = UDFS.FieldId +WHERE (UDF.ModuleId = @ModuleId) +GO + +Create PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateFieldSetting] +@fieldId int, +@SettingName nvarchar(50), +@SettingValue nvarchar(max) +AS +DELETE FROM {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] +WHERE (FieldId = @fieldId) AND (SettingName = @SettingName) +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) + VALUES (@fieldId,@SettingName,@SettingValue) +GO + + + +-- +-- NormalizeFlag +-- + +/* Update NormalizeFlag for DateTime */ +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'ConvertToUserDateTime' AS name, 'True' AS value +FROM {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='ConvertToUserDateTime') as fieldSettings ON fields.UserDefinedFieldId = fieldSettings.FieldId +WHERE (NormalizeFlag = 1) AND (FieldType = 'DateTime') AND (fieldSettings.FieldId IS NULL) +GO + +/* Update NormalizeFlag for Download */ +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'Abbreviate' AS name, 'True' AS value +FROM {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='Abbreviate') as fieldSettings ON fields.UserDefinedFieldId = fieldSettings.FieldId +WHERE (NormalizeFlag = 1) AND (FieldType = 'Download') AND (fieldSettings.FieldId IS NULL) +GO + +/* Update NormalizeFlag for EMail */ +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'Abbreviate' AS name, 'False' AS value +FROM {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='Abbreviate') as fieldSettings ON fields.UserDefinedFieldId = fieldSettings.FieldId +WHERE (NormalizeFlag = 1) AND (FieldType = 'NoLink') AND (fieldSettings.FieldId IS NULL) +GO + +/* Update NormalizeFlag for Image */ +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'AsLink' AS name, 'True' AS value +FROM {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='AsLink') as fieldSettings ON fields.UserDefinedFieldId = fieldSettings.FieldId +WHERE (NormalizeFlag = 1) AND (FieldType = 'Image') AND (fieldSettings.FieldId IS NULL) +GO + +/* Update NormalizeFlag for Separator */ +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'IsCollapsible' AS name, 'True' AS value +FROM {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='IsCollapsible') AS fieldSettings ON fields.UserDefinedFieldId = fieldSettings.FieldId +WHERE (NormalizeFlag = 1) AND (FieldType = 'Separator') AND (fieldSettings.FieldId IS NULL) + +/* Update NormalizeFlag for TextHtml */ +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'PlainText' AS name, 'True' AS value +FROM {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='PlainText') AS fieldSettings ON fields.UserDefinedFieldId = fieldSettings.FieldId +WHERE (NormalizeFlag = 1) AND (FieldType = 'TextHtml') AND (fieldSettings.FieldId IS NULL) +GO + +/* Update NormalizeFlag for URL */ +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'Abbreviate' AS name, 'True' AS value +FROM {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='Abbreviate') as fieldSettings ON fields.UserDefinedFieldId = fieldSettings.FieldId +WHERE (NormalizeFlag = 1) AND (FieldType = 'URL') AND (fieldSettings.FieldId IS NULL) +GO +/* Update NormalizeFlag for UserLink */ +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'ShowUserName' AS name, 'True' AS value +FROM {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='ShowUsername') as fieldSettings ON fields.UserDefinedFieldId = fieldSettings.FieldId +WHERE (fields.NormalizeFlag = 1) AND (fields.FieldType = 'UserLink') AND (fieldSettings.FieldId IS NULL) +GO + +-- +--MODULE SETTINGS +-- +--Image, UDT_ImageWidth -> Width +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'Width' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='Width') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'Image') AND (settings.SettingName = N'UDT_ImageWidth') AND (fieldsettings.FieldId IS NULL) +GO +--Image, UDT_ImageHeigth -> Width +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'Heigth' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='Heigth') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'Image') AND (settings.SettingName = N'UDT_ImageHeigth') AND (fieldsettings.FieldId IS NULL) +GO +--Expression, CalculatedColumnsRenderExpressionInForm -> Render In Form +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'RenderInForm' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='RenderInForm') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'Expression') AND (settings.SettingName = N'CalculatedColumnsRenderExpressionInForm') AND (fieldsettings.FieldId IS NULL) +GO + +--UserLink, UDT_UserLinkUserName -> ShowUserName +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'ShowUserName' AS name, + CASE WHEN settings.SettingValue = 'UserName' THEN 'True' ELSE 'False' END AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='ShowUserName') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'UserLink') AND (settings.SettingName = N'UDT_UserLinkUserName') AND (fieldsettings.FieldId IS NULL) +GO + +--CreatedBy, UDT_UserLinkUserName -->PreferDisplayName +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'PreferDisplayName' AS name, + CASE WHEN settings.SettingValue = 'UserName' THEN 'True' ELSE 'False' END AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='PreferDisplayName') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'CreatedBy') AND (settings.SettingName = N'UDT_UserLinkUserName') AND (fieldsettings.FieldId IS NULL) +GO + +--ChangedBy, UDT_UserLinkUserName -->PreferDisplayName +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'PreferDisplayName' AS name, + CASE WHEN settings.SettingValue = 'UserName' THEN 'True' ELSE 'False' END AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='PreferDisplayName') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'ChangedBy') AND (settings.SettingName = N'UDT_UserLinkUserName') AND (fieldsettings.FieldId IS NULL) +GO + + +--UserLink, UDT_UserLinkNewWindow ->OpenInNewWindow +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'OpenInNewWindow' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='OpenInNewWindow') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'UserLink') AND (settings.SettingName = N'UDT_UserLinkNewWindow') AND (fieldsettings.FieldId IS NULL) +GO + +--CreatedBy, UDT_UserLinkNewWindow ->OpenInNewWindow +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'OpenInNewWindow' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='OpenInNewWindow') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'CreatedBy') AND (settings.SettingName = N'UDT_UserLinkNewWindow') AND (fieldsettings.FieldId IS NULL) +GO + +--ChangedBy, UDT_UserLinkNewWindow ->OpenInNewWindow +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'OpenInNewWindow' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='OpenInNewWindow') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'ChangedBy') AND (settings.SettingName = N'UDT_UserLinkNewWindow') AND (fieldsettings.FieldId IS NULL) +GO + +--Download,UDT_URLNewWindow-->ShowOpenInNewWindow +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'ShowOpenInNewWindow' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='ShowOpenInNewWindow') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'Download') AND (settings.SettingName = N'UDT_URLNewWindow') AND (fieldsettings.FieldId IS NULL) +GO + +--Url,UDT_URLNewWindow-->ShowOpenInNewWindow +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'ShowOpenInNewWindow' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='ShowOpenInNewWindow') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'URL') AND (settings.SettingName = N'UDT_URLNewWindow') AND (fieldsettings.FieldId IS NULL) +GO + +--Url,URLDownloadTracking-->TrackDownloads +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'TrackDownloads' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='TrackDownloads') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'URL') AND (settings.SettingName = N'UDT_ URLDownloadTracking') AND (fieldsettings.FieldId IS NULL) +GO + +--Url,UDT_ForceDownload-->EnforceDownload +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'EnforceDownload' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='EnforceDownload') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'URL') AND (settings.SettingName = N'UDT_ForceDownload') AND (fieldsettings.FieldId IS NULL) +GO + +--Url,UDT_ForceDownload-->EnforceDownload +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'EnforceDownload' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='EnforceDownload') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'Download') AND (settings.SettingName = N'UDT_ForceDownload') AND (fieldsettings.FieldId IS NULL) +GO + +--CreatedBy ,UDT_CnCLink-->AsLink +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'AsLink' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='AsLink') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'CreatedBy') AND (settings.SettingName = N'UDT_CnCLink') AND (fieldsettings.FieldId IS NULL) +GO + +--ChangedBy ,UDT_CnCLink-->AsLink +INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] + (FieldId, SettingName, SettingValue) +SELECT fields.UserDefinedFieldId, 'AsLink' AS name, + settings.SettingValue AS value +FROM {databaseOwner}[{objectQualifier}ModuleSettings] AS settings INNER JOIN + {databaseOwner}[{objectQualifier}UserDefinedFields] AS fields ON settings.ModuleID = fields.ModuleId LEFT OUTER JOIN + (Select FieldId from {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] where settingname='AsLink') as fieldsettings ON fields.UserDefinedFieldId = fieldsettings.FieldId +WHERE (fields.FieldType = 'ChangedBy') AND (settings.SettingName = N'UDT_CnCLink') AND (fieldsettings.FieldId IS NULL) +GO + +-- if email tracking has been disabled, all trigger actions should be disabled after upgrade +UPDATE {databaseOwner}[{objectQualifier}TabModuleSettings] +SET SettingValue = 'False' +WHERE (SettingName LIKE N'UDT_TriggerOn%') AND (TabModuleID IN + (SELECT TabModuleID + FROM {databaseOwner}[{objectQualifier}TabModuleSettings] + WHERE (SettingName = N'UDT_EnableTracking') AND (SettingValue = N'False'))) +GO diff --git a/Providers/DataProviders/sqldataprovider/06.00.03.sqldataprovider b/Providers/DataProviders/sqldataprovider/06.00.03.sqldataprovider new file mode 100644 index 0000000..22f3531 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/06.00.03.sqldataprovider @@ -0,0 +1,22 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 6.0.3 *****/ + /***** *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ + +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedData] alter column FieldValue nvarchar(max) +GO + +UPDATE {databaseOwner}[{objectQualifier}UserDefinedData] set FieldValue = FieldValue +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddData] +GO \ No newline at end of file diff --git a/Providers/DataProviders/sqldataprovider/06.00.04.sqldataprovider b/Providers/DataProviders/sqldataprovider/06.00.04.sqldataprovider new file mode 100644 index 0000000..60b5a37 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/06.00.04.sqldataprovider @@ -0,0 +1,70 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 6.0.4 *****/ + /***** *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_AddData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddData] +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddData] +@UserDefinedRowId int, +@UserDefinedFieldId int, +@FieldValue nvarchar(max) +AS +INSERT INTO {databaseOwner}[{objectQualifier}dbo.UserDefinedData] + ( UserDefinedFieldId, UserDefinedRowId, FieldValue) + VALUES (@UserDefinedFieldId, @UserDefinedRowId, @FieldValue) +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_FillDefaultData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_FillDefaultData] +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_FillDefaultData] +@ModuleID INT, +@FieldId INT, /* can be null for any field */ +@DefaultValue NVarChar(max) /*can be Null to copy default expression (no evaluation!) */ +AS +IF @DefaultValue is Null + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedData] (UserDefinedFieldId, UserDefinedRowId, FieldValue) + SELECT F.UserDefinedFieldId, R.UserDefinedRowId, [Default] + FROM ({databaseOwner}[{objectQualifier}UserDefinedFields] F + INNER JOIN {databaseOwner}[{objectQualifier}UserDefinedRows] R ON F.ModuleId = R.ModuleId) + LEFT JOIN {databaseOwner}[{objectQualifier}UserDefinedData] D ON F.UserDefinedFieldId = D.UserDefinedFieldId AND R.UserDefinedRowId = D.UserDefinedRowId + WHERE (D.UserDefinedRowID Is Null) AND ([Default] IS Not Null) AND (@ModuleID = F.ModuleId) AND (@FieldId IS Null OR F.UserDefinedFieldId = @FieldId) + ELSE + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedData] (UserDefinedFieldId, UserDefinedRowId, FieldValue) + SELECT @FieldId, R.UserDefinedRowId, @DefaultValue + FROM ({databaseOwner}[{objectQualifier}UserDefinedFields] F + INNER JOIN {databaseOwner}[{objectQualifier}UserDefinedRows] R ON F.ModuleId = R.ModuleId) + LEFT JOIN {databaseOwner}[{objectQualifier}UserDefinedData] D ON F.UserDefinedFieldId = D.UserDefinedFieldId AND R.UserDefinedRowId = D.UserDefinedRowId + WHERE (D.UserDefinedRowID Is Null) AND (@ModuleID = F.ModuleId) AND (@FieldId IS Null OR F.UserDefinedFieldId = @FieldId) +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_UpdateData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateData] +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateData] +@UserDefinedRowId int, +@UserDefinedFieldId int, +@FieldValue NVarChar(max) +AS + DELETE FROM {databaseOwner}[{objectQualifier}UserDefinedData] + WHERE UserDefinedFieldId = @UserDefinedFieldId + AND UserDefinedRowId = @UserDefinedRowId + + IF @FieldValue NOT LIKE '' + INSERT INTO {databaseOwner}[{objectQualifier}UserDefinedData] + ( UserDefinedFieldId, UserDefinedRowId, FieldValue) + VALUES (@UserDefinedFieldId, @UserDefinedRowId,@FieldValue) +GO \ No newline at end of file diff --git a/Providers/DataProviders/sqldataprovider/06.00.06.sqldataprovider b/Providers/DataProviders/sqldataprovider/06.00.06.sqldataprovider new file mode 100644 index 0000000..b203ebe --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/06.00.06.sqldataprovider @@ -0,0 +1,25 @@ + /************************************************************/ + /***** SqlDataProvider *****/ + /***** Install/Upgrade for UserDefinedTable 6.0.6 *****/ + /***** *****/ + /***** *****/ + /***** Note: To manually execute this script you must *****/ + /***** perform a search AND replace operation *****/ + /***** for {databaseOwner} AND {objectQualifier} *****/ + /***** or use 'SQL' FROM Host Menu AND run this. *****/ + /***** *****/ + /***** *****/ + /************************************************************/ + + + +begin transaction +/* This code adds a dummy text column to the table, clears the 'text in row' table option + then removes the dummy column. This is to allow removal of the 'text in row' option + which is not supported on SQL Azure */ + +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedData] ADD [dummy] text; +EXECUTE sp_tableoption '{databaseOwner}[{objectQualifier}UserDefinedData]', 'text in row', 'OFF'; +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedData] DROP COLUMN [dummy]; + +commit transaction diff --git a/Providers/DataProviders/sqldataprovider/sqldataprovider.cs b/Providers/DataProviders/sqldataprovider/sqldataprovider.cs new file mode 100644 index 0000000..a6140fd --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/sqldataprovider.cs @@ -0,0 +1,286 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Framework.Providers; +using DotNetNuke.Modules.UserDefinedTable.Components; +using Microsoft.ApplicationBlocks.Data; + +// ReSharper disable CheckNamespace +namespace DotNetNuke.Modules.UserDefinedTable +// ReSharper restore CheckNamespace +{ + /// ----------------------------------------------------------------------------- + /// + /// The SqlDataProvider Class is an SQL Server implementation of the DataProvider Abstract + /// class that provides the DataLayer for the UserDefinedTables Module. + /// + /// ----------------------------------------------------------------------------- + public class SqlDataProvider : DataProvider + { + #region Private Members + + const string ProviderType = "data"; + const string SPPrefix = "UserDefinedTable_"; + + readonly ProviderConfiguration _providerConfiguration =ProviderConfiguration.GetProviderConfiguration (ProviderType); + + readonly string _connectionString; + readonly string _providerPath; + readonly string _objectQualifier; + readonly string _databaseOwner; + + #endregion + + #region Constructors + + public SqlDataProvider() + { + // Read the configuration specific information for this provider + var objProvider = (Provider) (_providerConfiguration.Providers[_providerConfiguration.DefaultProvider]); + + //Get Connection string from web.config + _connectionString = Config.GetConnectionString(); + + if (_connectionString == "") + { + // Use connection string specified in provider + _connectionString = objProvider.Attributes["connectionString"]; + } + + _providerPath = objProvider.Attributes["providerPath"]; + + _objectQualifier = objProvider.Attributes["objectQualifier"]; + if (_objectQualifier != "" && ! _objectQualifier.EndsWith("_")) + { + _objectQualifier += "_"; + } + + _databaseOwner = objProvider.Attributes["databaseOwner"]; + if (_databaseOwner != "" && ! _databaseOwner.EndsWith(".")) + { + _databaseOwner += "."; + } + } + + #endregion + + #region Properties + + public string ConnectionString + { + get { return _connectionString; } + } + + public string ProviderPath + { + get { return _providerPath; } + } + + public string ObjectQualifier + { + get { return _objectQualifier; } + } + + public string DatabaseOwner + { + get { return _databaseOwner; } + } + + #endregion + + #region Public Methods + + object GetNull(object Field) + { + return Null.GetNull(Field, DBNull.Value); + } + + public override IDataReader GetFields(int ModuleId) + { + return + ((SqlHelper.ExecuteReader(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "GetFields", + ModuleId))); + } + + public override IDataReader GetField(int UserDefinedFieldId) + { + return + ((SqlHelper.ExecuteReader(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "GetField", + UserDefinedFieldId))); + } + + public override IDataReader GetRow(int UserDefinedRowId, int ModuleId) + { + return + ((SqlHelper.ExecuteReader(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "GetRow", + UserDefinedRowId, ModuleId))); + } + + public override void DeleteField(int UserDefinedFieldId) + { + SqlHelper.ExecuteNonQuery(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "DeleteField", + UserDefinedFieldId); + } + + public override int AddField(int ModuleId, string FieldTitle, int BeforePos, string HelpText, bool Required, + string FieldType, string Default, bool Visible, bool ShowOnEdit, bool Searchable, + bool IsPrivateColumn, bool MultipleValues, string InputSettings, + string OutputSettings, bool NormalizeFlag, string validationRule, + string validationMessage, string EditStyle) + { + return + Convert.ToInt32(SqlHelper.ExecuteScalar(ConnectionString, + DatabaseOwner + ObjectQualifier + SPPrefix + "AddField", + ModuleId, FieldTitle, GetNull(BeforePos), GetNull(HelpText), + Required, FieldType, GetNull(Default), Visible, ShowOnEdit, + Searchable, IsPrivateColumn, MultipleValues, + GetNull(InputSettings), GetNull(OutputSettings), NormalizeFlag, + GetNull(validationRule), GetNull(validationMessage), + GetNull(EditStyle))); + } + + public override void FillDefaultData(int ModuleId, int FieldId, string DefaultValue) + { + SqlHelper.ExecuteNonQuery(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "FillDefaultData", + ModuleId, GetNull(FieldId), DefaultValue); + } + + + + public override void UpdateField(int UserDefinedFieldId, string FieldTitle, string HelpText, bool Required, + string FieldType, string Default, bool Visible, bool ShowOnEdit, + bool Searchable, bool IsPrivateColumn, bool MultipleValues, + string InputSettings, string OutputSettings, bool NormalizeFlag, + string validationRule, string validationMessage, string EditStyle) + { + SqlHelper.ExecuteNonQuery(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "UpdateField", + UserDefinedFieldId, FieldTitle, GetNull(HelpText), Required, FieldType, + GetNull(Default), Visible, ShowOnEdit, Searchable, IsPrivateColumn, MultipleValues, + GetNull(InputSettings), GetNull(OutputSettings), NormalizeFlag, + GetNull(validationRule), GetNull(validationMessage), GetNull(EditStyle)); + + } + + public override IDataReader GetRows(int ModuleId) + { + return + ((SqlHelper.ExecuteReader(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "GetRows", + ModuleId))); + } + + public override IDataReader GetFieldSettings(int moduleId) + { + return ((SqlHelper.ExecuteReader(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "GetFieldSettings", + moduleId))); + } + + public override void UpdateFieldSetting(int fieldid, string key, string value) + { + SqlHelper.ExecuteNonQuery(ConnectionString, + DatabaseOwner + ObjectQualifier + SPPrefix + "UpdateFieldSetting", + fieldid,key,value); + } + + public override void Reset(int ModuleId) + { + SqlHelper.ExecuteNonQuery(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "Reset", ModuleId); + } + + public override void DeleteRow(int UserDefinedRowId, int ModuleId) + { + SqlHelper.ExecuteNonQuery(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "DeleteRow", + UserDefinedRowId, ModuleId); + } + + public override void DeleteRows(int ModuleId) + { + SqlHelper.ExecuteNonQuery(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "DeleteRows", + ModuleId); + } + + public override int AddRow(int ModuleId) + { + return + Convert.ToInt32(SqlHelper.ExecuteScalar(ConnectionString, + DatabaseOwner + ObjectQualifier + SPPrefix + "AddRow", ModuleId)); + } + + public override IDataReader GetData(int UserDefinedRowId, int UserDefinedFieldId) + { + return + ((SqlHelper.ExecuteReader(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "GetData", + UserDefinedRowId, UserDefinedFieldId))); + } + + public override void AddData(int UserDefinedRowId, int UserDefinedFieldId, string FieldValue) + { + SqlHelper.ExecuteNonQuery(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "AddData", + UserDefinedRowId, UserDefinedFieldId, FieldValue); + } + + public override void UpdateData(int UserDefinedRowId, int UserDefinedFieldId, string FieldValue) + { + SqlHelper.ExecuteNonQuery(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "UpdateData", + UserDefinedRowId, UserDefinedFieldId, FieldValue); + } + + public override void UpdateData(int rowId, IDictionary values) + { + using (var con = new SqlConnection(ConnectionString)) + { + con.Open(); + var trx = con.BeginTransaction(); + try + { + foreach (var kvp in values) + { + SqlHelper.ExecuteNonQuery(trx, DatabaseOwner + ObjectQualifier + SPPrefix + "UpdateData", + rowId, kvp.Key, kvp.Value); + } + trx.Commit(); + } + catch + { + trx.Rollback(); + throw; + } + } + } + + public override void SwapFieldOrder(int FirstUserDefinedFieldId, int SecondUserDefinedFieldId) + { + SqlHelper.ExecuteNonQuery(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "SwapFieldOrder", + FirstUserDefinedFieldId, SecondUserDefinedFieldId); + } + + public override void DeleteData(int UserDefinedRowId, int UserDefinedFieldId) + { + SqlHelper.ExecuteNonQuery(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "DeleteData", + UserDefinedRowId, UserDefinedFieldId); + } + + public override int GetMaxFieldSize() + { + return Null.NullInteger; + // FieldValue is no longer stored in side a NVARCHAR(2000) column + } + + public override int GetFieldDataCount(int UserDefinedFieldID) + { + return + Convert.ToInt32(SqlHelper.ExecuteScalar(ConnectionString, + DatabaseOwner + ObjectQualifier + SPPrefix + "GetFieldDataCount", + UserDefinedFieldID)); + } + + public override void SetFieldOrder(int UserDefinedFieldID, int FieldOrder) + { + SqlHelper.ExecuteNonQuery(ConnectionString, DatabaseOwner + ObjectQualifier + SPPrefix + "SetFieldOrder", + UserDefinedFieldID, FieldOrder); + } + + #endregion + } +} \ No newline at end of file diff --git a/Providers/DataProviders/sqldataprovider/uninstall.sqldataprovider b/Providers/DataProviders/sqldataprovider/uninstall.sqldataprovider new file mode 100644 index 0000000..0960473 --- /dev/null +++ b/Providers/DataProviders/sqldataprovider/uninstall.sqldataprovider @@ -0,0 +1,128 @@ +/************************************************************/ +/***** SqlDataProvider *****/ +/***** Uninstall for Form and List *****/ +/***** *****/ +/***** *****/ +/***** Note: To manually execute this script you must *****/ +/***** perform a search and replace operation *****/ +/***** for {databaseOwner} and {objectQualifier} *****/ +/***** or use 'SQL' from Host Menu and run this. *****/ +/***** *****/ +/***** *****/ +/************************************************************/ + +/** Drop Tables **/ + +if exists (select * from dbo.sysobjects where id = object_id(N'FK_{objectQualifier}UserDefinedFields_{objectQualifier}Modules') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] DROP CONSTRAINT [FK_{objectQualifier}UserDefinedFields_{objectQualifier}Modules] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'FK_{objectQualifier}UserDefinedRows_{objectQualifier}Modules') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedRows] DROP CONSTRAINT [FK_{objectQualifier}UserDefinedRows_{objectQualifier}Modules] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'FK_{objectQualifier}UserDefinedData_{objectQualifier}UserDefinedRows') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedData] DROP CONSTRAINT [FK_{objectQualifier}UserDefinedData_{objectQualifier}UserDefinedRows] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'FK_{objectQualifier}UserDefinedData_{objectQualifier}UserDefinedFields') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedData] DROP CONSTRAINT [FK_{objectQualifier}UserDefinedData_{objectQualifier}UserDefinedFields] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'FK_{objectQualifier}UserDefinedFieldSettings_{objectQualifier}UserDefinedFields') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) +ALTER TABLE {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] DROP CONSTRAINT [FK_{objectQualifier}UserDefinedFieldSettings_{objectQualifier}UserDefinedFields] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedData') and OBJECTPROPERTY(id, N'IsTable') = 1) +DROP TABLE {databaseOwner}[{objectQualifier}UserDefinedData] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedFieldSettings') and OBJECTPROPERTY(id, N'IsTable') = 1) +DROP TABLE {databaseOwner}[{objectQualifier}UserDefinedFieldSettings] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedFields') and OBJECTPROPERTY(id, N'IsTable') = 1) +DROP TABLE {databaseOwner}[{objectQualifier}UserDefinedFields] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedRows') and OBJECTPROPERTY(id, N'IsTable') = 1) +DROP TABLE {databaseOwner}[{objectQualifier}UserDefinedRows] +GO + +/** Drop Stored Procedures **/ + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_AddData') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddData] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_AddField') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddField] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_AddRow') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_AddRow] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_DeleteData') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_DeleteData] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_DeleteField') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_DeleteField] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_DeleteRow') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_DeleteRow] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_DeleteRows') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_DeleteRows] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_GetData') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetData] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_GetField') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetField] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_GetFields') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFields] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_GetRow') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetRow] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_GetRows') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetRows] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_SwapFieldOrder') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_SwapFieldOrder] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_UpdateData') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateData] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_UpdateField') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_UpdateField] +GO + +IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}UserDefinedTable_Reset]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_Reset] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_FillDefaultData') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_FillDefaultData] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'{objectQualifier}UserDefinedTable_GetFieldDataCount') and OBJECTPROPERTY(id, N'IsProcedure') = 1) +DROP PROCEDURE {databaseOwner}[{objectQualifier}UserDefinedTable_GetFieldDataCount] +GO + +/************************************************************/ +/***** SqlDataProvider *****/ +/************************************************************/ \ No newline at end of file diff --git a/Serialization/ModuleSerializationController.cs b/Serialization/ModuleSerializationController.cs new file mode 100644 index 0000000..a4972ae --- /dev/null +++ b/Serialization/ModuleSerializationController.cs @@ -0,0 +1,624 @@ +using System; +using System.Collections; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Web; +using System.Xml; +using System.Xml.Serialization; +using DotNetNuke.Common; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Modules.Definitions; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Framework; +using DotNetNuke.Modules.UserDefinedTable.Interfaces; +using DotNetNuke.Security.Permissions; +using DotNetNuke.Security.Roles; +using DotNetNuke.Services.EventQueue; + +namespace DotNetNuke.Modules.UserDefinedTable.Serialization +{ + public class ModuleSerializationController + { + #region Private Shared Methods + + static void AddContent(XmlNode nodeModule, ModuleInfo module, int maxNumberOfRecords) + { + if (module.DesktopModule.BusinessControllerClass != "" && module.DesktopModule.IsPortable) + { + try + { + var businessController = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, + module.DesktopModule.BusinessControllerClass); + + var content = string.Empty; + if (businessController is IPortable2) + { + content = + Convert.ToString(((IPortable2) businessController).ExportModule(module.ModuleID, + module.TabID, + maxNumberOfRecords)); + } + else if (businessController is IPortable) + { + content = Convert.ToString(((IPortable) businessController).ExportModule(module.ModuleID)); + } + + if (content != "") + { + // add attributes to XML document +// ReSharper disable PossibleNullReferenceException + XmlNode newnode = nodeModule.OwnerDocument.CreateElement("content"); + + var xmlattr = nodeModule.OwnerDocument.CreateAttribute("type"); + xmlattr.Value = Globals.CleanName(module.DesktopModule.ModuleName); + newnode.Attributes.Append(xmlattr); + xmlattr = nodeModule.OwnerDocument.CreateAttribute("version"); + xmlattr.Value = module.DesktopModule.Version; + newnode.Attributes.Append(xmlattr); + + try + { + var doc = new XmlDocument(); + doc.LoadXml(content); +// ReSharper disable AssignNullToNotNullAttribute + newnode.AppendChild(newnode.OwnerDocument.ImportNode(doc.DocumentElement, true)); +// ReSharper restore AssignNullToNotNullAttribute + } + // ReSharper restore PossibleNullReferenceException + catch (Exception) + { + //only for invalid xhtml + content = HttpContext.Current.Server.HtmlEncode(content); + newnode.InnerXml = XmlUtils.XMLEncode(content); + } + nodeModule.AppendChild(newnode); + } + } + catch + { + //ignore errors + } + } + } + + static void AddSettings(XmlNode nodeModule, ModuleInfo module) + { + var objModuleController = new ModuleController(); + var moduleSettings = objModuleController.GetModuleSettings(module.ModuleID); + var tabModuleSettings = objModuleController.GetTabModuleSettings(module.TabModuleID); + + var handleModuleSettings = true; + var handleTabModuleSettings = true; + + if (module.DesktopModule.BusinessControllerClass != "" && module.DesktopModule.IsPortable) + { + try + { + var businessController = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, + module.DesktopModule.BusinessControllerClass); + if (businessController is IPortable2) + { + handleModuleSettings = + Convert.ToBoolean(!(((IPortable2) businessController).ManagesModuleSettings)); + handleTabModuleSettings = + Convert.ToBoolean(!(((IPortable2) businessController).ManagesTabModuleSettings)); + } + } + catch + { + } + } + + XmlAttribute xmlattr; + + if (moduleSettings.Count > 0 && handleModuleSettings) + { +// ReSharper disable PossibleNullReferenceException + XmlNode settingsNode = nodeModule.OwnerDocument.CreateElement("modulesettings"); + + foreach (string key in moduleSettings.Keys) + { + XmlNode settingNode = nodeModule.OwnerDocument.CreateElement("setting"); + xmlattr = nodeModule.OwnerDocument.CreateAttribute("name"); + xmlattr.Value = key; + settingNode.Attributes.Append(xmlattr); + // ReSharper restore PossibleNullReferenceException + xmlattr = nodeModule.OwnerDocument.CreateAttribute("value"); + xmlattr.Value = moduleSettings[key].ToString(); + settingNode.Attributes.Append(xmlattr); + settingsNode.AppendChild(settingNode); + } + nodeModule.AppendChild(settingsNode); + } + + if (tabModuleSettings.Count > 0 && handleTabModuleSettings) + { +// ReSharper disable PossibleNullReferenceException + XmlNode settingsNode = nodeModule.OwnerDocument.CreateElement("tabmodulesettings"); +// ReSharper restore PossibleNullReferenceException + foreach (string key in tabModuleSettings.Keys) + { + XmlNode settingNode = nodeModule.OwnerDocument.CreateElement("setting"); + xmlattr = nodeModule.OwnerDocument.CreateAttribute("name"); + xmlattr.Value = key; +// ReSharper disable PossibleNullReferenceException + settingNode.Attributes.Append(xmlattr); +// ReSharper restore PossibleNullReferenceException + xmlattr = nodeModule.OwnerDocument.CreateAttribute("value"); + xmlattr.Value = tabModuleSettings[key].ToString(); + settingNode.Attributes.Append(xmlattr); + settingsNode.AppendChild(settingNode); + } + nodeModule.AppendChild(settingsNode); + } + } + + static bool CheckIsInstance(int templateModuleId, Hashtable hModules) + { + // will be instance or module + var isInstance = false; + if (templateModuleId > 0) + { + if (hModules[templateModuleId] != null) + { + // this module has already been processed -> process as instance + isInstance = true; + } + } + + return isInstance; + } + + static void CreateEventQueueMessage(ModuleInfo module, string content, string version, int userId) + { + var oAppStartMessage = new EventMessage + { + Priority = MessagePriority.High, + ExpirationDate = DateTime.Now.AddYears(Convert.ToInt32(- 1)), + SentDate = DateTime.Now, + Body = "", + ProcessorType = + "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", + ProcessorCommand = "ImportModule" + }; + + //Add custom Attributes for this message + oAppStartMessage.Attributes.Add("BusinessControllerClass", module.DesktopModule.BusinessControllerClass); + oAppStartMessage.Attributes.Add("ModuleId", module.ModuleID.ToString(CultureInfo.InvariantCulture)); + oAppStartMessage.Attributes.Add("Content", content); + oAppStartMessage.Attributes.Add("Version", version); + oAppStartMessage.Attributes.Add("UserID", userId.ToString(CultureInfo.InvariantCulture)); + + //send it to occur on next App_Start Event + EventQueueController.SendMessage(oAppStartMessage, "Application_Start"); + } + + static ModuleInfo DeserializeModule(XmlNode nodeModule, XmlNode nodePane, int portalId, int tabId, + int moduleDefId) + { + //Create New Module + var objModule = new ModuleInfo + { + PortalID = portalId, + TabID = tabId, + ModuleOrder = - 1, + ModuleTitle = XmlUtils.GetNodeValue(nodeModule, "title", ""), + PaneName = XmlUtils.GetNodeValue(nodePane, "name", ""), + ModuleDefID = moduleDefId, + CacheTime = XmlUtils.GetNodeValueInt(nodeModule, "cachetime"), + Alignment = XmlUtils.GetNodeValue(nodeModule, "alignment", ""), + IconFile = + Globals.ImportFile(portalId, XmlUtils.GetNodeValue(nodeModule, "iconfile", "")), + AllTabs = XmlUtils.GetNodeValueBoolean(nodeModule, "alltabs") + }; + switch (XmlUtils.GetNodeValue(nodeModule, "visibility", "")) + { + case "Maximized": + objModule.Visibility = VisibilityState.Maximized; + break; + case "Minimized": + objModule.Visibility = VisibilityState.Minimized; + break; + case "None": + objModule.Visibility = VisibilityState.None; + break; + } + objModule.Color = XmlUtils.GetNodeValue(nodeModule, "color", ""); + objModule.Border = XmlUtils.GetNodeValue(nodeModule, "border", ""); + objModule.Header = XmlUtils.GetNodeValue(nodeModule, "header", ""); + objModule.Footer = XmlUtils.GetNodeValue(nodeModule, "footer", ""); + objModule.InheritViewPermissions = XmlUtils.GetNodeValueBoolean(nodeModule, "inheritviewpermissions", false); + + objModule.StartDate = XmlUtils.GetNodeValueDate(nodeModule, "startdate", Null.NullDate); + objModule.EndDate = XmlUtils.GetNodeValueDate(nodeModule, "enddate", Null.NullDate); + + if (XmlUtils.GetNodeValue(nodeModule, "containersrc", "") != "") + { + objModule.ContainerSrc = XmlUtils.GetNodeValue(nodeModule, "containersrc", ""); + } + objModule.DisplayTitle = XmlUtils.GetNodeValueBoolean(nodeModule, "displaytitle", true); + objModule.DisplayPrint = XmlUtils.GetNodeValueBoolean(nodeModule, "displayprint", true); + objModule.DisplaySyndicate = XmlUtils.GetNodeValueBoolean(nodeModule, "displaysyndicate", false); + objModule.IsWebSlice = XmlUtils.GetNodeValueBoolean(nodeModule, "iswebslice", false); + if (objModule.IsWebSlice) + { + objModule.WebSliceTitle = XmlUtils.GetNodeValue(nodeModule, "webslicetitle", objModule.ModuleTitle); + objModule.WebSliceExpiryDate = XmlUtils.GetNodeValueDate(nodeModule, "websliceexpirydate", + objModule.EndDate); + objModule.WebSliceTTL = XmlUtils.GetNodeValueInt(nodeModule, "webslicettl", + Convert.ToInt32(objModule.CacheTime/60)); + } + + return objModule; + } + + static void DeserializeModulePermissions(XmlNodeList nodeModulePermissions, int portalId, ModuleInfo module) + { + var objRoleController = new RoleController(); + var objPermissionController = new PermissionController(); + + foreach (XmlNode node in nodeModulePermissions) + { + var permissionKey = XmlUtils.GetNodeValue(node, "permissionkey", ""); + var permissionCode = XmlUtils.GetNodeValue(node, "permissioncode", ""); + var roleName = XmlUtils.GetNodeValue(node, "rolename", ""); + var allowAccess = XmlUtils.GetNodeValueBoolean(node, "allowaccess"); + + var roleId = int.MinValue; + switch (roleName) + { + case Globals.glbRoleAllUsersName: + roleId = Convert.ToInt32(Globals.glbRoleAllUsers); + break; + case Globals.glbRoleUnauthUserName: + roleId = Convert.ToInt32(Globals.glbRoleUnauthUser); + break; + default: + var objRole = objRoleController.GetRoleByName(portalId, roleName); + if (objRole != null) + { + roleId = objRole.RoleID; + } + break; + } + if (roleId != int.MinValue) + { + var permissionId = Convert.ToInt32(- 1); + var arrPermissions = objPermissionController.GetPermissionByCodeAndKey(permissionCode, permissionKey); + + int i; + for (i = 0; i <= arrPermissions.Count - 1; i++) + { + var permission = (PermissionInfo) (arrPermissions[i]); + permissionId = permission.PermissionID; + } + + // if role was found add, otherwise ignore + if (permissionId != - 1) + { + var modulePermission = new ModulePermissionInfo + { + ModuleID = module.ModuleID, + PermissionID = permissionId, + RoleID = roleId, + AllowAccess = allowAccess + }; + module.ModulePermissions.Add(modulePermission); + } + } + } + } + + + static void DeserializeModuleSettings(XmlNodeList nodeModuleSettings, int moduleId) + { + var objModules = new ModuleController(); + var applySettings = Convert.ToBoolean(objModules.GetModuleSettings(moduleId).Count == 0); + + foreach (XmlElement nodeSetting in nodeModuleSettings) + { + var name = nodeSetting.GetAttribute("name"); + var value = nodeSetting.GetAttribute("value"); + if (applySettings || nodeSetting.GetAttribute("installmode").ToLowerInvariant() == "force") + { + objModules.UpdateModuleSetting(moduleId, name, value); + } + } + } + + static void DeserializeTabModuleSettings(XmlNodeList nodeTabModuleSettings, int moduleId, int tabId) + { + var objModules = new ModuleController(); + var tabModuleId = objModules.GetModule(moduleId, tabId).TabModuleID; + + var applySettings = Convert.ToBoolean(objModules.GetTabModuleSettings(tabModuleId).Count == 0); + foreach (XmlElement nodeSetting in nodeTabModuleSettings) + { + var name = nodeSetting.Attributes["name"].Value; + var value = nodeSetting.Attributes["value"].Value; + if (applySettings || nodeSetting.GetAttribute("installmode").ToLowerInvariant() == "force") + { + objModules.UpdateTabModuleSetting(tabModuleId, name, value); + } + } + } + + + static bool FindModule(XmlNode nodeModule, int tabId, PortalTemplateModuleAction mergeTabs) + { + var modules = new ModuleController(); + var tabModules = modules.GetTabModules(tabId); + + var moduleFound = false; + var modTitle = XmlUtils.GetNodeValue(nodeModule, "title", ""); + if (mergeTabs == PortalTemplateModuleAction.Merge) + { + if (tabModules.Select(kvp => kvp.Value).Any(module => modTitle == module.ModuleTitle)) + { + moduleFound = true; + } + } + + return moduleFound; + } + + static void GetModuleContent(XmlNode nodeModule, int moduleId, int tabId, int portalId, bool isInstance) + { + var moduleController = new ModuleController(); + var module = moduleController.GetModule(moduleId, tabId, true); + var contentNode = nodeModule.SelectSingleNode("content[@type]"); + var strVersion = contentNode.Attributes["version"].Value; + var strcontent = contentNode.InnerXml; + if (strcontent.StartsWith(" node to define the Module Type + // This node was populated with the DesktopModuleInfo.ModuleName property + // Thus there is no mechanism to determine to which module definition the module belongs. + // + // Template from v4.3.5 on also have the element that is populated + // with the ModuleDefinitionInfo.FriendlyName. Therefore the module Instance identifies + // which Module Definition it belongs to. + + //Get the DesktopModule defined by the element + var objDesktopModule = + DesktopModuleController.GetDesktopModuleByModuleName( + XmlUtils.GetNodeValue(nodeModule, "definition", ""), Null.NullInteger); + if (objDesktopModule != null) + { + //Get the moduleDefinition from the element + var friendlyName = XmlUtils.GetNodeValue(nodeModule, "moduledefinition", ""); + + if (string.IsNullOrEmpty(friendlyName)) + { + //Module is pre 4.3.5 so get the first Module Definition (at least it won't throw an error then) + var moduleDefinitions = + ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID( + objDesktopModule.DesktopModuleID).Values; + foreach ( + var moduleDefinition in + moduleDefinitions) + { + objModuleDefinition = moduleDefinition; + break; + } + } + else + { + //Module is 4.3.5 or later so get the Module Definition by its friendly name + objModuleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(friendlyName, + objDesktopModule. + DesktopModuleID); + } + } + + return objModuleDefinition; + } + + #endregion + + #region Public Shared Methods + + public static void DeserializeModule(XmlNode nodeModule, XmlNode nodePane, int portalId, int tabId, + PortalTemplateModuleAction mergeTabs, Hashtable hModules) + { + var moduleController = new ModuleController(); + var objModuleDefinition = GetModuleDefinition(nodeModule); + + // will be instance or module + var templateModuleId = XmlUtils.GetNodeValueInt(nodeModule, "moduleID"); + var isInstance = CheckIsInstance(templateModuleId, hModules); + + //remove containersrc node if container is missing + var containerNode = nodeModule.SelectSingleNode("containersrc"); + if (containerNode != null) + { + var container = containerNode.Value; + if (! File.Exists(HttpContext.Current.Server.MapPath(container))) + { + nodeModule.RemoveChild(containerNode); + } + } + + if (objModuleDefinition != null) + { + //If Mode is Merge Check if Module exists + if (! FindModule(nodeModule, tabId, mergeTabs)) + { + var module = DeserializeModule(nodeModule, nodePane, portalId, tabId, + objModuleDefinition.ModuleDefID); + + int intModuleId; + if (! isInstance) + { + //Add new module + intModuleId = moduleController.AddModule(module); + if (templateModuleId > 0) + { + hModules.Add(templateModuleId, intModuleId); + } + } + else + { + //Add instance + module.ModuleID = Convert.ToInt32(hModules[templateModuleId]); + intModuleId = moduleController.AddModule(module); + } + + if (XmlUtils.GetNodeValue(nodeModule, "content", "") != "") + { + GetModuleContent(nodeModule, intModuleId, tabId, portalId, isInstance); + } + + // Process permissions and moduleSettings only once + if (! isInstance) + { + var nodeModulePermissions = nodeModule.SelectNodes("modulepermissions/permission"); + DeserializeModulePermissions(nodeModulePermissions, portalId, module); + + //Persist the permissions to the Data base + ModulePermissionController.SaveModulePermissions(module); + + var nodeModuleSettings = nodeModule.SelectNodes("modulesettings/setting"); + DeserializeModuleSettings(nodeModuleSettings, intModuleId); + } + + //apply TabModuleSettings + var nodeTabModuleSettings = nodeModule.SelectNodes("tabmodulesettings/setting"); + DeserializeTabModuleSettings(nodeTabModuleSettings, intModuleId, tabId); + } + } + } + + /// + /// SerializeModule + /// + /// The Xml Document to use for the Module + /// The ModuleInfo object to serialize + /// A flak that determines whether the content of the module is serialised. + public static XmlNode SerializeModule(XmlDocument xmlModule, ModuleInfo objModule, bool includeContent) + { + return SerializeModule(xmlModule, objModule, includeContent, Null.NullInteger); + } + + /// + /// SerializeModule + /// + /// The Xml Document to use for the Module + /// The ModuleInfo object to serialize + /// A flak that determines whether the content of the module is serialised. + /// Numer of reords. Choose Null.NullInteger (-1) to include all records + public static XmlNode SerializeModule(XmlDocument xmlModule, ModuleInfo objModule, bool includeContent, + int maxNumberofRecords) + { + var xserModules = new XmlSerializer(typeof (ModuleInfo)); + using (var sw = new StringWriter()) + { + xserModules.Serialize(sw, objModule); + xmlModule.LoadXml((sw.GetStringBuilder().ToString())); + } + + var nodeModule = xmlModule.SelectSingleNode("module"); +// ReSharper disable PossibleNullReferenceException + nodeModule.Attributes.Remove(nodeModule.Attributes["xmlns:xsd"]); + nodeModule.Attributes.Remove(nodeModule.Attributes["xmlns:xsi"]); + + //remove unwanted elements +// ReSharper disable AssignNullToNotNullAttribute + nodeModule.RemoveChild(nodeModule.SelectSingleNode("portalid")); + + nodeModule.RemoveChild(nodeModule.SelectSingleNode("tabid")); + nodeModule.RemoveChild(nodeModule.SelectSingleNode("tabmoduleid")); + nodeModule.RemoveChild(nodeModule.SelectSingleNode("moduleorder")); + nodeModule.RemoveChild(nodeModule.SelectSingleNode("panename")); + nodeModule.RemoveChild(nodeModule.SelectSingleNode("isdeleted")); + + foreach (XmlNode nodePermission in nodeModule.SelectNodes("modulepermissions/permission")) + { + nodePermission.RemoveChild(nodePermission.SelectSingleNode("modulepermissionid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("permissionid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("moduleid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("roleid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("userid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("username")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("displayname")); + } + // ReSharper restore AssignNullToNotNullAttribute + // ReSharper restore PossibleNullReferenceException + if (includeContent) + { + AddContent(nodeModule, objModule, maxNumberofRecords); + AddSettings(nodeModule, objModule); + } + + XmlNode newnode = xmlModule.CreateElement("definition"); + + var objModuleDef = ModuleDefinitionController.GetModuleDefinitionByID(objModule.ModuleDefID); + newnode.InnerText = + DesktopModuleController.GetDesktopModule(objModuleDef.DesktopModuleID, objModule.PortalID).ModuleName; + nodeModule.AppendChild(newnode); + + //Add Module Definition Info + XmlNode nodeDefinition = xmlModule.CreateElement("moduledefinition"); + nodeDefinition.InnerText = objModuleDef.FriendlyName; + nodeModule.AppendChild(nodeDefinition); + + return nodeModule; + } + + #endregion + } +} \ No newline at end of file diff --git a/Settings.ascx.cs b/Settings.ascx.cs new file mode 100644 index 0000000..59814fa --- /dev/null +++ b/Settings.ascx.cs @@ -0,0 +1,46 @@ +using System; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Modules.UserDefinedTable.Components; + + +namespace DotNetNuke.Modules.UserDefinedTable +{ + /// ----------------------------------------------------------------------------- + /// + /// Module Settings + /// + /// ----------------------------------------------------------------------------- + public partial class Settings : ModuleSettingsBase + { + #region Private Methods + + public override void LoadSettings() + { + txtUserRecordQuota.Text = Settings[SettingName.UserRecordQuota].AsString(); + chkEditOwnData.Checked = Convert.ToBoolean(Settings[SettingName.EditOnlyOwnItems]); + chkCaptcha.Checked = Convert.ToBoolean(Settings[SettingName.ForceCaptchaForAnonymous]); + chkInputFiltering.Checked = Convert.ToBoolean(Settings[SettingName.ForceInputFiltering]); + chkDisplayColumns.Checked = + Convert.ToBoolean(! Settings[SettingName.ShowAllColumnsForAdmins].AsBoolean(true)); + chkPrivateColumns.Checked = + Convert.ToBoolean(! Settings[SettingName.EditPrivateColumnsForAdmins].AsBoolean(true)); + chkHideSystemColumns.Checked = Convert.ToBoolean(! Settings[SettingName.ShowSystemColumns].AsBoolean()); + } + + public override void UpdateSettings() + { + var mc = new ModuleController(); + mc.UpdateModuleSetting(ModuleId, SettingName.UserRecordQuota, txtUserRecordQuota.Text); + mc.UpdateModuleSetting(ModuleId, SettingName.EditOnlyOwnItems, chkEditOwnData.Checked.ToString()); + mc.UpdateModuleSetting(ModuleId, SettingName.ForceCaptchaForAnonymous, chkCaptcha.Checked.ToString()); + mc.UpdateModuleSetting(ModuleId, SettingName.ForceInputFiltering, chkInputFiltering.Checked.ToString()); + mc.UpdateModuleSetting(ModuleId, SettingName.ShowAllColumnsForAdmins, + (!(chkDisplayColumns.Checked)).ToString()); + mc.UpdateModuleSetting(ModuleId, SettingName.EditPrivateColumnsForAdmins, + (!(chkPrivateColumns.Checked)).ToString()); + mc.UpdateModuleSetting(ModuleId, SettingName.ShowSystemColumns, (!(chkHideSystemColumns.Checked)).ToString()); + } + + #endregion + } +} \ No newline at end of file diff --git a/Settings.ascx.designer.cs b/Settings.ascx.designer.cs new file mode 100644 index 0000000..ea411b4 --- /dev/null +++ b/Settings.ascx.designer.cs @@ -0,0 +1,87 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable { + + + public partial class Settings { + + /// + /// chkEditOwnData control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkEditOwnData; + + /// + /// chkCaptcha control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkCaptcha; + + /// + /// chkInputFiltering control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkInputFiltering; + + /// + /// chkDisplayColumns control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkDisplayColumns; + + /// + /// chkHideSystemColumns control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkHideSystemColumns; + + /// + /// chkPrivateColumns control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkPrivateColumns; + + /// + /// lblUserRecordQuota control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl lblUserRecordQuota; + + /// + /// txtUserRecordQuota control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtUserRecordQuota; + } +} diff --git a/ShowXml.ashx.cs b/ShowXml.ashx.cs new file mode 100644 index 0000000..f1c36a1 --- /dev/null +++ b/ShowXml.ashx.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Entities.Users; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Security.Permissions; + +namespace DotNetNuke.Modules.UserDefinedTable +{ + /// + /// Summary description for ShowXml + /// + public class ShowXml : IHttpHandler + { + + public void ProcessRequest(HttpContext context) + { + try + { + PortalController.GetCurrentPortalSettings(); + + if ((context.Request.QueryString["tabid"] == null || context.Request.QueryString["mid"] == null) || + !(context.Request.IsAuthenticated)) + { + return; + } + // get TabId + var tabId = Convert.ToInt32(-1); + if (context.Request.QueryString["tabid"] != null) + { + tabId = int.Parse(context.Request.QueryString["tabid"]); + } + + // get ModuleId + var moduleId = Convert.ToInt32(-1); + if (context.Request.QueryString["mid"] != null) + { + moduleId = int.Parse(context.Request.QueryString["mid"]); + } + + var userInfo = UserController.GetCurrentUserInfo(); + var mc = new ModuleController(); + var settings = mc.GetModuleSettings(moduleId); + var moduleInfo = new ModuleController().GetModule(moduleId, tabId); + + if (ModulePermissionController.CanManageModule(moduleInfo)) + { + var udt = new UserDefinedTableController(moduleId, tabId, userInfo); + var ds = udt.GetDataSet(true); + + ds.Tables.Add(udt.Context(moduleInfo, userInfo, + context.Request[Definition.QueryStringParameter].AsString(), + settings[SettingName.SortField].AsString(), + settings[SettingName.SortOrder].AsString(), + settings[SettingName.Paging].AsString())); + context.Response.ContentType = "Text/Xml"; + ds.WriteXml(context.Response.OutputStream); + } + } + catch (Exception) + { + context.Response.Write("Not defined"); + } + } + + public bool IsReusable + { + get + { + return false; + } + } + } +} \ No newline at end of file diff --git a/Template.ascx.cs b/Template.ascx.cs new file mode 100644 index 0000000..ce93fe1 --- /dev/null +++ b/Template.ascx.cs @@ -0,0 +1,67 @@ +using System; +using DotNetNuke.Common; +using DotNetNuke.Modules.UserDefinedTable.Templates; +using DotNetNuke.UI.Modules; + +namespace DotNetNuke.Modules.UserDefinedTable +{ + /// ----------------------------------------------------------------------------- + /// + /// Editor for Module templates (aka Module Applications) + /// + /// ----------------------------------------------------------------------------- + public partial class Template : ModuleUserControlBase + { + protected void cmdSaveFile_Click(object sender, EventArgs e) + { + if (TemplateController.SaveTemplate(txtTitle.Text, txtDescription.Text, ModuleContext, false, + MaxNumberOfRecords())) + { + Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); + } + else + { + panConfirm.Visible = true; + panSave.Visible = false; + cmdSaveFile.Enabled = false; + txtDescription.Enabled = false; + txtTitle.Enabled = false; + } + } + + protected void cmdConfirmOverwriteFile_Click(object sender, EventArgs e) + { + TemplateController.SaveTemplate(txtTitle.Text, txtDescription.Text, ModuleContext, true, + MaxNumberOfRecords()); + Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); + } + + protected void cmdDenyOverwriteFile_Click(object sender, EventArgs e) + { + cmdSaveFile.Enabled = true; + panSave.Visible = true; + txtDescription.Enabled = true; + txtTitle.Enabled = true; + txtTitle.Text = ""; + panConfirm.Visible = false; + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + cmdConfirmOverwriteFile.Click += cmdConfirmOverwriteFile_Click; + cmdDenyOverwriteFile.Click += cmdDenyOverwriteFile_Click; + cmdSaveFile.Click += cmdSaveFile_Click; + } + + int MaxNumberOfRecords() + { + int returnValue; + if (! int.TryParse(txtNumbers.Text, out returnValue)) + { + returnValue = 1; + } + return returnValue; + } + } +} \ No newline at end of file diff --git a/Template.ascx.designer.cs b/Template.ascx.designer.cs new file mode 100644 index 0000000..f7e9e15 --- /dev/null +++ b/Template.ascx.designer.cs @@ -0,0 +1,132 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable { + + + public partial class Template { + + /// + /// divWarning control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl divWarning; + + /// + /// plTitle control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plTitle; + + /// + /// txtTitle control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtTitle; + + /// + /// plDescription control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plDescription; + + /// + /// txtDescription control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtDescription; + + /// + /// plNumberofRecords control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plNumberofRecords; + + /// + /// txtNumbers control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtNumbers; + + /// + /// panSave control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl panSave; + + /// + /// cmdSaveFile control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdSaveFile; + + /// + /// panConfirm control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl panConfirm; + + /// + /// lblConfirm control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblConfirm; + + /// + /// cmdConfirmOverwriteFile control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdConfirmOverwriteFile; + + /// + /// cmdDenyOverwriteFile control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdDenyOverwriteFile; + } +} diff --git a/TemplateList.ascx.cs b/TemplateList.ascx.cs new file mode 100644 index 0000000..4a9d6cc --- /dev/null +++ b/TemplateList.ascx.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Web.UI; +using System.Xml; +using DotNetNuke.Common; +using DotNetNuke.Common.Lists; +using DotNetNuke.Entities.Icons; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Modules.Actions; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Modules.UserDefinedTable.Templates; +using DotNetNuke.Security; +using DotNetNuke.Services.Exceptions; +using DotNetNuke.Services.Localization; + +namespace DotNetNuke.Modules.UserDefinedTable +{ + /// ----------------------------------------------------------------------------- + /// + /// Editor for Module Templates + /// + /// ----------------------------------------------------------------------------- + public partial class TemplateList : PortalModuleBase, IActionable, IPostBackEventHandler + { + readonly List _customizations = new List(); + + #region Optional Interfaces + + public ModuleActionCollection ModuleActions + { + get + { + var actions = new ModuleActionCollection(); + try + { + actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("Rescan", LocalResourceFile), "", + "", Utilities.IconURL("Refresh"), + string.Format("javascript:{0}", + Page.ClientScript.GetPostBackEventReference(this, "Rescan")), false, + SecurityAccessLevel.Edit, true, false); + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + return actions; + } + } + + public void RaisePostBackEvent(string eventArgument) + { + if (eventArgument == "Rescan") + { + TemplateController.ClearCache(); + Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); + } + } + + #endregion + + #region Events + + protected override void OnInit(EventArgs e) + { + Load+=Page_Load; + GridView1.SelectedIndexChanged += GridView1_SelectedIndexChanged; + } + + protected void Page_Load(object sender, EventArgs e) + { + + cmdConfig.NavigateUrl = ModuleContext.EditUrl("Manage"); + if (! IsPostBack) + { + Localization.LocalizeGridView(ref GridView1, LocalResourceFile); + } + BindData(); + if (GridView1.Rows.Count == 0) + { + lblTemplate.Visible = false; + } + } + + protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) + { + BindData(); + if (_customizations.Count > 0) + { + GridView1.Visible = false; + lblCustomizeTemplate.Text = string.Format(Localization.GetString("CustomizeTemplate", LocalResourceFile), + GridView1.SelectedRow.Cells[1].Text, + GridView1.SelectedRow.Cells[2].Text); + + cmdApply.Visible = true; + } + else + { + TemplateController.LoadTemplate(HttpUtility.HtmlDecode(GridView1.SelectedRow.Cells[1].Text), + ModuleContext.PortalId, ModuleContext.TabId); + DeleteMe(); + } + } + + protected void cmdApply_Click(object sender, EventArgs e) + { + XmlDocument doc = null; + foreach (var customizedValue in _customizations) + { + var parentNode = customizedValue.Node.ParentNode; + // ReSharper disable PossibleNullReferenceException + if (customizedValue.ValueSource != string.Empty) + { + ((XmlElement) parentNode).SetAttribute(customizedValue.ValueSource, customizedValue.Value); + ((XmlElement) parentNode).SetAttribute("installmode", "force"); + } + else + { + parentNode.InnerText = customizedValue.Value; + } + // ReSharper restore PossibleNullReferenceException + doc = customizedValue.Node.OwnerDocument; + } + + TemplateController.LoadTemplate(doc, ModuleContext.PortalId, ModuleContext.TabId); + DeleteMe(); + } + + #endregion + + #region Private functions + + void DeleteMe() + { + var m = new ModuleController(); + m.DeleteTabModule(ModuleContext.TabId, ModuleContext.ModuleId, false); + m.DeleteModule(ModuleContext.ModuleId); + Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); + } + + void LoadCustomization() + { + // Customizations.Clear() + + var doc = new XmlDocument(); + doc.LoadXml( + (TemplateController.Templates[HttpUtility.HtmlDecode((GridView1.SelectedRow.Cells[1].Text))]. + ExportContent)); + + var lists = new ListController(); + + var xmlnsManager = new XmlNamespaceManager(doc.NameTable); + xmlnsManager.AddNamespace("ask", "DotNetNuke/ModuleTemplate"); + + foreach (XmlElement node in doc.SelectNodes("//ask:user", xmlnsManager)) + { + var vsource = node.GetAttribute("valuesource"); + + string value = vsource != string.Empty + ? ((XmlElement) node.ParentNode).GetAttribute(vsource) + : node.ParentNode.InnerText.Trim(); + var editor = node.GetAttribute("editor").AsString("Text"); + var length = int.Parse(node.GetAttribute("length").AsString("255")); + var editorId = lists.GetListEntryInfo("DataType", editor).EntryID; + + var caption = node.GetAttribute("caption").AsString(vsource.AsString(node.ParentNode.Name)); + + _customizations.Add(new TemplateValueInfo + { + Caption = caption, + Editor = editorId, + Node = node, + Value = value, + ValueSource = vsource, + Length = length + }); + } + } + + void BindData() + { + if (GridView1.SelectedRow != null) + { + LoadCustomization(); + TemplateCustomValuesEditor.DataSource = _customizations; + TemplateCustomValuesEditor.DataBind(); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/TemplateList.ascx.designer.cs b/TemplateList.ascx.designer.cs new file mode 100644 index 0000000..6c87d4a --- /dev/null +++ b/TemplateList.ascx.designer.cs @@ -0,0 +1,96 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable { + + + public partial class TemplateList { + + /// + /// lblNewConfig control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblNewConfig; + + /// + /// cmdConfig control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink cmdConfig; + + /// + /// lblConfig control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblConfig; + + /// + /// lblTemplate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblTemplate; + + /// + /// GridView1 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.GridView GridView1; + + /// + /// TemplateDataSource control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.ObjectDataSource TemplateDataSource; + + /// + /// lblCustomizeTemplate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblCustomizeTemplate; + + /// + /// TemplateCustomValuesEditor control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.WebControls.CollectionEditorControl TemplateCustomValuesEditor; + + /// + /// cmdApply control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdApply; + } +} diff --git a/Templates/TemplateController.cs b/Templates/TemplateController.cs new file mode 100644 index 0000000..0b59e7c --- /dev/null +++ b/Templates/TemplateController.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Xml; +using DotNetNuke.Common; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Modules.UserDefinedTable.Serialization; +using DotNetNuke.Services.Exceptions; +using DotNetNuke.UI.Modules; + +namespace DotNetNuke.Modules.UserDefinedTable.Templates +{ + /// ----------------------------------------------------------------------------- + /// + /// + /// ----------------------------------------------------------------------------- + public class TemplateController + { + static string CacheKey + { + get { return string.Format("UDT_Tempaltes{0}", Globals.GetPortalSettings().PortalId); } + } + + static readonly object TemplateLock = new object(); + + public static IDictionary Templates + { + get + { + var templates = (IDictionary) (DataCache.GetCache(CacheKey)); + + if (templates == null) + { + lock (TemplateLock) + { + templates = new Dictionary(); + var folderNames = new[] + { + Globals.GetPortalSettings().HomeDirectoryMapPath + + Definition.TemplateFolderName, + Globals.HostMapPath + Definition.TemplateFolderName + }; + foreach (var folderName in folderNames) + { + if (Directory.Exists(folderName)) + { + var folder = new DirectoryInfo(folderName); + foreach (var file in folder.GetFiles("*.dnn_userdefinedtable.module.template")) + { + try + { + var doc = new XmlDocument(); + doc.Load(file.FullName); + var templateNode = doc.SelectSingleNode("/moduletemplate"); + // ReSharper disable PossibleNullReferenceException + var template = new TemplateInfo + { + Name = templateNode.Attributes["title"].Value, + Description = templateNode.Attributes["description"].Value, + ExportContent = templateNode.InnerXml + }; + // ReSharper restore PossibleNullReferenceException + templates[template.Name] = template; + } + catch (Exception exp) + { + var e = + new Exception( + string.Format("UDT Template: {0} caused an exception", file.FullName), + exp); + Exceptions.LogException(e); + } + } + } + DataCache.SetCache(CacheKey, templates); + } + } + } + return templates; + } + } + + /// + /// Returns a list of all Templates, needed for ObjectDatasource + /// + public ICollection TemplateList() + { + return Templates.Values; + } + + public static void LoadTemplate(string name, int portalId, int tabid) + { + var doc = new XmlDocument(); + doc.LoadXml((Templates[name].ExportContent)); + ModuleSerializationController.DeserializeModule(doc.DocumentElement, doc.DocumentElement, portalId, tabid, + PortalTemplateModuleAction.Ignore, new Hashtable()); + } + + public static void LoadTemplate(XmlDocument content, int portalId, int tabid) + { + ModuleSerializationController.DeserializeModule(content.DocumentElement, content.DocumentElement, portalId, + tabid, PortalTemplateModuleAction.Ignore, new Hashtable()); + } + + public static void ClearCache() + { + DataCache.RemoveCache(CacheKey); + } + + public static bool SaveTemplate(string name, string description, ModuleInstanceContext context, + bool forceOverwrite, int maxNumberOfRecords) + { + var doc = new XmlDocument(); + var moduleInfo = new ModuleController().GetModule(context.Configuration.ModuleID, context.Configuration.TabID); + var node = ModuleSerializationController.SerializeModule(doc, moduleInfo, true, maxNumberOfRecords); + // add PaneName as element "name" + var paneNode = doc.CreateElement("name"); + paneNode.InnerXml = context.Configuration.PaneName; + node.AppendChild(paneNode); + var template = new TemplateInfo + { + Name = name, + Description = description, + ExportContent = XslTemplatingUtilities.PrettyPrint(node.OuterXml) + }; + + var fileName = string.Format("{0}.{1}.module.template", Globals.CleanFileName(name), + moduleInfo.DesktopModule.ModuleName.ToLowerInvariant()); + + var portalSettings = context.PortalSettings; + var folder = Utilities.GetFolder(portalSettings, Definition.TemplateFolderName); + + if (Utilities.SaveScript( template.GetXml(), fileName, folder, forceOverwrite)) + { + ClearCache(); + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/Templates/TemplateInfo.cs b/Templates/TemplateInfo.cs new file mode 100644 index 0000000..b7aaace --- /dev/null +++ b/Templates/TemplateInfo.cs @@ -0,0 +1,64 @@ +using System; +using System.IO; +using System.Xml; + +namespace DotNetNuke.Modules.UserDefinedTable.Templates +{ + /// ----------------------------------------------------------------------------- + /// + /// + /// ----------------------------------------------------------------------------- + [Serializable] + public class TemplateInfo + { + string _Name; + string _Description; + string _Export; + XmlNode _AdditionalData; + + public string Name + { + get { return _Name; } + set { _Name = value; } + } + + public string Description + { + get { return _Description; } + set { _Description = value; } + } + + public string ExportContent + { + get { return _Export; } + set { _Export = value; } + } + + public XmlNode AdditionalData + { + get { return _AdditionalData; } + set { _AdditionalData = value; } + } + + + public string GetXml() + { + using (var strXML = new StringWriter()) + { + using (var xmlWriter = new XmlTextWriter(strXML)) + { + xmlWriter.Formatting = Formatting.Indented; + xmlWriter.WriteStartElement("moduletemplate"); + xmlWriter.WriteAttributeString("title", Name); + xmlWriter.WriteAttributeString("description", Description); + xmlWriter.WriteAttributeString("xmlns", "ask", null, "DotNetNuke/ModuleTemplate"); + xmlWriter.WriteRaw(ExportContent); + xmlWriter.WriteEndElement(); + xmlWriter.Close(); + } + + return strXML.ToString(); + } + } + } +} \ No newline at end of file diff --git a/Templates/TemplateValueInfo.cs b/Templates/TemplateValueInfo.cs new file mode 100644 index 0000000..9e30c54 --- /dev/null +++ b/Templates/TemplateValueInfo.cs @@ -0,0 +1,70 @@ +using System; +using System.Xml; + +namespace DotNetNuke.Modules.UserDefinedTable.Templates +{ + [Serializable] + public class TemplateValueInfo + { + #region Private Fields + + int _EditorId; + string _ValueSource; + string _Value; + string _Caption; + XmlNode _Node; + int _length; + + #endregion + + #region Public Properties + + public int Editor + { + get { return _EditorId; } + set { _EditorId = value; } + } + + public string ValueSource + { + get { return _ValueSource; } + set { _ValueSource = value; } + } + + public string Value + { + get { return _Value; } + set { _Value = value; } + } + + public string Caption + { + get { return _Caption; } + set { _Caption = value; } + } + + public XmlNode Node + { + get { return _Node; } + set { _Node = value; } + } + + public bool TrueColumn + { + get { return true; } + } + + public bool FalseColumn + { + get { return false; } + } + + public int Length + { + get { return _length; } + set { _length = value; } + } + + #endregion + } +} \ No newline at end of file diff --git a/Token2Xsl.ascx.cs b/Token2Xsl.ascx.cs new file mode 100644 index 0000000..b8b71d6 --- /dev/null +++ b/Token2Xsl.ascx.cs @@ -0,0 +1,907 @@ +using System; +using System.Collections; +using System.Data; +using System.Drawing; +using System.IO; +using System.Text.RegularExpressions; +using System.Web; +using System.Web.UI.WebControls; +using System.Xml; +using DotNetNuke.Common; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Modules.UserDefinedTable.Components; +using DotNetNuke.Services.FileSystem; +using DotNetNuke.Services.Localization; +using DotNetNuke.UI.Modules; + + +namespace DotNetNuke.Modules.UserDefinedTable +{ + /// ----------------------------------------------------------------------------- + /// + /// The Token2Xsl Class provides an option to create a XSL rendering file derived + /// from a html template for the UserDefinedTable + /// + /// ----------------------------------------------------------------------------- + public partial class Token2Xsl : ModuleUserControlBase + { + #region Controls & Constants & Properties + + DataSet _schemaDataSet; + + public enum ErrorOutput + { + TokenTemplate, + XslTranformation, + Save + } + + UserDefinedTableController _udtController; + + UserDefinedTableController UdtController + { + get { return _udtController ?? (_udtController = new UserDefinedTableController(ModuleContext)); } + } + + string CurrentListType + { + get { return ViewState["CurrentListType"].AsString(ddlListTemplateType.SelectedValue); } + set { ViewState["CurrentListType"] = value; } + } + + string ReturnUrl + { + get { return ViewState["ReturnUrl"].AsString(ModuleContext.EditUrl("Manage")); } + set { ViewState["ReturnUrl"] = value; } + } + + bool IsTrackingEmailMode + { + get + { + return ViewState["tracking"].AsBoolean(Convert.ToBoolean(Request.QueryString["tracking"].AsString().Length > 0)); + } + set { ViewState["tracking"] = value; } + } + + #endregion + + #region Private Methods + + void TemplatesPopulateColumnDropDownLists() + { + ddlColumnsForListView.Items.Clear(); + ddlColumnsForDetailView.Items.Clear(); + ddlColumnsForTrackingEmail.Items.Clear(); + + + ddlColumnsForListView.Items.Add(new ListItem("UDT:EditLink", "[UDT:EditLink]")); + ddlColumnsForTrackingEmail.Items.Add(new ListItem("UDT:EditLink", "[UDT:EditLink]")); + if (chkShowDetailView.Checked) + { + ddlColumnsForListView.Items.Add(new ListItem("UDT:DetailView", "[UDT:DetailView]")); + } + + ddlColumnsForDetailView.Items.Add(new ListItem("UDT:EditLink", "[UDT:EditLink]")); + ddlColumnsForDetailView.Items.Add(new ListItem("UDT:ListView", "[UDT:ListView]")); + foreach (DataColumn col in _schemaDataSet.Tables[DataSetTableName.Data].Columns) + { + var colName = col.ColumnName; + if (colName != "EditLink") + { + ddlColumnsForListView.Items.Add(new ListItem(colName, string.Format("[{0}]", colName))); + ddlColumnsForDetailView.Items.Add(new ListItem(colName, string.Format("[{0}]", colName))); + ddlColumnsForTrackingEmail.Items.Add(new ListItem(colName, string.Format("[{0}]", colName))); + } + } + ddlColumnsForListView.Items.Add(new ListItem("[ ] Hard Space", "[ ]")); + ddlColumnsForDetailView.Items.Add(new ListItem("[ ] Hard Space", "[ ]")); + ddlColumnsForTrackingEmail.Items.Add(new ListItem("[ ] Hard Space", "[ ]")); + foreach (var contextString in Enum.GetNames(typeof (XslTemplatingUtilities.ContextValues))) + { + ddlColumnsForListView.Items.Add(new ListItem(string.Format("Context:{0}", contextString), + string.Format("[Context:{0}]", contextString))); + ddlColumnsForDetailView.Items.Add(new ListItem(string.Format("Context:{0}", contextString), + string.Format("[Context:{0}]", contextString))); + ddlColumnsForTrackingEmail.Items.Add(new ListItem(string.Format("Context:{0}", contextString), + string.Format("[Context:{0}]", contextString))); + } + + ddlHeaders.Items.Clear(); + foreach (DataRow row in _schemaDataSet.Tables[DataSetTableName.Fields].Rows) + { + var title = row[FieldsTableColumn.Title].ToString(); + ddlHeaders.Items.Add(new ListItem(title, string.Format("[{0}]", title))); + } + } + + void TemplatesSetVisibility(bool isViewMode) + { + if (isViewMode) + { + dshListView.Visible = true; + dshOptions.Visible = true; + dshTrackingEmail.Visible = false; + dvListview.Visible = true; + dvOptions.Visible = true; + dvTrackingEmail.Visible = false; + + var showDetails = chkShowDetailView.Checked; + dshDetailView.Visible = showDetails; + dvDetailView.Visible = showDetails; + if (showDetails && txtListTemplate.Text.IndexOf("UDT:DetailView") < 0) + { + txtListTemplate.Text = txtListTemplate.Text.Replace("UDT:EditLink", "UDT:DetailView"); + } + if (! showDetails) + { + txtListTemplate.Text = txtListTemplate.Text.Replace("UDT:DetailView", txtListTemplate.Text.IndexOf("UDT:EditLink") > 0 + ? "" : + "UDT:EditLink"); + } + } + else + { + dshListView.Visible = false; + dshOptions.Visible = false; + dshDetailView.Visible = false; + dshTrackingEmail.Visible = true; + + dvListview.Visible = false; + dvOptions.Visible = false; + dvDetailView.Visible = false; + dvTrackingEmail.Visible = true; + } + } + + + IList GetBasicElements() + { + var elements = new ArrayList {"[UDT:EditLink]"}; + foreach (DataRow row in _schemaDataSet.Tables[DataSetTableName.Fields].Rows) + { + if (Convert.ToBoolean(row[FieldsTableColumn.Visible])) + { + elements.Add(string.Format("[{0}]", + XmlConvert.DecodeName(row[FieldsTableColumn.ValueColumn].ToString()))); + } + } + return elements; + } + + IList GetCurrentElements() + { + var txt = txtListTemplate.Text; + try + { + switch (CurrentListType) + { + case "table": + var doc1 = new XmlDocument(); + doc1.LoadXml(txt); + var elements = new ArrayList(); + var cells = doc1.SelectNodes("/tr/td"); + if (cells != null) + foreach (XmlElement node in cells) + { + elements.Add(node.InnerXml); + } + return elements; + default: + + if (CurrentListType != "nothing") + { + var doc = new XmlDocument(); + doc.LoadXml(txt); + var node = doc.SelectSingleNode(string.Format("/{0}", GetOuterTag(CurrentListType))); + if (node != null) + { + txt = node.InnerXml; + } + } + return Regex.Split(txt, GetDelimiter(false)); + } + } + catch (Exception) + { + return null; + } + } + + string BuildContent(IList elements) + { + var listType = ddlListTemplateType.SelectedValue; + if (elements != null) + { + CurrentListType = listType; + using (var sw = new StringWriter()) + { + var delimiter = GetDelimiter(); + using (var xw = new XmlTextWriter(sw)) + { + var notFirst = false; + xw.Formatting = Formatting.Indented; + var outerTag = GetOuterTag(ddlListTemplateType.SelectedValue); + if (outerTag != string.Empty) + { + xw.WriteStartElement(outerTag); + xw.WriteAttributeString("class", "dnnGridItem"); + } + foreach (string element in elements) + { + if (GetInnerTag() != string.Empty) + { + xw.WriteStartElement(GetInnerTag()); + } + if (notFirst) + { + xw.WriteRaw(delimiter); + } + else + { + notFirst = true; + } + xw.WriteRaw(element); + if (GetInnerTag() != string.Empty) + { + xw.WriteEndElement(); + } + } + if (outerTag != string.Empty) + { + xw.WriteEndElement(); + } + xw.Flush(); + } + + return sw.ToString(); + } + } + return string.Empty; + } + + string GetDelimiter(bool notCurrent = true) + { + if (notCurrent && ddlListTemplateType.SelectedValue == "table") + { + return (""); + } + var delimiter = ""; + if (txtListTemplateDelimiter.Text != "") + { + delimiter = txtListTemplateDelimiter.Text; + } + delimiter += "\r\n"; + return delimiter; + } + + string GetOuterTag(string listType) + { + switch (listType) + { + case "table": + return "tr"; + case "nothing": + return ""; + case "ol": + case "ul": + return "li"; + default: + return listType; + } + } + + string GetInnerTag() + { + switch (ddlListTemplateType.SelectedValue) + { + case "table": + return "td"; + default: + return ""; + } + } + + void ListTemplateSetHeaderAndFooter() + { + switch (ddlListTemplateType.SelectedValue) + { + case "table": + lblListTemplateHead.Text = @"<table class=""dnnFormItem"">"; + lblListTemplateFooter.Text = @"...
    </table>"; + break; + case "div": + lblListTemplateHead.Text = ""; + lblListTemplateFooter.Text = @"..."; + break; + case "ol": + lblListTemplateHead.Text = @"<ol>"; + lblListTemplateFooter.Text = @"...
    </ol>"; + break; + case "ul": + lblListTemplateHead.Text = @"<ul>"; + lblListTemplateFooter.Text = @"...
    </ul>"; + break; + case "p": + lblListTemplateHead.Text = ""; + lblListTemplateFooter.Text = @"..."; + break; + case "nothing": + lblListTemplateHead.Text = @"..."; + lblListTemplateFooter.Text = ""; + break; + } + } + + bool isValid(string x, ErrorOutput pos, bool addRoot) + { + if (addRoot) + { + x = string.Format("{0}", x); + } + using (var rdr = new XmlTextReader(new StringReader(x))) + { + try + { + while (rdr.Read()) + { + } + return true; + } + catch (Exception ex) + { + switch (pos) + { + case ErrorOutput.TokenTemplate: + lblTemplateError.Text = (Localization.GetString("error.Text", LocalResourceFile) + + ex.Message); + lblTemplateError.Visible = true; + break; + case ErrorOutput.XslTranformation: + lblXslScriptError.Text = (Localization.GetString("error.Text", LocalResourceFile) + + ex.Message); + lblXslScriptError.Visible = true; + break; + case ErrorOutput.Save: + lblSaveXslError.Text = (Localization.GetString("error.Text", LocalResourceFile) + ex.Message); + lblSaveXslError.Visible = true; + break; + } + return false; + } + } + } + + void setupDelimiter() + { + if (ddlListTemplateType.SelectedValue == "table") + { + txtListTemplateDelimiter.Enabled = false; + txtListTemplateDelimiter.BackColor = Color.LightGray; + addColumnWithTagsToListTemplate.Enabled = true; + } + else + { + txtListTemplateDelimiter.Enabled = true; + txtListTemplateDelimiter.BackColor = Color.White; + addColumnWithTagsToListTemplate.Enabled = false; + } + } + + void LockControls(bool isLockRequested) + { + if (isLockRequested) + { + cmdRebuildContent.Enabled = false; + cmdSaveFile.Enabled = false; + cmdGenerateXslt.Enabled = false; + addColumnToListTemplate.Enabled = false; + addColumnWithTagsToListTemplate.Enabled = false; + ddlListTemplateType.Enabled = false; + ddlColumnsForListView.Enabled = false; + txtListTemplate.Enabled = false; + txtFileName.Enabled = false; + txtXslScript.Enabled = false; + } + else + { + cmdRebuildContent.Enabled = true; + cmdSaveFile.Enabled = true; + cmdGenerateXslt.Enabled = true; + addColumnToListTemplate.Enabled = true; + addColumnWithTagsToListTemplate.Enabled = true; + ddlListTemplateType.Enabled = true; + ddlColumnsForListView.Enabled = true; + txtListTemplate.Enabled = true; + txtFileName.Enabled = true; + txtXslScript.Enabled = true; + } + } + + void ShowXslEditor() + { + txtFileName.BackColor = Color.White; + txtFileName.Enabled = true; + cmdSaveFile.Enabled = true; + dshHtml.IsExpanded = false; + dshXslt.IsExpanded = true; + dshSave.IsExpanded = true; + dshDetailView.IsExpanded = false; + dshOptions.IsExpanded = false; + dshListView.IsExpanded = false; + } + + + void SetupClientScripts() + { + cmdRebuildContent.Attributes.Add("onclick", + string.Format("return confirm(\'{0}\')", + Localization.GetString("confirmOnRebuild.Text", + LocalResourceFile))); + addColumnToListTemplate.Attributes.Add("onclick", + string.Format( + "AddCurrentItemIntoTextBox(event, \'{0}\', \'{1}\', \'{2}\', \'False\')", + txtListTemplate.ClientID, ddlColumnsForListView.ClientID, + txtXslScript.ClientID)); + addColumnWithTagsToListTemplate.Attributes.Add("onclick", + string.Format( + "AddCurrentItemIntoTextBox(event, \'{0}\', \'{1}\', \'{2}\', \'True\')", + txtListTemplate.ClientID, ddlColumnsForListView.ClientID, + txtXslScript.ClientID)); + addColumnToDetailTemplate.Attributes.Add("onclick", + string.Format( + "AddCurrentItemIntoTextBox(event, \'{0}\', \'{1}\', \'{2}\', \'False\')", + txtDetailTemplate.ClientID, ddlColumnsForDetailView.ClientID, + txtXslScript.ClientID)); + addColumnToTrackingEmail.Attributes.Add("onclick", + string.Format( + "AddCurrentItemIntoTextBox(event, \'{0}\', \'{1}\', \'{2}\', \'False\')", + txtTrackingEmailTemplate.ClientID, + ddlColumnsForTrackingEmail.ClientID, txtXslScript.ClientID)); + addHeader.Attributes.Add("onclick", + string.Format( + "AddCurrentItemIntoTextBox(event, \'{0}\', \'{1}\', \'{2}\', \'False\')", + txtHeaderTemplate.ClientID, ddlHeaders.ClientID, txtXslScript.ClientID)); + var url = ResolveUrl("HelpPopup.aspx?resourcekey=Help_HiddenColumns"); + hlpColumns.NavigateUrl = string.Format("javascript:OpenHelpWindow(\'{0}\');", url); + } + + string TokenTemplateSettingsAsXml() + { + using (var strXml = new StringWriter()) + { + using (var writer = new XmlTextWriter(strXml)) + { + writer.WriteStartElement("udt:template"); + writer.WriteAttributeString("listType", ddlListTemplateType.SelectedValue); + writer.WriteAttributeString("delimiter", txtListTemplateDelimiter.Text); + writer.WriteAttributeString("listView", txtListTemplate.Text); + writer.WriteAttributeString("headerView", txtHeaderTemplate.Text); + writer.WriteAttributeString("detailView", txtDetailTemplate.Text); + writer.WriteAttributeString("trackingEmail", txtTrackingEmailTemplate.Text); + if (chkEnablePaging.Checked) + { + writer.WriteAttributeString("paging", "true"); + } + if (chkEnableSearch.Checked) + { + writer.WriteAttributeString("searching", "true"); + } + if (chkEnableSorting.Checked) + { + writer.WriteAttributeString("sorting", "true"); + } + if (chkShowDetailView.Checked) + { + writer.WriteAttributeString("showDetailView", "true"); + } + if (IsTrackingEmailMode) + { + writer.WriteAttributeString("isTrackingMode", "true"); + } + writer.WriteEndElement(); + } + + return strXml.ToString(); + } + } + + + void EditExistingScriptAndTemplates(IFileInfo file) + { + ViewState[Definition.XSLFolderName] = file.Folder; + txtFolderName.Text = file.Folder; + txtFileName.Text = file.FileName; + txtFileName.MaxLength = + Convert.ToInt32(200 - + (ModuleContext.PortalSettings.HomeDirectoryMapPath + "/" + file.Folder).Length); + string fileContent; + using (var stream = FileManager.Instance.GetFileContent(file)) + { + using (var x = new StreamReader(stream)) + { + fileContent = x.ReadToEnd(); + } + } + + fileContent = fileContent.Replace(XslTemplatingUtilities.HardSpace, + XslTemplatingUtilities.SpacePlaceholder); + var doc = new XmlDocument(); + doc.LoadXml(fileContent); + var nameSpaceManager = new XmlNamespaceManager(doc.NameTable); + nameSpaceManager.AddNamespace("udt", "DotNetNuke/UserDefinedTable"); + nameSpaceManager.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform"); + var scriptRoot = doc.SelectSingleNode("/xsl:stylesheet", nameSpaceManager); + var templateDefinition = + // ReSharper disable PossibleNullReferenceException + (XmlElement) (scriptRoot.SelectSingleNode("udt:template", nameSpaceManager)); + + if (templateDefinition != null) + { + if (templateDefinition.HasAttribute("headerView")) + { + txtHeaderTemplate.Text = + (HttpUtility.HtmlDecode(templateDefinition.Attributes["headerView"].Value).Replace( + XslTemplatingUtilities.SpacePlaceholder, XslTemplatingUtilities.HardSpace)); + } + + if (templateDefinition.HasAttribute("listView")) + { + txtListTemplate.Text = + (HttpUtility.HtmlDecode(templateDefinition.Attributes["listView"].Value).Replace( + XslTemplatingUtilities.SpacePlaceholder, XslTemplatingUtilities.HardSpace)); + } + if (templateDefinition.HasAttribute("detailView")) + { + txtDetailTemplate.Text = + (HttpUtility.HtmlDecode(templateDefinition.Attributes["detailView"].Value).Replace( + XslTemplatingUtilities.SpacePlaceholder, XslTemplatingUtilities.HardSpace)); + } + chkEnablePaging.Checked = templateDefinition.HasAttribute("paging"); + chkEnableSorting.Checked = templateDefinition.HasAttribute("sorting"); + chkEnableSearch.Checked = templateDefinition.HasAttribute("searching"); + chkShowDetailView.Checked = templateDefinition.HasAttribute("showDetailView"); + if (templateDefinition.HasAttribute("isTrackingMode")) + { + IsTrackingEmailMode = true; + txtTrackingEmailTemplate.Text = + (HttpUtility.HtmlDecode(templateDefinition.Attributes["trackingEmail"].Value).Replace( + XslTemplatingUtilities.SpacePlaceholder, XslTemplatingUtilities.HardSpace)); + } + + if (templateDefinition.HasAttribute("listType")) + { + ddlListTemplateType.SelectedValue = templateDefinition.Attributes["listType"].Value; + setupDelimiter(); + } + if (templateDefinition.HasAttribute("delimiter")) + { + txtListTemplateDelimiter.Text = + HttpUtility.HtmlDecode(templateDefinition.Attributes["delimiter"].Value); + } + scriptRoot.RemoveChild(templateDefinition); + } + txtXslScript.Text = + (XslTemplatingUtilities.PrettyPrint(doc).Replace(XslTemplatingUtilities.SpacePlaceholder, + XslTemplatingUtilities.HardSpace)); + ShowXslEditor(); + // ReSharper restore PossibleNullReferenceException + } + + #endregion + + #region Event Handlers + protected override void OnInit(EventArgs e) + { + Load += Page_Load; + cmdRebuildContent.Click += cmdRebuildContent_Click; + cmdGenerateXslt.Click += cmdGenerateXslt_Click; + cmdBack.Click += cmdBack_Click; + cmdSaveFile.Click += cmdSaveFile_Click; + cmdConfirmOverwriteFile.Click += cmdConfirmOverwriteFile_Click; + cmdDenyOverwriteFile.Click += cmdDenyOverwriteFile_Click; + chkShowDetailView.CheckedChanged += chkShowDetailView_CheckedChanged; + cmdRebuildDetail.Click += cmdRebuildDetail_Click; + cmdRebuildContent.Click += cmdRebuildContent_Click; + cmdRebuildTrackingEmail.Click += cmdRebuildTrackingEmail_Click; + //hlpColumns. + + ddlListTemplateType.SelectedIndexChanged += ddlListType_SelectedIndexChanged; + } + void Page_Load(object sender, EventArgs e) + { + _schemaDataSet = UdtController.GetSchemaDataset(); + SetupClientScripts(); + + if (! IsPostBack) + { + if (Request.QueryString["fileid"].AsString().Length > 0 || + Request.QueryString["Edit"].AsString().ToLowerInvariant() == "current") + { + IFileInfo file=null; + if (Request.QueryString["Edit"].AsString().ToLowerInvariant() == "current") + { + var script = ModuleContext.Settings[SettingName.XslUserDefinedStyleSheet].ToString(); + if (!string.IsNullOrEmpty( script)) + file = FileManager.Instance.GetFile(ModuleContext.PortalId,script); + ReturnUrl = Globals.NavigateURL(); + } + else + { + var fileId = int.Parse(Request.QueryString["fileid"]); + file = FileManager.Instance.GetFile(fileId); + ReturnUrl = ModuleContext.EditUrl("Manage"); + } + if (file != null + && file.Extension.ToLowerInvariant().StartsWith("xsl") + && Utilities.HasWritePermission(file.Folder, ModuleContext.PortalId)) + { + EditExistingScriptAndTemplates(file); + } + else + InitializeNewScript(); + } + else + { + InitializeNewScript(); + } + ListTemplateSetHeaderAndFooter(); + TemplatesPopulateColumnDropDownLists(); + TemplatesSetVisibility( ! IsTrackingEmailMode); + } + } + + void InitializeNewScript() + { + ViewState[Definition.XSLFolderName] = Definition.XSLFolderName; + if (IsTrackingEmailMode) + { + txtTrackingEmailTemplate.Text = string.Concat("", "\r\n", + XslTemplatingUtilities.GenerateDetailViewTokenText + (UdtController.GetSchemaDataset().Tables[ + DataSetTableName.Fields], + includeEditLink: false)); + } + else + { + txtListTemplate.Text = BuildContent(GetBasicElements()); + txtListTemplateDelimiter.Enabled = false; + txtListTemplateDelimiter.BackColor = Color.LightGray; + txtDetailTemplate.Text = + XslTemplatingUtilities.GenerateDetailViewTokenText( + _schemaDataSet.Tables[DataSetTableName.Fields]); + } + txtFolderName.Text = Definition.XSLFolderName; + txtFileName.MaxLength = + Convert.ToInt32(200 - + (ModuleContext.PortalSettings.HomeDirectoryMapPath + "/" + + Definition.XSLFolderName + "/").Length); + } + + void cmdRebuildContent_Click(object sender, EventArgs e) + { + ddlListTemplateType.Enabled = true; + lblTemplateError.Visible = false; + lblXslScriptError.Visible = false; + lblSaveXslError.Visible = false; + + txtListTemplate.Text = BuildContent(GetBasicElements()); + if (chkShowDetailView.Checked && txtListTemplate.Text.IndexOf("UDT:DetailView") < 0) + { + txtListTemplate.Text = txtListTemplate.Text.Replace("UDT:EditLink", "UDT:DetailView"); + } + txtXslScript.Text = ""; + txtFileName.BackColor = Color.LightGray; + txtFileName.Enabled = false; + cmdSaveFile.Enabled = false; + } + + void cmdGenerateXslt_Click(object sender, EventArgs e) + { + lblTemplateError.Visible = false; + lblXslScriptError.Visible = false; + lblSaveXslError.Visible = false; + + var listTemplate = txtListTemplate.Text; + var detailTemplate = txtDetailTemplate.Text; + var headerTemplate = txtHeaderTemplate.Text; + if (IsTrackingEmailMode) + { + if (isValid(txtTrackingEmailTemplate.Text, ErrorOutput.XslTranformation, addRoot: true)) + { + txtXslScript.Text = + XslTemplatingUtilities.TransformTokenTextToXslScript(UdtController.GetSchemaDataset(), + txtTrackingEmailTemplate.Text); + txtXslScript.Enabled = true; + ShowXslEditor(); + } + } + else + { + if (isValid(listTemplate, ErrorOutput.XslTranformation, addRoot: true) && + (! chkShowDetailView.Checked || isValid(detailTemplate, ErrorOutput.XslTranformation, addRoot: true))) + { + txtXslScript.Text = XslTemplatingUtilities.TransformTokenTextToXslScript(_schemaDataSet, listTemplate, + detailTemplate, + headerTemplate, + chkEnablePaging.Checked, + chkEnableSorting.Checked, + chkEnableSearch.Checked, + chkShowDetailView.Checked, + CurrentListType); + txtXslScript.Enabled = true; + ShowXslEditor(); + } + } + } + + void cmdBack_Click(object sender, EventArgs e) + { + Response.Redirect(ReturnUrl, true); + } + + void ddlListType_SelectedIndexChanged(object sender, EventArgs e) + { + lblTemplateError.Visible = false; + lblXslScriptError.Visible = false; + lblSaveXslError.Visible = false; + //content must always be valid XML + if (isValid(txtListTemplate.Text, ErrorOutput.TokenTemplate, true)) + { + var elements = GetCurrentElements(); + if (elements != null) + { + txtListTemplate.Text = BuildContent(GetCurrentElements()); + setupDelimiter(); + } + else + { + ddlListTemplateType.SelectedValue = CurrentListType; + lblTemplateError.Text = Localization.GetString("noTransformButValid", LocalResourceFile); + lblTemplateError.Visible = true; + } + } + else + { + ddlListTemplateType.SelectedValue = CurrentListType; + } + ListTemplateSetHeaderAndFooter(); + txtXslScript.Text = ""; + txtFileName.BackColor = Color.LightGray; + txtFileName.Enabled = false; + cmdSaveFile.Enabled = false; + } + + string GetFileName() + { + var fileName = txtFileName.Text.Trim(); + fileName = Globals.CleanFileName(fileName); + if (! fileName.ToLowerInvariant().EndsWith(".xsl")) + { + fileName += ".xsl"; + } + txtFileName.Text = fileName; + return fileName; + } + + string GetFileContent() + { + var fileContent = txtXslScript.Text; + fileContent = fileContent.Replace("", + (TokenTemplateSettingsAsXml() + "\r\n" + "")); + return fileContent; + } + + + IFolderInfo GetFolder() + { + return Utilities.GetFolder(ModuleContext.PortalSettings, + ViewState[Definition.XSLFolderName].AsString(), Definition.XSLFolderName); + } + + + static bool SaveScript(string fileContent, string fileName, IFolderInfo folder, bool forceOverWrite) + { + return Utilities.SaveScript( fileContent, fileName, folder, forceOverWrite); + } + + void cmdSaveFile_Click(object sender, EventArgs e) + { + if (isValid(txtXslScript.Text, ErrorOutput.Save, false)) //XSLTstylesheet must be at least valid XML! + { + //get content + var fileContent = GetFileContent(); + var fileName = GetFileName(); + + if (fileName.Length > 4) + { + var folder = GetFolder(); + + if (SaveScript(fileContent, fileName, folder, forceOverWrite: false)) + { + //update setting: + UpdateSettings(folder.FolderPath + fileName); + Response.Redirect(ReturnUrl, true); + } + else + { + LockControls(true); + panConfirm.Visible = true; + } + } + } + } + + void cmdConfirmOverwriteFile_Click(object sender, EventArgs e) + { + var fileContent = GetFileContent(); + var fileName = GetFileName(); + var folder = GetFolder(); + SaveScript(fileContent, fileName, folder, forceOverWrite: true); + UpdateSettings(folder.FolderPath + fileName); + Response.Redirect(ReturnUrl, true); + } + + void UpdateSettings(string fileWithPath) + { + var moduleController = new ModuleController(); + if (IsTrackingEmailMode) + { + moduleController.UpdateTabModuleSetting(ModuleContext.TabModuleId, SettingName.TrackingScript, fileWithPath); + } + else + { + moduleController.UpdateTabModuleSetting(ModuleContext.TabModuleId, SettingName.RenderingMethod, + RenderingMethod.UserdefinedXSL); + moduleController.UpdateTabModuleSetting(ModuleContext.TabModuleId, SettingName.XslUserDefinedStyleSheet, + fileWithPath); + } + } + + void cmdDenyOverwriteFile_Click(object sender, EventArgs e) + { + txtFileName.Text = ""; + LockControls(false); + panConfirm.Visible = false; + } + + //void cmdColumnsHelp_Click(object sender, EventArgs e) + //{ + // var url = ResolveUrl("HelpPopup.aspx?resourcekey=Help_HiddenColumns"); + + // var columnsHelpPopup = ""; + // Page.ClientScript.RegisterStartupScript(GetType(), "columnsHelpPopup", columnsHelpPopup); + //} + + void chkShowDetailView_CheckedChanged(object sender, EventArgs e) + { + TemplatesSetVisibility(isViewMode: true); + TemplatesPopulateColumnDropDownLists(); + dshDetailView.IsExpanded = chkShowDetailView.Checked; + } + + void cmdRebuildDetail_Click(object sender, EventArgs e) + { + txtDetailTemplate.Text = + XslTemplatingUtilities.GenerateDetailViewTokenText(_schemaDataSet.Tables[DataSetTableName.Fields]); + } + + protected void cmdRebuildTrackingEmail_Click(object sender, EventArgs e) + { + txtTrackingEmailTemplate.Text = string.Concat("", + "\r\n", + XslTemplatingUtilities.GenerateDetailViewTokenText( + UdtController.GetSchemaDataset().Tables[ + DataSetTableName.Fields], includeEditLink: false)); + } + + #endregion + } +} \ No newline at end of file diff --git a/Token2Xsl.ascx.designer.cs b/Token2Xsl.ascx.designer.cs new file mode 100644 index 0000000..d311da0 --- /dev/null +++ b/Token2Xsl.ascx.designer.cs @@ -0,0 +1,600 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Modules.UserDefinedTable { + + + public partial class Token2Xsl { + + /// + /// hlpColumns control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink hlpColumns; + + /// + /// dshHtml control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.SectionHeadControl dshHtml; + + /// + /// tblHtml control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl tblHtml; + + /// + /// dshListView control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.SectionHeadControl dshListView; + + /// + /// dvListview control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl dvListview; + + /// + /// plListType control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plListType; + + /// + /// ddlListTemplateType control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList ddlListTemplateType; + + /// + /// cmdRebuildContent control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdRebuildContent; + + /// + /// plDelimiter control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plDelimiter; + + /// + /// txtListTemplateDelimiter control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtListTemplateDelimiter; + + /// + /// lblTemplateError control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblTemplateError; + + /// + /// lblListTemplateHead control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblListTemplateHead; + + /// + /// plHeaderList control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plHeaderList; + + /// + /// ddlHeaders control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList ddlHeaders; + + /// + /// addHeader control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink addHeader; + + /// + /// txtHeaderTemplate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtHeaderTemplate; + + /// + /// plColumns control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plColumns; + + /// + /// ddlColumnsForListView control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList ddlColumnsForListView; + + /// + /// addColumnToListTemplate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink addColumnToListTemplate; + + /// + /// addColumnWithTagsToListTemplate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink addColumnWithTagsToListTemplate; + + /// + /// txtListTemplate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtListTemplate; + + /// + /// lblListTemplateFooter control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblListTemplateFooter; + + /// + /// dshDetailView control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.SectionHeadControl dshDetailView; + + /// + /// dvDetailView control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl dvDetailView; + + /// + /// plColumns2 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plColumns2; + + /// + /// ddlColumnsForDetailView control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList ddlColumnsForDetailView; + + /// + /// addColumnToDetailTemplate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink addColumnToDetailTemplate; + + /// + /// cmdRebuildDetail control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdRebuildDetail; + + /// + /// txtDetailTemplate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtDetailTemplate; + + /// + /// dshTrackingEmail control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.SectionHeadControl dshTrackingEmail; + + /// + /// dvTrackingEmail control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl dvTrackingEmail; + + /// + /// plColumns3 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plColumns3; + + /// + /// ddlColumnsForTrackingEmail control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList ddlColumnsForTrackingEmail; + + /// + /// addColumnToTrackingEmail control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.HyperLink addColumnToTrackingEmail; + + /// + /// cmdRebuildTrackingEmail control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdRebuildTrackingEmail; + + /// + /// txtTrackingEmailTemplate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtTrackingEmailTemplate; + + /// + /// dshOptions control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.SectionHeadControl dshOptions; + + /// + /// dvOptions control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl dvOptions; + + /// + /// lblEnableSorting control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl lblEnableSorting; + + /// + /// chkEnableSorting control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkEnableSorting; + + /// + /// lblEnablePaging control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl lblEnablePaging; + + /// + /// chkEnablePaging control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkEnablePaging; + + /// + /// lblEnableSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl lblEnableSearch; + + /// + /// chkEnableSearch control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkEnableSearch; + + /// + /// lblSearchIsObsolete control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblSearchIsObsolete; + + /// + /// lblShowDetailView control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl lblShowDetailView; + + /// + /// chkShowDetailView control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkShowDetailView; + + /// + /// lblXslScriptError control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblXslScriptError; + + /// + /// cmdGenerateXslt control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Button cmdGenerateXslt; + + /// + /// dshXslt control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.SectionHeadControl dshXslt; + + /// + /// tblXslt control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlGenericControl tblXslt; + + /// + /// txtXslScript control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtXslScript; + + /// + /// dshSave control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.SectionHeadControl dshSave; + + /// + /// tblSave control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlTable tblSave; + + /// + /// lblSaveXslError control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblSaveXslError; + + /// + /// plFolderName control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plFolderName; + + /// + /// txtFolderName control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtFolderName; + + /// + /// plFileName control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::DotNetNuke.UI.UserControls.LabelControl plFileName; + + /// + /// txtFileName control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtFileName; + + /// + /// cmdSaveFile control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdSaveFile; + + /// + /// panConfirm control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Panel panConfirm; + + /// + /// lblConfirm control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblConfirm; + + /// + /// cmdConfirmOverwriteFile control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdConfirmOverwriteFile; + + /// + /// cmdDenyOverwriteFile control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdDenyOverwriteFile; + + /// + /// cmdBack control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton cmdBack; + } +} diff --git a/UserDefinedTable.sln b/UserDefinedTable.sln new file mode 100644 index 0000000..7f07af3 --- /dev/null +++ b/UserDefinedTable.sln @@ -0,0 +1,26 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FormAndList", "FormAndList.csproj", "{DDE04CE2-57E6-4B1C-BF12-C36FCC7B7333}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FormAndList.Tests", "Tests\FormAndList.Tests.csproj", "{769BDA20-06BB-4640-A27A-EE1257E161B6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DDE04CE2-57E6-4B1C-BF12-C36FCC7B7333}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DDE04CE2-57E6-4B1C-BF12-C36FCC7B7333}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DDE04CE2-57E6-4B1C-BF12-C36FCC7B7333}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DDE04CE2-57E6-4B1C-BF12-C36FCC7B7333}.Release|Any CPU.Build.0 = Release|Any CPU + {769BDA20-06BB-4640-A27A-EE1257E161B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {769BDA20-06BB-4640-A27A-EE1257E161B6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {769BDA20-06BB-4640-A27A-EE1257E161B6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {769BDA20-06BB-4640-A27A-EE1257E161B6}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/UserDefinedTable.vs2013.sln b/UserDefinedTable.vs2013.sln new file mode 100644 index 0000000..0117526 --- /dev/null +++ b/UserDefinedTable.vs2013.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.21005.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FormAndList", "FormAndList.csproj", "{DDE04CE2-57E6-4B1C-BF12-C36FCC7B7333}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DDE04CE2-57E6-4B1C-BF12-C36FCC7B7333}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DDE04CE2-57E6-4B1C-BF12-C36FCC7B7333}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DDE04CE2-57E6-4B1C-BF12-C36FCC7B7333}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DDE04CE2-57E6-4B1C-BF12-C36FCC7B7333}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/configuration.ascx b/configuration.ascx new file mode 100644 index 0000000..6892450 --- /dev/null +++ b/configuration.ascx @@ -0,0 +1,256 @@ +<%@ Control Language="C#" Explicit="True" Inherits="DotNetNuke.Modules.UserDefinedTable.Configuration" + TargetSchema="http://schemas.microsoft.com/intellisense/ie5" CodeBehind="Configuration.ascx.cs" AutoEventWireup="false"%> +<%@ Register TagPrefix="Portal" TagName="URL" Src="~/controls/URLControl.ascx" %> +<%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %> +<%@ Register TagPrefix="dnn" TagName="TextEditor" Src="~/controls/TextEditor.ascx" %> +<%@ Register TagPrefix="dnn" Assembly="DotNetNuke" Namespace="DotNetNuke.UI.WebControls" %> +<%@ Register src="Controls/Fields.ascx" tagname="Fields" tagprefix="fnl" %> + +
    +
      +
    • +
    • +
    +
    +

    +
    +
    +
    + +
    + + +
    +
    +
    + +
    +
    +

    +
    +
    +
    + + + + + + + + + +
    +
    + +
    +
    +
    + +
    + + +
    + +
    +
    + +

    +
    +
    +
    + + + + + + +
    +
    + +
    + +
    +
    +
    + +
    +
    +
    +
    + +
    +
    + + +

    +
    +
    + + + + + +
    +
    + +
    + +
    + + +
    +
    +
    + + +
    + + +
    +
    + + + + + +
    +
    + + + + 1 + 5 + 10 + 15 + 20 + 25 + 30 + 40 + 50 + +
    + + +
    + + +
    + +   + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + + +
    +
    + +

    +
    +
    + + + + + + + +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + + + + +
    +
    + + +
    + +    + +
    +
    + +
    + +
    + + +
      +
    • +
    • +
    + +
    + + diff --git a/datatypes.config b/datatypes.config new file mode 100644 index 0000000..c3b082c --- /dev/null +++ b/datatypes.config @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/default.ascx b/default.ascx new file mode 100644 index 0000000..72af8c1 --- /dev/null +++ b/default.ascx @@ -0,0 +1,2 @@ +<%@ Control Language="C#" Inherits="DotNetNuke.Modules.UserDefinedTable.Default" Codebehind="Default.ascx.cs" AutoEventWireup="false" %> +
    diff --git a/form.ascx b/form.ascx new file mode 100644 index 0000000..f7f80ae --- /dev/null +++ b/form.ascx @@ -0,0 +1,44 @@ +<%@ Control Language="C#" Inherits="DotNetNuke.Modules.UserDefinedTable.EditForm" CodeBehind="Form.ascx.cs" AutoEventWireup="false" %> +
    + +
    +
      +
    • + +
    • +
    • + +
    • +
    • + +
    • +
    • + +
    • +
    +
    +
    + \ No newline at end of file diff --git a/helppopup.aspx b/helppopup.aspx new file mode 100644 index 0000000..4a16f34 --- /dev/null +++ b/helppopup.aspx @@ -0,0 +1,18 @@ +<%@ Page Language="C#" Inherits="DotNetNuke.Modules.UserDefinedTable.HelpPopup" Codebehind="HelpPopup.aspx.cs" %> + + + + + + + + + + + +
    + + + + + diff --git a/icon_fnl_32px.gif b/icon_fnl_32px.gif new file mode 100644 index 0000000000000000000000000000000000000000..1b644665e4b68d1e4cf115af64b95a20532435e3 GIT binary patch literal 2422 zcmV-+35oVcNk%w1VK4wN0QUd@0001PZf$gQbZ~TddwhI+eu063f`f*Lg^7)ejEszq zk&Tj*m6DH=larB_n3b5Cnw*`Tp`xFrt(&W~o2|O0pq!|po}#0qqo}W`si~^1tE{Z6 zuCA@7tFfl7vZk)KuduGAw7smdwW_hWv9qtVw6wLixw^W#qO`%LxyPrw$f~))s=LRl zzRRh-%(K78w!Ou$y~w@2z>CW0jLYba%;}8J?2ggxn%D50*zv5u&8@=FuEf!@z{;_~ z&a%YMy1>S{#?HRP$-KqQy~xk8!qBkA)3C~>i&eg!p*ul=-%Fois z&)CJ#*1^!(!qeWy(AmY)+{)3`&Ct=!($&b(*~!$}%GBJ>)7;I}+0546%h=z}*xuIH z&ezz_+1k(1(b3Y=)X~(`)Ya9|*4fb4+}GLA)!En5*xc3F+11(I*4*FQ+tS(D+1uOP z+1%RN+}+&U+uYsR-QC^8+UdaD>B8OY#N6q{-t5ZP;K|tH&f4S7+~dyO<;dRb(Awe9 z+vU;R<<;8Y*4^RN-R0EZ=-J)i+27^e-{Z#N@66-x&E)Xa;O5fc>DA!q*W>Nilbz>EP$?<>%<;=-}b#?dIs|+Is~?cwe0<>~3^>h9?4?d|RD?cwS0hR_4@#XFH=G}BQ`S|Jj`R)As?f?Dh z|NZUp@$vHV^z!uc^7Qod^Yirc^z`)e^z`)j`1k+*@&Eqx`T6<#`~3U-`~3U+{QUd; z{QLj_00000A^8LW00930EC2ui05AYB000R80RIUbNU)&6g9sBU?AH&U!-o(fN`y$S zqCM(_v7j zA+tso7Kp^_KIuFjIN%Ux^t1zLtMNRYt?Ccv=D3^XtT%P?}N zli+&mv7?JIYgiJYZ3gudj3#;vQAHPLP*DXNt0ck*DNpTzPCDtJL(Y-mgab}9OzN@> zHfxN6hBPo1)Xy=Q95z}ji?s#UG^o^a%PqL%qDwB=VAIW-Y`XKtDs@oF)iYU=whEVy zp=Qi9Qqh$rHhK6VsGx;l0}mjt#91Xl{YaCEovk=FB2-YNLY#5P6{Acu;Dl4oIpyr) z4l1wMAtyqOKC0L%tcaIMER8h(V#+ke1XA94=%J{NsKC5($20hFCCw(MbfHHYXQ+|J z6|mTl!y?rfLx+J1R%_2L^Bg10ufd`!4JLkIh`|OQoB#wYG|(`~T!EOlpn)jb!_F@6 zNb}3D`Eb?FCYxMgg&J;fu>~c@OfpFuD5KnsH}tpzk393ZLr*)t;1Nu>2X!@wmvQka8OhnG$tIid1agQV zMhilVH17aoGtLLK<40RP|4g!))(BG^BDCP5%%JrcVbily~CkSCp4K;icxw{MA6Ysq6aFcmGfB&gWpLAV~O*TWXxy&x$hrdfj6}{um${0&eJ)`hg z5wf4#cfTe)@XXu}JnghokvsF~kG?zJz=I$*m$P|TVHofeTKDJ&kC@2}WB8-TJm7&o zczB~5eyC3Ex?+V?T&)}2TVMm@F*EbMV`e0zpf~P!!EO|y4(rp10Z);p5O$9q5u~3y z?T5D=gM22j8P9KZkpKp+@x7(xt^@C8mtvwPXFr7;*2hhXp{ zlzkv$2?#L%00bc500a;~01{9LG;-q_+Mwmo;%N<9F=iBTn8g=0!b>;6!yP9ufB*g(Mt7h9|heh_`tL6=Gn?SjjlW-$mvAfgk# o@Wn5J!Cmeiqr2ekE-}J;3_{X_fH`Z(MD{U}_PSRqRSF0IJInl0`v3p{ literal 0 HcmV?d00001 diff --git a/list.ascx b/list.ascx new file mode 100644 index 0000000..c6b896f --- /dev/null +++ b/list.ascx @@ -0,0 +1,39 @@ +<%@ Control Language="C#" Inherits="DotNetNuke.Modules.UserDefinedTable.List" AutoEventWireup="false" CodeBehind="List.ascx.cs" %> +<%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %> +<%@ Import Namespace="DotNetNuke.Entities.Icons" %> +<%@ Register TagPrefix="dnn" Assembly="DotNetNuke" Namespace="DotNetNuke.UI.WebControls" %> +
    + +    +    +    + +
    + +
    + + + + + + + + + + + + + + + +
    +
      +
    • + +
    • +
    +
    +
    \ No newline at end of file diff --git a/makethumbnail.ashx b/makethumbnail.ashx new file mode 100644 index 0000000..7eb4fd2 --- /dev/null +++ b/makethumbnail.ashx @@ -0,0 +1 @@ +<%@ WebHandler Language="C#" CodeBehind="MakeThumbnail.ashx.cs" Class="DotNetNuke.Modules.UserDefinedTable.MakeThumbnail" %> diff --git a/module.css b/module.css new file mode 100644 index 0000000..84a71f1 --- /dev/null +++ b/module.css @@ -0,0 +1,71 @@ +/* ================================ + CSS STYLES FOR Module DNN.UserDefinedTable + ================================ +*/ + + + +.UDT_UponSubmit +{ + margin-top :1em; +} +.UDT_Caption +{ + display:block; +} + +.fnlSettingsWarning { + margin: 4% 0 0 32%; + padding: 0; +} + +.dnnFormItem span.CommandButton { + clear: both; + display: block; + margin-left: 32%; + overflow: hidden; +} +.dnnForm .dnnFormItem .dnnFormLabelWithoutHelp label span { + line-height: 1.4; + padding-right: 1.8em; + display: block; + position: relative; +} +.dnnForm .dnnFormItem .dnnFormLabelWithoutHelp +{ + width: 100%; + padding: 0px; + margin: 0px; +} +#dnnFormAndListConfig .Sortable .Draggable +{ + cursor: move; +} + + +.dnnFormAndList .dnnGridHeader th{ + font-size: 100%; + white-space: nowrap; +} + + +.fnlForm +{ +margin: 1em auto 1em; +} +/* +#ssPageSettings .dnnTextEditor +{ + margin-left: 32%; +}*/ + +.pushRight { + margin-left: 32%; +} +.dnnForm input.dnnFormRequired{ + border-left: 5px red solid!important; + padding-right: -5px!important; +} +.dnnFormItem textarea.dnn2rows { + min-height: 1em; +} \ No newline at end of file diff --git a/releasenotes.htm b/releasenotes.htm new file mode 100644 index 0000000..09b99ae --- /dev/null +++ b/releasenotes.htm @@ -0,0 +1,74 @@ +

    + Release Notes +

    +

    DotNetNuke Form and List 06.01.00

    +

    Changes to 6.1.0

    +
      +
    • Fix for DNN 7.2.2.
    • +
    • Allowed for custom datatypes.config (to be placed in Portals/_default/UserDefinedTable). +

      datatypes.config in the DesktopModules/UserDefinedTable will remain to be overwriten on installation of a new version. However, if you copy it to the folder mentioned above, your cusotmizations will not be overwriten on installation anymore.

      +
    • +
    +

    Changes to 6.0.7

    +
      +
    • Corrected an error in datatypes.config.
    • +
    +

    Changes to 6.0.6

    +
      +
    • Add in Sql to remove 'text on row' setting for UserDefinedTable to make SQL Azure compatible.
    • +
    • Add new azureCompatible element to manifest.
    • +
    • Added a fix for importing templates.
    • +
    +

    Changes to 6.0.2

    +
      +
    • Fix: MakeThumbnail was broken if the application pool was configured to .Net 4
    • +
    • Change: Data is now stored in nvarchar(max) instead of ntext
    • +
    +

    Changes to 6.0.1

    +
      +
    • Scripts now compatible with SQL Azure.
    • +
    +

    Changes to 6.0.0

    +
      +
    • Icons are shown in module action buttons (workaraound to core issue eith IconAPI)
    • +
    • Fix to Token2XSL Editor, changing List type raised exception
    • +
    • MakeTumbnail and ShowXml handlers had been missing in install package
    • +
    • Updated help texts for better understanding of filter statement, token support in email subject and css style
    • +
    +

    + Major changes (for 6.0.x):

    +
      +
    • DNN 6 Form Patterns including modal PopUps and Tabs
    • +
    • DST Support for following data types: Time, DateTime, CreatedAt, ChangedAt
    • +
    • New FileManager API for XSLT scripts and following data types: Url, Download, + Image
    • +
    • Usage of Telerik Controls
    • +
    • Some JQuery candy: changing of field order with drag'n'drop, new editor for + multiple field values
    • +
    • New field settings (similiar to module settings)  facilitates more special + settings by type.
    • +
    • Form is now WAI compliant
    • +
    • Multi value option for data type 'Text'
    • +
    • Support of Icon API
    • +
    • Moved module wide data type settings (e.g. thumbnail height/width) directly to + data type
    • +
    • Rendering methods are now reduced to DataGrid and XSLT. The option for predefined XSLT scripts was removed. + The old scripts are no longer delivered with the module. If an existing instance still uses an old script, + the script will be copied into the portal (folder XslStylesheet/UDT Legacy). +
    • +
    • Removed few settings/ features in exchange of a better UI and a lighter code + base.
    • +
    • It is now converted to C#
    • +
    • Important for updates
      + The switch to Form Pattern has an effect on how the form is rendered. CSS tweaks for the old form will certainly fail. + Please test the new UI before upgrading. +
    • +
    +

    + This release is compiled against the .Net 3.5 Framework using VS2010.
    + Minimum DotNetNuke core version is 6.1.0 +

    + + + + \ No newline at end of file diff --git a/settings.ascx b/settings.ascx new file mode 100644 index 0000000..661a2e6 --- /dev/null +++ b/settings.ascx @@ -0,0 +1,35 @@ +<%@ Control Language="C#" Inherits="DotNetNuke.Modules.UserDefinedTable.Settings" AutoEventWireup="false" CodeBehind="Settings.ascx.cs" %> +<%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %> +
    +

    +

    +

    +

    +

    +

    +

    +

    +

    +

    +

    +

    + + + + + +
    + + + +
    +
    + diff --git a/showxml.ashx b/showxml.ashx new file mode 100644 index 0000000..8a95ef6 --- /dev/null +++ b/showxml.ashx @@ -0,0 +1 @@ +<%@ WebHandler Language="C#" CodeBehind="ShowXml.ashx.cs" Class="DotNetNuke.Modules.UserDefinedTable.ShowXml" %> diff --git a/template.ascx b/template.ascx new file mode 100644 index 0000000..1b94a22 --- /dev/null +++ b/template.ascx @@ -0,0 +1,42 @@ +<%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %> +<%@ Control Language="C#" Inherits="DotNetNuke.Modules.UserDefinedTable.Template" + CodeBehind="Template.ascx.cs" AutoEventWireup="false" %> + + + +
    +
    +
    + + +
    +
    + + + +
    +
    + + + +
    +
      +
    • +
    • +
    +
      +
    • +
    • +
    • + +
    • +
    • + +
    • +
    +
    + diff --git a/templatelist.ascx b/templatelist.ascx new file mode 100644 index 0000000..b77bd71 --- /dev/null +++ b/templatelist.ascx @@ -0,0 +1,42 @@ +<%@ Control Language="C#" Inherits="DotNetNuke.Modules.UserDefinedTable.TemplateList" + CodeBehind="TemplateList.ascx.cs" AutoEventWireup="false" %> +<%@ Register TagPrefix="dnn" Assembly="DotNetNuke" Namespace="DotNetNuke.UI.WebControls" %> +
    + Start with a new   + + Configuration + +  or choose a template: +
    + + + + + + + + + + + + + + + + + +
    + + + + +
    \ No newline at end of file diff --git a/token2xsl.ascx b/token2xsl.ascx new file mode 100644 index 0000000..b45ca5e --- /dev/null +++ b/token2xsl.ascx @@ -0,0 +1,294 @@ +<%@ Register TagPrefix="dnn" TagName="SectionHead" Src="~/controls/SectionHeadControl.ascx" %> +<%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %> +<%@ Control Language="C#" Inherits="DotNetNuke.Modules.UserDefinedTable.Token2Xsl" + TargetSchema="http://schemas.microsoft.com/intellisense/ie5" Codebehind="Token2Xsl.ascx.cs" AutoEventWireup="false" %> + + + +
    +
    + +
    +
    + +
    + +
    + + + + + + + + + + + +
    + + + + + + + + + + + + +
    + + + ; +
    +
    + + + + + + + +
    + + + + + +
    + + + + + + + + +
    + + + + + + + +
    + + +
    + +
    + + + + + + + +
    + + + + + + + +
    + +
    + +
    + + + + + + + +
    + + + + + + + +
    + +
    + +
    + + + + + + + + + + + + + + + + + +
    + + + +
    + + + +
    + + + +
    + + + +
    +
    +

    + + +

    +
    + +
    + +
    + + + + + + + + + + + + + + + + +
    + +
    + + + + +
    + + + +    + +
    + +    +    + + +
    +
    + +
    + diff --git a/xslstylesheets/tracking/auto.xsl b/xslstylesheets/tracking/auto.xsl new file mode 100644 index 0000000..ef5a176 --- /dev/null +++ b/xslstylesheets/tracking/auto.xsl @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + +

    + +

    +
    + + + + + + + + number + text + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + edit + + /images/edit.gif + + + + +
    + : + + +
    + + + + +
    +
    + + diff --git a/xslstylesheets/xslscripts.xml b/xslstylesheets/xslscripts.xml new file mode 100644 index 0000000..e1b782d --- /dev/null +++ b/xslstylesheets/xslscripts.xml @@ -0,0 +1,345 @@ + + + + <?xml version="1.0" encoding="UTF-8"?> +<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:udt="DotNetNuke/UserDefinedTable" exclude-result-prefixes ="udt"> + <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/> + <!-- + This prefix is used to generate module specific query strings + Each querystring or form value that starts with udt_{ModuleId}_param + will be added as parameter starting with param + --> + <xsl:variable name="prefix_param">udt_<xsl:value-of select="//udt:Context/udt:ModuleId"/>_param</xsl:variable> +{SEARCHING0} +{PAGING0} +{SORTING0} +{DETAIL0} + <xsl:template match="udt:Data" mode="list"> + {PAGING5} + [LISTVIEW] + {PAGING6} + </xsl:template> + <xsl:template match="/udt:UserDefinedTable"> +{DETAIL1} +{SEARCHING1} +<xsl:variable name="currentData" select="udt:Data{SEARCHING2}" /> +{PAGING1} +<xsl:if test="$currentData"> + [OPENTAG] + {SORTING1} + [HEADERVIEW] + <xsl:apply-templates select="$currentData" mode="list"> + {SORTING2} + {PAGING2} + </xsl:apply-templates> + [/OPENTAG] +</xsl:if> +{PAGING3} +{DETAIL2} + </xsl:template> +{SEARCHING3} +{SORTING3} +{PAGING4} + <xsl:template name="EditLink"> + <xsl:if test="udt:EditLink"> + <a href="{udt:EditLink}"><img border="0" alt="edit" src="{//udt:Context/udt:ApplicationPath}/images/edit.gif" /></a> + </xsl:if> + </xsl:template> +{DETAIL3} +</xsl:stylesheet> + + + <xsl:param name="param_detail" /> + <xsl:template match="udt:Data" mode="detail"> + [DETAILVIEW] + </xsl:template> + + + <xsl:choose> + <xsl:when test="$param_detail"> + <!--master-detail view--> + <xsl:apply-templates select="udt:Data[udt:UserDefinedRowId=$param_detail]" mode="detail" /> + </xsl:when> + <xsl:otherwise> + + + </xsl:otherwise> +</xsl:choose> + + + <xsl:template name="ListView"> +<a href="{//udt:Context/udt:ApplicationPath}/tabid/{//udt:Context/udt:TabId}/Default.aspx"><img border="0" alt="Back" src="{//udt:Context/udt:ApplicationPath}/images/lt.gif" /></a> +</xsl:template> + +<xsl:template name="DetailView"> +<a href="?{$prefix_param}_detail={udt:UserDefinedRowId}"><img border="0" alt="detail" src="{//udt:Context/udt:ApplicationPath}/images/view.gif" /></a> +</xsl:template> + + + +<xsl:param name="param_orderby" select="//udt:Fields[udt:UserDefinedFieldId=//udt:Context/udt:OrderBy]/udt:SortColumn"/> +<xsl:param name="param_direction" select="//udt:Context/udt:OrderDirection"/> +<!--wrong string would break stylesheet, so fallback to ascending if userinput is wrong--> +<xsl:variable name="orderDirection"> + <xsl:choose> + <xsl:when test="$param_direction='descending'"> + <xsl:text>descending</xsl:text> + </xsl:when> + <xsl:otherwise> + <xsl:text>ascending</xsl:text> + </xsl:otherwise> + </xsl:choose> +</xsl:variable> +<xsl:variable name="orderType"> +<xsl:variable name="DataType" select="//udt:Fields[udt:SortColumn=$param_orderby]/udt:FieldType" /> + <xsl:choose> + <xsl:when test="$DataType='Int32' or $DataType='Decimal' or $DataType='Currency'">number</xsl:when> + <xsl:otherwise>text</xsl:otherwise> + </xsl:choose> +</xsl:variable> + + + + <!-- DEFINE ANY HEADERS HERE, EXAMPLE IS FOR TABLE TYPE LISTING --> + <!-- Parameter header is optional! --> + <!-- + <tr class="dnnGridHeader"> + <td/> + <td> + <xsl:apply-templates select ="udt:Fields[udt:FieldTitle='NameOfColumn']"> + <xsl:with-param name ="header" select ="NewHeaderName"/> + </xsl:apply-templates> + </td>... + </tr> + --> + + + <xsl:sort select="*[name()=$param_orderby]" order="{$orderDirection}" data-type="{$orderType}" /> + + + <xsl:template match="udt:Fields" name ="SortingHeader"> + <xsl:param name ="header" select ="udt:FieldTitle"/> + <xsl:if test="udt:Visible='true' or udt:Visible='True'"> + <a> + <xsl:attribute name ="href"> + <xsl:choose > + <xsl:when test="udt:ValueColumn=$param_orderby"> + <xsl:variable name="flippedDirection"> + <xsl:choose> + <xsl:when test="$orderDirection='ascending'"> + <xsl:text>descending</xsl:text> + </xsl:when> + <xsl:otherwise> + <xsl:text>ascending</xsl:text> + </xsl:otherwise> + </xsl:choose> + </xsl:variable> + ?<xsl:value-of select="$prefix_param"/>_orderby=<xsl:value-of select="udt:ValueColumn"/>&amp;amp;<xsl:value-of select="$prefix_param"/>_direction=<xsl:value-of select="$flippedDirection"/>{SEARCHING4} + </xsl:when> + <xsl:otherwise> + ?<xsl:value-of select="$prefix_param"/>_orderby=<xsl:value-of select="udt:ValueColumn"/>&amp;amp;<xsl:value-of select="$prefix_param"/>_direction=<xsl:value-of select="$orderDirection"/>{SEARCHING4} + </xsl:otherwise> + </xsl:choose> + </xsl:attribute> + <!--flipped order direction--> + <xsl:value-of select ="$header"/> + <xsl:if test="udt:ValueColumn=$param_orderby"> + <img src="{//udt:Context/udt:ApplicationPath}/images/sort{$orderDirection}.gif" border="0" /> + </xsl:if> + </a> + </xsl:if> + </xsl:template> + + + <xsl:param name="param_page" select="1" /> +<xsl:variable name="paging" select="//udt:Context/udt:Paging" /> + + + + <xsl:variable name="from"> + <xsl:choose> + <xsl:when test="$paging"> + <xsl:value-of select="$paging * number($param_page) - $paging" /> + </xsl:when> + <xsl:otherwise>0</xsl:otherwise> + </xsl:choose> +</xsl:variable> +<xsl:variable name="to"> + <xsl:choose> + <xsl:when test="$paging"> + <xsl:value-of select="$paging * number($param_page) +1" /> + </xsl:when> + <xsl:otherwise> + <xsl:value-of select="count($currentData)+1" /> + </xsl:otherwise> + </xsl:choose> +</xsl:variable> + + + + <xsl:with-param name ="from" select ="$from"/> +<xsl:with-param name ="to" select ="$to"/> + + + + <xsl:if test="$paging"> +<xsl:call-template name="renderPaging"> +<xsl:with-param name="maxPages" select="ceiling(count($currentData) div $paging)" /> +</xsl:call-template> +</xsl:if> + + + <xsl:template name="pagingSinglePages"> +<!--renders paging links--> + <xsl:param name="pageNumber" select="1" /> + <xsl:param name="maxPages" select="ceiling(count(//udt:Data) div $paging)" /> + <xsl:choose> + <xsl:when test="number($param_page)=$pageNumber"> + <span class="NormalDisabled">[<xsl:value-of select="$pageNumber" />]</span> + </xsl:when> + <xsl:otherwise> + <a href="?{$prefix_param}_page={$pageNumber}{SEARCHING4}" class="CommandButton"><xsl:value-of select="$pageNumber" /></a> + </xsl:otherwise> + </xsl:choose>&#160; + <xsl:if test="$pageNumber &amp;lt; $maxPages"> + <xsl:call-template name="pagingSinglePages"> + <xsl:with-param name="pageNumber" select="$pageNumber +1" /> + <xsl:with-param name="maxPages" select="$maxPages"/> + </xsl:call-template> + </xsl:if> + </xsl:template> + <xsl:template name="renderPaging"> + <xsl:param name="maxPages" select="ceiling(count(//udt:Data) div $paging)" /> + <xsl:variable name="previous" select="number($param_page) - 1" /> + <xsl:variable name="next" select="number($param_page) + 1" /> + <table class="dnnFormItem" bordercolor="Gray" border="0" style="border-color:Gray;border-width:1px;border-style:Solid;width:100%;"> + <tr> + <td class="Normal" align="Left"> + <xsl:value-of select ="//udt:Context/udt:LocalizedString_Page"/>&amp;#160;<xsl:value-of select="number($param_page)"/>&amp;#160;<xsl:value-of select ="//udt:Context/udt:LocalizedString_Of"/>&amp;#160;<xsl:value-of select="$maxPages"/> + </td> + <td class="Normal" align="Right" > + <xsl:choose> + <xsl:when test="number($param_page)&gt;1"> + <a href="?{SEARCHING4}" class="CommandButton"> + <xsl:value-of select ="//udt:Context/udt:LocalizedString_First"/> + </a> + </xsl:when> + <xsl:otherwise> + <span class="NormalDisabled"> + <xsl:value-of select ="//udt:Context/udt:LocalizedString_First"/> + </span> + </xsl:otherwise> + </xsl:choose>&#160;&#160; + <xsl:choose> + <xsl:when test="number($param_page)&gt;1"> + <a href="?{$prefix_param}_page={$previous}{SEARCHING4}" class="CommandButton"> + <xsl:value-of select ="//udt:Context/udt:LocalizedString_Previous"/> + </a> + </xsl:when> + <xsl:otherwise> + <span class="NormalDisabled"> + <xsl:value-of select ="//udt:Context/udt:LocalizedString_Previous"/> + </span> + </xsl:otherwise> + </xsl:choose>&#160;&#160; + <xsl:variable name ="startpage"> + <xsl:choose> + <xsl:when test ="number($param_page)&amp;gt;5"> + <xsl:value-of select="number($param_page) -4"/> + </xsl:when> + <xsl:otherwise>1</xsl:otherwise> + </xsl:choose> + </xsl:variable> + <xsl:variable name ="endpage"> + <xsl:choose> + <xsl:when test="$startpage+9&amp;gt;$maxPages"> + <xsl:value-of select ="$maxPages"/> + </xsl:when> + <xsl:otherwise> + <xsl:value-of select ="$startpage +9"/> + </xsl:otherwise> + </xsl:choose> + </xsl:variable> + <xsl:call-template name="pagingSinglePages"> + <xsl:with-param name="pageNumber" select="$startpage"/> + <xsl:with-param name="maxPages" select="$endpage"/> + </xsl:call-template> + <xsl:choose> + <xsl:when test="number($param_page)&amp;lt;$maxPages"> + <a href="?{$prefix_param}_page={$next}{SEARCHING4}" class="CommandButton"> + <xsl:value-of select ="//udt:Context/udt:LocalizedString_Next"/> + </a> + </xsl:when> + <xsl:otherwise> + <span class="NormalDisabled"> + <xsl:value-of select ="//udt:Context/udt:LocalizedString_Next"/> + </span> + </xsl:otherwise> + </xsl:choose>&#160;&#160; + <xsl:choose> + <xsl:when test="number($param_page)&amp;lt;$maxPages"> + <a href="?{$prefix_param}_page={$maxPages}{SEARCHING4}" class="CommandButton"> + <xsl:value-of select ="//udt:Context/udt:LocalizedString_Last"/> + </a> + </xsl:when> + <xsl:otherwise> + <span class="NormalDisabled"> + <xsl:value-of select ="//udt:Context/udt:LocalizedString_Last"/> + </span> + </xsl:otherwise> + </xsl:choose>&#160;&#160; + </td> + </tr> + </table> +</xsl:template> + + + + <xsl:param name="from" select="1"/> + <xsl:param name="to" select="count(*)"/> + <xsl:if test="position() &amp;gt; $from and position() &amp;lt; $to"> + + + + </xsl:if> + + + + + <xsl:param name="param_search" /> +<xsl:param name="param_searchpostback" /> +<xsl:param name="param_ispostback" /> +<xsl:variable name="search"> +<xsl:choose> + <xsl:when test="$param_ispostback"> + <xsl:value-of select="$param_searchpostback" /> + </xsl:when> + <xsl:otherwise> + <xsl:value-of select="$param_search" /> + </xsl:otherwise> +</xsl:choose> +</xsl:variable> + + + + <xsl:variable name="searchColumns" select="//udt:Fields[udt:Searchable='true']/udt:ValueColumn" /> +<xsl:if test="//udt:Fields[udt:Searchable='true']"> +<xsl:call-template name="SearchForm" /> +</xsl:if> + + + + [contains(*[name()=$searchColumns][1],$search) or contains(*[name()=$searchColumns][2],$search) or contains(*[name()=$searchColumns][3],$search) or contains(*[name()=$searchColumns][4],$search) or contains(*[name()=$searchColumns][5],$search)] + + + <xsl:template name="SearchForm"> +<input type="text" name="{$prefix_param}_searchPostback" value="{$search}" /> +<input type="submit" name="go" value="{//udt:Context/udt:LocalizedString_Search}" /> +<input type="hidden" name="{$prefix_param}_ispostback" value="true" /> +</xsl:template> + + + + &amp;amp;{$prefix_param}_search={$search} + + \ No newline at end of file